<commit_before>Package.describe({
    summary: "Accounts Templates styled for Ratchet.",
    version: "1.6.1",
    name: "useraccounts:ratchet",
    git: "https://github.com/meteor-useraccounts/ratchet.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.6.1",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_reCaptcha.html",
        "lib/at_reCaptcha.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_ratchet.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:ratchet",
        "useraccounts:core@1.6.1",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<commit_msg>minor release - Bump to version 1.7.0<commit_after>Package.describe({
    summary: "Accounts Templates styled for Ratchet.",
    version: "1.7.0",
    name: "useraccounts:ratchet",
    git: "https://github.com/meteor-useraccounts/ratchet.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.7.0",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_reCaptcha.html",
        "lib/at_reCaptcha.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_ratchet.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:ratchet",
        "useraccounts:core@1.7.0",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'bobbigmac:nipple-nubbin',
  version: '1.0.0',
  // Brief, one-line summary of the package.
  summary: 'Wraps nipplejs: A virtual joystick for touch capable interfaces.',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/bobbigmac/nipple-nubbin',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  "nipplejs": "0.3.1"
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.1');

  api.addFiles('.npm/package/node_modules/nipplejs/dist/nipplejs.min.js', ['client']);
  api.addFiles('nipple-nubbin.js', ['client']);
  api.export("Nipple", ['client']);
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('bobbigmac:nipple-nubbin');
  api.addFiles('nipple-nubbin-tests.js', 'client');
});
<commit_msg>Match version # to npm<commit_after>Package.describe({
  name: 'bobbigmac:nipple-nubbin',
  version: '0.3.1',
  // Brief, one-line summary of the package.
  summary: 'Wraps nipplejs: A virtual joystick for touch capable interfaces.',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/bobbigmac/nipple-nubbin',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  "nipplejs": "0.3.1"
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.1');

  api.addFiles('.npm/package/node_modules/nipplejs/dist/nipplejs.min.js', ['client']);
  api.addFiles('nipple-nubbin.js', ['client']);
  api.export("Nipple", ['client']);
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('bobbigmac:nipple-nubbin');
  api.addFiles('nipple-nubbin-tests.js', 'client');
});
<|endoftext|>


<commit_before>Package.describe({
    summary: "Accounts Templates styled for Twitter Bootstrap.",
    version: "1.2.0",
    name: "useraccounts:bootstrap",
    git: "https://github.com/meteor-useraccounts/bootstrap.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.2.0",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_bootstrap.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:bootstrap",
        "useraccounts:core@1.2.0",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<commit_msg>patch release - Bump to version 1.2.1<commit_after>Package.describe({
    summary: "Accounts Templates styled for Twitter Bootstrap.",
    version: "1.2.1",
    name: "useraccounts:bootstrap",
    git: "https://github.com/meteor-useraccounts/bootstrap.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.2.1",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_bootstrap.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:bootstrap",
        "useraccounts:core@1.2.1",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<|endoftext|>


<commit_before>var fs = Npm.require('fs');
var path = Npm.require('path');

Package.describe({
  "summary": "Render you app even before the DDP connection comes live. - magic?",
  "version": "2.3.1",
  "git": "https://github.com/meteorhacks/fast-render",
  "name": "meteorhacks:fast-render"
});

Npm.depends({
  "connect": "2.13.0"
});

Package.onUse(function(api) {
  configure(api);
  api.export('FastRender', ['client', 'server']);
  api.export('__init_fast_render', ['client']);
});

Package.onTest(function(api) {
  configure(api);
  api.use('tinytest', ['client', 'server']);
  api.use('http', 'server');

  api.addFiles([
    'tests/utils.js'
  ], ['client', 'server']);

  api.addFiles([
    'tests/client/fast_render.js',
    'tests/client/ddp_update.js'
  ], 'client');

  api.addFiles([
    'tests/server/context.js',
    'tests/server/integration.js'
  ], 'server');
});

function configure (api) {
  api.versionsFrom('METEOR@0.9.3');
  api.use('meteorhacks:inject-data@1.2.3', ['client', 'server']);
  api.use('iron:router@0.9.0 || 1.0.0', ['client', 'server'], {weak: true});
  api.use('chuangbo:cookie@1.1.0', 'client');
  api.use('meteorhacks:picker@1.0.1', 'server');

  api.use(['minimongo', 'livedata', 'ejson', 'underscore', 'webapp', 'routepolicy', 'accounts-base'], ['server']);
  api.use(['minimongo', 'underscore', 'deps', 'ejson', 'accounts-base'], ['client']);

  api.addFiles([
    'lib/utils.js'
  ], ['client', 'server']);

  api.addFiles([
    'lib/server/namespace.js',
    'lib/server/utils.js',
    'lib/server/routes.js',
    'lib/server/publish_context.js',
    'lib/server/context.js',
    'lib/server/iron_router_support.js',
  ], 'server');

  api.addFiles([
    'lib/client/fast_render.js',
    'lib/client/debugger.js',
    'lib/client/ddp_update.js',
    'lib/client/auth.js',
    'lib/client/boot.js'
  ], 'client');

}
<commit_msg>Bump version<commit_after>var fs = Npm.require('fs');
var path = Npm.require('path');

Package.describe({
  "summary": "Render you app even before the DDP connection comes live. - magic?",
  "version": "2.3.2",
  "git": "https://github.com/meteorhacks/fast-render",
  "name": "meteorhacks:fast-render"
});

Npm.depends({
  "connect": "2.13.0"
});

Package.onUse(function(api) {
  configure(api);
  api.export('FastRender', ['client', 'server']);
  api.export('__init_fast_render', ['client']);
});

Package.onTest(function(api) {
  configure(api);
  api.use('tinytest', ['client', 'server']);
  api.use('http', 'server');

  api.addFiles([
    'tests/utils.js'
  ], ['client', 'server']);

  api.addFiles([
    'tests/client/fast_render.js',
    'tests/client/ddp_update.js'
  ], 'client');

  api.addFiles([
    'tests/server/context.js',
    'tests/server/integration.js'
  ], 'server');
});

function configure (api) {
  api.versionsFrom('METEOR@0.9.3');
  api.use('meteorhacks:inject-data@1.2.3', ['client', 'server']);
  api.use('iron:router@0.9.0 || 1.0.0', ['client', 'server'], {weak: true});
  api.use('chuangbo:cookie@1.1.0', 'client');
  api.use('meteorhacks:picker@1.0.1', 'server');

  api.use(['minimongo', 'livedata', 'ejson', 'underscore', 'webapp', 'routepolicy', 'accounts-base'], ['server']);
  api.use(['minimongo', 'underscore', 'deps', 'ejson', 'accounts-base'], ['client']);

  api.addFiles([
    'lib/utils.js'
  ], ['client', 'server']);

  api.addFiles([
    'lib/server/namespace.js',
    'lib/server/utils.js',
    'lib/server/routes.js',
    'lib/server/publish_context.js',
    'lib/server/context.js',
    'lib/server/iron_router_support.js',
  ], 'server');

  api.addFiles([
    'lib/client/fast_render.js',
    'lib/client/debugger.js',
    'lib/client/ddp_update.js',
    'lib/client/auth.js',
    'lib/client/boot.js'
  ], 'client');

}
<|endoftext|>


<commit_before>Package.describe({
    name: 'risul:chance',
    summary: 'Meteor package for Chance - Random generator helper for JavaScript: http://chancejs.com',
    version: '1.0.6',
    git: 'https://github.com/risul/meteor-chance'
});

Npm.depends({
    chance: '0.7.5'
});

Package.onUse(function(api) {
    api.versionsFrom('METEOR@1.0');
    api.export('Chance');
    api.addFiles('.npm/package/node_modules/chance/chance.js', ['client']);
    api.addFiles('lib/chance.js', 'server');
});<commit_msg>Updated to latest chance.js<commit_after>Package.describe({
    name: 'risul:chance',
    summary: 'Meteor package for Chance - Random generator helper for JavaScript: http://chancejs.com',
    version: '1.0.7',
    git: 'https://github.com/risul/meteor-chance'
});

Npm.depends({
    chance: '0.7.6'
});

Package.onUse(function(api) {
    api.versionsFrom('METEOR@1.0');
    api.export('Chance');
    api.addFiles('.npm/package/node_modules/chance/chance.js', ['client']);
    api.addFiles('lib/chance.js', 'server');
});<|endoftext|>


<commit_before>// memcached.js
//
// implementation of Databank interface using memcached
//
// Copyright 2011,2012 StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('databank'),
    Step = require('step'),
    memcached = require('memcached'),
    crypto = require('crypto');

var Databank = databank.Databank;
var DatabankError = databank.DatabankError;
var AlreadyExistsError = databank.AlreadyExistsError;
var NoSuchThingError = databank.NoSuchThingError;
var NotConnectedError = databank.NotConnectedError;
var AlreadyConnectedError = databank.AlreadyConnectedError;

function MemcachedDatabank(params) {
    this.serverLocations = params.serverLocations || '127.0.0.1:11211';
    this.options = params.options || {};
    this.schema = params.schema || {};
    this.expire = params.expire || 2592000;
    this.client = null;
}

MemcachedDatabank.prototype = new Databank();

MemcachedDatabank.prototype.toKey = function(type, id) {
    var idstr = ""+id;
    if (this.isLegalForKeys(idstr) && (type.length + idstr.length + 1) <= 250) {
        return type + ':' + idstr;
    } else {
        return type + ':hash:' + this.hash(idstr);
    }
};

MemcachedDatabank.prototype.isLegalForKeys = function(idstr) {
    return !/[^!-~]/.test(idstr);
};

MemcachedDatabank.prototype.hash = function(idstr) {

    var hash = crypto.createHash('md5'),
        str, data;

    data = idstr;

    hash.update(data);
    str = hash.digest('base64');

    // Make it a little more FS-safe

    str = str.replace(/\+/g, '-');
    str = str.replace(/\//g, '_');
    str = str.replace(/=/g, '');

    return str;
};

MemcachedDatabank.prototype.connect = function(params, callback) {

    if (this.client) {
        callback(new AlreadyConnectedError());
        return;
    }

    this.client = new memcached(this.serverLocations, this.options);
    callback(null);
};

MemcachedDatabank.prototype.disconnect = function(callback) {

    if (!this.client) {
        callback(new NotConnectedError());
        return;
    }

    this.client = null;
    callback(null);
};

MemcachedDatabank.prototype.create = function(type, id, value, callback) {

    var bank = this,
        key = this.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.client.add(key, JSON.stringify(value), bank.expire, this);
        },
        function(err, result) {
            if (err) throw err;
            if (!result) throw new AlreadyExistsError(type, id); // Key miss
            bank.index(type, id, value, this);
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, value);
            }
        }
    );
};

MemcachedDatabank.prototype.read = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    bank.client.get(key, function(err, value) {
        if (err) {
            callback(err, null);
        } else if (value === false) {
            callback(new NoSuchThingError(type, id), null);
        } else {
            callback(null, JSON.parse(value));
        }
    });
};

