<commit_before>/*!
 * formvalidation.js (https://github.com/chemerisuk/formvalidation.js)
 *
 * HTML5 form validation api polyfill
 *
 * Copyright (c) 2013 Maksim Chemerisuk
 *
 */
window.addEventListener && (function(document, window, bodyEl, htmlEl) {
    var tooltipApi = (function() {
            var validityEl = bodyEl.appendChild(document.createElement("div")),
                invalidInput = null,
                buildErrorClass = (function() {
                    var rUpperCase = /[A-Z]/g,
                        camelCaseToDashSeparated = function(l) {
                            return "-" + l.toLowerCase();
                        };

                    return function(errorType, input) {
                        var inputType = input.getAttribute("type");

                        if (errorType === "typeMismatch" && inputType) {
                            // special case for email-mismatch, url-mismatch etc.
                            return inputType.toLowerCase() + "-mismatch";
                        } else {
                            // convert camel case to dash separated
                            return errorType.replace(rUpperCase, camelCaseToDashSeparated);
                        }
                    };
                })();

            validityEl.id = "validity";

            return {
                show: function(input, force) {
                    if ((force || !invalidInput || invalidInput === input) && !input.validity.valid) {
                        var // validity vars
                            validity = input.validity,
                            classesArray = [],
                            errorMessage,
                            // position vars
                            boundingRect = input.getBoundingClientRect(),
                            clientTop = htmlEl.clientTop || bodyEl.clientTop || 0,
                            clientLeft = htmlEl.clientLeft || bodyEl.clientLeft || 0,
                            scrollTop = (window.pageYOffset || htmlEl.scrollTop || bodyEl.scrollTop),
                            scrollLeft = (window.pageXOffset || htmlEl.scrollLeft || bodyEl.scrollLeft);

                        for (var errorType in validity) {
                            if (validity[errorType]) {
                                classesArray.push(buildErrorClass(errorType, input));
                            }
                        }

                        if (validity.patternMismatch) {
                            // if pattern check fails use title to get error message
                            errorMessage = input.title;
                        }

                        if (validity.customError) {
                            errorMessage = input.validationMessage;
                        }

                        validityEl.textContent = errorMessage || "";
                        validityEl.className = classesArray.join(" ");
                        validityEl.style.top = boundingRect.bottom + scrollTop - clientTop + "px";
                        validityEl.style.left = boundingRect.left + scrollLeft - clientLeft + "px";

                        invalidInput = input;
                    }
                },
                hide: function(input, force) {
                    if (force || !invalidInput || invalidInput === input) {
                        validityEl.removeAttribute("class");

                        invalidInput = null;
                    }
                },
                getForm: function() {
                    return invalidInput ? invalidInput.form : null;
                }
            };
        })();

    if (!("validity" in document.createElement("input"))) {
        var rNumber = /^-?[0-9]*(\.[0-9]+)?$/,
            rEmail = /^([a-z0-9_\.\-\+]+)@([\da-z\.\-]+)\.([a-z\.]{2,6})$/i,
            rUrl = /^(https?:\/\/)?[\da-z\.\-]+\.[a-z\.]{2,6}[#&+_\?\/\w \.\-=]*$/i;

        window.ValidityState = function() {
            this.customError = false;
            this.patternMismatch = false;
            this.rangeOverflow = false;
            this.rangeUnderflow = false;
            this.stepMismatch = false;
            this.tooLong = false;
            this.typeMismatch = false;
            this.valid = true;
            this.valueMissing = false;
        };

        HTMLInputElement.prototype.setCustomValidity = HTMLTextAreaElement.prototype.setCustomValidity = function(message) {
            this.validationMessage = message;
            this.validity.customError = !!message;
        };

        // TODO: input[type=number]

        HTMLInputElement.prototype.checkValidity = HTMLTextAreaElement.prototype.checkValidity = function() {
            var validity = new ValidityState();

            switch(this.type) {
                case "image":
                case "submit":
                case "button":
                    return true;

                case "radio":
                    if (!this.checked && this.getAttribute("required")) {
                        validity.valueMissing = Array.prototype.some.call(this.form.elements, function(el) {
                            return this.name === el.name && el.checked;
                        }, this);
                        validity.valid = !validity.valueMissing;
                    }
                    break;
                case "checkbox":
                    validity.valueMissing = (!this.checked && this.getAttribute("required"));
                    validity.valid = !validity.valueMissing;
                    break;
                default: {
                    if (this.value) {
                        switch (this.getAttribute("type")) {
                        case "number":
                            validity.typeMismatch = !numberRe.test(this.value);
                            validity.valid = !validity.typeMismatch;
                            break;
                        case "email":
                            validity.typeMismatch = !rEmail.test(this.value);
                            validity.valid = !validity.typeMismatch;
                            break;
                        case "url":
                            validity.typeMismatch = !rUrl.test(this.value);
                            validity.valid = !validity.typeMismatch;
                            break;
                        }

                        if (this.type !== "textarea") {
                            var pattern = this.getAttribute("pattern");

                            if (pattern) {
                                pattern = new RegExp("^(?:" + pattern + ")$");

                                validity.patternMismatch = !pattern.test(this.value);
                                validity.valid = !validity.patternMismatch;
                            }
                        }
                    } else {
                        validity.valueMissing = !!this.getAttribute("required");
                        validity.valid = !validity.valueMissing;
                    }
                }
            }

            if (this.validity) {
                validity.customError = this.validity.customError;
                validity.valid &= !validity.customError;
            }

            this.validity = validity;

            if (!validity.valid) {
                // trigger invalid event
                var evt = document.createEvent("Event");

                evt.initEvent("invalid", false, false);

                this.dispatchEvent(evt);
            }

            // TODO: set validationMessage

            return validity.valid;
        };

        HTMLFormElement.prototype.checkValidity = function() {
            var inputs = Array.prototype.slice.call(this.elements, 0);

            for (var i = 0, n = inputs.length; i < n; ++i) {
                if (!inputs[i].checkValidity()) {
                    return false;
                }
            }

            return true;
        };
    }

    document.addEventListener("invalid", function(e) {
        tooltipApi.show(e.target, false);
        // don't show native tooltip
        e.preventDefault();
    }, true);

    document.addEventListener("change", function(e) {
        if (e.target.checkValidity()) {
            tooltipApi.hide(e.target, false);
        }
    }, false);

    document.addEventListener("input", function(e) {
        var target = e.target;
        // polyfill textarea maxlength attribute
        if (target.type == "textarea") {
            var maxlength = parseInt(target.getAttribute("maxlength"), 10);

            if (maxlength) {
                target.value = target.value.substr(0, maxlength);
            }
        }

        // hide tooltip on user input
        tooltipApi.hide(target, true);
    }, false);

    // validate all elements on a form submit
    document.addEventListener("submit", function(e) {
        if (e.target.checkValidity()) {
            tooltipApi.hide(null, true);
        } else {
            // prevent form submition because of errors
            e.preventDefault();
        }
    }, true);

    // hide tooltip when user resets the form
    document.addEventListener("reset", function(e) {
        tooltipApi.hide(null, true);
    }, false);

    // hide tooltip when user goes to other part of page
    document.addEventListener("click", function(e) {
        if (e.target.form !== tooltipApi.getForm()) {
            tooltipApi.hide(null, true);
        }
    }, true);

})(document, window, document.body, document.documentElement);<commit_msg>refactoring<commit_after>/*!
 * formvalidation.js (https://github.com/chemerisuk/formvalidation.js)
 *
 * HTML5 form validation api polyfill
 *
 * Copyright (c) 2013 Maksim Chemerisuk
 *
 */
window.addEventListener && (function(document, window, bodyEl, htmlEl) {
    var bindEvent = function(eventType, capturing, handler) {
            document.addEventListener(eventType, handler, capturing);
        },
        fireEvent = function(eventType, thisPtr) {
            var evt = document.createEvent("Event");

            evt.initEvent(eventType, false, false);

            thisPtr.dispatchEvent(evt);
        },
        none = function(form, test) {
            var inputs = Array.prototype.slice.call(form.elements, 0);

            for (var i = 0, n = inputs.length; i < n; ++i) {
                if (!test(inputs[i])) {
                    return false;
                }
            }

            return true;
        },
        tooltipApi = (function() {
            var validityEl = bodyEl.appendChild(document.createElement("div")),
                invalidInput = null,
                buildErrorClass = (function() {
                    var rUpperCase = /[A-Z]/g,
                        camelCaseToDashSeparated = function(l) {
                            return "-" + l.toLowerCase();
                        };

                    return function(errorType, input) {
                        var inputType = input.getAttribute("type");

                        if (errorType === "typeMismatch" && inputType) {
                            // special case for email-mismatch, url-mismatch etc.
                            return inputType.toLowerCase() + "-mismatch";
                        } else {
                            // convert camel case to dash separated
                            return errorType.replace(rUpperCase, camelCaseToDashSeparated);
                        }
                    };
                })();

            validityEl.id = "validity";

            return {
                show: function(input, force) {
                    if ((force || !invalidInput || invalidInput === input) && !input.validity.valid) {
                        var // validity vars
                            validity = input.validity,
                            classesArray = [],
                            errorMessage,
                            // position vars
                            boundingRect = input.getBoundingClientRect(),
                            clientTop = htmlEl.clientTop || bodyEl.clientTop || 0,
                            clientLeft = htmlEl.clientLeft || bodyEl.clientLeft || 0,
                            scrollTop = (window.pageYOffset || htmlEl.scrollTop || bodyEl.scrollTop),
                            scrollLeft = (window.pageXOffset || htmlEl.scrollLeft || bodyEl.scrollLeft);

                        for (var errorType in validity) {
                            if (validity[errorType]) {
                                classesArray.push(buildErrorClass(errorType, input));
                            }
                        }

                        if (validity.patternMismatch) {
                            // if pattern check fails use title to get error message
                            errorMessage = input.title;
                        }

                        if (validity.customError) {
                            errorMessage = input.validationMessage;
                        }

                        validityEl.textContent = errorMessage || "";
                        validityEl.className = classesArray.join(" ");
                        validityEl.style.top = boundingRect.bottom + scrollTop - clientTop + "px";
                        validityEl.style.left = boundingRect.left + scrollLeft - clientLeft + "px";

                        invalidInput = input;
                    }
                },
                hide: function(input, force) {
                    if (force || !invalidInput || invalidInput === input) {
                        validityEl.removeAttribute("class");

                        invalidInput = null;
                    }
                },
                getForm: function() {
                    return invalidInput ? invalidInput.form : null;
                }
            };
        })();

    if (!("validity" in document.createElement("input"))) {
        var rNumber = /^-?[0-9]*(\.[0-9]+)?$/,
            rEmail = /^([a-z0-9_\.\-\+]+)@([\da-z\.\-]+)\.([a-z\.]{2,6})$/i,
            rUrl = /^(https?:\/\/)?[\da-z\.\-]+\.[a-z\.]{2,6}[#&+_\?\/\w \.\-=]*$/i;

        window.ValidityState = function() {
            this.customError = false;
            this.patternMismatch = false;
            this.rangeOverflow = false;
            this.rangeUnderflow = false;
            this.stepMismatch = false;
            this.tooLong = false;
            this.typeMismatch = false;
            this.valid = true;
            this.valueMissing = false;
        };

        HTMLInputElement.prototype.setCustomValidity = HTMLTextAreaElement.prototype.setCustomValidity = function(message) {
            this.validationMessage = message;
            this.validity.customError = !!message;
        };

        // TODO: input[type=number]

        HTMLInputElement.prototype.checkValidity = HTMLTextAreaElement.prototype.checkValidity = function() {
            var validity = new ValidityState();

            switch(this.type) {
                case "image":
                case "submit":
                case "button":
                    return true;

                case "radio":
                    if (!this.checked && this.getAttribute("required")) {
                        var name = this.name;

                        validity.valueMissing = none(this.form, function(input) {
                            return input.checked && input.name === name;
                        });
                        validity.valid = !validity.valueMissing;
                    }
                    break;
                case "checkbox":
                    validity.valueMissing = (!this.checked && this.getAttribute("required"));
                    validity.valid = !validity.valueMissing;
                    break;
                default: {
                    if (this.value) {
                        switch (this.getAttribute("type")) {
                        case "number":
                            validity.typeMismatch = !numberRe.test(this.value);
                            validity.valid = !validity.typeMismatch;
                            break;
                        case "email":
                            validity.typeMismatch = !rEmail.test(this.value);
                            validity.valid = !validity.typeMismatch;
                            break;
                        case "url":
                            validity.typeMismatch = !rUrl.test(this.value);
                            validity.valid = !validity.typeMismatch;
                            break;
                        }

                        if (this.type !== "textarea") {
                            var pattern = this.getAttribute("pattern");

                            if (pattern) {
                                pattern = new RegExp("^(?:" + pattern + ")$");

                                validity.patternMismatch = !pattern.test(this.value);
                                validity.valid = !validity.patternMismatch;
                            }
                        }
                    } else {
                        validity.valueMissing = !!this.getAttribute("required");
                        validity.valid = !validity.valueMissing;
                    }
                }
            }

            if (this.validity) {
                validity.customError = this.validity.customError;
                validity.validationMessage = this.validity.validationMessage;
                validity.valid &= !validity.customError;
            }

            this.validity = validity;

            return validity.valid || !!fireEvent("invalid", this);
        };

        HTMLFormElement.prototype.checkValidity = function() {
            return none(this, function(input) {
                return !input.checkValidity();
            });
        };
    }

    bindEvent("invalid", true, function(e) {
        tooltipApi.show(e.target, false);
        // don't show native tooltip
        e.preventDefault();
    });

    bindEvent("change", false, function(e) {
        if (e.target.checkValidity()) {
            tooltipApi.hide(e.target, false);
        }
    });

    bindEvent("input", false, function(e) {
        var target = e.target;
        // polyfill textarea maxlength attribute
        if (target.type == "textarea") {
            var maxlength = parseInt(target.getAttribute("maxlength"), 10);

            if (maxlength) {
                target.value = target.value.substr(0, maxlength);
            }
        }

        // hide tooltip on user input
        tooltipApi.hide(target, true);
    });

    // validate all elements on a form submit
    bindEvent("submit", true, function(e) {
        if (e.target.checkValidity()) {
            tooltipApi.hide(null, true);
        } else {
            // prevent form submition because of errors
            e.preventDefault();
        }
    });

    // hide tooltip when user resets the form
    bindEvent("reset", false, function(e) {
        tooltipApi.hide(null, true);
    });

    // hide tooltip when user goes to other part of page
    bindEvent("click", true, function(e) {
        if (e.target.form !== tooltipApi.getForm()) {
            tooltipApi.hide(null, true);
        }
    });

})(document, window, document.body, document.documentElement);<|endoftext|>


<commit_before>module.exports = function (obj, sub) {
  if (sub) {
    sub = sub.split('.')
  }

  if (obj === null || obj === undefined) return false

  if (!sub) return true

  var current = obj
  var prop
  for (var i = 0; i < sub.length; i++) {
    prop = sub[i]
    if (current[prop] === null || current[prop] === undefined) return false
    current = current[prop]
  }

  return true
}
<commit_msg>compress<commit_after>module.exports = function (obj, sub) {
  if (sub) sub = sub.split('.')

  if (obj === null || obj === undefined) return false

  if (!sub) return true

  var current = obj
  var prop
  for (var i = 0; i < sub.length; i++) {
    prop = sub[i]
    if (current[prop] === null || current[prop] === undefined) return false
    current = current[prop]
  }

  return true
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require('fs');
const spawn = require('child_process').spawn;
const createGzip = require('zlib').createGzip;

const glob = require('glob');
const split = require('split');
const request = require('request');
const tar = require('tar-fs');

const COMMENT_LINES =/^#/;

const IGNORE_FILES = ['.npmignore', '.yarnignore'];

const handleResponse = (packageUrl, cb, err, resp, body) => {
    if (err) {
        throw err
    }

    if (cb) {
        cb(packageUrl, resp, body, err);
    }

    if (resp.statusCode === 200) {
        console.log(`successfully published version ${packageUrl}`);
    }
    else {
        console.error(`mmm, something is going on here... we got back an unexpected status code back (${resp.statusCode})`);
        console.error(resp);
    }

}

const map = (header) => {
    header.name = `package/${header.name}`;
    return header
  };

// we compress and upload the package after gathering the list of packages needed
const compressAndUpload = (dir, packageUrl, cb, entries) => (
    tar.pack(dir, {entries, map})
        .pipe(createGzip())
        .pipe(
            request.put(packageUrl, handleResponse.bind(null, packageUrl, cb))
        )
);

_getFilesByIgnore = (ignoreFile, dir, onDone, onError) => {

    console.log(`using ignorefile: ${ignoreFile}`);

    const globRules = ['node_modules'];

    fs.createReadStream(`${dir}/${ignoreFile}`)
        .pipe(split())
        .on('data',
            (pattern) => pattern &&
            !pattern.match(COMMENT_LINES) &&
            globRules.push(pattern)
        ).on('end', () =>
            glob("**/*", { cwd: dir, ignore: globRules }, (err, files) => onDone(files))
        ).on('error', onError);
};

_getFilesByGit = (dir, onDone, onError) => {
    const files = [];

    console.log(`using git to get the list of files to be packaged`);

    spawn('git', ['ls-files'], {cwd: dir}).stdout
        .pipe(split())
        .on('data', (line) => files.push(line))
        .on('end', () => resolve(files))
        .on('error', onError);
};

_getFiles = (dir) => {
    // we would follow different strategies here:
    // 1. if .npmignore is there, use it.
    // 2. if .yarnignore is there, use it.
    // 3. get files from git

    const ignoreFile = IGNORE_FILES.find((file) => fs.existsSync(`${dir}/${file}`));

    const action = ignoreFile ? _getFilesByIgnore.bind(null, ignoreFile) : _getFilesByGit;

    return new Promise(action.bind(null, dir));
}

const dryRun = (dir, cb) => {

    _getFiles(dir).then((files) => {
        console.log(`all these files would be packaged: ${JSON.stringify(files, null, '\t')}`);
    });
};

const publish = (dir, registry, name, version, cb) => {
    const packageUrl = `${registry}/package/${name}/${version}`;

    _getFiles(dir).then(compressAndUpload.bind(null, dir, packageUrl, cb));
};

module.exports = {
    publish,
    dryRun,
};

<commit_msg>fixing _getFilesByGit -> resolve/onDone<commit_after>#!/usr/bin/env node

const fs = require('fs');
const spawn = require('child_process').spawn;
const createGzip = require('zlib').createGzip;

const glob = require('glob');
const split = require('split');
const request = require('request');
const tar = require('tar-fs');

const COMMENT_LINES =/^#/;

const IGNORE_FILES = ['.npmignore', '.yarnignore'];

const handleResponse = (packageUrl, cb, err, resp, body) => {
    if (err) {
        throw err
    }

    if (cb) {
        cb(packageUrl, resp, body, err);
    }

    if (resp.statusCode === 200) {
        console.log(`successfully published version ${packageUrl}`);
    }
    else {
        console.error(`mmm, something is going on here... we got back an unexpected status code back (${resp.statusCode})`);
        console.error(resp);
    }

}

const map = (header) => {
    header.name = `package/${header.name}`;
    return header
  };

// we compress and upload the package after gathering the list of packages needed
const compressAndUpload = (dir, packageUrl, cb, entries) => (
    tar.pack(dir, {entries, map})
        .pipe(createGzip())
        .pipe(
            request.put(packageUrl, handleResponse.bind(null, packageUrl, cb))
        )
);

_getFilesByIgnore = (ignoreFile, dir, onDone, onError) => {

    console.log(`using ignorefile: ${ignoreFile}`);

    const globRules = ['node_modules'];

    fs.createReadStream(`${dir}/${ignoreFile}`)
        .pipe(split())
        .on('data',
            (pattern) => pattern &&
            !pattern.match(COMMENT_LINES) &&
            globRules.push(pattern)
        ).on('end', () =>
            glob("**/*", { cwd: dir, ignore: globRules }, (err, files) => onDone(files))
        ).on('error', onError);
};

_getFilesByGit = (dir, onDone, onError) => {
    const files = [];

    console.log(`using git to get the list of files to be packaged`);

    spawn('git', ['ls-files'], {cwd: dir}).stdout
        .pipe(split())
        .on('data', (line) => files.push(line))
        .on('end', () => onDone(files))
        .on('error', onError);
};

_getFiles = (dir) => {
    // we would follow different strategies here:
    // 1. if .npmignore is there, use it.
    // 2. if .yarnignore is there, use it.
    // 3. get files from git

    const ignoreFile = IGNORE_FILES.find((file) => fs.existsSync(`${dir}/${file}`));

    const action = ignoreFile ? _getFilesByIgnore.bind(null, ignoreFile) : _getFilesByGit;

    return new Promise(action.bind(null, dir));
}

const dryRun = (dir, cb) => {

    _getFiles(dir).then((files) => {
        console.log(`all these files would be packaged: ${JSON.stringify(files, null, '\t')}`);
    });
};

const publish = (dir, registry, name, version, cb) => {
    const packageUrl = `${registry}/package/${name}/${version}`;

    _getFiles(dir).then(compressAndUpload.bind(null, dir, packageUrl, cb));
};

module.exports = {
    publish,
    dryRun,
};

<|endoftext|>


<commit_before>$(function() {
  $('body').on('click', '[data-apos-search-filter]', function() {
    $(this).closest('form').submit();
  });
  $('body').on('keyup', '[data-apos-search-field]', function (e) {
    if (e.keyCode == 13) {
      $(this).closest('form').submit();
      return false;
    }
  });
});

apos.on('notfound', function(info) {
  $(function() {
    $.get('/search', { q: info.suggestedSearch }, function(html) {
      $('[data-notfound-search-results]').html(html);
    });
  });
});
<commit_msg>namespace the data attribute<commit_after>$(function() {
  $('body').on('click', '[data-apos-search-filter]', function() {
    $(this).closest('form').submit();
  });
  $('body').on('keyup', '[data-apos-search-field]', function (e) {
    if (e.keyCode == 13) {
      $(this).closest('form').submit();
      return false;
    }
  });
});

apos.on('notfound', function(info) {
  $(function() {
    $.get('/search', { q: info.suggestedSearch }, function(html) {
      $('[data-apos-notfound-search-results]').html(html);
    });
  });
});
<|endoftext|>


<commit_before>function ResumeHandler() {}

function isGenerator(v) {
  return v && v.constructor && v.constructor.name == 'GeneratorFunction';
}

function isGeneratorProto(v) {
  return v && v.constructor && v.constructor.name == 'GeneratorFunctionPrototype';
}

function step(iterator, error, returnValues, next) {
  var iteration;

  try {
    if (error) {
      iteration = iterator.throw.call(iterator, error);
    } else {
      iteration = iterator.next.apply(iterator, returnValues);
    }
  } catch (err) {
    return next(err);
  }

  var value = iteration.value;

  if (iteration.done) return next(null, value);

  if (value instanceof ResumeHandler) {
    value.resume = function(error) {
      setTimeout(step.bind(null, iterator, error, Array.prototype.slice.call(arguments, 1), next), 0);
    };
    iterator.next();
  } else if (isGeneratorProto(value)) {
    step(value, null, [], function(error) {
      step(iterator, error, Array.prototype.slice.call(arguments, 1), next);
    });
  } else if (Array.isArray(value)) {
    if (!value.length) {
      step(iterator, null, [[]], next);
      return;
    }
    // jshint ignore:start
    var results = [];
    var errors = [];
    var outstanding = value.length;
    for (var i = 0, l = value.length; i < l; i++) {
      if (!isGeneratorProto(value[i])) {
        results[i] = value[i];
        finish();
        continue;
      }
      step(value[i], null, [], function(n, error, result) {
        if (error) {
          errors.push(error);
        } else {
          results[n] = result;
        }
        finish();
      }.bind(null, i));
      function finish() {
        outstanding--;
        if (outstanding === 0) {
          if (errors.length === 1) {
            step(iterator, errors[0], [], next);
          } else if (errors.length > 1) {
            step(iterator, new Error('Parallel yield got multiple errors:\n' + errors.map(function(err) { return err.stack || err; }).join('\n')), [], next);
          } else {
            step(iterator, null, [results], next);
          }
        }
      }
    }
    // jshint ignore:end
  } else if (typeof value == 'object') {
    if (!Object.keys(value).length) {
      step(iterator, null, [{}], next);
      return;
    }
    // jshint ignore:start
    var keys = Object.keys(value);
    var results = {};
    var errors = [];
    var outstanding = keys.length;
    for (var i = 0, l = keys.length; i < l; i++) {
      if (!isGeneratorProto(value[keys[i]])) {
        results[keys[i]] = value[keys[i]];
        finish();
        continue;
      }
      step(value[keys[i]], null, [], function(n, error, result) {
        if (error) {
          errors.push(error);
        } else {
          results[keys[n]] = result;
        }
        finish();
      }.bind(null, i));
      function finish() {
        outstanding--;
        if (outstanding === 0) {
          if (errors.length === 1) {
            step(iterator, errors[0], [], next);
          } else if (errors.length > 1) {
            step(iterator, new Error('Parallel yield got multiple errors:\n' + errors.map(function(err) { return err.stack; }).join('\n')), [], next);
          } else {
            step(iterator, null, [results], next);
          }
        }
      }
    }
    // jshint ignore:end
  } else {
    throw new Error('Yielded something other than a generator, an array of generators, or a ResumeHandler: ' + value);
  }
}

var go = {};

go.run = function(generator, callback) {
  if (typeof generator === 'function') generator = generator();
  if (!isGeneratorProto(generator)) throw new Error('First argument to run() must be a generator or a generator function, got: ' + generator);
  step(generator, null, [], callback);
};

go.wrap = function(f) {
  return function* wrapper() {
    var args = Array.prototype.slice.call(arguments);
    var resumeHandler = new ResumeHandler();
    args.push(function() {
      if (!resumeHandler.resume) {
        throw new Error('Wrapped function returned before its resumeHandler was ready: ' + f);
      }
      resumeHandler.resume.apply(null, arguments);
    });
    yield resumeHandler;
    f.apply(this, args);
    return yield null;
  };
};

go.express = function(app) {
  var methods = ['get', 'post', 'put', 'delete'];
  methods.forEach(function(method) {
    var original = app[method];
    app[method] = function() {
      var args = Array.prototype.slice.call(arguments);
      args = args.map(function(arg) {
        if (!isGenerator(arg)) return arg;
        return function(req, res, next) {
          step(arg(req, res, next), null, [], function(err, json) {
            if (err) return next(err);
            res.send(json);
          });
        };
      });
      return original.apply(app, args);
    };
  });
};

go.wait = go.wrap(function(interval, cb) {
  setTimeout(() => cb(), interval);
});

module.exports = go;
<commit_msg>Remove go.express()<commit_after>function ResumeHandler() {}

function isGenerator(v) {
  return v && v.constructor && v.constructor.name == 'GeneratorFunction';
}

function isGeneratorProto(v) {
  return v && v.constructor && v.constructor.name == 'GeneratorFunctionPrototype';
}

function step(iterator, error, returnValues, next) {
  var iteration;

  try {
    if (error) {
      iteration = iterator.throw.call(iterator, error);
    } else {
      iteration = iterator.next.apply(iterator, returnValues);
    }
  } catch (err) {
    return next(err);
  }

  var value = iteration.value;

  if (iteration.done) return next(null, value);

  if (value instanceof ResumeHandler) {
    value.resume = function(error) {
      setTimeout(step.bind(null, iterator, error, Array.prototype.slice.call(arguments, 1), next), 0);
    };
    iterator.next();
  } else if (isGeneratorProto(value)) {
    step(value, null, [], function(error) {
      step(iterator, error, Array.prototype.slice.call(arguments, 1), next);
    });
  } else if (Array.isArray(value)) {
    if (!value.length) {
      step(iterator, null, [[]], next);
      return;
    }
    // jshint ignore:start
    var results = [];
    var errors = [];
    var outstanding = value.length;
    for (var i = 0, l = value.length; i < l; i++) {
      if (!isGeneratorProto(value[i])) {
        results[i] = value[i];
        finish();
        continue;
      }
      step(value[i], null, [], function(n, error, result) {
        if (error) {
          errors.push(error);
        } else {
          results[n] = result;
        }
        finish();
      }.bind(null, i));
      function finish() {
        outstanding--;
        if (outstanding === 0) {
          if (errors.length === 1) {
            step(iterator, errors[0], [], next);
          } else if (errors.length > 1) {
            step(iterator, new Error('Parallel yield got multiple errors:\n' + errors.map(function(err) { return err.stack || err; }).join('\n')), [], next);
          } else {
            step(iterator, null, [results], next);
          }
        }
      }
    }
    // jshint ignore:end
  } else if (typeof value == 'object') {
    if (!Object.keys(value).length) {
      step(iterator, null, [{}], next);
      return;
    }
    // jshint ignore:start
    var keys = Object.keys(value);
    var results = {};
    var errors = [];
    var outstanding = keys.length;
    for (var i = 0, l = keys.length; i < l; i++) {
      if (!isGeneratorProto(value[keys[i]])) {
        results[keys[i]] = value[keys[i]];
        finish();
        continue;
      }
      step(value[keys[i]], null, [], function(n, error, result) {
        if (error) {
          errors.push(error);
        } else {
          results[keys[n]] = result;
        }
        finish();
      }.bind(null, i));
      function finish() {
        outstanding--;
        if (outstanding === 0) {
          if (errors.length === 1) {
            step(iterator, errors[0], [], next);
          } else if (errors.length > 1) {
            step(iterator, new Error('Parallel yield got multiple errors:\n' + errors.map(function(err) { return err.stack; }).join('\n')), [], next);
          } else {
            step(iterator, null, [results], next);
          }
        }
      }
    }
    // jshint ignore:end
  } else {
    throw new Error('Yielded something other than a generator, an array of generators, or a ResumeHandler: ' + value);
  }
}

var go = {};

go.run = function(generator, callback) {
  if (typeof generator === 'function') generator = generator();
  if (!isGeneratorProto(generator)) throw new Error('First argument to run() must be a generator or a generator function, got: ' + generator);
  step(generator, null, [], callback);
};

go.wrap = function(f) {
  return function* wrapper() {
    var args = Array.prototype.slice.call(arguments);
    var resumeHandler = new ResumeHandler();
    args.push(function() {
      if (!resumeHandler.resume) {
        throw new Error('Wrapped function returned before its resumeHandler was ready: ' + f);
      }
      resumeHandler.resume.apply(null, arguments);
    });
    yield resumeHandler;
    f.apply(this, args);
    return yield null;
  };
};

go.wait = go.wrap(function(interval, cb) {
  setTimeout(() => cb(), interval);
});

module.exports = go;
<|endoftext|>


<commit_before>'use strict';

var RNG = require('rng')

function first (o) {
  for(var k in o)
    return k
}

var create = module.exports = function (seed, cb) {
  var rng = new RNG.MT(seed)
  var l = 10000

  var heap = []
  var result
  var ended
  var queued = false

  function next () {
    if(queued) return
    queued = true
    if(ended) return

    rng.random() < 0.4 ? setImmediate(call) : setTimeout(call)

    function call() {

      queued = false

      var key = first(heap)
      var cb = heap[key]
      delete heap[key]
      if(cb) {
        try { cb() }
        catch (err) { return async.done(err) }
      }
      else return

      setImmediate(next)

    }
  }

  function async (cb) {
    return function () {
      var args = [].slice.call(arguments)
      var self = this
      function _cb () {
        console.log(args)
        return cb.apply(self, args)
      }

      if(rng.random() < 0.3)
        try { return _cb() }
        catch (err) { return async.done(err) }

      while (true) {
        var i = rng.range(0, 0xffff)
        if(!heap[i]) {
          heap[i] = _cb
          break;
        }
      }

      next ()

    }
  }

  async.through = function () {
    return function (read) {
      return function (abort, cb) {
        read(abort, async(cb))
      }
    }
  }

  process.on('exit', forgot)

  function forgot () {
    async.done(new Error('never called'))
  }

  async.done = function (err, value) {
    if(ended) return
    ended = true
    if(result) {
      result.passed = false
      result.calls ++
      return
    }

    process.removeListener('exit', forgot)

    result = {
      error: err,
      value: value,
      passed: !err,
      calls: 1,
      seed: seed
    }

    if(cb) cb(null, result)
    else if(err) throw err
  }

  return async
}

create.test = function (test, cb) {
  var total = 100
  var n = total, results = []
  for( var i = 0; i < total; i++)
    (function (i) {

      var async = create(i, function (err, result) {
        if(err) result.error = err
        results[i] = result
        done()
      })

      test(async)

    })(i)

  function done () {
    if(--n) return
    var stats = {
      passes: 0,
      total: results.length,
      failures: 0,
      errors: 0
    }
    var err = null

    if(stats.failures)
      err = new Error(
          'failed ' + stats.failures
        + ' out of ' + stats.total)

    results.forEach(function (e) {
      if((!e.error) && e.calls === 1)
        stats.passes ++
      else
        stats.failures ++
      if(e.calls > 1)
        stats.errors ++
    })

    if(cb) cb(err, results, stats)
    else if(err) throw err
    else console.log(stats)
  }
}

if(!module.parent) {

  var async = create(Date.now())

  async(function () {
    console.log(1)
  }) ()
  async(function () {
    console.log(2)
  }) ()
  async(function () {
    console.log(3)
  }) ()

}
<commit_msg>throw if any tests fail<commit_after>'use strict';

var RNG = require('rng')

function first (o) {
  for(var k in o)
    return k
}

var create = module.exports = function (seed, cb) {
  var rng = new RNG.MT(seed)
  var l = 10000

  var heap = []
  var result
  var ended
  var queued = false

  function next () {
    if(queued) return
    queued = true
    if(ended) return

    rng.random() < 0.4 ? setImmediate(call) : setTimeout(call)

    function call() {

      queued = false

      var key = first(heap)
      var cb = heap[key]
      delete heap[key]
      if(cb) {
        try { cb() }
        catch (err) { return async.done(err) }
      }
      else return

      setImmediate(next)

    }
  }

  function async (cb) {
    return function () {
      var args = [].slice.call(arguments)
      var self = this
      function _cb () {
        console.log(args)
        return cb.apply(self, args)
      }

      if(rng.random() < 0.3)
        try { return _cb() }
        catch (err) { return async.done(err) }

      while (true) {
        var i = rng.range(0, 0xffff)
        if(!heap[i]) {
          heap[i] = _cb
          break;
        }
      }

      next ()

    }
  }

  async.through = function () {
    return function (read) {
      return function (abort, cb) {
        read(abort, async(cb))
      }
    }
  }

  process.on('exit', forgot)
  process.setMaxListeners(Infinity)

  function forgot () {
    async.done(new Error('never called'))
  }

  async.done = function (err, value) {
    if(ended) return
    ended = true
    if(result) {
      result.passed = false
      result.calls ++
      result.error = result.error || new Error('called done twice')
      return
    }

    process.removeListener('exit', forgot)

    result = {
      error: err,
      value: value,
      passed: !err,
      calls: 1,
      seed: seed
    }

    if(cb) cb(err, result)
    else if(err) throw err
  }

  return async
}

create.test = function (test, cb) {
  var total = 100
  var n = total, results = []
  for( var i = 0; i < total; i++)
    (function (i) {

      var async = create(i, function (err, result) {
        if(err) result.error = err
        results[i] = result
        done()
      })

      test(async)

    })(i)

  function done () {
    if(--n) return
    var stats = {
      passes: 0,
      total: results.length,
      failures: 0,
      errors: 0
    }
    var err = null

    results.forEach(function (e) {
      if((!e.error) && e.calls === 1)
        stats.passes ++
      else
        stats.failures ++
      if(e.calls > 1)
        stats.errors ++
    })

    if(stats.failures)
      err = new Error(
          'failed ' + stats.failures
        + ' out of ' + stats.total)

    if(cb) cb(err, results, stats)
    else if(err) throw err
    else console.log(stats)
  }
}

if(!module.parent) {

  var async = create(Date.now())

  async(function () {
    console.log(1)
  }) ()
  async(function () {
    console.log(2)
  }) ()
  async(function () {
    console.log(3)
  }) ()

}
<|endoftext|>


<commit_before>/*
 * sass-partial-dependencies
 * https://github.com/tbremer/sass-partial-dependencies
 *
 * Copyright (c) 2014 Thomas Bremer, contributors
 * Licensed under the MIT license.
 */
 'use strict';
 var fs = require('fs');
 var path = require('path');
 var chalk = require('chalk');
 var glob = require('glob');
 var _ = require('underscore');

 module.exports = function(needle, haystack) {
 	var timerStart = Date.now();
 	var isVerbose = (process.argv.indexOf('--verbose') !== -1 || process.argv.indexOf('-v') !== -1) ? true : false;

	// Check if file exists | return false
	if (!fs.existsSync(needle)) {
		if (isVerbose) {
			console.log(chalk.cyan('File doesn\'t exist.'));
		}
		return false;
	}
	// Check if file is a *.css file, SASS doesn't import those
	if (path.extname(needle) === '.css') {
		if (isVerbose) {
			console.log(chalk.cyan('SASS won\'t import *.css files'));
		}
		return false;
	}

	//Look for verbose for logging options
	// We have passed our base checks, lets define some variables.

	var dependentFiles = [],
	    ext            = path.extname(needle);

	// If a hastack wasn't sent in, then we define it here. We also remove the needle from the haystack.
	if (haystack === undefined) {
		haystack = glob.sync('**/*' + ext);
	}
	haystack = _.without(haystack, needle);

	_.each(haystack, function(straw, index, array) {
		if (isVerbose) {
			console.log('Current file: ' + chalk.cyan(path.basename(straw)));
		}
		var thisContents, relPath, isDependent, isPartial;
		thisContents = fs.readFileSync(straw, {encoding: 'utf8'});
		relPath = path.relative(straw, needle).replace('../', '').replace('/_','/').replace(ext, '');
		if (relPath[0] === '_') {
			relPath = relPath.replace('_','');
		}
		isDependent = thisContents.indexOf(relPath) !== -1 ? true : false;
		if (isDependent) {
			isPartial = path.basename(straw)[0] === '_' ? true : false;
			if (isPartial) {
				if (isVerbose) {
					console.log(chalk.cyan(path.basename(needle)), chalk.white(' is a partial, adding it to the haystack'));
				}
				array.push(needle);
			} else {
				dependentFiles.push(straw);
			}
		}
	});

	if(dependentFiles.length === 0) {
		if (isVerbose) {
			console.log(chalk.cyan(path.basename(needle)), chalk.white(' does not have any dependencies'));
		}
		return false;
	}
	if (isVerbose) {
		console.log('Dependencies: ' + chalk.cyan(dependentFiles.join(', ')));
	}
	var timerEnd = Date.now();
	if (isVerbose) {
		console.log('Dependent Files took: ' + chalk.cyan((timerEnd - timerStart) + 'ms'));
	}
	return dependentFiles;
};
<commit_msg>remove some verbose comments<commit_after>/*
 * sass-partial-dependencies
 * https://github.com/tbremer/sass-partial-dependencies
 *
 * Copyright (c) 2014 Thomas Bremer, contributors
 * Licensed under the MIT license.
 */
 'use strict';
 var fs = require('fs');
 var path = require('path');
 var chalk = require('chalk');
 var glob = require('glob');
 var _ = require('underscore');

 module.exports = function(needle, haystack) {
 	var timerStart = Date.now();
 	var isVerbose = (process.argv.indexOf('--verbose') !== -1 || process.argv.indexOf('-v') !== -1) ? true : false;

	// Check if file exists | return false
	if (!fs.existsSync(needle)) {
		if (isVerbose) {
			console.log(chalk.cyan('File doesn\'t exist.'));
		}
		return false;
	}
	// Check if file is a *.css file, SASS doesn't import those
	if (path.extname(needle) === '.css') {
		if (isVerbose) {
			console.log(chalk.cyan('SASS won\'t import *.css files'));
		}
		return false;
	}

	//Look for verbose for logging options
	// We have passed our base checks, lets define some variables.

	var dependentFiles = [],
	    ext            = path.extname(needle);

	// If a hastack wasn't sent in, then we define it here. We also remove the needle from the haystack.
	if (haystack === undefined) {
		haystack = glob.sync('**/*' + ext);
	}
	haystack = _.without(haystack, needle);

	_.each(haystack, function(straw, index, array) {
		var thisContents, relPath, isDependent, isPartial;
		thisContents = fs.readFileSync(straw, {encoding: 'utf8'});
		relPath = path.relative(straw, needle).replace('../', '').replace('/_','/').replace(ext, '');
		if (relPath[0] === '_') {
			relPath = relPath.replace('_','');
		}
		isDependent = thisContents.indexOf(relPath) !== -1 ? true : false;
		if (isDependent) {
			isPartial = path.basename(straw)[0] === '_' ? true : false;
			if (isPartial) {
				if (isVerbose) {
					console.log(chalk.cyan(path.basename(needle)), chalk.white(' is a partial, adding it to the haystack'));
				}
				array.push(needle);
			} else {
				dependentFiles.push(straw);
			}
		}
	});

	if(dependentFiles.length === 0) {
		if (isVerbose) {
			console.log(chalk.cyan(path.basename(needle)), chalk.white(' does not have any dependencies'));
		}
		return false;
	}
	if (isVerbose) {
		console.log('Dependencies: ' + chalk.cyan(dependentFiles.join(', ')));
	}
	var timerEnd = Date.now();
	if (isVerbose) {
		console.log('sass-get-dependencies took: ' + chalk.cyan((timerEnd - timerStart) + 'ms'));
	}
	return dependentFiles;
};
<|endoftext|>


<commit_before>/**
 * Destination Database Adapter - Built with you in mind.
 * for MongoDB
 *
 * @author Nijiko Yonskai
 * @copyright 2013
 * @license MIT
 */
var Mongode = require('mongode');

/**
 * Adapter Constructor
 *
 * Does adapter setup, checks, and creates a connection to the mongodb database.
 *
 * @param  {Object} settings    Database settings
 * @param  {Object} objective   Current Destination
 * @param  {Object} destination Destination Framework
 * @return {Object}
 */
var Database = module.exports = function (settings, objective, framework) {
  if (!Mongode) framework.log.database.fatal('Missing node_module:', 'Mongode');
  var uri;

  this.framework = framework;
  this.log = framework.log.database;
  this.BSON = Mongode.BSON;
  this.collections = {};

  this.identifier = function (id) {
    return (typeof id !== 'string') ? id : Mongode.ObjectID(id);
  };

  if (settings.urls) {
    uri = settings.urls;
    if (framework.log.level === 'debug') this.log.debug('Opening Connections To:', uri);
    else this.log.info('Opening Connections...');
  } else {
    uri = 'mongodb://' +  (settings.username ? settings.username + ':' + settings.password + '@' : '') + settings.host + (settings.port ? ':' + settings.port : '') + '/' + (settings.database || '_test');
    if (framework.log.level === 'debug') this.log.debug('Opening Connection To:', uri);
    else this.log.info('Opening Connection...');
  }

  this.connection = Mongode.connect(uri, settings.options || {});

  return this;
};

Database.prototype.parse = function (filter) {
  if (filter.id)
    return { _id: (typeof filter.id === 'string') ? new this.ObjectID(filter.id) : filter.id };

  var query = {};
  for (var type in filter) {
    if (typeof filter[type] === 'object')
      query[type] = filter[type];
    else if (filter[type] === null)
      query[type] = { $type: 10 };
    else
      query[type] = filter[type];
  }

  return query;
};

Database.prototype.define = function (name, object) {
  this.log.info('Storing Collection: ' + name);
  this.log.debug('Collection Model:', object);
  this.collections[name] = this.connection.collection(name);
  this.collections[name].model = object;
};

Database.prototype.create = function (collection, data, callback) {
  if (data.id === null) {
    delete data.id;
  }

  if (data.id) {
    data._id = data.id;
    delete data.id;
  }

  this.collections[collection].insert(data, {}, function (err, m) {
    callback(err, err ? null : m[0]._id);
  });
};

Database.prototype.update = function (collection, data, callback) {
  var query = {};

  if (data.where) {
    query = this.parse(data.where);
    delete data.where;
  } else query._id = (typeof data.id === 'string') ? new this.ObjectID(data.id) : data.id;

  this.collections[collection].update(query, data, function (err) {
    callback(err);
  });
};

Database.prototype.exists = function (collection, query, callback) {
  query = this.parse(query);

  this.collections[collection].findOne(query, { _id: 1 }, function (err, data) {
    callback(err, !!(data && data._id));
  });
};

Database.prototype.find = function (collection, query, projection, callback) {
  if (query.id) {
    query._id = (typeof query.id === 'string') ? new this.ObjectID(query.id) : query.id;
    delete query.id;
  } else query = this.parse(query);

  if (typeof projection === 'function')
    callback = projection, projection = null;

  this.collections[collection].findOne(query, projection, function (err, data) {
    callback(err, data);
  });
};

Database.prototype.upsert = function (model, data, callback) {
  var query = {};

  if (data.where) {
    query = this.parse(data.where);
    delete data.where;
  } else {
    if (data.id)
      query._id = (typeof data.id === 'string') ? new this.ObjectID(data.id) : data.id;
    else
      query._id = data._id ? data._id : new this.ObjectID();

    data.id = query._id;

    if (data._id)
      delete data._id;
  }

  this.collections[collection].update(query, { $set: data }, { upsert: true, multi: false }, function (error, rowsAffected) {
    callback(error, data);
  });
};

Database.prototype.remove = function (collection, data, callback) {
  var query = {};

  if (data.where) {
    query = this.parse(data.where);
    delete data.where;
  } else
    query._id = (typeof data.id === 'string') ? new this.ObjectID(data.id) : data.id;

  this.collections[collection].remove(query, callback);
};

Database.prototype.all = function (collection, filter, callback) {
  (!filter) && (filter = {});
  var query = filter.where ? this.parse(filter.where) : {};
  var projection = filter.projection;
  var cursor = this.collections[collection].find(query, projection);

  if (filter.order) {
    if (typeof filter.order === 'string') {
      var order = filter.order.split(",");
      filter.order = {};

      for (var index = 0; index < order.length; index++) {
        var set = order[index].split(" ").filter(function (n) {
          return n;
        });

        if (!(set[0] && set[1])) throw new Error(
          "Invalid ordering set."
        );

        filter.order[set[0]] = filter.order[set[1]];
      }
    }

    for (var key in filter.order) {
      if (!filter.order.hasOwnProperty(key)) return;
      var value = filter.order[key];
      var match = value.match(/\s+(A|DE)SC$/);

      filter.order[key] = (match && match[1] === 'DE') ? -1 : 1;
    }

    cursor.sort(filter.order);
  }

  if (filter.limit)
    cursor.limit(filter.limit);

  if (filter.skip)
    cursor.skip(filter.skip);
  else if (filter.offset)
    cursor.skip(filter.offset);

  cursor.toArray(function (error, data) {
    if (error) return callback(error);

    var output = data.map(function (o) {
      o.id = o._id;
      return o;
    });

    if (filter && filter.include) {
      var keys = Object.keys(filter.include);
      for (var index = 0; index < keys.length; index++) {
        var includeCollection = keys[index];
        var includeFilter = filter.include[includeCollection];
        var last = index === keys.length - 1;

        this.all(includeCollection, includeFilter, function (error, data) {
          output[includeCollection] = data;

          if (last) callback(null, output);
        });
      }
    } else callback(null, output);
  });
};

Database.prototype.empty = function (collection, callback) {
  this.collections[collection].remove({}, callback);
};

Database.prototype.count = function (collection, where, callback) {
  if (typeof where === 'function')
    callback = where, where = undefined;

  this.collections[collection].count(where, function (error, count) {
    callback(error, count);
  });
};

Database.prototype.updateAttributes = function (model, query, data, cb) {
  var query = this.parse(query);

  this.collection(model).findAndModify(query, [['_id','asc']], { $set: data }, {}, function (error, object) {
    cb(error, object);
  });
};

Database.prototype.close = function () {
  this.client.close();
};<commit_msg>Projections<commit_after>/**
 * Destination Database Adapter - Built with you in mind.
 * for MongoDB
 *
 * @author Nijiko Yonskai
 * @copyright 2013
 * @license MIT
 */
var Mongode = require('mongode');

/**
 * Adapter Constructor
 *
 * Does adapter setup, checks, and creates a connection to the mongodb database.
 *
 * @param  {Object} settings    Database settings
 * @param  {Object} objective   Current Destination
 * @param  {Object} destination Destination Framework
 * @return {Object}
 */
var Database = module.exports = function (settings, objective, framework) {
  if (!Mongode) framework.log.database.fatal('Missing node_module:', 'Mongode');
  var uri;

  this.framework = framework;
  this.log = framework.log.database;
  this.BSON = Mongode.BSON;
  this.collections = {};

  this.identifier = function (id) {
    return (typeof id !== 'string') ? id : Mongode.ObjectID(id);
  };

  if (settings.urls) {
    uri = settings.urls;
    if (framework.log.level === 'debug') this.log.debug('Opening Connections To:', uri);
    else this.log.info('Opening Connections...');
  } else {
    uri = 'mongodb://' +  (settings.username ? settings.username + ':' + settings.password + '@' : '') + settings.host + (settings.port ? ':' + settings.port : '') + '/' + (settings.database || '_test');
    if (framework.log.level === 'debug') this.log.debug('Opening Connection To:', uri);
    else this.log.info('Opening Connection...');
  }

  this.connection = Mongode.connect(uri, settings.options || {});

  return this;
};

Database.prototype.parse = function (filter) {
  if (filter.id)
    return { _id: (typeof filter.id === 'string') ? new this.ObjectID(filter.id) : filter.id };

  var query = {};
  for (var type in filter) {
    if (typeof filter[type] === 'object')
      query[type] = filter[type];
    else if (filter[type] === null)
      query[type] = { $type: 10 };
    else
      query[type] = filter[type];
  }

  return query;
};

Database.prototype.define = function (name, object) {
  this.log.info('Storing Collection: ' + name);
  this.log.debug('Collection Model:', object);
  this.collections[name] = this.connection.collection(name);
  this.collections[name].model = object;
};

Database.prototype.create = function (collection, data, callback) {
  if (data.id === null) {
    delete data.id;
  }

  if (data.id) {
    data._id = data.id;
    delete data.id;
  }

  this.collections[collection].insert(data, {}, function (err, m) {
    callback(err, err ? null : m[0]._id);
  });
};

Database.prototype.update = function (collection, data, callback) {
  var query = {};

  if (data.where) {
    query = this.parse(data.where);
    delete data.where;
  } else query._id = (typeof data.id === 'string') ? new this.ObjectID(data.id) : data.id;

  this.collections[collection].update(query, data, function (err) {
    callback(err);
  });
};

Database.prototype.exists = function (collection, query, callback) {
  query = this.parse(query);

  this.collections[collection].findOne(query, { _id: 1 }, function (err, data) {
    callback(err, !!(data && data._id));
  });
};

Database.prototype.find = function (collection, query, projection, callback) {
  if (query.id) {
    query._id = (typeof query.id === 'string') ? new this.ObjectID(query.id) : query.id;
    delete query.id;
  } else query = this.parse(query);

  if (typeof projection === 'function')
    callback = projection, projection = {};
  else if (!projection)
    projection = {};

  this.collections[collection].findOne(query, projection, function (err, data) {
    callback(err, data);
  });
};

Database.prototype.upsert = function (model, data, callback) {
  var query = {};

  if (data.where) {
    query = this.parse(data.where);
    delete data.where;
  } else {
    if (data.id)
      query._id = (typeof data.id === 'string') ? new this.ObjectID(data.id) : data.id;
    else
      query._id = data._id ? data._id : new this.ObjectID();

    data.id = query._id;

    if (data._id)
      delete data._id;
  }

  this.collections[collection].update(query, { $set: data }, { upsert: true, multi: false }, function (error, rowsAffected) {
    callback(error, data);
  });
};

Database.prototype.remove = function (collection, data, callback) {
  var query = {};

  if (data.where) {
    query = this.parse(data.where);
    delete data.where;
  } else
    query._id = (typeof data.id === 'string') ? new this.ObjectID(data.id) : data.id;

  this.collections[collection].remove(query, callback);
};

Database.prototype.all = function (collection, filter, callback) {
  (!filter) && (filter = {});
  var query = filter.where ? this.parse(filter.where) : {};
  var projection = filter.projection;
  var cursor = this.collections[collection].find(query, projection);

  if (filter.order) {
    if (typeof filter.order === 'string') {
      var order = filter.order.split(",");
      filter.order = {};

      for (var index = 0; index < order.length; index++) {
        var set = order[index].split(" ").filter(function (n) {
          return n;
        });

        if (!(set[0] && set[1])) throw new Error(
          "Invalid ordering set."
        );

        filter.order[set[0]] = filter.order[set[1]];
      }
    }

    for (var key in filter.order) {
      if (!filter.order.hasOwnProperty(key)) return;
      var value = filter.order[key];
      var match = value.match(/\s+(A|DE)SC$/);

      filter.order[key] = (match && match[1] === 'DE') ? -1 : 1;
    }

    cursor.sort(filter.order);
  }

  if (filter.limit)
    cursor.limit(filter.limit);

  if (filter.skip)
    cursor.skip(filter.skip);
  else if (filter.offset)
    cursor.skip(filter.offset);

  cursor.toArray(function (error, data) {
    if (error) return callback(error);

    var output = data.map(function (o) {
      o.id = o._id;
      return o;
    });

    if (filter && filter.include) {
      var keys = Object.keys(filter.include);
      for (var index = 0; index < keys.length; index++) {
        var includeCollection = keys[index];
        var includeFilter = filter.include[includeCollection];
        var last = index === keys.length - 1;

        this.all(includeCollection, includeFilter, function (error, data) {
          output[includeCollection] = data;

          if (last) callback(null, output);
        });
      }
    } else callback(null, output);
  });
};

Database.prototype.empty = function (collection, callback) {
  this.collections[collection].remove({}, callback);
};

Database.prototype.count = function (collection, where, callback) {
  if (typeof where === 'function')
    callback = where, where = undefined;

  this.collections[collection].count(where, function (error, count) {
    callback(error, count);
  });
};

Database.prototype.updateAttributes = function (model, query, data, cb) {
  var query = this.parse(query);

  this.collection(model).findAndModify(query, [['_id','asc']], { $set: data }, {}, function (error, object) {
    cb(error, object);
  });
};

Database.prototype.close = function () {
  this.client.close();
};<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var logStream = null;
var flushTimer = null;

function openLogStream() {
   if( !logStream ) {
      logStream = fs.createWriteStream('quizResults/results.txt', {'flags': 'a'});
   }
}
//
// this is your magic password to access quiz results
// currently the quiz supports a single instructor and a single quiz.
//
var instructorCode = "BrettRunsFast";

var app = express();

app.use(express.static("static"));

app.get('/results', function(req, res){
    res.end();
});

//
// enable presentquiz
//
app.post('/startquiz', function(req, res) {
   console.log("start of quiz");
   openLogStream();
   logStream.write("#quiz_start "+  ((new Date()) + "\n"));
   res.end();
});

//
// upload a quiz question.
//
app.post('/submitAnswers', function(request, response) {
  var body = [];
  //
  // Guess what? You forgot to start a quiz and students are now trying answer the quiz.
  // Have no fear, we'll open the file for you so the values aren't lost (which tends to
  // iritate people.
  //
  openLogStream();
  request.on('data', function(chunk) {
     body.push(chunk);
  }).on('end', function() {
     body = Buffer.concat(body).toString();
     logStream.write(body + "\n");
     response.end();

  });
});

//
// Close the quiz. Answers will still be accepted and stored but they won't be part of the quiz results
// per se.
//
app.post('/endquiz', function(req, res) {
  console.log("end of quiz");
  logStream.end("#end of quiz\n");
  logStream = null;
});

app.listen(8080, function() {
    console.log("phyquiz listening on port 8080");
});
<commit_msg>removed old file<commit_after><|endoftext|>


<commit_before>var _ = require('underscore'),
    q = require('q'),
    probedock = require('probedock-node');

function ProbeDockKarmaReporter(logger, options) {
  this.log = logger.create('reporter.probedock');
  this.options = options || {};
}

ProbeDockKarmaReporter.$inject = ['logger', 'config.probedock'];
exports['reporter:probedock'] = [ 'type', ProbeDockKarmaReporter ];

_.extend(ProbeDockKarmaReporter.prototype, {

  onRunStart: function() {
    this.config = probedock.client.loadConfig(this.options.config);
    this.testRun = probedock.client.startTestRun(this.config);
    this.uploads = [];
  },

  onSpecComplete: function(browser, result) {
    if (result.skipped) {
      return;
    }

    var name = result.suite.join(' ') + ' ' + result.description,
        options = {
          nameParts: result.suite.concat([ result.description ])
        };

    if (!result.success) {
      options.message = browser.name + ': ' + result.log.join("\n");
    }

    this.testRun.add(null, name, result.success, result.time, options);
  },

  onRunComplete: function() {
    this.testRun.end();

    var log = this.log;

    var numberOfResults = this.testRun.results.length;
    if (numberOfResults) {
      var numberOfResultsWithKey = _.reduce(this.testRun.results, function(memo, result) {
        return memo + (result.key ? 1 : 0);
      }, 0);

      log.info('Found ' + (numberOfResultsWithKey ? numberOfResultsWithKey : 'no') + ' results to send to Probe Dock (' + numberOfResults + ' results in total)');
    }

    var startTime = new Date().getTime();

    var promise = probedock.client.process(this.testRun, this.config).then(_.partial(logInfo, startTime, log)).fail(logError);

    this.uploads.push(promise);

    var uploads = this.uploads;
    promise.fin(function() {
      uploads.splice(uploads.indexOf(promise), 1);
    });
  },

  onExit: function(done) {
    if (this.uploads.length) {
      this.log.info('Waiting on test results to be published to Probe Dock...');
    }
    q.all(this.uploads).fin(done);
  }
});

function logInfo(startTime, log, info) {
  if (info.errors.length) {
    _.each(info.errors, function(error) {
      log.warn(error);
    });
  } else if (!info.published) {
    log.info('Publishing disabled');
  } else {
    var duration = new Date().getTime() - startTime;
    log.info('Test results successfully published in ' + (duration / 1000) + 's');
  }
}

function logError(err) {
  log.warn(err.message + "\n" + err.stack);
}
<commit_msg>Disabled missing key check.<commit_after>var _ = require('underscore'),
    q = require('q'),
    probedock = require('probedock-node');

function ProbeDockKarmaReporter(logger, options) {
  this.log = logger.create('reporter.probedock');
  this.options = options || {};
}

ProbeDockKarmaReporter.$inject = ['logger', 'config.probedock'];
exports['reporter:probedock'] = [ 'type', ProbeDockKarmaReporter ];

_.extend(ProbeDockKarmaReporter.prototype, {

  onRunStart: function() {
    this.config = probedock.client.loadConfig(this.options.config);
    this.testRun = probedock.client.startTestRun(this.config);
    this.uploads = [];
  },

  onSpecComplete: function(browser, result) {
    if (result.skipped) {
      return;
    }

    var name = result.suite.join(' ') + ' ' + result.description,
        options = {
          nameParts: result.suite.concat([ result.description ])
        };

    if (!result.success) {
      options.message = browser.name + ': ' + result.log.join("\n");
    }

    this.testRun.add(null, name, result.success, result.time, options);
  },

  onRunComplete: function() {
    this.testRun.end();

    var log = this.log;

    var numberOfResults = this.testRun.results.length;
    if (numberOfResults) {
      log.info('Found ' + numberOfResults + ' results to send to Probe Dock');
    }

    var startTime = new Date().getTime();

    var promise = probedock.client.process(this.testRun, this.config).then(_.partial(logInfo, startTime, log)).fail(logError);

    this.uploads.push(promise);

    var uploads = this.uploads;
    promise.fin(function() {
      uploads.splice(uploads.indexOf(promise), 1);
    });
  },

  onExit: function(done) {
    if (this.uploads.length) {
      this.log.info('Waiting on test results to be published to Probe Dock...');
    }
    q.all(this.uploads).fin(done);
  }
});

function logInfo(startTime, log, info) {
  if (info.errors.length) {
    _.each(info.errors, function(error) {
      log.warn(error);
    });
  } else if (!info.published) {
    log.info('Publishing disabled');
  } else {
    var duration = new Date().getTime() - startTime;
    log.info('Test results successfully published in ' + (duration / 1000) + 's');
  }
}

function logError(err) {
  log.warn(err.message + "\n" + err.stack);
}
<|endoftext|>


<commit_before>/**
 * @module  auth
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {String} [config.loginUrl="/login"] URL to login-in
 * @property {Boolean} [config.useOAuth=false] Use OAuth method to authenticate
 * @property {String} [config.oAuthAccessTokenURL="/oauth/access_token"] OAuth endpoint to retrieve access token
 */
exports.config = _.extend({
	loginUrl: '/login',
	useOAuth: false,
	oAuthAccessTokenURL: '/oauth/access_token'
}, Alloy.CFG.T ? Alloy.CFG.T.auth : {});

var Q = require('T/ext/q');
var HTTP = require('T/http');
var Event = require('T/event');
var Cache = require('T/cache');
var Util = require('T/util');

var OAuth = require('T/support/oauth');

/**
 * OAuth object instance of oauth module
 * @see  support/oauth
 * @type {Object}
 */
exports.OAuth = OAuth;

var Me = null;

/**
 * User model object
 * Don't rely direcly on this property but use {@link getUser) instead
 * @type {Backbone.Model}
 */
exports.me = Me;

////////////
// Driver //
////////////

function getStoredDriverString() {
	var hasDriver = Ti.App.Properties.hasProperty('auth.driver');
	var hasMe = Ti.App.Properties.hasProperty('auth.me');
	if (hasDriver && hasMe) {
		return Ti.App.Properties.getString('auth.driver');
	}
}

function driverLogin(opt) {
	var driver = exports.loadDriver(opt.driver);
	var method = opt.stored === true ? 'storedLogin' : 'login';

	return Q.promise(function(resolve, reject) {
		driver[ method ]({
			data: opt.data,
			success: resolve,
			error: reject
		});
	});
}

///////////////////////
// Server side login //
///////////////////////

function serverLoginWithOAuth(opt, dataFromDriver) {
	var oAuthPostData = {
		client_id: OAuth.getClientID(),
		client_secret: OAuth.getClientSecret(),
		grant_type: 'password',
		username: '-',
		password: '-'
	};

	return Q.promise(function(resolve, reject) {
		HTTP.send({
			url: exports.config.oAuthAccessTokenURL,
			method: 'POST',
			data: _.extend({}, oAuthPostData, dataFromDriver),
			suppressFilters: ['oauth'],
			success: function(data) {
				OAuth.storeCredentials(data);
				resolve(data);
			},
			error: reject,
		});
	});
}

function serverLoginWithCookie(opt, dataFromDriver) {
	return Q.promise(function(resolve, reject) {
		HTTP.send({
			url: opt.loginUrl,
			method: 'POST',
			data: dataFromDriver,
			success: function(data) {
				HTTP.exportCookiesToSystem();
				resolve(data);
			},
			error: reject,
		});
	});
}

function apiLogin(opt, dataFromDriver) {
	var driver = exports.loadDriver(opt.driver);
	opt.loginUrl = driver.config.loginUrl || exports.config.loginUrl;

	if (exports.config.useOAuth == true) {
		return serverLoginWithOAuth(opt, dataFromDriver);
	} else {
		return serverLoginWithCookie(opt, dataFromDriver);
	}
}

//////////////////////
// Fetch user model //
//////////////////////

function fetchUserModel(opt, dataFromServer) {
	dataFromServer = dataFromServer || {};
	return Q.promise(function(resolve, reject) {
		Me = Alloy.createModel('user', { id: dataFromServer.id || 'me' });
		Me.fetch({
			http: {
				refresh: true,
				cache: false,
			},
			success: function() {
				Ti.App.Properties.setObject('auth.me', Me.toJSON());
				resolve();
			},
			error: function(model, err) {
				reject(err);
			}
		});
	});
}

/**
 * Load a driver
 * @return {Object}
 */
exports.loadDriver = function(name) {
	return Alloy.Globals.Trimethyl.loadDriver('auth', name, {
		login: function() {},
		storedLogin: function() {},
		isStoredLoginAvailable: function() {},
		logout: function() {}
	});
};

/**
 * Add an event to current module
 */
exports.event = function(name, cb) {
	Event.on('auth.' + name, cb);
};

/**
 * Get current User model
 * @return {Backbone.Model}
 */
exports.getUser = function(){
	return Me;
};

/**
 * Check if the user is logged in
 * @return {Boolean}
 */
exports.isLoggedIn = function() {
	return Me !== null;
};

/**
 * Get current User ID
 * Return 0 if no user is logged in
 * @return {Number}
 */
exports.getUserID = function(){
	if (Me === null) return 0;
	return Me.id;
};

/**
 * Login using selected driver
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {String} [opt.driver="bypass"] The driver to use as string
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 */
exports.login = function(opt) {
	opt = _.defaults(opt || {}, {
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop,
		silent: false,
		driver: 'bypass'
	});

	driverLogin(opt)

	.then(function(dataFromDriver) {
		return apiLogin(opt, _.extend({}, dataFromDriver, {
			method: opt.driver
		}));
	})

	.then(function(dataFromServer) {
		return fetchUserModel(opt, dataFromServer);
	})

	.then(function() {
		Ti.App.Properties.setString('auth.driver', opt.driver);

		var payload = {
			id: Me.id
		};

		opt.success(payload);
		if (opt.silent !== true) {
			Event.trigger('auth.success', payload);
		}
	})

	.fail(function(err) {
		Event.trigger('auth.error', err);
		opt.error(err);
	});
};

/**
 * Check if the stored login feature is available
 * Stored login indicate if the auth can be completed using stored credentials on the device
 * but require an Internet connection anyway
 * @return {Boolean}
 */
exports.isStoredLoginAvailable = function() {
	var driver = getStoredDriverString();
	if (driver == null) return false;

	return exports.loadDriver(driver).isStoredLoginAvailable();
};

/**
 * Login using stored credentials on the device
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 */
exports.storedLogin = function(opt) {
	opt = _.defaults(opt || {}, {
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop
	});

	if (exports.isStoredLoginAvailable()) {
		exports.login(_.extend(opt || {}, {
			stored: true,
			driver: getStoredDriverString()
		}));
	} else {
		opt.error();
	}
};

/**
 * Check if an offline login is available
 * @return {Boolean}
 */
exports.isOfflineLoginAvailable = function() {
	return Ti.App.Properties.hasProperty('auth.me');
};

/**
 * Login using offline properties
 * This method doesn't require an internet connection
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 */
exports.offlineLogin = function(opt) {
	opt = _.defaults(opt || {}, {
		silent: false,
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop
	});

	if (exports.isOfflineLoginAvailable()) {

		Me = Alloy.createModel('user', Ti.App.Properties.getObject('auth.me'));

		var payload = {
			id: Me.id,
			offline: true
		};

		opt.success(payload);
		if (opt.silent !== true) {
			Event.trigger('auth.success', payload);
		}

	} else {
		opt.error();
	}
};

/**
 * This method will select the best behaviour and will login the user
 * @param {Object} opt
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 * @param {Function} [opt.timeout=10000] Timeout after the auto login will cause an error
 */
exports.autoLogin = function(opt) {
	opt = _.defaults(opt || {}, {
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop,
		timeout: 10000,
		silent: false
	});

	var success = opt.success;
	var error = opt.error;

	var timeouted = false;
	var errorTimeout = setTimeout(function() {
		timeouted = true;
		opt.error();
	}, opt.timeout);

	opt.success = function() {
		clearTimeout(errorTimeout);
		success.apply(null, arguments);
	};

	opt.error = function() {
		clearTimeout(errorTimeout);
		 // reset to noop to prevent that is invoked lately
		success = Alloy.Globals.noop;
		error.apply(null, arguments);
	};

	if (Ti.Network.online) {

		var driver = getStoredDriverString();
		if (exports.config.useOAuth == true && driver === 'bypass') {

			if (OAuth.getAccessToken() != null) {

				fetchUserModel()
				.then(function() {
					if (timeouted) return;

					var payload = {
						id: Me.id,
						oauth: true
					};

					opt.success(payload);
					if (opt.silent !== true) {
						Event.trigger('auth.success', payload);
					}

				})
				.fail(function(err) {
					opt.error(err);
					if (opt.silent != true) {
						Event.trigger('auth.error', err);
					}
				});

			} else {
				opt.error();
			}

		} else {

			if (exports.isStoredLoginAvailable()) {
				exports.storedLogin({
					success: function(payload) {
						if (timeouted) return;
						opt.success(payload);
						if (opt.silent != true) {
							Event.trigger('auth.success', payload);
						}
					},
					error: opt.error,
					silent: true // manage internally
				});
			} else {
				opt.error();
			}

		}

	} else {
		if (exports.isOfflineLoginAvailable()) {
			exports.offlineLogin({
				success: function(payload) {
					if (timeouted) return;
					opt.success(payload);
					if (opt.silent != true) {
						Event.trigger('auth.success', payload);
					}
				},
				error: opt.error,
				silent: true // manage internally
			});
		} else {
			opt.error();
		}
	}
};

/**
 * Logout the user
 * @param  {Function} callback Callback to invoke on completion
 */
exports.logout = function(callback) {
	Event.trigger('auth.logout', {
		id: exports.getUserID()
	});

	var driver = getStoredDriverString();
	if (driver != null) {
		exports.loadDriver(driver).logout();
	}

	HTTP.send({
		url: '/logout',
		method: 'POST',
		timeout: 3000,
		complete: function() {
			Me = null;

			Ti.App.Properties.removeProperty('auth.me');
			Ti.App.Properties.removeProperty('auth.driver');

			Cache.purge();

			if (exports.config.useOAuth == true) {
				OAuth.resetCredentials();
			} else {
				Ti.Network.removeHTTPCookiesForDomain(Util.getDomainFromURL(HTTP.config.base));
			}

			if (_.isFunction(callback)) callback();
		}
	});
};

//////////
// Init //
//////////

if (exports.config.useOAuth == true) {
	HTTP.addFilter('oauth', OAuth.httpFilter);
}
<commit_msg>Little movement<commit_after>/**
 * @module  auth
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {String} [config.loginUrl="/login"] URL to login-in
 * @property {Boolean} [config.useOAuth=false] Use OAuth method to authenticate
 * @property {String} [config.oAuthAccessTokenURL="/oauth/access_token"] OAuth endpoint to retrieve access token
 */
exports.config = _.extend({
	loginUrl: '/login',
	useOAuth: false,
	oAuthAccessTokenURL: '/oauth/access_token'
}, Alloy.CFG.T ? Alloy.CFG.T.auth : {});

var Q = require('T/ext/q');
var HTTP = require('T/http');
var Event = require('T/event');
var Cache = require('T/cache');
var Util = require('T/util');

var OAuth = require('T/support/oauth');
var Me = null;

/**
 * OAuth object instance of oauth module
 * @see  support/oauth
 * @type {Object}
 */
exports.OAuth = OAuth;

/**
 * User model object
 * Don't rely direcly on this property but use {@link getUser) instead
 * @type {Backbone.Model}
 */
exports.me = Me;

////////////
// Driver //
////////////

function getStoredDriverString() {
	var hasDriver = Ti.App.Properties.hasProperty('auth.driver');
	var hasMe = Ti.App.Properties.hasProperty('auth.me');
	if (hasDriver && hasMe) {
		return Ti.App.Properties.getString('auth.driver');
	}
}

function driverLogin(opt) {
	var driver = exports.loadDriver(opt.driver);
	var method = opt.stored === true ? 'storedLogin' : 'login';

	return Q.promise(function(resolve, reject) {
		driver[ method ]({
			data: opt.data,
			success: resolve,
			error: reject
		});
	});
}

///////////////////////
// Server side login //
///////////////////////

function serverLoginWithOAuth(opt, dataFromDriver) {
	var oAuthPostData = {
		client_id: OAuth.getClientID(),
		client_secret: OAuth.getClientSecret(),
		grant_type: 'password',
		username: '-',
		password: '-'
	};

	return Q.promise(function(resolve, reject) {
		HTTP.send({
			url: exports.config.oAuthAccessTokenURL,
			method: 'POST',
			data: _.extend({}, oAuthPostData, dataFromDriver),
			suppressFilters: ['oauth'],
			success: function(data) {
				OAuth.storeCredentials(data);
				resolve(data);
			},
			error: reject,
		});
	});
}

function serverLoginWithCookie(opt, dataFromDriver) {
	return Q.promise(function(resolve, reject) {
		HTTP.send({
			url: opt.loginUrl,
			method: 'POST',
			data: dataFromDriver,
			success: function(data) {
				HTTP.exportCookiesToSystem();
				resolve(data);
			},
			error: reject,
		});
	});
}

function apiLogin(opt, dataFromDriver) {
	var driver = exports.loadDriver(opt.driver);
	opt.loginUrl = driver.config.loginUrl || exports.config.loginUrl;

	if (exports.config.useOAuth == true) {
		return serverLoginWithOAuth(opt, dataFromDriver);
	} else {
		return serverLoginWithCookie(opt, dataFromDriver);
	}
}

//////////////////////
// Fetch user model //
//////////////////////

function fetchUserModel(opt, dataFromServer) {
	dataFromServer = dataFromServer || {};
	return Q.promise(function(resolve, reject) {
		Me = Alloy.createModel('user', { id: dataFromServer.id || 'me' });
		Me.fetch({
			http: {
				refresh: true,
				cache: false,
			},
			success: function() {
				Ti.App.Properties.setObject('auth.me', Me.toJSON());
				resolve();
			},
			error: function(model, err) {
				reject(err);
			}
		});
	});
}

/**
 * Load a driver
 * @return {Object}
 */
exports.loadDriver = function(name) {
	return Alloy.Globals.Trimethyl.loadDriver('auth', name, {
		login: function() {},
		storedLogin: function() {},
		isStoredLoginAvailable: function() {},
		logout: function() {}
	});
};

/**
 * Add an event to current module
 */
exports.event = function(name, cb) {
	Event.on('auth.' + name, cb);
};

/**
 * Get current User model
 * @return {Backbone.Model}
 */
exports.getUser = function(){
	return Me;
};

/**
 * Check if the user is logged in
 * @return {Boolean}
 */
exports.isLoggedIn = function() {
	return Me !== null;
};

/**
 * Get current User ID
 * Return 0 if no user is logged in
 * @return {Number}
 */
exports.getUserID = function(){
	if (Me === null) return 0;
	return Me.id;
};

/**
 * Login using selected driver
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {String} [opt.driver="bypass"] The driver to use as string
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 */
exports.login = function(opt) {
	opt = _.defaults(opt || {}, {
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop,
		silent: false,
		driver: 'bypass'
	});

	driverLogin(opt)

	.then(function(dataFromDriver) {
		return apiLogin(opt, _.extend({}, dataFromDriver, {
			method: opt.driver
		}));
	})

	.then(function(dataFromServer) {
		return fetchUserModel(opt, dataFromServer);
	})

	.then(function() {
		Ti.App.Properties.setString('auth.driver', opt.driver);

		var payload = {
			id: Me.id
		};

		opt.success(payload);
		if (opt.silent !== true) {
			Event.trigger('auth.success', payload);
		}
	})

	.fail(function(err) {
		Event.trigger('auth.error', err);
		opt.error(err);
	});
};

/**
 * Check if the stored login feature is available
 * Stored login indicate if the auth can be completed using stored credentials on the device
 * but require an Internet connection anyway
 * @return {Boolean}
 */
exports.isStoredLoginAvailable = function() {
	var driver = getStoredDriverString();
	if (driver == null) return false;

	return exports.loadDriver(driver).isStoredLoginAvailable();
};

/**
 * Login using stored credentials on the device
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 */
exports.storedLogin = function(opt) {
	opt = _.defaults(opt || {}, {
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop
	});

	if (exports.isStoredLoginAvailable()) {
		exports.login(_.extend(opt || {}, {
			stored: true,
			driver: getStoredDriverString()
		}));
	} else {
		opt.error();
	}
};

/**
 * Check if an offline login is available
 * @return {Boolean}
 */
exports.isOfflineLoginAvailable = function() {
	return Ti.App.Properties.hasProperty('auth.me');
};

/**
 * Login using offline properties
 * This method doesn't require an internet connection
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 */
exports.offlineLogin = function(opt) {
	opt = _.defaults(opt || {}, {
		silent: false,
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop
	});

	if (exports.isOfflineLoginAvailable()) {

		Me = Alloy.createModel('user', Ti.App.Properties.getObject('auth.me'));

		var payload = {
			id: Me.id,
			offline: true
		};

		opt.success(payload);
		if (opt.silent !== true) {
			Event.trigger('auth.success', payload);
		}

	} else {
		opt.error();
	}
};

/**
 * This method will select the best behaviour and will login the user
 * @param {Object} opt
 * @param  {Object} opt
 * @param {Boolean} [opt.silent=false] Silence all global events
 * @param {Function} [opt.success=null] The success callback to invoke
 * @param {Function} [opt.error=null] The error callback to invoke
 * @param {Function} [opt.timeout=10000] Timeout after the auto login will cause an error
 */
exports.autoLogin = function(opt) {
	opt = _.defaults(opt || {}, {
		success: Alloy.Globals.noop,
		error: Alloy.Globals.noop,
		timeout: 10000,
		silent: false
	});

	var success = opt.success;
	var error = opt.error;

	var timeouted = false;
	var errorTimeout = setTimeout(function() {
		timeouted = true;
		opt.error();
	}, opt.timeout);

	opt.success = function() {
		clearTimeout(errorTimeout);
		success.apply(null, arguments);
	};

	opt.error = function() {
		clearTimeout(errorTimeout);
		 // reset to noop to prevent that is invoked lately
		success = Alloy.Globals.noop;
		error.apply(null, arguments);
	};

	if (Ti.Network.online) {

		var driver = getStoredDriverString();
		if (exports.config.useOAuth == true && driver === 'bypass') {

			if (OAuth.getAccessToken() != null) {

				fetchUserModel()
				.then(function() {
					if (timeouted) return;

					var payload = {
						id: Me.id,
						oauth: true
					};

					opt.success(payload);
					if (opt.silent !== true) {
						Event.trigger('auth.success', payload);
					}

				})
				.fail(function(err) {
					opt.error(err);
					if (opt.silent != true) {
						Event.trigger('auth.error', err);
					}
				});

			} else {
				opt.error();
			}

		} else {

			if (exports.isStoredLoginAvailable()) {
				exports.storedLogin({
					success: function(payload) {
						if (timeouted) return;
						opt.success(payload);
						if (opt.silent != true) {
							Event.trigger('auth.success', payload);
						}
					},
					error: opt.error,
					silent: true // manage internally
				});
			} else {
				opt.error();
			}

		}

	} else {
		if (exports.isOfflineLoginAvailable()) {
			exports.offlineLogin({
				success: function(payload) {
					if (timeouted) return;
					opt.success(payload);
					if (opt.silent != true) {
						Event.trigger('auth.success', payload);
					}
				},
				error: opt.error,
				silent: true // manage internally
			});
		} else {
			opt.error();
		}
	}
};

/**
 * Logout the user
 * @param  {Function} callback Callback to invoke on completion
 */
exports.logout = function(callback) {
	Event.trigger('auth.logout', {
		id: exports.getUserID()
	});

	var driver = getStoredDriverString();
	if (driver != null) {
		exports.loadDriver(driver).logout();
	}

	HTTP.send({
		url: '/logout',
		method: 'POST',
		timeout: 3000,
		complete: function() {
			Me = null;

			Ti.App.Properties.removeProperty('auth.me');
			Ti.App.Properties.removeProperty('auth.driver');

			Cache.purge();

			if (exports.config.useOAuth == true) {
				OAuth.resetCredentials();
			} else {
				Ti.Network.removeHTTPCookiesForDomain(Util.getDomainFromURL(HTTP.config.base));
			}

			if (_.isFunction(callback)) callback();
		}
	});
};

//////////
// Init //
//////////

if (exports.config.useOAuth == true) {
	HTTP.addFilter('oauth', OAuth.httpFilter);
}
<|endoftext|>


<commit_before>module.exports = SteamID;

var UInt64 = require('cuint').UINT64;

// Universe constants
SteamID.Universe = {
	"INVALID": 0,
	"PUBLIC": 1,
	"BETA": 2,
	"INTERNAL": 3,
	"DEV": 4
};

// Type constants
SteamID.Type = {
	"INVALID": 0,
	"INDIVIDUAL": 1,
	"MULTISEAT": 2,
	"GAMESERVER": 3,
	"ANON_GAMESERVER": 4,
	"PENDING": 5,
	"CONTENT_SERVER": 6,
	"CLAN": 7,
	"CHAT": 8,
	"P2P_SUPER_SEEDER": 9,
	"ANON_USER": 10
};

// Instance constants
SteamID.Instance = {
	"ALL": 0,
	"DESKTOP": 1,
	"CONSOLE": 2,
	"WEB": 4
};

// Type chars
SteamID.TypeChars = {};
SteamID.TypeChars[SteamID.Type.INVALID] = 'I';
SteamID.TypeChars[SteamID.Type.INDIVIDUAL] = 'U';
SteamID.TypeChars[SteamID.Type.MULTISEAT] = 'M';
SteamID.TypeChars[SteamID.Type.GAMESERVER] = 'G';
SteamID.TypeChars[SteamID.Type.ANON_GAMESERVER] = 'A';
SteamID.TypeChars[SteamID.Type.PENDING] = 'P';
SteamID.TypeChars[SteamID.Type.CONTENT_SERVER] = 'C';
SteamID.TypeChars[SteamID.Type.CLAN] = 'g';
SteamID.TypeChars[SteamID.Type.CHAT] = 'T';

SteamID.AccountIDMask = 0xFFFFFFFF;
SteamID.AccountInstanceMask = 0x000FFFFF;

SteamID.ChatInstanceFlags = {
	"Clan": (SteamID.AccountInstanceMask + 1) >> 1,
	"Lobby": (SteamID.AccountInstanceMask + 1) >> 2,
	"MMSLobby": (SteamID.AccountInstanceMask + 1) >> 3
};

function SteamID(input) {
	// Instance variables
	this.universe = SteamID.Universe.INVALID;
	this.type = SteamID.Type.INVALID;
	this.instance = SteamID.Instance.ALL;
	this.accountid = 0;

	if(!input) {
		// Use the default invalid values
		return;
	}

	var matches;
	if((matches = input.match(/^STEAM_([0-5]):([0-1]):([0-9]+)$/))) {
		// Steam2 ID
		this.universe = parseInt(matches[1], 10) || SteamID.Universe.PUBLIC; // If it's 0, turn it into 1 for public
		this.type = SteamID.Type.INDIVIDUAL;
		this.instance = SteamID.Instance.DESKTOP;
		this.accountid = (parseInt(matches[3], 10) * 2) + parseInt(matches[2], 10);
	} else if((matches = input.match(/^\[([a-zA-Z]):([0-5]):([0-9]+)(:[0-9]+)?\]$/))) {
		// Steam3 ID
		this.universe = parseInt(matches[2], 10);
		this.accountid = parseInt(matches[3], 10);

		var typeChar = matches[1];

		if(matches[4]) {
			this.instance = parseInt(matches[4].substring(1), 10);
		} else {
			switch(typeChar) {
				case 'g':
				case 'T':
				case 'c':
				case 'L':
					this.instance = SteamID.Instance.ALL;
					break;

				default:
					this.instance = SteamID.Instance.DESKTOP;
			}
		}

		if(typeChar == 'c') {
			this.instance |= SteamID.ChatInstanceFlags.Clan;
			this.type = SteamID.Type.CHAT;
		} else if(typeChar == 'L') {
			this.instance |= SteamID.ChatInstanceFlags.Lobby;
			this.type = SteamID.Type.CHAT;
		} else {
			this.type = getTypeFromChar(typeChar);
		}
	} else if(isNaN(input)) {
		throw new Error("Unknown input format");
	} else {
		var num = new UInt64(input, 10);
		this.accountid = num.toNumber() & 0xFFFFFFFF;
		this.instance = num.shiftRight(32).toNumber() & 0xFFFFF;
		this.type = num.shiftRight(20).toNumber() & 0xF;
		this.universe = num.shiftRight(4).toNumber();
	}
}

SteamID.prototype.isValid = function() {
	if(this.type <= SteamID.Type.INVALID || this.type > SteamID.Type.ANON_USER) {
		return false;
	}

	if(this.universe <= SteamID.Universe.INVALID || this.universe > SteamID.Universe.DEV) {
		return false;
	}

	if(this.type == SteamID.Type.INDIVIDUAL && (this.accountid === 0 || this.instance > SteamID.Instance.WEB)) {
		return false;
	}

	if(this.type == SteamID.Type.CLAN && (this.accountid === 0 || this.instance != SteamID.Instance.ALL)) {
		return false;
	}

	if(this.type == SteamID.Type.GAMESERVER && this.accountid === 0) {
		return false;
	}

	return true;
};

SteamID.prototype.getSteam2RenderedID = function(newerFormat) {
	if(this.type != SteamID.Type.INDIVIDUAL) {
		throw new Error("Can't get Steam2 rendered ID for non-individual ID");
	} else {
		var universe = this.universe;
		if(!newerFormat && universe === 1) {
			universe = 0;
		}

		return "STEAM_" + universe + ':' + (this.accountid & 1) + ':' + Math.floor(this.accountid / 2);
	}
};

SteamID.prototype.getSteam3RenderedID = function() {
	var typeChar = SteamID.TypeChars[this.type] || 'i';

	if(this.instance & SteamID.ChatInstanceFlags.Clan) {
		typeChar = 'c';
	} else if(this.instance & SteamID.ChatInstanceFlags.Lobby) {
		typeChar = 'L';
	}

	var renderInstance = (this.type == SteamID.Type.ANON_GAMESERVER || this.type == SteamID.Type.MULTISEAT || (this.type == SteamID.Type.INDIVIDUAL && this.instance != SteamID.Instance.DESKTOP));
	return '[' + typeChar + ':' + this.universe + ':' + this.accountid + (renderInstance ? ':' + this.instance : '') + ']';
};

SteamID.prototype.getSteamID64 = function() {
	return new UInt64(this.accountid, (this.universe << 24) | (this.type << 20) | (this.instance)).toString();
};

SteamID.prototype.toString = SteamID.prototype.getSteamID64;

// Private methods/functions
function getTypeFromChar(typeChar) {
	for(var type in SteamID.TypeChars) {
		if(SteamID.TypeChars[type] == typeChar) {
			return parseInt(type, 10);
		}
	}

	return SteamID.Type.INVALID;
}
<commit_msg>Only default individual accounts to desktop instance<commit_after>module.exports = SteamID;

var UInt64 = require('cuint').UINT64;

// Universe constants
SteamID.Universe = {
	"INVALID": 0,
	"PUBLIC": 1,
	"BETA": 2,
	"INTERNAL": 3,
	"DEV": 4
};

// Type constants
SteamID.Type = {
	"INVALID": 0,
	"INDIVIDUAL": 1,
	"MULTISEAT": 2,
	"GAMESERVER": 3,
	"ANON_GAMESERVER": 4,
	"PENDING": 5,
	"CONTENT_SERVER": 6,
	"CLAN": 7,
	"CHAT": 8,
	"P2P_SUPER_SEEDER": 9,
	"ANON_USER": 10
};

// Instance constants
SteamID.Instance = {
	"ALL": 0,
	"DESKTOP": 1,
	"CONSOLE": 2,
	"WEB": 4
};

// Type chars
SteamID.TypeChars = {};
SteamID.TypeChars[SteamID.Type.INVALID] = 'I';
SteamID.TypeChars[SteamID.Type.INDIVIDUAL] = 'U';
SteamID.TypeChars[SteamID.Type.MULTISEAT] = 'M';
SteamID.TypeChars[SteamID.Type.GAMESERVER] = 'G';
SteamID.TypeChars[SteamID.Type.ANON_GAMESERVER] = 'A';
SteamID.TypeChars[SteamID.Type.PENDING] = 'P';
SteamID.TypeChars[SteamID.Type.CONTENT_SERVER] = 'C';
SteamID.TypeChars[SteamID.Type.CLAN] = 'g';
SteamID.TypeChars[SteamID.Type.CHAT] = 'T';

SteamID.AccountIDMask = 0xFFFFFFFF;
SteamID.AccountInstanceMask = 0x000FFFFF;

SteamID.ChatInstanceFlags = {
	"Clan": (SteamID.AccountInstanceMask + 1) >> 1,
	"Lobby": (SteamID.AccountInstanceMask + 1) >> 2,
	"MMSLobby": (SteamID.AccountInstanceMask + 1) >> 3
};

function SteamID(input) {
	// Instance variables
	this.universe = SteamID.Universe.INVALID;
	this.type = SteamID.Type.INVALID;
	this.instance = SteamID.Instance.ALL;
	this.accountid = 0;

	if(!input) {
		// Use the default invalid values
		return;
	}

	var matches;
	if((matches = input.match(/^STEAM_([0-5]):([0-1]):([0-9]+)$/))) {
		// Steam2 ID
		this.universe = parseInt(matches[1], 10) || SteamID.Universe.PUBLIC; // If it's 0, turn it into 1 for public
		this.type = SteamID.Type.INDIVIDUAL;
		this.instance = SteamID.Instance.DESKTOP;
		this.accountid = (parseInt(matches[3], 10) * 2) + parseInt(matches[2], 10);
	} else if((matches = input.match(/^\[([a-zA-Z]):([0-5]):([0-9]+)(:[0-9]+)?\]$/))) {
		// Steam3 ID
		this.universe = parseInt(matches[2], 10);
		this.accountid = parseInt(matches[3], 10);

		var typeChar = matches[1];

		if(matches[4]) {
			this.instance = parseInt(matches[4].substring(1), 10);
		} else if(typeChar == 'U') {
			this.instance = SteamID.Instance.DESKTOP;
		}

		if(typeChar == 'c') {
			this.instance |= SteamID.ChatInstanceFlags.Clan;
			this.type = SteamID.Type.CHAT;
		} else if(typeChar == 'L') {
			this.instance |= SteamID.ChatInstanceFlags.Lobby;
			this.type = SteamID.Type.CHAT;
		} else {
			this.type = getTypeFromChar(typeChar);
		}
	} else if(isNaN(input)) {
		throw new Error("Unknown input format");
	} else {
		var num = new UInt64(input, 10);
		this.accountid = num.toNumber() & 0xFFFFFFFF;
		this.instance = num.shiftRight(32).toNumber() & 0xFFFFF;
		this.type = num.shiftRight(20).toNumber() & 0xF;
		this.universe = num.shiftRight(4).toNumber();
	}
}

SteamID.prototype.isValid = function() {
	if(this.type <= SteamID.Type.INVALID || this.type > SteamID.Type.ANON_USER) {
		return false;
	}

	if(this.universe <= SteamID.Universe.INVALID || this.universe > SteamID.Universe.DEV) {
		return false;
	}

	if(this.type == SteamID.Type.INDIVIDUAL && (this.accountid === 0 || this.instance > SteamID.Instance.WEB)) {
		return false;
	}

	if(this.type == SteamID.Type.CLAN && (this.accountid === 0 || this.instance != SteamID.Instance.ALL)) {
		return false;
	}

	if(this.type == SteamID.Type.GAMESERVER && this.accountid === 0) {
		return false;
	}

	return true;
};

SteamID.prototype.getSteam2RenderedID = function(newerFormat) {
	if(this.type != SteamID.Type.INDIVIDUAL) {
		throw new Error("Can't get Steam2 rendered ID for non-individual ID");
	} else {
		var universe = this.universe;
		if(!newerFormat && universe === 1) {
			universe = 0;
		}

		return "STEAM_" + universe + ':' + (this.accountid & 1) + ':' + Math.floor(this.accountid / 2);
	}
};

SteamID.prototype.getSteam3RenderedID = function() {
	var typeChar = SteamID.TypeChars[this.type] || 'i';

	if(this.instance & SteamID.ChatInstanceFlags.Clan) {
		typeChar = 'c';
	} else if(this.instance & SteamID.ChatInstanceFlags.Lobby) {
		typeChar = 'L';
	}

	var renderInstance = (this.type == SteamID.Type.ANON_GAMESERVER || this.type == SteamID.Type.MULTISEAT || (this.type == SteamID.Type.INDIVIDUAL && this.instance != SteamID.Instance.DESKTOP));
	return '[' + typeChar + ':' + this.universe + ':' + this.accountid + (renderInstance ? ':' + this.instance : '') + ']';
};

SteamID.prototype.getSteamID64 = function() {
	return new UInt64(this.accountid, (this.universe << 24) | (this.type << 20) | (this.instance)).toString();
};

SteamID.prototype.toString = SteamID.prototype.getSteamID64;

// Private methods/functions
function getTypeFromChar(typeChar) {
	for(var type in SteamID.TypeChars) {
		if(SteamID.TypeChars[type] == typeChar) {
			return parseInt(type, 10);
		}
	}

	return SteamID.Type.INVALID;
}
<|endoftext|>