MemcachedDatabank.prototype.update = function(type, id, value, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.deindex(type, id, this);
        },
        function(err) {
            if (err) throw err;
            bank.client.replace(key, JSON.stringify(value), bank.expire, this);
        },
        function(err, result) {
            if (err) throw err;
            if (!result) throw new NoSuchThingError(type, id);
            bank.index(type, id, value, this);
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, value);
            }
        }
    );
};

MemcachedDatabank.prototype.del = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.deindex(type, id, this);
        },
        function(err) {
            if (err) throw err;
            bank.client.del(key, this);
        },
        function(err, value) {
            if (err) {
                callback(err);
            } else if (!value) { // key miss
                callback(new NoSuchThingError(type, id), null);
            } else {
                callback(null);
            }
        }
    );
};

MemcachedDatabank.prototype.save = function(type, id, value, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.deindex(type, id, this);
        },
        function(err) {
            if (err) throw err;
            bank.client.set(key, JSON.stringify(value), bank.expire, this);
        },
        function(err, result) {
            if (err) throw err;
            if (!result) throw new NoSuchThingError(type, id);
            bank.index(type, id, value, this);
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, value);
            }
        }
    );
};

MemcachedDatabank.prototype.readAll = function(type, ids, callback) {

    var bank = this,
        keys = [],
        keyToId = {},
        key,
        i;

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    for (i = 0; i < ids.length; i++) {
        key = bank.toKey(type, ids[i]);
        keys.push(key);
        keyToId[key] = ids[i];
    }

    bank.client.getMulti(keys, function(err, results) {
        var key, idMap = {}, i, id;
        if (err) {
            callback(err, null);
        } else {
            for (i = 0; i < keys.length; i++) {
                key = keys[i];
                id = keyToId[key];
                if (results.hasOwnProperty(key)) {
                    idMap[id] = JSON.parse(results[key]);
                } else {
                    idMap[id] = null;
                }
            }
            callback(null, idMap);
        }
    });
};

// FIXME: update indices...?

MemcachedDatabank.prototype.incr = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    bank.client.incr(key, 1, function(err, result) {
        if (err) {
            callback(err, null);
        } else {
            callback(null, result);
        }
    });
};

// FIXME: update indices...?

MemcachedDatabank.prototype.decr = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    bank.client.decr(key, 1, function(err, result) {
        if (err) {
            callback(err, null);
        } else {
            callback(null, result);
        }
    });
};

MemcachedDatabank.prototype.index = function(type, id, value, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    // FIXME: this seems like a terrible way to scan a type;
    // I could use some other ideas

    Step(
        function() {
            // XXX: make sure we don't recurse here
            bank.append('databank-type-keys', type, key, this);
        },
        function(err, allKeys) {
            var i = 0, group = this.group(), indices, k;
            if (err) throw err;
            if (bank.hasOwnProperty('schema') &&
                bank.schema.hasOwnProperty(type) &&
                bank.schema[type].hasOwnProperty('indices')) {
                indices = bank.schema[type].indices;
                for (i = 0; i < indices.length; i++) {
                    k = Databank.deepProperty(value, indices[i]);
                    bank.append('databank-type-index', type + ':' + k, key, group());
                }
            }
        },
        function(err, resultses) {
            if (err) {
                callback(err);
            } else {
                callback(null);
            }
        }
    );
};

MemcachedDatabank.prototype.deindex = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id),
        value;

    // FIXME: this seems like a terrible way to scan a type;
    // I could use some other ideas

    Step(
        function() {
            bank.read(type, id, this);
        },
        function(err, results) {
            if (err) throw err;
            value = results;
            // XXX: make sure we don't recurse here
            bank.remove('databank-type-keys', type, key, this);
        },
        function(err, allKeys) {
            var i = 0, group = this.group(), indices, k;
            if (err) throw err;
            if (bank.hasOwnProperty('schema') &&
                bank.schema.hasOwnProperty(type) &&
                bank.schema[type].hasOwnProperty('indices')) {
                indices = bank.schema[type].indices;
                for (i = 0; i < indices.length; i++) {
                    k = Databank.deepProperty(value, indices[i]);
                    bank.remove('databank-type-index', type + ':' + k, key, group());
                }
            }
        },
        function(err, resultses) {
            if (err) {
                callback(err);
            } else {
                callback(null);
            }
        }
    );
};

module.exports = MemcachedDatabank;
<commit_msg>Revert "Check for false return"<commit_after>// memcached.js
//
// implementation of Databank interface using memcached
//
// Copyright 2011,2012 StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('databank'),
    Step = require('step'),
    memcached = require('memcached'),
    crypto = require('crypto');

var Databank = databank.Databank;
var DatabankError = databank.DatabankError;
var AlreadyExistsError = databank.AlreadyExistsError;
var NoSuchThingError = databank.NoSuchThingError;
var NotConnectedError = databank.NotConnectedError;
var AlreadyConnectedError = databank.AlreadyConnectedError;

function MemcachedDatabank(params) {
    this.serverLocations = params.serverLocations || '127.0.0.1:11211';
    this.options = params.options || {};
    this.schema = params.schema || {};
    this.expire = params.expire || 2592000;
    this.client = null;
}

MemcachedDatabank.prototype = new Databank();

MemcachedDatabank.prototype.toKey = function(type, id) {
    var idstr = ""+id;
    if (this.isLegalForKeys(idstr) && (type.length + idstr.length + 1) <= 250) {
        return type + ':' + idstr;
    } else {
        return type + ':hash:' + this.hash(idstr);
    }
};

MemcachedDatabank.prototype.isLegalForKeys = function(idstr) {
    return !/[^!-~]/.test(idstr);
};

MemcachedDatabank.prototype.hash = function(idstr) {

    var hash = crypto.createHash('md5'),
        str, data;

    data = idstr;

    hash.update(data);
    str = hash.digest('base64');

    // Make it a little more FS-safe

    str = str.replace(/\+/g, '-');
    str = str.replace(/\//g, '_');
    str = str.replace(/=/g, '');

    return str;
};

MemcachedDatabank.prototype.connect = function(params, callback) {

    if (this.client) {
        callback(new AlreadyConnectedError());
        return;
    }

    this.client = new memcached(this.serverLocations, this.options);
    callback(null);
};

MemcachedDatabank.prototype.disconnect = function(callback) {

    if (!this.client) {
        callback(new NotConnectedError());
        return;
    }

    this.client = null;
    callback(null);
};

MemcachedDatabank.prototype.create = function(type, id, value, callback) {

    var bank = this,
        key = this.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.client.add(key, JSON.stringify(value), bank.expire, this);
        },
        function(err, result) {
            if (err) throw err;
            if (!result) throw new AlreadyExistsError(type, id); // Key miss
            bank.index(type, id, value, this);
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, value);
            }
        }
    );
};

MemcachedDatabank.prototype.read = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    bank.client.get(key, function(err, value) {
        if (err) {
            // FIXME: find key-misses and return no-such-thing error
            callback(err, null);
        } else {
            callback(null, JSON.parse(value));
        }
    });
};

MemcachedDatabank.prototype.update = function(type, id, value, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.deindex(type, id, this);
        },
        function(err) {
            if (err) throw err;
            bank.client.replace(key, JSON.stringify(value), bank.expire, this);
        },
        function(err, result) {
            if (err) throw err;
            if (!result) throw new NoSuchThingError(type, id);
            bank.index(type, id, value, this);
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, value);
            }
        }
    );
};

MemcachedDatabank.prototype.del = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.deindex(type, id, this);
        },
        function(err) {
            if (err) throw err;
            bank.client.del(key, this);
        },
        function(err, value) {
            if (err) {
                callback(err);
            } else if (!value) { // key miss
                callback(new NoSuchThingError(type, id), null);
            } else {
                callback(null);
            }
        }
    );
};

MemcachedDatabank.prototype.save = function(type, id, value, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    Step(
        function() {
            bank.deindex(type, id, this);
        },
        function(err) {
            if (err) throw err;
            bank.client.set(key, JSON.stringify(value), bank.expire, this);
        },
        function(err, result) {
            if (err) throw err;
            if (!result) throw new NoSuchThingError(type, id);
            bank.index(type, id, value, this);
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, value);
            }
        }
    );
};

MemcachedDatabank.prototype.readAll = function(type, ids, callback) {

    var bank = this,
        keys = [],
        keyToId = {},
        key,
        i;

    if (!bank.client) {
        callback(new NotConnectedError());
        return;
    }

    for (i = 0; i < ids.length; i++) {
        key = bank.toKey(type, ids[i]);
        keys.push(key);
        keyToId[key] = ids[i];
    }

    bank.client.getMulti(keys, function(err, results) {
        var key, idMap = {}, i, id;
        if (err) {
            callback(err, null);
        } else {
            for (i = 0; i < keys.length; i++) {
                key = keys[i];
                id = keyToId[key];
                if (results.hasOwnProperty(key)) {
                    idMap[id] = JSON.parse(results[key]);
                } else {
                    idMap[id] = null;
                }
            }
            callback(null, idMap);
        }
    });
};

// FIXME: update indices...?

MemcachedDatabank.prototype.incr = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    bank.client.incr(key, 1, function(err, result) {
        if (err) {
            callback(err, null);
        } else {
            callback(null, result);
        }
    });
};

// FIXME: update indices...?

MemcachedDatabank.prototype.decr = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    bank.client.decr(key, 1, function(err, result) {
        if (err) {
            callback(err, null);
        } else {
            callback(null, result);
        }
    });
};

MemcachedDatabank.prototype.index = function(type, id, value, callback) {

    var bank = this,
        key = bank.toKey(type, id);

    // FIXME: this seems like a terrible way to scan a type;
    // I could use some other ideas

    Step(
        function() {
            // XXX: make sure we don't recurse here
            bank.append('databank-type-keys', type, key, this);
        },
        function(err, allKeys) {
            var i = 0, group = this.group(), indices, k;
            if (err) throw err;
            if (bank.hasOwnProperty('schema') &&
                bank.schema.hasOwnProperty(type) &&
                bank.schema[type].hasOwnProperty('indices')) {
                indices = bank.schema[type].indices;
                for (i = 0; i < indices.length; i++) {
                    k = Databank.deepProperty(value, indices[i]);
                    bank.append('databank-type-index', type + ':' + k, key, group());
                }
            }
        },
        function(err, resultses) {
            if (err) {
                callback(err);
            } else {
                callback(null);
            }
        }
    );
};

MemcachedDatabank.prototype.deindex = function(type, id, callback) {

    var bank = this,
        key = bank.toKey(type, id),
        value;

    // FIXME: this seems like a terrible way to scan a type;
    // I could use some other ideas

    Step(
        function() {
            bank.read(type, id, this);
        },
        function(err, results) {
            if (err) throw err;
            value = results;
            // XXX: make sure we don't recurse here
            bank.remove('databank-type-keys', type, key, this);
        },
        function(err, allKeys) {
            var i = 0, group = this.group(), indices, k;
            if (err) throw err;
            if (bank.hasOwnProperty('schema') &&
                bank.schema.hasOwnProperty(type) &&
                bank.schema[type].hasOwnProperty('indices')) {
                indices = bank.schema[type].indices;
                for (i = 0; i < indices.length; i++) {
                    k = Databank.deepProperty(value, indices[i]);
                    bank.remove('databank-type-index', type + ':' + k, key, group());
                }
            }
        },
        function(err, resultses) {
            if (err) {
                callback(err);
            } else {
                callback(null);
            }
        }
    );
};

module.exports = MemcachedDatabank;
<|endoftext|>


<commit_before>(function($) {
	$(document).ready(function() {

		/** -----------------------------------------------
		 * TABLE OF CONTENTS
		 *
		 * Transform a #table-of-contents div to a nested list
		 */
		if($("#table-of-contents").length > 0) {
			var toc = '

In this document:
';

			// Remove existing anchor redirection in the url
			var pageURL = window.location.href.replace(/#[a-zA-Z0-9\-\_]*/g, '');

			$('#left-column h1[id], #left-column h2[id], #left-column h3[id], #left-column h4[id]').each(function(i) {
				var current = $(this);
				toc += '
' + current.html() + '
';
			});

			toc += '

';

			$('#table-of-contents').prepend(toc);
		}

		/** ---------------------------------------------
		 * HEADING ANCHOR LINKS
		 *
		 * Automatically adds anchor links to headings that have IDs
		 */
		var url = window.location.href;

		$("#left-column h1[id], #left-column h2[id], #left-column h3[id], #left-column h4[id], #left-column h5[id], #left-column h6[id]").each(function() {
			var link = '¶';
			$(this).append(' ' + link);
		});

		$("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]").mouseenter(function() {
			$(this).addClass('hover');
		});

		$("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]").mouseleave(function() {
			$(this).removeClass('hover');
		});

		/** ---------------------------------------------
		 * LANGAUGE SELECTER
		 *
		 * Hide the change button and do it onclick
		 */
		$("#Form_LanguageForm .Actions").hide();

		$("#Form_LanguageForm select").change(function() {
			$("#Form_LanguageForm").submit();
		});
	});
})(jQuery);
<commit_msg>MINOR Removing SyntaxHighlighter toolbar, it destroys the layout whitespace a bit<commit_after>(function($) {
	$(document).ready(function() {

		/** -----------------------------------------------
		 * TABLE OF CONTENTS
		 *
		 * Transform a #table-of-contents div to a nested list
		 */
		if($("#table-of-contents").length > 0) {
			var toc = '

In this document:
';

			// Remove existing anchor redirection in the url
			var pageURL = window.location.href.replace(/#[a-zA-Z0-9\-\_]*/g, '');

			$('#left-column h1[id], #left-column h2[id], #left-column h3[id], #left-column h4[id]').each(function(i) {
				var current = $(this);
				toc += '
' + current.html() + '
';
			});

			toc += '

';

			$('#table-of-contents').prepend(toc);
		}

		/** ---------------------------------------------
		 * HEADING ANCHOR LINKS
		 *
		 * Automatically adds anchor links to headings that have IDs
		 */
		var url = window.location.href;

		$("#left-column h1[id], #left-column h2[id], #left-column h3[id], #left-column h4[id], #left-column h5[id], #left-column h6[id]").each(function() {
			var link = '¶';
			$(this).append(' ' + link);
		});

		$("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]").mouseenter(function() {
			$(this).addClass('hover');
		});

		$("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]").mouseleave(function() {
			$(this).removeClass('hover');
		});

		/** ---------------------------------------------
		 * LANGAUGE SELECTER
		 *
		 * Hide the change button and do it onclick
		 */
		$("#Form_LanguageForm .Actions").hide();

		$("#Form_LanguageForm select").change(function() {
			$("#Form_LanguageForm").submit();
		});
	});

	// Syntaxhighlighter defaults
	SyntaxHighlighter.defaults.toolbar = false;
})(jQuery);
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Karl STEIN
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

Package.describe({
  name: 'jalik:ufs',
  version: '1.0.1',
  author: 'karl.stein.pro@gmail.com',
  summary: 'Base package for UploadFS',
  homepage: 'https://github.com/jalik/jalik-ufs',
  git: 'https://github.com/jalik/jalik-ufs.git',
  documentation: 'README.md',
});

Package.onUse(function (api) {
  api.versionsFrom('1.9');
  api.use('check');
  api.use('ecmascript');
  api.use('underscore');
  api.use('matb33:collection-hooks@1.0.1');
  api.use('mongo');
  api.use('webapp', 'server');
  api.mainModule('ufs.js');
});

Npm.depends({
  mkdirp: '0.3.5',
  'spark-md5': '3.0.0',
});
<commit_msg>1.0.2<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Karl STEIN
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

Package.describe({
  name: 'jalik:ufs',
  version: '1.0.2',
  author: 'karl.stein.pro@gmail.com',
  summary: 'Base package for UploadFS',
  homepage: 'https://github.com/jalik/jalik-ufs',
  git: 'https://github.com/jalik/jalik-ufs.git',
  documentation: 'README.md',
});

Package.onUse(function (api) {
  api.versionsFrom('1.9');
  api.use('check');
  api.use('ecmascript');
  api.use('underscore');
  api.use('matb33:collection-hooks@1.0.1');
  api.use('mongo');
  api.use('webapp', 'server');
  api.mainModule('ufs.js');
});

Npm.depends({
  mkdirp: '0.3.5',
  'spark-md5': '3.0.0',
});
<|endoftext|>


<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 Kevin Conway

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*jslint node: true, indent: 2, passfail: true */

(function (context, generator) {
  "use strict";

  generator.call(
    context,
    'deferredjs',
    ['modelo', 'deferjs'],
    function (Modelo, defer) {

      var Deferred,
        DeferredObject,
        PromiseObject,
        CollectionModule;

      PromiseObject = Modelo.define(function (options) {

        this.callback = function (fn) {
          options.deferred.callback(fn);
          return this;
        };
        this.done = this.callback;
        this.succeess = this.callback;

        this.errback = function (fn) {
          options.deferred.errback(fn);
          return this;
        };
        this.failure = this.errback;
        this.error = this.errback;

      });

      DeferredObject = Modelo.define(function () {

        this.callbacks = [];
        this.errbacks = [];
        this.resolved = false;
        this.failed = false;

      });

      // This method, and its aliases `success` and `done`, can be used
      // to register a callbcak function with the deferred. All callbacks
      // registered using this method, or its aliases, are passed in a
      // single value as input. This input parameter is the resolved
      // value for the deferred.
      DeferredObject.prototype.callback = function (fn) {

        if (this.failed === true) {

          return this;

        }

        if (this.resolved === true) {

          defer(defer.bind(fn, null, this.value));
          return this;

        }

        if (typeof fn === "function") {

          this.callbacks.push(fn);
          return this;

        }

        throw new TypeError("Callback must be a function.");

      };
      DeferredObject.prototype.succeess = DeferredObject.prototype.callback;
      DeferredObject.prototype.done = DeferredObject.prototype.callback;

      // This method, and its aliases `failure` and `error`, can be used
      // to register errbacks with the deferred that are executed when
      // an error is thrown. Callbacks registered using this method, and
      // its aliases, are passed a single input parameter that contains
      // the error that was thrown.
      DeferredObject.prototype.errback = function (fn) {

        if (this.resolved === true) {

          return this;

        }

        if (this.failed === true) {

          defer(defer.bind(fn, null, this.value));
          return this;

        }

        if (typeof fn === "function") {

          this.errbacks.push(fn);
          return this;

        }

        throw new TypeError("Errback must be a function.");

      };
      DeferredObject.prototype.failure = DeferredObject.prototype.errback;
      DeferredObject.prototype.error = DeferredObject.prototype.errback;

      // This method is used to mark the deferred as resolved and
      // to execute all the success callbacks registered. The value
      // passed to this method is the value that will be passed to
      // all callbacks.
      //
      // This method only triggers the callbacks once after which
      // neither it nor the `fail` method have any effect.
      DeferredObject.prototype.resolve = function (value) {

        var x;

        if (this.resolved === true || this.failed === true) {

          return this;

        }

        this.resolved = true;
        this.value = value;

        this.callbacks.reverse();
        for (x = this.callbacks.length - 1; x >= 0; x = x - 1) {

          defer(defer.bind(this.callbacks[x], null, value));

        }

        return this;

      };
      DeferredObject.prototype.ready = DeferredObject.prototype.resolve;

      // This method is used to mark the deferred as failed and
      // to execute all the failure errbacks registered. The error value
      // passed to this method is the value that will be passed to
      // all errbacks.
      //
      // This method only triggers the errbacks once after which
      // neither it nor the `resolve` method have any effect.
      DeferredObject.prototype.fail = function (value) {

        var x;

        if (this.failed === true || this.resolved === true) {

          return this;

        }

        this.failed = true;
        this.value = value;

        this.errbacks.reverse();
        for (x = this.errbacks.length - 1; x >= 0; x = x - 1) {

          defer(defer.bind(this.errbacks[x], null, value));

        }

        return this;

      };
      DeferredObject.prototype.reject = DeferredObject.prototype.fail;

      // Deferreds should never be returned directly to avoid the potential
      // of runtime manipulation. Instead, return the value of this method
      // any time that you would normally want to return the deferred.
      DeferredObject.prototype.promise = function () {

        return new PromiseObject({"deferred": this});

      };

      CollectionModule = (function () {

        var AnyCollection,
          AllCollection;

        AnyCollection = function AnyCollection() {

          var args = Array.prototype.slice.call(arguments),
            d = new DeferredObject(),
            x;

          for (x = args.length - 1; x >= 0; x = x - 1) {

            args[x].errback(defer.bind(d.fail, d));
            args[x].callback(defer.bind(d.resolve, d));

          }

          return d.promise();

        };

        AllCollection = function AllCollection() {

          var args = Array.prototype.slice.call(arguments),
            d = new DeferredObject(),
            values = [],
            x;

          function resolve(value) {

            values.push(value);

            if (values.length === args.length) {

              d.resolve(values);

            }

          }

          for (x = args.length - 1; x >= 0; x = x - 1) {

            args[x].errback(defer.bind(d.fail, d));
            args[x].callback(resolve);

          }

          return d.promise();

        };

        return {
          "All": AllCollection,
          "Any": AnyCollection
        };

      }());

      // Similar to other modules in this package, the interface returned
      // by this module is a set of wrappers around the actual objects.
      //
      // In this case deferred objects can be created in any of the following
      // ways::
      //
      //      new Deferred();
      //      Deferred();
      //      new Deferred.Deferred();
      //      Deferred.Deferred();
      //
      // The choice comes down to style and preference.
      Deferred = function () {
        return new DeferredObject();
      };
      Deferred.Deferred = Deferred;

      // Deferred.Promise exposes a secondary interface for creating promises.
      // Using the `promise` method of a deferred and creating a new promise
      // object while passing in your deferred have the same effect.
      Deferred.Promise = function (d) {
        return new PromiseObject({"deferred": d});
      };

      Deferred.Collection = CollectionModule;

      return Deferred;

    }
  );

}(this, (function (context) {
  "use strict";

  // Ignoring the unused "name" in the Node.js definition function.
  /*jslint unparam: true */
  if (typeof require === "function" &&
        module !== undefined &&
        !!module.exports) {

    // If this module is loaded in Node, require each of the
    // dependencies and pass them along.
    return function (name, deps, mod) {

      var x,
        dep_list = [];

      for (x = 0; x < deps.length; x = x + 1) {

        dep_list.push(require(deps[x]));

      }

      module.exports = mod.apply(context, dep_list);

    };

  }
  /*jslint unparam: false */

  if (context.window !== undefined) {

    // If this module is being used in a browser environment first
    // generate a list of dependencies, run the provided definition
    // function with the list of dependencies, and insert the returned
    // object into the global namespace using the provided module name.
    return function (name, deps, mod) {

      var namespaces = name.split('/'),
        root = context,
        dep_list = [],
        current_scope,
        current_dep,
        i,
        x;

      for (i = 0; i < deps.length; i = i + 1) {

        current_scope = root;
        current_dep = deps[i].split('/');

        for (x = 0; x < current_dep.length; x = x + 1) {

          current_scope = current_scope[current_dep[x]] =
                          current_scope[current_dep[x]] || {};

        }

        dep_list.push(current_scope);

      }

      current_scope = root;
      for (i = 1; i < namespaces.length; i = i + 1) {

        current_scope = current_scope[namespaces[i - 1]] =
                        current_scope[namespaces[i - 1]] || {};

      }

      current_scope[namespaces[i - 1]] = mod.apply(context, dep_list);

    };

  }

  throw new Error("Unrecognized environment.");

}(this))));
<commit_msg>Add: A+ compliant then method<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 Kevin Conway

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*jslint node: true, indent: 2, passfail: true */

(function (context, generator) {
  "use strict";

  generator.call(
    context,
    'deferredjs',
    ['modelo', 'deferjs'],
    function (Modelo, defer) {

      var Deferred,
        DeferredObject,
        PromiseObject,
        CollectionModule;

      function executeAndReturnPromise(fn) {

        var fnPromise,
          args = Array.prototype.slice.call(arguments, 1),
          d = new DeferredObject();

        try {

          fnPromise = fn.apply(null, args);
          if (!!fnPromise && !!fnPromise.then &&
              typeof fnPromise.then === 'function') {

            return fnPromise;

          }

          d.resolve(fnPromise);

        } catch (e) {

          d.fail(e);

        }

        return d.promise();

      }

      function convert(fn) {

        return defer.bind(executeAndReturnPromise, null, fn);

      }

      function proxy(deferred, fn) {

        var args = Array.prototype.slice.call(arguments, 2),
          p = convert(fn).apply(null, args);

        p.callback(defer.bind(deferred.resolve, deferred));
        p.errback(defer.bind(deferred.fail, deferred));

      }

      PromiseObject = Modelo.define(function (options) {

        this.callback = function (fn) {
          options.deferred.callback(fn);
          return this;
        };
        this.done = this.callback;
        this.succeess = this.callback;

        this.errback = function (fn) {
          options.deferred.errback(fn);
          return this;
        };
        this.failure = this.errback;
        this.error = this.errback;

        this.then = function then(cback, eback) {
          return options.deferred.then(cback, eback);
        };

      });

      DeferredObject = Modelo.define(function () {

        this.callbacks = [];
        this.errbacks = [];
        this.resolved = false;
        this.failed = false;

      });

      // This method, and its aliases `success` and `done`, can be used
      // to register a callbcak function with the deferred. All callbacks
      // registered using this method, or its aliases, are passed in a
      // single value as input. This input parameter is the resolved
      // value for the deferred.
      DeferredObject.prototype.callback = function (fn) {

        if (this.failed === true) {

          return this;

        }

        if (this.resolved === true) {

          defer(defer.bind(fn, null, this.value));
          return this;

        }

        if (typeof fn === "function") {

          this.callbacks.push(fn);
          return this;

        }

        throw new TypeError("Callback must be a function.");

      };
      DeferredObject.prototype.succeess = DeferredObject.prototype.callback;
      DeferredObject.prototype.done = DeferredObject.prototype.callback;

      // This method, and its aliases `failure` and `error`, can be used
      // to register errbacks with the deferred that are executed when
      // an error is thrown. Callbacks registered using this method, and
      // its aliases, are passed a single input parameter that contains
      // the error that was thrown.
      DeferredObject.prototype.errback = function (fn) {

        if (this.resolved === true) {

          return this;

        }

        if (this.failed === true) {

          defer(defer.bind(fn, null, this.value));
          return this;

        }

        if (typeof fn === "function") {

          this.errbacks.push(fn);
          return this;

        }

        throw new TypeError("Errback must be a function.");

      };
      DeferredObject.prototype.failure = DeferredObject.prototype.errback;
      DeferredObject.prototype.error = DeferredObject.prototype.errback;

      DeferredObject.prototype.then = function then(callback, errback) {

        var d = new DeferredObject();

        if (typeof callback !== 'function') {

          callback = defer.bind(d.resolve, d);

        } else {

          callback = defer.bind(proxy, null, d, callback);

        }

        if (typeof errback !== 'function') {

          errback = defer.bind(d.fail, d);

        } else {

          errback = defer.bind(proxy, null, d, errback);

        }

        this.callback(callback);
        this.errback(errback);

        return d.promise();

      };

      // This method is used to mark the deferred as resolved and
      // to execute all the success callbacks registered. The value
      // passed to this method is the value that will be passed to
      // all callbacks.
      //
      // This method only triggers the callbacks once after which
      // neither it nor the `fail` method have any effect.
      DeferredObject.prototype.resolve = function (value) {

        var x;

        if (this.resolved === true || this.failed === true) {

          return this;

        }

        this.resolved = true;
        this.value = value;

        this.callbacks.reverse();
        for (x = this.callbacks.length - 1; x >= 0; x = x - 1) {

          defer(defer.bind(this.callbacks[x], null, value));

        }

        return this;

      };
      DeferredObject.prototype.ready = DeferredObject.prototype.resolve;

      // This method is used to mark the deferred as failed and
      // to execute all the failure errbacks registered. The error value
      // passed to this method is the value that will be passed to
      // all errbacks.
      //
      // This method only triggers the errbacks once after which
      // neither it nor the `resolve` method have any effect.
      DeferredObject.prototype.fail = function (value) {

        var x;

        if (this.failed === true || this.resolved === true) {

          return this;

        }

        this.failed = true;
        this.value = value;

        this.errbacks.reverse();
        for (x = this.errbacks.length - 1; x >= 0; x = x - 1) {

          defer(defer.bind(this.errbacks[x], null, value));

        }

        return this;

      };
      DeferredObject.prototype.reject = DeferredObject.prototype.fail;

      // Deferreds should never be returned directly to avoid the potential
      // of runtime manipulation. Instead, return the value of this method
      // any time that you would normally want to return the deferred.
      DeferredObject.prototype.promise = function () {

        return new PromiseObject({"deferred": this});

      };

      CollectionModule = (function () {

        var AnyCollection,
          AllCollection;

        AnyCollection = function AnyCollection() {

          var args = Array.prototype.slice.call(arguments),
            d = new DeferredObject(),
            x;

          for (x = args.length - 1; x >= 0; x = x - 1) {

            args[x].errback(defer.bind(d.fail, d));
            args[x].callback(defer.bind(d.resolve, d));

          }

          return d.promise();

        };

        AllCollection = function AllCollection() {

          var args = Array.prototype.slice.call(arguments),
            d = new DeferredObject(),
            values = [],
            x;

          function resolve(value) {

            values.push(value);

            if (values.length === args.length) {

              d.resolve(values);

            }

          }

          for (x = args.length - 1; x >= 0; x = x - 1) {

            args[x].errback(defer.bind(d.fail, d));
            args[x].callback(resolve);

          }

          return d.promise();

        };

        return {
          "All": AllCollection,
          "Any": AnyCollection
        };

      }());

      // Similar to other modules in this package, the interface returned
      // by this module is a set of wrappers around the actual objects.
      //
      // In this case deferred objects can be created in any of the following
      // ways::
      //
      //      new Deferred();
      //      Deferred();
      //      new Deferred.Deferred();
      //      Deferred.Deferred();
      //
      // The choice comes down to style and preference.
      Deferred = function () {
        return new DeferredObject();
      };
      Deferred.Deferred = Deferred;

      // Deferred.Promise exposes a secondary interface for creating promises.
      // Using the `promise` method of a deferred and creating a new promise
      // object while passing in your deferred have the same effect.
      Deferred.Promise = function (d) {
        return new PromiseObject({"deferred": d});
      };

      Deferred.Collection = CollectionModule;

      return Deferred;

    }
  );

}(this, (function (context) {
  "use strict";

  // Ignoring the unused "name" in the Node.js definition function.
  /*jslint unparam: true */
  if (typeof require === "function" &&
        module !== undefined &&
        !!module.exports) {

    // If this module is loaded in Node, require each of the
    // dependencies and pass them along.
    return function (name, deps, mod) {

      var x,
        dep_list = [];

      for (x = 0; x < deps.length; x = x + 1) {

        dep_list.push(require(deps[x]));

      }

      module.exports = mod.apply(context, dep_list);

    };

  }
  /*jslint unparam: false */

  if (context.window !== undefined) {

    // If this module is being used in a browser environment first
    // generate a list of dependencies, run the provided definition
    // function with the list of dependencies, and insert the returned
    // object into the global namespace using the provided module name.
    return function (name, deps, mod) {

      var namespaces = name.split('/'),
        root = context,
        dep_list = [],
        current_scope,
        current_dep,
        i,
        x;

      for (i = 0; i < deps.length; i = i + 1) {

        current_scope = root;
        current_dep = deps[i].split('/');

        for (x = 0; x < current_dep.length; x = x + 1) {

          current_scope = current_scope[current_dep[x]] =
                          current_scope[current_dep[x]] || {};

        }

        dep_list.push(current_scope);

      }

      current_scope = root;
      for (i = 1; i < namespaces.length; i = i + 1) {

        current_scope = current_scope[namespaces[i - 1]] =
                        current_scope[namespaces[i - 1]] || {};

      }

      current_scope[namespaces[i - 1]] = mod.apply(context, dep_list);

    };

  }

  throw new Error("Unrecognized environment.");

}(this))));
<|endoftext|>


<commit_before>(function($) {
	$.entwine("ss", function($) {
		/**
		 * GridFieldAddExistingSearchButton
		 */

		$(".add-existing-search-dialog").entwine({
			loadDialog: function(deferred) {
				var dialog = this.addClass("loading").children(".ui-dialog-content").empty();

				deferred.done(function(data) {
					dialog.html(data).parent().removeClass("loading");
				});
			}
		});

		$(".ss-gridfield .add-existing-search").entwine({
			onclick: function() {
				var dialog = $("

").appendTo("body").dialog({
					modal: true,
					resizable: false,
					width: 500,
					height: 600,
					close: function() {
						$(this).dialog("destroy").remove();
					}
				});

				dialog.parent().addClass("add-existing-search-dialog").loadDialog(
					$.get(this.prop("href"))
				);
				dialog.data("grid", this.closest(".ss-gridfield"));

				return false;
			}
		});

		$(".add-existing-search-dialog .add-existing-search-form").entwine({
			onsubmit: function() {
				this.closest(".add-existing-search-dialog").loadDialog($.get(
					this.prop("action"), this.serialize()
				));
				return false;
			}
		});

		$(".add-existing-search-dialog .add-existing-search-items a").entwine({
			onclick: function() {
				var link = this.closest(".add-existing-search-items").data("add-link");
				var id   = this.data("id");

				var dialog = this.closest(".add-existing-search-dialog")
				                 .addClass("loading")
				                 .children(".ui-dialog-content")
				                 .empty()

				$.post(link, { id: id }, function() {
					dialog.data("grid").reload();
					dialog.dialog("close");
				});

				return false;
			}
		});

		$(".add-existing-search-dialog .add-existing-search-pagination a").entwine({
			onclick: function() {
				this.closest(".add-existing-search-dialog").loadDialog($.get(
					this.prop("href")
				));
				return false;
			}
		});

		/**
		 * GridFieldAddNewInlineButton
		 */

		$(".ss-gridfield.ss-gridfield-editable").entwine({
			reload: function(opts, success) {
				var grid  = this;
				var added = grid.find(".ss-gridfield-inline-new").detach();

				this._super(opts, function() {
					if(added.length) {
						added.appendTo(grid.find("tbody"));
						grid.find(".ss-gridfield-no-items").hide();
					}

					if(success) success.apply(grid, arguments);
				});
			},
			onaddnewinline: function() {
				var tmpl = window.tmpl;
				var row = this.find(".ss-gridfield-add-inline-template");
				var num = this.data("add-inline-num") || 1;

				tmpl.cache["ss-gridfield-add-inline-template"] = tmpl(row.html());

				this.find("tbody").append(tmpl("ss-gridfield-add-inline-template", { num: num }));
				this.find(".ss-gridfield-no-items").hide();
				this.data("add-inline-num", num + 1);
			}
		});

		$(".ss-gridfield-add-new-inline").entwine({
			onclick: function() {
				this.getGridField().trigger("addnewinline");
				return false;
			}
		});

		$(".ss-gridfield-delete-inline").entwine({
			onclick: function() {
				var msg = ss.i18n._t("GridFieldExtensions.CONFIRMDEL", "Are you sure you want to delete this?");

				if(confirm(msg)) {
					this.parents("tr").remove();
				}

				return false;
			}
		});

		/**
		 * GridFieldAddNewMultiClass
		 */

		$(".ss-gridfield-add-new-multi-class .ss-ui-button").entwine({
			onclick: function() {
				var link = this.data("href");
				var cls  = this.parents(".ss-gridfield-add-new-multi-class").find("select").val();

				if(cls && cls.length) {
					this.getGridField().showDetailView(link.replace("{class}", cls));
				}

				return false;
			}
		});

		$(".ss-gridfield-add-new-multi-class select").entwine({
			onadd: function() {
				this.update();
			},
			onchange: function() {
				this.update();
			},
			update: function() {
				var btn = this.parents(".ss-gridfield-add-new-multi-class").find(".ss-ui-button");

				if(this.val() && this.val().length) {
					btn.button("enable");
				} else {
					btn.button("disable");
				}
			}
		});

		/**
		 * GridFieldEditableColumns
		 */

		$('.ss-gridfield.ss-gridfield-editable .ss-gridfield-item').entwine({
			onclick: function() {
				// Stop the default click action when fields are clicked on.
			}
		});

		/**
		 * GridFieldOrderableRows
		 */

		$(".ss-gridfield-orderable tbody").entwine({
			onadd: function() {
				var self = this;

				var helper = function(e, row) {
					return row.clone()
					          .addClass("ss-gridfield-orderhelper")
					          .width("auto")
					          .find(".col-buttons")
					          .remove()
					          .end();
				};

				var update = function() {
					var grid = self.getGridField();

					var data = grid.getItems().map(function() {
						return { name: "order[]", value: $(this).data("id") };
					});

					grid.reload({
						url: grid.data("url-reorder"),
						data: data.get()
					});
				};

				this.sortable({
					handle: ".handle",
					helper: helper,
					opacity: .7,
					update: update
				});
			},
			onremove: function() {
				this.sortable("destroy");
			}
		});

		$(".ss-gridfield-orderable .ss-gridfield-previouspage, .ss-gridfield-orderable .ss-gridfield-nextpage").entwine({
			onadd: function() {
				var grid = this.getGridField();

				if(this.is(":disabled")) {
					return false;
				}

				var drop = function(e, ui) {
					var page;

					if($(this).hasClass("ss-gridfield-previouspage")) {
						page = "prev";
					} else {
						page = "next";
					}

					grid.find("tbody").sortable("cancel");
					grid.reload({
						url: grid.data("url-movetopage"),
						data: [
							{ name: "move[id]", value: ui.draggable.data("id") },
							{ name: "move[page]", value: page }
						]
					});
				};

				this.droppable({
					accept: ".ss-gridfield-item",
					activeClass: "ui-droppable-active ui-state-highlight",
					disabled: this.prop("disabled"),
					drop: drop,
					tolerance: "pointer"
				});
			},
			onremove: function() {
				if(this.hasClass("ui-droppable")) this.droppable("destroy");
			}
		});
	});
})(jQuery);
<commit_msg>FIX: Don't try to remove sortable if it doesn't exist in the first place<commit_after>(function($) {
	$.entwine("ss", function($) {
		/**
		 * GridFieldAddExistingSearchButton
		 */

		$(".add-existing-search-dialog").entwine({
			loadDialog: function(deferred) {
				var dialog = this.addClass("loading").children(".ui-dialog-content").empty();

				deferred.done(function(data) {
					dialog.html(data).parent().removeClass("loading");
				});
			}
		});

		$(".ss-gridfield .add-existing-search").entwine({
			onclick: function() {
				var dialog = $("

").appendTo("body").dialog({
					modal: true,
					resizable: false,
					width: 500,
					height: 600,
					close: function() {
						$(this).dialog("destroy").remove();
					}
				});

				dialog.parent().addClass("add-existing-search-dialog").loadDialog(
					$.get(this.prop("href"))
				);
				dialog.data("grid", this.closest(".ss-gridfield"));

				return false;
			}
		});

		$(".add-existing-search-dialog .add-existing-search-form").entwine({
			onsubmit: function() {
				this.closest(".add-existing-search-dialog").loadDialog($.get(
					this.prop("action"), this.serialize()
				));
				return false;
			}
		});

		$(".add-existing-search-dialog .add-existing-search-items a").entwine({
			onclick: function() {
				var link = this.closest(".add-existing-search-items").data("add-link");
				var id   = this.data("id");

				var dialog = this.closest(".add-existing-search-dialog")
				                 .addClass("loading")
				                 .children(".ui-dialog-content")
				                 .empty()

				$.post(link, { id: id }, function() {
					dialog.data("grid").reload();
					dialog.dialog("close");
				});

				return false;
			}
		});

		$(".add-existing-search-dialog .add-existing-search-pagination a").entwine({
			onclick: function() {
				this.closest(".add-existing-search-dialog").loadDialog($.get(
					this.prop("href")
				));
				return false;
			}
		});

		/**
		 * GridFieldAddNewInlineButton
		 */

		$(".ss-gridfield.ss-gridfield-editable").entwine({
			reload: function(opts, success) {
				var grid  = this;
				var added = grid.find(".ss-gridfield-inline-new").detach();

				this._super(opts, function() {
					if(added.length) {
						added.appendTo(grid.find("tbody"));
						grid.find(".ss-gridfield-no-items").hide();
					}

					if(success) success.apply(grid, arguments);
				});
			},
			onaddnewinline: function() {
				var tmpl = window.tmpl;
				var row = this.find(".ss-gridfield-add-inline-template");
				var num = this.data("add-inline-num") || 1;

				tmpl.cache["ss-gridfield-add-inline-template"] = tmpl(row.html());

				this.find("tbody").append(tmpl("ss-gridfield-add-inline-template", { num: num }));
				this.find(".ss-gridfield-no-items").hide();
				this.data("add-inline-num", num + 1);
			}
		});

		$(".ss-gridfield-add-new-inline").entwine({
			onclick: function() {
				this.getGridField().trigger("addnewinline");
				return false;
			}
		});

		$(".ss-gridfield-delete-inline").entwine({
			onclick: function() {
				var msg = ss.i18n._t("GridFieldExtensions.CONFIRMDEL", "Are you sure you want to delete this?");

				if(confirm(msg)) {
					this.parents("tr").remove();
				}

				return false;
			}
		});

		/**
		 * GridFieldAddNewMultiClass
		 */

		$(".ss-gridfield-add-new-multi-class .ss-ui-button").entwine({
			onclick: function() {
				var link = this.data("href");
				var cls  = this.parents(".ss-gridfield-add-new-multi-class").find("select").val();

				if(cls && cls.length) {
					this.getGridField().showDetailView(link.replace("{class}", cls));
				}

				return false;
			}
		});

		$(".ss-gridfield-add-new-multi-class select").entwine({
			onadd: function() {
				this.update();
			},
			onchange: function() {
				this.update();
			},
			update: function() {
				var btn = this.parents(".ss-gridfield-add-new-multi-class").find(".ss-ui-button");

				if(this.val() && this.val().length) {
					btn.button("enable");
				} else {
					btn.button("disable");
				}
			}
		});

		/**
		 * GridFieldEditableColumns
		 */

		$('.ss-gridfield.ss-gridfield-editable .ss-gridfield-item').entwine({
			onclick: function() {
				// Stop the default click action when fields are clicked on.
			}
		});

		/**
		 * GridFieldOrderableRows
		 */

		$(".ss-gridfield-orderable tbody").entwine({
			onadd: function() {
				var self = this;

				var helper = function(e, row) {
					return row.clone()
					          .addClass("ss-gridfield-orderhelper")
					          .width("auto")
					          .find(".col-buttons")
					          .remove()
					          .end();
				};

				var update = function() {
					var grid = self.getGridField();

					var data = grid.getItems().map(function() {
						return { name: "order[]", value: $(this).data("id") };
					});

					grid.reload({
						url: grid.data("url-reorder"),
						data: data.get()
					});
				};

				this.sortable({
					handle: ".handle",
					helper: helper,
					opacity: .7,
					update: update
				});
			},
			onremove: function() {
                if(this.data('sortable'))
				    this.sortable("destroy");
			}
		});

		$(".ss-gridfield-orderable .ss-gridfield-previouspage, .ss-gridfield-orderable .ss-gridfield-nextpage").entwine({
			onadd: function() {
				var grid = this.getGridField();

				if(this.is(":disabled")) {
					return false;
				}

				var drop = function(e, ui) {
					var page;

					if($(this).hasClass("ss-gridfield-previouspage")) {
						page = "prev";
					} else {
						page = "next";
					}

					grid.find("tbody").sortable("cancel");
					grid.reload({
						url: grid.data("url-movetopage"),
						data: [
							{ name: "move[id]", value: ui.draggable.data("id") },
							{ name: "move[page]", value: page }
						]
					});
				};

				this.droppable({
					accept: ".ss-gridfield-item",
					activeClass: "ui-droppable-active ui-state-highlight",
					disabled: this.prop("disabled"),
					drop: drop,
					tolerance: "pointer"
				});
			},
			onremove: function() {
				if(this.hasClass("ui-droppable")) this.droppable("destroy");
			}
		});
	});
})(jQuery);
<|endoftext|>


<commit_before>Package.describe({
  summary: 'Routing for Meteor'
});

Package.on_use(function (api) {
  api.use([
    'meteor',
    'deps',
    'underscore',
    'handlebars',
    'posture',
    'controller'
  ], 'client');

  api.add_files([
    'lib/route_path.js',
    'lib/route_context.js',
    'lib/route.js',
    'lib/router.js'
  ], ['client', 'server']);

  api.add_files([
    'lib/client/location.js',
    'lib/client/route_controller.js',
    'lib/client/client_router.js',
    'lib/client/helpers.js'
  ], 'client');

  api.add_files([
    'lib/server/route_controller.js',
    'lib/server/server_router.js'
  ], 'server');
});

Package.on_test(function (api) {
  api.use('iron-router', 'client');
  api.use('reactive-dict', 'client');
  api.use('tinytest', 'client');
  api.use('test-helpers', 'client');

  api.add_files([
    'test/test-helpers.js',
    'test/route_path_test.js',
    'test/route_context_test.js',
    'test/route_test.js',
    'test/router_test.js'
  ], ['client', 'server']);

  api.add_files([
    'test/client/location_test.js',
    'test/client/route_controller_test.js',
    'test/client/client_router_test.js',
  ], 'client');

  api.add_files([
    'test/server/route_controller_test.js',
    'test/server/server_router_test.js',
  ], 'server');
});
<commit_msg>Updated package so IronRouter runs on client and server.<commit_after>Package.describe({
  summary: 'Routing for Meteor'
});

Package.on_use(function (api) {
  api.use([
    'meteor',
    'deps',
    'underscore',
    'handlebars',
    'posture',
    'controller'
  ], 'client');

  api.add_files([
    'lib/route_path.js',
    'lib/route_context.js',
    'lib/route.js',
    'lib/router.js'
  ], ['client', 'server']);

  api.add_files([
    'lib/client/location.js',
    'lib/client/route_controller.js',
    'lib/client/client_router.js',
    'lib/client/helpers.js'
  ], 'client');

  api.add_files([
    'lib/server/route_controller.js',
    'lib/server/server_router.js'
  ], 'server');
});

Package.on_test(function (api) {
  api.use('iron-router', ['client', 'server']);
  api.use('reactive-dict', 'client');
  api.use('tinytest', 'client');
  api.use('test-helpers', 'client');

  api.add_files([
    'test/test-helpers.js',
    'test/route_path_test.js',
    'test/route_context_test.js',
    'test/route_test.js',
    'test/router_test.js'
  ], ['client', 'server']);

  api.add_files([
    'test/client/location_test.js',
    'test/client/route_controller_test.js',
    'test/client/client_router_test.js',
  ], 'client');

  api.add_files([
    'test/server/route_controller_test.js',
    'test/server/server_router_test.js',
  ], 'server');
});
<|endoftext|>


<commit_before>'use strict';

var debug = require('debug')('gitevents-milestone');
var config = require('../common/config');

var createMilestone = function(payload, event, repo, github) {
  return new Promise(function(resolve, reject) {
    github.issues.createMilestone({
      user: config.github.org,
      repo: repo,
      title: event.name,
      due_on: event.startDate,
      description: event.id
    }, function(error) {
      if (error) { return reject(new Error(error)); }
      debug('GitHub:createdMilestone - ' + repo);
      return resolve();
    });
  });
};

var getMilestones = function getMilestones(repo, eventId, github) {
  return new Promise(function(resolve, reject) {
    github.issues.getAllMilestones({
      user: config.github.org,
      repo: repo,
      state: 'open'
    }, function (error, milestones) {
      if (error) { return reject(new Error(error)); }

      if (milestones.length > 0) {
        milestones.forEach(function(milestone) {
          if (milestone.description === eventId) {
            return resolve({ 'milestone': milestone, 'repo': repo });
          }
        });
        return resolve({ 'milestone': false, 'repo': repo });
      } else {
        resolve({ 'milestone': false, 'repo': repo });
      }
    })
  });
}

module.exports = function milestone(payload, event, github) {
  return new Promise(function(resolve, reject) {
    debug('Setup Milestones');

    for (var repo in config.github.repos) {
      if (config.github.repos.hasOwnProperty(repo)) {
        getMilestones(config.github.repos[repo], event.id, github)
          .then(function gotMilestones(args) {
            var milestone = args.milestone;
            var repo = args.repo;

            if (milestone === false) {
              if (args.repo === config.github.repos.gitevent) {
                createMilestone(payload, event, args.repo, github);
              } else {
                if (args.repo !== config.github.repos.gitevent) {
                  createMilestone(payload, event, args.repo, github);
                }
              }
            } else {
              debug(milestone.id + ' already exists for ' + args.repo);
            }
        }, function(error) {
          return new Error(error);
        });
      }
    }
  });
};
<commit_msg>add milestone to issue not firing<commit_after>'use strict';

var debug = require('debug')('gitevents-milestone');
var config = require('../common/config');

var createMilestone = function createMilestone(payload, event, repo, github) {
  return new Promise(function(resolve, reject) {
    github.issues.createMilestone({
      user: config.github.org,
      repo: repo,
      title: event.name,
      due_on: event.startDate,
      description: event.id
    }, function(error, milestone) {
      if (error) { return reject(new Error(error)); }
      debug('GitHub:createdMilestone - ' + repo);
      return resolve({ 'milestone': milestone, 'repo': repo });
    });
  });
};

var getMilestones = function getMilestones(repo, eventId, github) {
  return new Promise(function(resolve, reject) {
    github.issues.getAllMilestones({
      user: config.github.org,
      repo: repo,
      state: 'open'
    }, function (error, milestones) {
      if (error) { return reject(new Error(error)); }

      if (milestones.length > 0) {
        milestones.forEach(function(milestone) {
          if (milestone.description === eventId) {
            return resolve({ 'milestone': milestone, 'repo': repo });
          }
        });
        return resolve({ 'milestone': false, 'repo': repo });
      } else {
        resolve({ 'milestone': false, 'repo': repo });
      }
    })
  });
}

var addMilestone = function addMilestone(issue, repo, milestone, github) {
  return new Promise(function(resolve, reject) {
    debug('GitHub:addMilestone');
    console.log(issue, repo, milestone, github);

    github.issues.edit({
      user: config.github.org,
      repo: repo,
      title: issue.title,
      body: issue.body,
      assignee: issue.assignee,
      state: issue.state,
      milestone: milestone.number,
      labels: issue.labels
    }, function (error, issue) {
      if (error) { return reject(new Error(error)); }
      debug('Milestone added to issue');
      return resolve({ 'issue': issue });
    });

  });
};

module.exports = function milestone(payload, event, github) {
  return new Promise(function(resolve, reject) {
    debug('Setup Milestones');

    for (var repo in config.github.repos) {
      if (config.github.repos.hasOwnProperty(repo)) {
        getMilestones(config.github.repos[repo], event.id, github)
          .then(function gotMilestones(args) {
            var milestone = args.milestone;
            var repo = args.repo;

            if (milestone === false) {
              if (args.repo === config.github.repos.gitevent) {
                createMilestone(payload, event, args.repo, github)
                  .then(function(args) {
                    console.log(args)
                    console.log('adding milestone to resources')
                    addMilestone(issue, args.repo, args.milestone, github);
                  });
              } else {
                if (args.repo !== config.github.repos.gitevent) {
                  createMilestone(payload, event, args.repo, github)
                    .then(function(args) {
                      console.log(args)
                      console.log('adding milestone to everything else')
                      addMilestone(issue, args.repo, args.milestone, github);
                  });
                }
              }
            } else {
              debug(milestone.id + ' already exists for ' + args.repo);
            }
        }, function(error) {
          return new Error(error);
        });
      }
    }
  });
};
<|endoftext|>