<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/array",
    "firebug/lib/string",
],
function(FBTrace, Arr, Str) {

// ********************************************************************************************* //

var Obj = {};

// ********************************************************************************************* //

Obj.bind = function()  // fn, thisObject, args => thisObject.fn(arguments, args);
{
   var args = Arr.cloneArray(arguments), fn = args.shift(), object = args.shift();
   return function bind() { return fn.apply(object, Arr.arrayInsert(Arr.cloneArray(args), 0, arguments)); }
};

Obj.bindFixed = function() // fn, thisObject, args => thisObject.fn(args);
{
    var args = Arr.cloneArray(arguments), fn = args.shift(), object = args.shift();
    return function() { return fn.apply(object, args); }
};

Obj.extend = function(l, r)
{
    if (!l || !r)
    {
        FBTrace.sysout("object.extend; ERROR", [l, r]);
        throw new Error("Obj.extend on undefined object");
    }

    var newOb = {};
    for (var n in l)
        newOb[n] = l[n];
    for (var n in r)
        newOb[n] = r[n];
    return newOb;
};

Obj.descend = function(prototypeParent, childProperties)
{
    function protoSetter() {};
    protoSetter.prototype = prototypeParent;
    var newOb = new protoSetter();
    for (var n in childProperties)
        newOb[n] = childProperties[n];
    return newOb;
};

// ************************************************************************************************

Obj.hasProperties = function(ob)
{
    try
    {
        var obString = Str.safeToString(ob);
        if (obString === '[object StorageList]' || obString === '[xpconnect wrapped native prototype]')
            return true;

        for (var name in ob)
        {
            // Try to access the property before declaring existing properties.
            // It's because some properties can't be read see:
            // issue 3843, https://bugzilla.mozilla.org/show_bug.cgi?id=455013
            var value = ob[name];
            return true;
        }
    }
    catch (exc)
    {
        if (FBTrace.DBG_ERRORS)
            FBTrace.sysout("lib.hasProperties("+Str.safeToString(ob)+") ERROR "+exc, exc);

        if (ob.wrappedJSObject)  // workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=648560
            return true;
    }
    return false;
};

Obj.getPrototype = function(ob)
{
    try
    {
        return ob.prototype;
    } catch (exc) {}
    return null;
};

Obj.getUniqueId = function()
{
    return this.getRandomInt(0,65536);
}

Obj.getRandomInt = function(min, max)
{
    return Math.floor(Math.random() * (max - min + 1) + min);
}

// Cross Window instanceof; type is local to this window
Obj.XW_instanceof = function(obj, type)
{
    if (obj instanceof type)
        return true;  // within-window test

    if (!type)
        return false;

    if (!obj)
        return (type == "undefined");

    // compare strings: obj constructor.name to type.name.
    // This is not perfect, we should compare type.prototype to object.__proto__,
    // but mostly code does not change the constructor object.
    do
    {
        // then the function that constructed us is the argument
        if (obj.constructor && obj.constructor.name == type.name)
            return true;
    }
    while(obj = obj.__proto__);  // walk the prototype chain.

    return false;

    // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Property_Inheritance_Revisited
    // /Determining_Instance_Relationships
}

/**
 * Tells if the given property of the provided object is a non-native getter or not.
 * This method depends on PropertyPanel.jsm module available in Firefox 5+
 * isNonNativeGetter has been introduced in Firefox 7
 *
 * @param object aObject The object that contains the property.
 * @param string aProp The property you want to check if it is a getter or not.
 * @return boolean True if the given property is a getter, false otherwise.
 */
Obj.isNonNativeGetter = function()
{
    try
    {
        var scope = {};
        Components.utils.import("resource:///modules/PropertyPanel.jsm", scope);

        if (scope.isNonNativeGetter)
            Obj.isNonNativeGetter = scope.isNonNativeGetter;
    }
    catch (err)
    {
    }

    return true;
}

// ********************************************************************************************* //

return Obj;

// ********************************************************************************************* //
});
<commit_msg>[1.9] Fix for Obj.isNonNativeGetter (related to R12074)<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/array",
    "firebug/lib/string",
],
function(FBTrace, Arr, Str) {

// ********************************************************************************************* //

var Obj = {};

// ********************************************************************************************* //

Obj.bind = function()  // fn, thisObject, args => thisObject.fn(arguments, args);
{
   var args = Arr.cloneArray(arguments), fn = args.shift(), object = args.shift();
   return function bind() { return fn.apply(object, Arr.arrayInsert(Arr.cloneArray(args), 0, arguments)); }
};

Obj.bindFixed = function() // fn, thisObject, args => thisObject.fn(args);
{
    var args = Arr.cloneArray(arguments), fn = args.shift(), object = args.shift();
    return function() { return fn.apply(object, args); }
};

Obj.extend = function(l, r)
{
    if (!l || !r)
    {
        FBTrace.sysout("object.extend; ERROR", [l, r]);
        throw new Error("Obj.extend on undefined object");
    }

    var newOb = {};
    for (var n in l)
        newOb[n] = l[n];
    for (var n in r)
        newOb[n] = r[n];
    return newOb;
};

Obj.descend = function(prototypeParent, childProperties)
{
    function protoSetter() {};
    protoSetter.prototype = prototypeParent;
    var newOb = new protoSetter();
    for (var n in childProperties)
        newOb[n] = childProperties[n];
    return newOb;
};

// ************************************************************************************************

Obj.hasProperties = function(ob)
{
    try
    {
        var obString = Str.safeToString(ob);
        if (obString === '[object StorageList]' || obString === '[xpconnect wrapped native prototype]')
            return true;

        for (var name in ob)
        {
            // Try to access the property before declaring existing properties.
            // It's because some properties can't be read see:
            // issue 3843, https://bugzilla.mozilla.org/show_bug.cgi?id=455013
            var value = ob[name];
            return true;
        }
    }
    catch (exc)
    {
        if (FBTrace.DBG_ERRORS)
            FBTrace.sysout("lib.hasProperties("+Str.safeToString(ob)+") ERROR "+exc, exc);

        if (ob.wrappedJSObject)  // workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=648560
            return true;
    }
    return false;
};

Obj.getPrototype = function(ob)
{
    try
    {
        return ob.prototype;
    } catch (exc) {}
    return null;
};

Obj.getUniqueId = function()
{
    return this.getRandomInt(0,65536);
}

Obj.getRandomInt = function(min, max)
{
    return Math.floor(Math.random() * (max - min + 1) + min);
}

// Cross Window instanceof; type is local to this window
Obj.XW_instanceof = function(obj, type)
{
    if (obj instanceof type)
        return true;  // within-window test

    if (!type)
        return false;

    if (!obj)
        return (type == "undefined");

    // compare strings: obj constructor.name to type.name.
    // This is not perfect, we should compare type.prototype to object.__proto__,
    // but mostly code does not change the constructor object.
    do
    {
        // then the function that constructed us is the argument
        if (obj.constructor && obj.constructor.name == type.name)
            return true;
    }
    while(obj = obj.__proto__);  // walk the prototype chain.

    return false;

    // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Property_Inheritance_Revisited
    // /Determining_Instance_Relationships
}

/**
 * Tells if the given property of the provided object is a non-native getter or not.
 * This method depends on PropertyPanel.jsm module available in Firefox 5+
 * isNonNativeGetter has been introduced in Firefox 7
 *
 * @param object aObject The object that contains the property.
 * @param string aProp The property you want to check if it is a getter or not.
 * @return boolean True if the given property is a getter, false otherwise.
 */
Obj.isNonNativeGetter = function(obj, propName)
{
    try
    {
        var scope = {};
        Components.utils.import("resource:///modules/PropertyPanel.jsm", scope);

        if (scope.isNonNativeGetter)
        {
            Obj.isNonNativeGetter = scope.isNonNativeGetter;
            return Obj.isNonNativeGetter(obj, propName);
        }
    }
    catch (err)
    {
    }

    return true;
}

// ********************************************************************************************* //

return Obj;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>var querystring = require('querystring');
var http = require('http');
var utils = require('./utils');

function nyt (keys) {
    var myKeys = keys;
    var A = '&';
    var Q = '?';
    var E = '=';
    var S = '/';
    var D = '.';
    var API_KEY = 'api-key';
    var V1 = 'v1';
    var V2 = 'v2';
    var V3 = 'v3';
    var DEFAULT = 'json';
    var SVC = 'svc';

	var request = function (path, data, callback, args) {
		var options = {
			hostname: 'api.nytimes.com',
			path: path
		}
		var req = http.request(options, function(res) {
			res.setEncoding('utf8');
			var buffer = '';
			res.on('data', function(chunk) {
				buffer += chunk;
			});
			res.on('end', function() {
				callback(buffer);
			});
		});

		req.on('error', function(err) {
			callback(err);
		});

		req.end();
	}

	var get = function (path, callback, args) {
		request(path, undefined, callback, args);
	}

    this.article = {
        get : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var path = '/svc/search/v2/articlesearch.json' +
                '?' + querystring.stringify(args) +
                '&' + 'api-key=' + myKeys['article'];
            get(path, callback, args);
        }
    }

    this.bestSellers = {
        get : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var books = '/svc/books/';
            var date = "";
            if (typeof args.date != undefined) {
                date = args.date;
            }
            var list_name = args['list-name'];
            var args = utils.removeArgs(['date', 'list-name'], args);
            var path = books + version + 'lists/' +
                date + '/' + list_name +
                '.json' + querystring.stringify(args) + '?' + 'api-key=' + myKeys['best-sellers'];
            get(path, callback, args);
        },
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var path = '/svc/books/' + version + 'lists' + format + '?' + querystring.stringify(args) + '&' + 'api-key=' + myKeys['best-sellers'];
            get(path, callback, args);
        },
        history : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var path = '/svc/books/' + version + 'lists/best-sellers/history' + format + '?' + querystring.stringify(args) + '&' + 'api-key=' + myKeys['best-sellers'];
            get(path, callback, args);
        },
        overview : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var path = '/svc/books/' + version + 'lists/overview' + format + '?' + querystring.stringify(args) + '&' + 'api-key=' + myKeys['best-sellers'];
            get(path, callback, args);
        },
        names : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var path = '/svc/books/' + version + 'lists/names' + format + '?' + 'api-key=' + myKeys['best-sellers'];
            get(path, callback, args);
        }
    }

    this.community = {
        recent : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var path = '/svc/community/' + version + 'comments/recent' + format + '?force-replies=0' + '&' + querystring.stringify(args) + '&api-key=' + myKeys['community'];
            get(path, callback, args);
        },
        random : function (args, callback) {

        },
        byDate : function (args, callback) {

        },
        byUser : function (args, callback) {

        },
        byURL : function (args, callback) {

        }
    }

    this.districts = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var query = '';
            if (querystring.stringify(args) != '') {
                query = querystring.stringify(args) + '&';
            }
            var path = '/svc/politics/' + version + 'districts' + format + '?' + 'api-key=' + query + myKeys['districts'];
            get(path, callback, args);
        }
    }

    this.eventListings = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var query = '';
            if (querystring.stringify(args)) {
                query = querystring.stringify(args) + '&';
            }
            var path = '/svc/events/' + version + 'listings' + format + '?' + query + 'api-key=' + myKeys['event-listings'];

            get(path, callback, args);
        }
    }

    this.geo = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var query = '';
            if (querystring.stringify(args)) {
                query = querystring.stringify(args) + '&';
            }
            var path = '/svc/semantic/' + version + 'geocodes/query' + format + '?' + query + 'api-key=' + myKeys['geo'];
            get(path, callback, args);
        }
    }

    this.mostPopular = {
        emailed : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var query = '';
            if (querystring.stringify(args)) {
                query = querystring.stringify(args) + '&';
            }
            var section = args.section;
            var timePeriod = args['time-period'];
            var path = '/svc/mostpopular/' + version + 'mostemailed/' + section +
                '/' + timePeriod + format + '?' + query + 'api-key='+ myKeys['most-popular'];
            get(path, callback, args);
        },
        shared : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var query = '';
            if (querystring.stringify(args)) {
                query = querystring.stringify(args) + '&';
            }
            var section = args.section;
            var timePeriod = args['time-period'];
            var path = '/svc/mostpopular/' + version + 'mostshared/' + section +
                '/' + timePeriod + format + '?' + query + 'api-key=' + myKeys['most-popular'];
            get(path, callback, args);
        },
        viewed : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var version = 'v2/';
            var format = '.json';
            var query = '';
            if (querystring.stringify(args)) {
                query = querystring.stringify(args) + '&';
            }
            var section = args.section;
            var timePeriod = args['time-period'];
            var path = '/svc/mostpopular/' + version + 'mostviewed/' + section +
                '/' + timePeriod + format + '?' + query + 'api-key=' + myKeys['most-popular'];
            get(path, callback, args);
        }
    }

    this.newswire = {
        recent : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var source = utils.checkField(args['source'], '');
            var format = utils.checkField(args['format'], DEFAULT);
            var section = utils.checkField(args['section'], '');
            var timePeriod = utils.checkField(args['time-period'], '');

            var query = utils.checkQuery(args);
            var path = S.concat(SVC,S,'news',S,V3,S,'content',S,source,S,section,S,timePeriod,D,format,Q,
                               query,API_KEY,E,myKeys['newswire']);

            get(path, callback, args);
        },
        specific : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var query = utils.checkQuery(args);
            var path = S.concat(SVC, S, 'news', S, V3, S, 'content', D,
                                   DEFAULT, Q, query, API_KEY, E, myKeys['newswire']);

            get(path, callback, args);
        }
    }

    this.timesTags = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var query = utils.checkQuery(args);
            var path = S.concat(SVC,S,'suggest',S,V1,S,'timestags',Q,query,API_KEY,E,myKeys['timestags']);
            get(path, callback, args);

        }
    }

}

module.exports = nyt;
<commit_msg>refactored concatenation method, and utilized utils<commit_after>var querystring = require('querystring');
var http = require('http');
var utils = require('./utils');

function nyt (keys) {
    var myKeys = keys;
    var A = '&';
    var Q = '?';
    var E = '=';
    var S = '/';
    var D = '.';
    var API_KEY = 'api-key';
    var V1 = 'v1';
    var V2 = 'v2';
    var V3 = 'v3';
    var DEFAULT = 'json';
    var SVC = 'svc';

	var request = function (path, data, callback, args) {
		var options = {
			hostname: 'api.nytimes.com',
			path: path
		}
		var req = http.request(options, function(res) {
			res.setEncoding('utf8');
			var buffer = '';
			res.on('data', function(chunk) {
				buffer += chunk;
			});
			res.on('end', function() {
				callback(buffer);
			});
		});

		req.on('error', function(err) {
			callback(err);
		});

		req.end();
	}

	var get = function (path, callback, args) {
		request(path, undefined, callback, args);
	}

    this.article = {
        get : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var query = checkQuery(args);
            var format = checkField(args['format'], DEFAULT);

            var path = S.concat(SVC, S, 'search', S, V2, S, 'articlesearch',
                                D, format, API_KEY, E, myKeys['article']);
            get(path, callback, args);
        }
    }

    this.bestSellers = {
        get : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var date = utils.checkField(args['date'], '');
            var list_name = args['list-name'];
            args = utils.removeArgs(['date', 'list-name'], args);
            var query = utils.checkQuery(args);

            var path = S.concat(SVC, S, 'books', S, V2, S, 'lists', S,
                               date, S, list_name, D, format, query, Q,
                               API_KEY, E, myKeys['best-sellers']);
            get(path, callback, args);
        },
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);

            var path = S.concat(SVC, C, 'books', S, V2, S, 'lists', D, format, Q,
                               query, API_KEY, E, myKeys['best-sellers']);
            get(path, callback, args);
        },
        history : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);

            var path = S.concat(SVC, S, 'books', S, V2, S, 'lists', S,
                                'best-sellers', S, 'history', D, format,
                                Q, query, API_KEY, E, myKeys['best-sellers']);
            get(path, callback, args);
        },
        overview : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var query = checkQuery(args);
            var format = utils.checkField(args['format'], DEFAULT);
            var path = utils.concat(SVC, 'books', S, V2, S, 'lists', S, 'overview',
                                   D, format, Q, query, API_KEY, E,
                                   myKeys['best-sellers']);
            get(path, callback, args);
        },
        names : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = checkField(args['format'], DEFAULT);
            var path = S.concat(SVC, S, 'books', S, V2, 'lists', S, 'names',
                               D, format, Q, API_KEY, E, myKeys[best-sellers]);
            get(path, callback, args);
        }
    }

    this.community = {
        recent : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);

            var path = S.concat(SVC, S, 'community', S, V2, 'comments', S, 'recent',
                               D, format, Q, 'format-replies', E, '0', A,
                               query, A, API_KEY, E, myKeys['community']);
            get(path, callback, args);
        },
        random : function (args, callback) {

        },
        byDate : function (args, callback) {

        },
        byUser : function (args, callback) {

        },
        byURL : function (args, callback) {

        }
    }

    this.districts = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);
            var path = S.concat(SVC, S, 'politics', S, V2, 'districts', D, format,
                               Q, API_KEY, E, query, myKeys['districts']);
            get(path, callback, args);
        }
    }

    this.eventListings = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);

            var path = S.concat(SVC, S, 'events', S, V2, S, D, format, Q, query,
                                API_KEY, E, myKeys['event-listings']);

            get(path, callback, args);
        }
    }

    this.geo = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);

            var path = S.concat(SVC, S, 'semantic', S, V2, 'geocodes', S, 'query',
                               D, format, Q, query, API_KEY, E, myKeys['geo']);
            get(path, callback, args);
        }
    }

    this.mostPopular = {
        emailed : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);
            var section = utils.checkField(args['section'], '');
            var timePeriod = utils.checkField(args['time-period'], '');

            var path = S.concat(SVC, S, 'mostpopular', S, V2, 'mostemailed',
                               S, section, S, timePeriod, D, format, Q, query,
                               API_KEY, E, myKeys['most-popular']);
            get(path, callback, args);
        },
        shared : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);
            var section = utils.checkField(args['section'], '');
            var timePeriod = utils.checkField(args['time-period'], '');

            var path = S.concat(SVC, S, 'mostpopular', S, V2, 'mostshared', S,
                               section, S, timePeriod, D, format, Q, query, API_KEY,
                               E, myKeys['most-popular']);
            get(path, callback, args);
        },
        viewed : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var format = utils.checkField(args['format'], DEFAULT);
            var query = utils.checkQuery(args);
            var section = utils.checkField(args['section'], '');
            var timePeriod = utils.checkField(args['time-period'], '');

            var path = S.concat(SVC, S, 'mostpopular', S, V2, S, 'mostviewed', S,
                               section, S, timePeriod, D, format, Q, query, API_KEY,
                               E, myKeys['most-popular']);
            get(path, callback, args);
        }
    }

    this.newswire = {
        recent : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var source = utils.checkField(args['source'], '');
            var format = utils.checkField(args['format'], DEFAULT);
            var section = utils.checkField(args['section'], '');
            var timePeriod = utils.checkField(args['time-period'], '');

            var query = utils.checkQuery(args);
            var path = S.concat(SVC,S,'news',S,V3,S,'content',S,source,S,section,
                                S,timePeriod,D,format,Q,
                                query,API_KEY,E,myKeys['newswire']);

            get(path, callback, args);
        },
        specific : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var query = utils.checkQuery(args);
            var path = S.concat(SVC, S, 'news', S, V3, S, 'content', D,
                                   DEFAULT, Q, query, API_KEY, E, myKeys['newswire']);

            get(path, callback, args);
        }
    }

    this.timesTags = {
        search : function (args, callback) {
            var callbackReturn = utils.checkCallback(args, callback);
            args = callbackReturn.args;
            callback = callbackReturn.callback;

            var query = utils.checkQuery(args);
            var path = S.concat(SVC,S,'suggest',S,V1,S,'timestags',Q,query,API_KEY,E,myKeys['timestags']);
            get(path, callback, args);

        }
    }

}

module.exports = nyt;
<|endoftext|>


<commit_before>import { resolve } from 'path'

// Retrieve error message of a standard error
export const getErrorMessage = function ({
  error: { type, description, details },
  message,
}) {
  // Retrieve both the main message and the stack
  const stack = getStack(description, details)

  // Add error type to message
  const errorMessage = stack ? `${type} - ${stack}` : type

  // Add original event's message
  const errorMessageA = message ? `${message}\n${errorMessage}` : errorMessage

  return errorMessageA
}

const getStack = function (description, details = '') {
  // Only include description if it's not already in the stack trace
  const stack =
    !description || details.includes(description)
      ? details
      : `${description}\n${details}`

  // Remove `Error:` as it gets prepended to `error.stack` (i.e. `details`)
  const stackA = stack.replace(/^[\w]*Error: /u, '')

  // Shorten stack trace directory paths
  const stackB = stackA.split(ROOT_DIR).join('')
  return stackB
}

const ROOT_DIR = resolve(__dirname, '../../..')
<commit_msg>Use import.meta.url<commit_after>import { resolve } from 'path'
import { fileURLToPath } from 'url'

// Retrieve error message of a standard error
export const getErrorMessage = function ({
  error: { type, description, details },
  message,
}) {
  // Retrieve both the main message and the stack
  const stack = getStack(description, details)

  // Add error type to message
  const errorMessage = stack ? `${type} - ${stack}` : type

  // Add original event's message
  const errorMessageA = message ? `${message}\n${errorMessage}` : errorMessage

  return errorMessageA
}

const getStack = function (description, details = '') {
  // Only include description if it's not already in the stack trace
  const stack =
    !description || details.includes(description)
      ? details
      : `${description}\n${details}`

  // Remove `Error:` as it gets prepended to `error.stack` (i.e. `details`)
  const stackA = stack.replace(/^[\w]*Error: /u, '')

  // Shorten stack trace directory paths
  const stackB = stackA.split(ROOT_DIR).join('')
  return stackB
}

const ROOT_DIR = resolve(fileURLToPath(new URL('../../..', import.meta.url)))
<|endoftext|>


<commit_before>module.exports = function post (callee, preCall) {
    return function callHook () {
        var aborted
        var result = preCall.apply({ abort: abort }, arguments)
        if (aborted) return aborted.returnValue
        return callee.apply(undefined, Array.isArray(result) ? result : arguments)

        function abort (returnValue) {
            aborted = { returnValue: returnValue }
        }
    }
}
<commit_msg>clear up arg rewriting, and make it specific. Don't overload return.<commit_after>module.exports = function post (callee, preCall) {
    return function callHook () {
        var aborted,
            rewrittenArgs,
            ctx = { abort: abort, setArguments: setArguments }

        preCall.apply(ctx, arguments)
        if (aborted) return aborted.returnValue
        return callee.apply(undefined, rewrittenArgs ? rewrittenArgs : arguments)

        function abort (returnValue) {
            aborted = { returnValue: returnValue }
        }

        function setArguments () {
            rewrittenArgs = arguments
        }
    }
}
<|endoftext|>


<commit_before>import  * as THREE from '../node_modules/three/build/three.module.js'

// Settings
const maxLeafNodes = 10;
const maxMatchingTriangles = 0.5;

// Utilities
const getBufferGeometryVertexElem = (geo, tri, vert, elem) => {
    return geo.attributes.position.array[(geo.index ? geo.index.array[3 * tri + vert] : (3 * tri + vert)) * 3  + elem];
}

const getGeometryVertexElem = (geo, tri, vert, elem) => {
    return geo.faces[tri][abcFields[vert]][xyzFields[elem]];
}

const abcFields = ['a', 'b', 'c'];
const xyzFields = ['x', 'y', 'z'];
const getLongestEdgeIndex = bb => {
    let splitDimIdx = -1;
    let splitDist = -Infinity;
    xyzFields.forEach((d, i) => {
        const dist = bb.max[d] - bb.min[d];
        if (dist > splitDist) {
            splitDist = dist;
            splitDimIdx = i;
        }
    });
    return splitDimIdx;
}

// reusable vectors
const avgtemp = new THREE.Vector3();
const vectemp = new THREE.Vector3();
const centemp = new THREE.Vector3();

const getBounds = (tris, bounds, avg, geo, getValFunc) => {
    avg.set(0, 0, 0);

    for (let i = 0; i < tris.length; i ++) {
        const tri = tris[i];

        for (let v = 0; v < 3; v ++) {
            const x = getValFunc(geo, tri, v, 0);
            const y = getValFunc(geo, tri, v, 1);
            const z = getValFunc(geo, tri, v, 2);

            vectemp.x = x;
            vectemp.y = y;
            vectemp.z = z;
            bounds.expandByPoint(vectemp);

            avg.x += x;
            avg.y += y;
            avg.z += z;
        }
    }

    avg.x /= tris.length * 3;
    avg.y /= tris.length * 3;
    avg.z /= tris.length * 3;
}

const getSphere = (tris, sphere, geo, getValFunc) => {
    const center = sphere.center;
    let maxRadiusSq = 0;

    for (let i = 0; i < tris.length; i ++) {
        const tri = tris[i];

        for (let v = 0; v < 3; v ++) {
            const x = getValFunc(geo, tri, v, 0);
            const y = getValFunc(geo, tri, v, 1);
            const z = getValFunc(geo, tri, v, 2);

            vectemp.x = x;
            vectemp.y = y;
            vectemp.z = z;

            maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(vectemp));
        }
    }

    sphere.radius = Math.sqrt(maxRadiusSq);
}

// Classes
class TriangleBoundsNode {
    constructor() {
        this.boundingBox = new THREE.Box3();
        this.boundingSphere = new THREE.Sphere();
        this.children = [];
        this.tris = [];
    }
}

class TriangleBoundsTree {
    constructor(geo) {
        if (geo.isBufferGeometry || geo.isGeometry) {
            this._root = this._buildTree(geo);
        } else {
            throw new Error('Object is not Geometry or BufferGeometry');
        }
    }

    /* Public API */
    collectCandidates(origray) {
        const candidates = [];
        const recurse = (node, ray) => {

            if (!ray.intersectsSphere(node.boundingSphere) || !ray.intersectsBox(node.boundingBox)) return;

            if (node.children.length) {
                node.children.forEach(c => recurse(c, ray))
            } else {
                st = window.performance.now()
                candidates.push(...node.tris)
                dttime += window.performance.now() - st;
            }
        }
        recurse(this._root, origray);

        return candidates;
    }

    /* Private Functions */
    _buildTree(geo) {
        const vertexElem = geo.isBufferGeometry ? getBufferGeometryVertexElem : getGeometryVertexElem;

        // a list of every available triangle index
        const origTris =
            geo.isBufferGeometry ?
                new Array(geo.index ? (geo.index.count / 3) : (pos.length / 9)) :
                Array(geo.faces.length);

        for (let i = 0; i < origTris.length; i ++) origTris[i] = i;

        // use a queue to run the node creation functions
        // because otherwise we run the risk of a stackoverflow
        // In the case of buffer geometry it also seems to be
        // faster than recursing
        const queue = [];
        const createNode = tris => {
            const node = new TriangleBoundsNode();

            // get the bounds of the triangles
            getBounds(tris, node.boundingBox, avgtemp, geo, vertexElem);
            node.boundingBox.getCenter(node.boundingSphere.center);
            getSphere(tris, node.boundingSphere, geo, vertexElem);

            if (tris.length <= maxLeafNodes) {
                node.tris = tris;
                return node;
            }

            // decide which axis to split on (longest edge)
            const splitDimIdx = getLongestEdgeIndex(node.boundingBox);
            const splitDimStr = xyzFields[splitDimIdx];

            const left = [], right = [];
            let sharedCount = 0;
            for (let i = 0; i < tris.length; i ++) {
                const tri = tris[i];

                let inLeft = false;
                let inRight = false;

                for (let v = 0; v < 3; v ++) {
                    const val = vertexElem(geo, tri, v, splitDimIdx);

                    inLeft = inLeft || val >= avgtemp[splitDimStr];
                    inRight = inRight || val <= avgtemp[splitDimStr];
                }

                if (inLeft) left.push(tri);
                if (inRight) right.push(tri);
                if (inLeft && inRight) sharedCount ++;
            }

            if (sharedCount / tris.length >= maxMatchingTriangles) {
                node.tris = tris;
            } else {
                if (left.length)    queue.push(() => node.children.push(createNode(left)));
                if (right.length)   queue.push(() => node.children.push(createNode(right)));
            }

            return node;
        }

        const n = createNode(origTris);
        while (queue.length) queue.pop()();
        return n;
    }
}

export default TriangleBoundsTree;
<commit_msg>Clean up candidate collection<commit_after>import  * as THREE from '../node_modules/three/build/three.module.js'

// Settings
const maxLeafNodes = 10;
const maxMatchingTriangles = 0.5;

// Utilities
const getBufferGeometryVertexElem = (geo, tri, vert, elem) => {
    return geo.attributes.position.array[(geo.index ? geo.index.array[3 * tri + vert] : (3 * tri + vert)) * 3  + elem];
}

const getGeometryVertexElem = (geo, tri, vert, elem) => {
    return geo.faces[tri][abcFields[vert]][xyzFields[elem]];
}

const abcFields = ['a', 'b', 'c'];
const xyzFields = ['x', 'y', 'z'];
const getLongestEdgeIndex = bb => {
    let splitDimIdx = -1;
    let splitDist = -Infinity;
    xyzFields.forEach((d, i) => {
        const dist = bb.max[d] - bb.min[d];
        if (dist > splitDist) {
            splitDist = dist;
            splitDimIdx = i;
        }
    });
    return splitDimIdx;
}

// reusable vectors
const avgtemp = new THREE.Vector3();
const vectemp = new THREE.Vector3();
const centemp = new THREE.Vector3();

const getBounds = (tris, bounds, avg, geo, getValFunc) => {
    avg.set(0, 0, 0);

    for (let i = 0; i < tris.length; i ++) {
        const tri = tris[i];

        for (let v = 0; v < 3; v ++) {
            const x = getValFunc(geo, tri, v, 0);
            const y = getValFunc(geo, tri, v, 1);
            const z = getValFunc(geo, tri, v, 2);

            vectemp.x = x;
            vectemp.y = y;
            vectemp.z = z;
            bounds.expandByPoint(vectemp);

            avg.x += x;
            avg.y += y;
            avg.z += z;
        }
    }

    avg.x /= tris.length * 3;
    avg.y /= tris.length * 3;
    avg.z /= tris.length * 3;
}

const getSphere = (tris, sphere, geo, getValFunc) => {
    const center = sphere.center;
    let maxRadiusSq = 0;

    for (let i = 0; i < tris.length; i ++) {
        const tri = tris[i];

        for (let v = 0; v < 3; v ++) {
            const x = getValFunc(geo, tri, v, 0);
            const y = getValFunc(geo, tri, v, 1);
            const z = getValFunc(geo, tri, v, 2);

            vectemp.x = x;
            vectemp.y = y;
            vectemp.z = z;

            maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(vectemp));
        }
    }

    sphere.radius = Math.sqrt(maxRadiusSq);
}

// Classes
class TriangleBoundsNode {
    constructor() {
        this.boundingBox = new THREE.Box3();
        this.boundingSphere = new THREE.Sphere();
        this.children = [];
        this.tris = [];
    }
}

class TriangleBoundsTree {
    constructor(geo) {
        if (geo.isBufferGeometry || geo.isGeometry) {
            this._root = this._buildTree(geo);
        } else {
            throw new Error('Object is not Geometry or BufferGeometry');
        }
    }

    /* Public API */
    collectCandidates(origray) {
        const candidates = [];
        const recurse = (node, ray) => {

            if (!ray.intersectsSphere(node.boundingSphere) || !ray.intersectsBox(node.boundingBox)) return;

            if (node.children.length) node.children.forEach(c => recurse(c, ray))
            else candidates.push(...node.tris)
        }
        recurse(this._root, origray);

        return candidates;
    }

    /* Private Functions */
    _buildTree(geo) {
        const vertexElem = geo.isBufferGeometry ? getBufferGeometryVertexElem : getGeometryVertexElem;

        // a list of every available triangle index
        const origTris =
            geo.isBufferGeometry ?
                new Array(geo.index ? (geo.index.count / 3) : (pos.length / 9)) :
                Array(geo.faces.length);

        for (let i = 0; i < origTris.length; i ++) origTris[i] = i;

        // use a queue to run the node creation functions
        // because otherwise we run the risk of a stackoverflow
        // In the case of buffer geometry it also seems to be
        // faster than recursing
        const queue = [];
        const createNode = tris => {
            const node = new TriangleBoundsNode();

            // get the bounds of the triangles
            getBounds(tris, node.boundingBox, avgtemp, geo, vertexElem);
            node.boundingBox.getCenter(node.boundingSphere.center);
            getSphere(tris, node.boundingSphere, geo, vertexElem);

            if (tris.length <= maxLeafNodes) {
                node.tris = tris;
                return node;
            }

            // decide which axis to split on (longest edge)
            const splitDimIdx = getLongestEdgeIndex(node.boundingBox);
            const splitDimStr = xyzFields[splitDimIdx];

            const left = [], right = [];
            let sharedCount = 0;
            for (let i = 0; i < tris.length; i ++) {
                const tri = tris[i];

                let inLeft = false;
                let inRight = false;

                for (let v = 0; v < 3; v ++) {
                    const val = vertexElem(geo, tri, v, splitDimIdx);

                    inLeft = inLeft || val >= avgtemp[splitDimStr];
                    inRight = inRight || val <= avgtemp[splitDimStr];
                }

                if (inLeft) left.push(tri);
                if (inRight) right.push(tri);
                if (inLeft && inRight) sharedCount ++;
            }

            if (sharedCount / tris.length >= maxMatchingTriangles) {
                node.tris = tris;
            } else {
                if (left.length)    queue.push(() => node.children.push(createNode(left)));
                if (right.length)   queue.push(() => node.children.push(createNode(right)));
            }

            return node;
        }

        const n = createNode(origTris);
        while (queue.length) queue.pop()();
        return n;
    }
}

export default TriangleBoundsTree;
<|endoftext|>


<commit_before>// Function that provides map of rules found in ignorefiles for given ignorefile
// type. Additinally it invokes event on changes in map which are results of
// changes in ignorefiles.

'use strict';

var invoke    = require('es5-ext/lib/Function/invoke')
  , extend    = require('es5-ext/lib/Object/extend')
  , forEach   = require('es5-ext/lib/Object/for-each')
  , isCopy    = require('es5-ext/lib/Object/is-copy')
  , endsWith  = require('es5-ext/lib/String/prototype/ends-with')
  , deferred  = require('deferred')
  , path      = require('path')
  , findRoot  = require('./_find-root')
  , readFile  = require('./read-file').readFile

  , dirname = path.dirname, sep = path.sep
  , ConfMap, readRules, readRulesWatcher, paths, getMap, lockId = 0;

paths = function (root, path2) {
	var starter, data;
	if (root === path2) {
		return [root];
	}
	starter = [root];
	if (endsWith.call(root, sep)) {
		data = path2.slice(root.length).split(sep);
		starter.push(root += data.shift());
	} else {
		data = path2.slice(root.length + 1).split(sep);
	}
	return starter.concat(data.map(function (path) {
		return (root += sep + path);
	}));
};

readRules = function (path) {
	return this.readFile(path + sep + this.filename)(function (src) {
		return (src == null) ? src : this.parse(src, path);
	}.bind(this));
};
readRulesWatcher = function (path) {
	var watcher, promise, current;
	watcher = this.readFile(path + sep + this.filename);
	promise = watcher(function (src) {
		return (current = ((src == null) ? src : this.parse(src, path)));
	}.bind(this));
	watcher.on('change', function (data) {
		data = ((data == null) ? data : this.parse(data, path));
		if (!isCopy(current, data, Infinity)) {
			current = promise.value = data;
			promise.emit('change', current, path);
		}
	}.bind(this));
	promise.close = watcher.close;
	return promise;
};

ConfMap = function (path, watch) {
	this.path = path;
	this.watch = watch;
	this.data = { root: null, map: {} };
	extend(this, deferred());
	if (this.watch) {
		this.onRulesChange = this.onRulesChange.bind(this);
		this.rulePromises = {};
		this.promise.close = this.close.bind(this);
	}
};
ConfMap.prototype = {
	init: function (findRoot) {
		this.findRoot = findRoot;
		if (this.watch) {
			findRoot.on('change', this.updateRoot.bind(this));
		}
		findRoot.end(function (root) {
			if (root) {
				this.data.root = root;
				this.addPaths(root, this.path).end(function () {
					this.resolve(this.data);
				}.bind(this), this.resolve);
			} else {
				this.resolve(this.data);
			}
		}.bind(this), this.resolve);
		return this.promise;
	},
	close: function () {
		this.findRoot.close();
		forEach(this.rulePromises, invoke('close'));
		delete this.rulePromises;
	},
	parse: String,
	readFile: function (path) {
		return readFile(path, { loose: true, watch: this.watch });
	},
	onRulesChange: function (rules, path) {
		if (rules == null) {
			delete this.data.map[path];
		} else {
			this.data.map[path] = rules;
		}
		this.promise.emit('change', this.data);
	},
	addPaths: function (root, path) {
		return deferred.map(paths(root, path), function (path) {
			var rules = this.readRules(path);
			if (this.watch) {
				this.rulePromises[path] = rules;
				rules.on('change', this.onRulesChange);
			}
			return rules.aside(function (rules) {
				if (rules != null) {
					this[path] = rules;
				}
			}.bind(this.data.map))(null, function (err) {
				// Watcher might have been closed in a meantime, if it was we ignore
				// this error as we're not interested in that value anymore
				return this.rulePromises[path] ? err : null;
			}.bind(this));
		}, this);
	},
	removePaths: function (root, path) {
		paths(root, path).forEach(function (path) {
			var promise = this.rulePromises[path];
			delete this.rulePromises[path];
			delete this.data.map[path];
			promise.close();
		}, this);
	},
	updateRoot: function (root) {
		var lock = ++lockId;
		if (!root) {
			this.removePaths(this.data.root, this.path);
			this.data.root = null;
			this.promise.emit('change', this.data);
		} else if (!this.data.root) {
			this.data.root = root;
			this.addPaths(root, this.path).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
		} else if (this.data.root < root) {
			this.removePaths(this.data.root, dirname(root));
			this.data.root = root;
			this.promise.emit('change', this.data);
		} else {
			this.addPaths(root, dirname(this.data.root)).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
			this.data.root = root;
		}
	}
};

getMap = module.exports = function (path, mode, watch, parse) {
	var map = new ConfMap(path, watch);
	map.filename = mode.filename;
	map.readRules = watch ? readRulesWatcher : readRules;
	if (parse) {
		map.parse = parse;
	}
	return map.init(findRoot(watch ? mode.isRootWatcher : mode.isRoot,
		path, { watch: watch }));
};
getMap.ConfMap = ConfMap;
getMap.readRules = readRules;
getMap.readRulesWatcher = readRulesWatcher;
<commit_msg>Algorithm cleanup<commit_after>// Function that provides map of rules found in ignorefiles for given ignorefile
// type. Additinally it invokes event on changes in map which are results of
// changes in ignorefiles.

'use strict';

var invoke    = require('es5-ext/lib/Function/invoke')
  , extend    = require('es5-ext/lib/Object/extend')
  , forEach   = require('es5-ext/lib/Object/for-each')
  , isCopy    = require('es5-ext/lib/Object/is-copy')
  , endsWith  = require('es5-ext/lib/String/prototype/ends-with')
  , deferred  = require('deferred')
  , path      = require('path')
  , findRoot  = require('./_find-root')
  , readFile  = require('./read-file').readFile

  , dirname = path.dirname, sep = path.sep
  , ConfMap, readRules, readRulesWatcher, paths, getMap, lockId = 0;

paths = function (root, path2) {
	var starter, data;
	starter = [root];
	if (root === path2) {
		return starter;
	}
	if (endsWith.call(root, sep)) {
		data = path2.slice(root.length).split(sep);
		starter.push(root += data.shift());
	} else {
		data = path2.slice(root.length + 1).split(sep);
	}
	return starter.concat(data.map(function (path) {
		return (root += sep + path);
	}));
};

readRules = function (path) {
	return this.readFile(path + sep + this.filename)(function (src) {
		return (src == null) ? src : this.parse(src, path);
	}.bind(this));
};
readRulesWatcher = function (path) {
	var watcher, promise, current;
	watcher = this.readFile(path + sep + this.filename);
	promise = watcher(function (src) {
		return (current = ((src == null) ? src : this.parse(src, path)));
	}.bind(this));
	watcher.on('change', function (data) {
		data = ((data == null) ? data : this.parse(data, path));
		if (!isCopy(current, data, Infinity)) {
			current = promise.value = data;
			promise.emit('change', current, path);
		}
	}.bind(this));
	promise.close = watcher.close;
	return promise;
};

ConfMap = function (path, watch) {
	this.path = path;
	this.watch = watch;
	this.data = { root: null, map: {} };
	extend(this, deferred());
	if (this.watch) {
		this.onRulesChange = this.onRulesChange.bind(this);
		this.rulePromises = {};
		this.promise.close = this.close.bind(this);
	}
};
ConfMap.prototype = {
	init: function (findRoot) {
		this.findRoot = findRoot;
		if (this.watch) {
			findRoot.on('change', this.updateRoot.bind(this));
		}
		findRoot.end(function (root) {
			if (root) {
				this.data.root = root;
				this.addPaths(root, this.path).end(function () {
					this.resolve(this.data);
				}.bind(this), this.resolve);
			} else {
				this.resolve(this.data);
			}
		}.bind(this), this.resolve);
		return this.promise;
	},
	close: function () {
		if (this.rulePromises) {
			this.findRoot.close();
			forEach(this.rulePromises, invoke('close'));
			delete this.rulePromises;
		}
	},
	parse: String,
	readFile: function (path) {
		return readFile(path, { loose: true, watch: this.watch });
	},
	onRulesChange: function (rules, path) {
		if (rules == null) {
			delete this.data.map[path];
		} else {
			this.data.map[path] = rules;
		}
		this.promise.emit('change', this.data);
	},
	addPaths: function (root, path) {
		return deferred.map(paths(root, path), function (path) {
			var rules = this.readRules(path);
			if (this.watch) {
				this.rulePromises[path] = rules;
				rules.on('change', this.onRulesChange);
			}
			return rules.aside(function (rules) {
				if (rules != null) {
					this[path] = rules;
				}
			}.bind(this.data.map))(null, function (err) {
				// Watcher might have been closed in a meantime, if it was we ignore
				// this error as we're not interested in that value anymore
				return this.rulePromises[path] ? err : null;
			}.bind(this));
		}, this);
	},
	removePaths: function (root, path) {
		paths(root, path).forEach(function (path) {
			var promise = this.rulePromises[path];
			delete this.rulePromises[path];
			delete this.data.map[path];
			promise.close();
		}, this);
	},
	updateRoot: function (root) {
		var lock = ++lockId;
		if (!root) {
			this.removePaths(this.data.root, this.path);
			this.data.root = null;
			this.promise.emit('change', this.data);
		} else if (!this.data.root) {
			this.data.root = root;
			this.addPaths(root, this.path).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
		} else if (this.data.root < root) {
			this.removePaths(this.data.root, dirname(root));
			this.data.root = root;
			this.promise.emit('change', this.data);
		} else {
			this.addPaths(root, dirname(this.data.root)).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
			this.data.root = root;
		}
	}
};

getMap = module.exports = function (path, mode, watch, parse) {
	var map = new ConfMap(path, watch);
	map.filename = mode.filename;
	map.readRules = watch ? readRulesWatcher : readRules;
	if (parse) {
		map.parse = parse;
	}
	return map.init(findRoot(watch ? mode.isRootWatcher : mode.isRoot,
		path, { watch: watch }));
};
getMap.ConfMap = ConfMap;
getMap.readRules = readRules;
getMap.readRulesWatcher = readRulesWatcher;
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.10.0
var _app, fs, getViewDir, path, pug, setViewDir;

fs = require('fs');

path = require('path');

pug = require('pug');

module.exports.pug = pug;

_app = null;

setViewDir = (function(_this) {
  return function(path) {
    if (_app == null) {
      return;
    }
    _app.set('views', path);
    return fs.stat(viewsPath, function(e, stat) {
      if (e) {
        console.log("views directory not found at " + viewsPath + ". creating");
        return fs.mkDir(viewsPath, function(e, res) {
          if (e != null) {
            return console.log(e);
          }
        });
      }
    });
  };
})(this);

getViewDir = (function(_this) {
  return function() {
    if (_app == null) {
      return null;
    }
    return _app.get('views');
  };
})(this);

module.exports.setViewDir = setViewDir;

module.exports.getViewDir = getViewDir;

module.exports.init = function(app, options, callback) {
  var cB, viewsPath;
  if (typeof (cB = arguments[arguments.length - 1]) !== 'function') {
    throw "apihero-module-pug::init - callback required";
  }
  _app = app;
  if (!((options != null) && typeof options === 'object')) {
    options = {};
  }
  if ((viewsPath = options.hasOwnProperty('viewsPath') ? options.viewsPath : app.get('views')) == null) {
    return setViewsDir(path.join(app_root, 'views'));
  }
};
<commit_msg>updated build<commit_after>// Generated by CoffeeScript 1.10.0
var _app, fs, getViewDir, path, pug, setViewDir;

fs = require('fs');

path = require('path');

pug = require('pug');

module.exports.pug = pug;

_app = null;

setViewDir = (function(_this) {
  return function(viewsPath, callback) {
    if (_app == null) {
      return;
    }
    console.log("seeting: " + viewsPath);
    _app.set('views', path);
    return fs.stat(viewsPath, function(e, stat) {
      if (e) {
        console.log("views directory not found at " + viewsPath + ". creating");
        fs.mkDir(viewsPath, function(e, res) {
          if (e != null) {
            return console.log(e);
          }
        });
      }
      return callback();
    });
  };
})(this);

getViewDir = (function(_this) {
  return function() {
    if (_app == null) {
      return null;
    }
    return _app.get('views');
  };
})(this);

module.exports.setViewDir = setViewDir;

module.exports.getViewDir = getViewDir;

module.exports.init = function(app, options, callback) {
  var cB, viewsPath;
  if (typeof (cB = arguments[arguments.length - 1]) !== 'function') {
    throw "apihero-module-pug::init - callback required";
  }
  _app = app;
  if (!((options != null) && typeof options === 'object')) {
    options = {};
  }
  viewsPath = options.hasOwnProperty('viewsPath') ? options.viewsPath : app.get('views');
  if (viewsPath) {
    return callback(null);
  } else {
    return setViewsDir(path.join(app_root, 'views'), callback);
  }
};
<|endoftext|>


<commit_before>'use strict';

var modelos = require('modelos');
var slugify = require('slugify');
var salvarServico = require('xml/salvar');
var carregarServico = require('xml/carregar');
var validacoes = require('validacoes');
//var limparModelo = require('limpar-modelo');

var modificado = m.prop(false);

module.exports = {

  controller: function () {
    this.cabecalho = new modelos.Cabecalho();
    this.servico = carregarServico(m.route.param('id'), this.cabecalho);

    this.salvar = function () {
      if (validacoes.valida(this.servico().nome)) {
        return salvarServico(this.servico, this.cabecalho.metadados)
          .then(_.bind(this.cabecalho.limparErro, this.cabecalho))
          .then(function () {
            modificado(false);
          }).then(function () {
            var oldId = m.route.param('id');
            var newId = slugify(this.servico().nome());
            if (!_.isEqual(oldId, newId)) {
              m.route('/editar/servico/' + newId);
            }
          }.bind(this));
      } else {
        return m.deferred().reject(this.servico().nome.erro()).promise;
      }
    };

    this.publicar = function () {
      //this.servico(limparModelo(this.servico()));
      var id = this.servico().id;
      if (validacoes.valida(this.servico())) {
          return this.salvar().then(function() {
              m.request({
                  method: 'PUT',
                  url: '/editar/api/servico/' + id
              });
          });
      } else {
        return false;
      }
    };
  },

  view: function (ctrl) {
    var binding = {
      servico: ctrl.servico,
      novo: m.route.param('id') === 'novo'
    };

    return m('#conteudo', {
      config: function (element, isInitialized) {
        if (isInitialized) {
          return;
        }

        jQuery(element).on('change', function () {
          modificado(true);
        });

        jQuery(window).bind('beforeunload', function () {
          if (modificado()) {
            return 'Suas últimas alterações ainda não foram salvas.';
          }
        });
      }
    }, [
      m('span.cabecalho-cor'),
      m('#wrapper', [
        m.component(require('componentes/cabecalho'), {
          salvar: _.bind(ctrl.salvar, ctrl),
          publicar: _.bind(ctrl.publicar, ctrl),
          cabecalho: ctrl.cabecalho
        }),
        m.component(require('componentes/menu-lateral'), binding),

        m('#servico', m('.scroll', [
          m.component(require('componentes/dados-basicos'), binding),
          m.component(require('componentes/solicitantes'), binding),
          m.component(require('componentes/etapas'), binding),
          m.component(require('componentes/outras-informacoes'), binding),
        ]))
      ])
    ]);
  }
};
<commit_msg>Remove comentário do código de validação - #282<commit_after>'use strict';

var modelos = require('modelos');
var slugify = require('slugify');
var salvarServico = require('xml/salvar');
var carregarServico = require('xml/carregar');
var validacoes = require('validacoes');
var limparModelo = require('limpar-modelo');

var modificado = m.prop(false);

module.exports = {

  controller: function () {
    this.cabecalho = new modelos.Cabecalho();
    this.servico = carregarServico(m.route.param('id'), this.cabecalho);

    this.salvar = function () {
      if (validacoes.valida(this.servico().nome)) {
        return salvarServico(this.servico, this.cabecalho.metadados)
          .then(_.bind(this.cabecalho.limparErro, this.cabecalho))
          .then(function () {
            modificado(false);
          }).then(function () {
            var oldId = m.route.param('id');
            var newId = slugify(this.servico().nome());
            if (!_.isEqual(oldId, newId)) {
              m.route('/editar/servico/' + newId);
            }
          }.bind(this));
      } else {
        return m.deferred().reject(this.servico().nome.erro()).promise;
      }
    };

    this.publicar = function () {
      this.servico(limparModelo(this.servico()));
      var id = this.servico().id;
      if (validacoes.valida(this.servico())) {
          return this.salvar().then(function() {
              m.request({
                  method: 'PUT',
                  url: '/editar/api/servico/' + id
              });
          });
      } else {
        return false;
      }
    };
  },

  view: function (ctrl) {
    var binding = {
      servico: ctrl.servico,
      novo: m.route.param('id') === 'novo'
    };

    return m('#conteudo', {
      config: function (element, isInitialized) {
        if (isInitialized) {
          return;
        }

        jQuery(element).on('change', function () {
          modificado(true);
        });

        jQuery(window).bind('beforeunload', function () {
          if (modificado()) {
            return 'Suas últimas alterações ainda não foram salvas.';
          }
        });
      }
    }, [
      m('span.cabecalho-cor'),
      m('#wrapper', [
        m.component(require('componentes/cabecalho'), {
          salvar: _.bind(ctrl.salvar, ctrl),
          publicar: _.bind(ctrl.publicar, ctrl),
          cabecalho: ctrl.cabecalho
        }),
        m.component(require('componentes/menu-lateral'), binding),

        m('#servico', m('.scroll', [
          m.component(require('componentes/dados-basicos'), binding),
          m.component(require('componentes/solicitantes'), binding),
          m.component(require('componentes/etapas'), binding),
          m.component(require('componentes/outras-informacoes'), binding),
        ]))
      ])
    ]);
  }
};
<|endoftext|>


<commit_before>const Model = require('../../mongoose/model');
const {Schema} = require('mongoose');

class User extends Model {

    static get $options() {
        return {strict: false};
    };

    static get $visible() {
        return ['_id', 'name', 'username', 'email', 'avatar'];
    }

    static get $schema() {
        return {
            username: {type: String, index: true, sparse: true, unique: true},
            email: {type: String, index: true, sparse: true, unique: true},
            password: {type: String},
            avatar_etag: {type: String},
            name: {type: String},
            is_banned: {type: Boolean},
            meta: {type: Object},
            roles: {type: Array},
            sessions: [
                {
                    _agent: {type: String},
                    _ip: {type: String},
                    _client: {type: Schema.Types.ObjectId},
                    created_at: {type: Date, default: Date.now}
                }
            ]
        };
    }

    get is_disabled() {
        return this.get('enabled') === false || this.get('blocked') === true
    }

    afterLogin({request,session}) {

    }

    afterLogout({request,session}) {

    }

}

module.exports = User;
<commit_msg>[auth model] scope<commit_after>const Model = require('../../mongoose/model');
const {Schema} = require('mongoose');

class User extends Model {

    static get $options() {
        return {strict: false};
    };

    static get $visible() {
        return ['_id', 'name', 'username', 'email', 'avatar', 'scope'];
    }

    static get $schema() {
        return {
            username: {type: String, index: true, sparse: true, unique: true},
            email: {type: String, index: true, sparse: true, unique: true},
            password: {type: String},
            avatar_etag: {type: String},
            name: {type: String},
            is_banned: {type: Boolean},
            meta: {type: Object},
            scope: {type: Array},
            sessions: [
                {
                    _agent: {type: String},
                    _ip: {type: String},
                    _client: {type: Schema.Types.ObjectId},
                    created_at: {type: Date, default: Date.now}
                }
            ]
        };
    }

    get is_disabled() {
        return this.get('enabled') === false || this.get('blocked') === true
    }

    afterLogin({request, session}) {

    }

    afterLogout({request, session}) {

    }

}

module.exports = User;
<|endoftext|>


<commit_before>'use strict'

const {Buffer} = require('buffer')
const electron = require('electron')
const v8Util = process.atomBinding('v8_util')
const {ipcMain, isPromise, webContents} = electron

const fs = require('fs')

const objectsRegistry = require('./objects-registry')

const hasProp = {}.hasOwnProperty

// The internal properties of Function.
const FUNCTION_PROPERTIES = [
  'length', 'name', 'arguments', 'caller', 'prototype'
]

// The remote functions in renderer processes.
// id => Function
let rendererFunctions = v8Util.createDoubleIDWeakMap()

// Return the description of object's members:
let getObjectMembers = function (object) {
  let names = Object.getOwnPropertyNames(object)
  // For Function, we should not override following properties even though they
  // are "own" properties.
  if (typeof object === 'function') {
    names = names.filter((name) => {
      return !FUNCTION_PROPERTIES.includes(name)
    })
  }
  // Map properties to descriptors.
  return names.map((name) => {
    let descriptor = Object.getOwnPropertyDescriptor(object, name)
    let member = {name, enumerable: descriptor.enumerable, writable: false}
    if (descriptor.get === undefined && typeof object[name] === 'function') {
      member.type = 'method'
    } else {
      if (descriptor.set || descriptor.writable) member.writable = true
      member.type = 'get'
    }
    return member
  })
}

// Return the description of object's prototype.
let getObjectPrototype = function (object) {
  let proto = Object.getPrototypeOf(object)
  if (proto === null || proto === Object.prototype) return null
  return {
    members: getObjectMembers(proto),
    proto: getObjectPrototype(proto)
  }
}

// Convert a real value into meta data.
let valueToMeta = function (sender, value, optimizeSimpleObject = false) {
  // Determine the type of value.
  const meta = { type: typeof value }
  if (meta.type === 'object') {
    // Recognize certain types of objects.
    if (value === null) {
      meta.type = 'value'
    } else if (ArrayBuffer.isView(value)) {
      meta.type = 'buffer'
    } else if (Array.isArray(value)) {
      meta.type = 'array'
    } else if (value instanceof Error) {
      meta.type = 'error'
    } else if (value instanceof Date) {
      meta.type = 'date'
    } else if (isPromise(value)) {
      meta.type = 'promise'
    } else if (hasProp.call(value, 'callee') && value.length != null) {
      // Treat the arguments object as array.
      meta.type = 'array'
    } else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) {
      // Treat simple objects as value.
      meta.type = 'value'
    }
  }

  // Fill the meta object according to value's type.
  if (meta.type === 'array') {
    meta.members = value.map((el) => valueToMeta(sender, el))
  } else if (meta.type === 'object' || meta.type === 'function') {
    meta.name = value.constructor ? value.constructor.name : ''

    // Reference the original value if it's an object, because when it's
    // passed to renderer we would assume the renderer keeps a reference of
    // it.
    meta.id = objectsRegistry.add(sender, value)
    meta.members = getObjectMembers(value)
    meta.proto = getObjectPrototype(value)
  } else if (meta.type === 'buffer') {
    meta.value = Buffer.from(value)
  } else if (meta.type === 'promise') {
    // Add default handler to prevent unhandled rejections in main process
    // Instead they should appear in the renderer process
    value.then(function () {}, function () {})

    meta.then = valueToMeta(sender, function (onFulfilled, onRejected) {
      value.then(onFulfilled, onRejected)
    })
  } else if (meta.type === 'error') {
    meta.members = plainObjectToMeta(value)

    // Error.name is not part of own properties.
    meta.members.push({
      name: 'name',
      value: value.name
    })
  } else if (meta.type === 'date') {
    meta.value = value.getTime()
  } else {
    meta.type = 'value'
    meta.value = value
  }
  return meta
}

// Convert object to meta by value.
const plainObjectToMeta = function (obj) {
  return Object.getOwnPropertyNames(obj).map(function (name) {
    return {
      name: name,
      value: obj[name]
    }
  })
}

// Convert Error into meta data.
const exceptionToMeta = function (error) {
  return {
    type: 'exception',
    message: error.message,
    stack: error.stack || error
  }
}

const throwRPCError = function (message) {
  const error = new Error(message)
  error.code = 'EBADRPC'
  error.errno = -72
  throw error
}

const removeRemoteListenersAndLogWarning = (meta, args, callIntoRenderer) => {
  let message = `Attempting to call a function in a renderer window that has been closed or released.` +
    `\nFunction provided here: ${meta.location}`

  if (args.length === 0) return message
  if (!args[0].sender || !args[0].sender.eventNames) return message

  const sender = args[0].sender
  const remoteEvents = sender.eventNames().filter((eventName) => {
    return sender.listeners(eventName).includes(callIntoRenderer)
  })

  if (remoteEvents.length > 0) {
    message += `\nRemote event names: ${remoteEvents.join(', ')}`
    remoteEvents.forEach((eventName) => {
      sender.removeListener(eventName, callIntoRenderer)
    })
  }

  return message
}

// Convert array of meta data from renderer into array of real values.
const unwrapArgs = function (sender, args) {
  const metaToValue = function (meta) {
    let i, len, member, ref, returnValue
    switch (meta.type) {
      case 'value':
        return meta.value
      case 'remote-object':
        return objectsRegistry.get(meta.id)
      case 'array':
        return unwrapArgs(sender, meta.value)
      case 'buffer':
        return Buffer.from(meta.value)
      case 'date':
        return new Date(meta.value)
      case 'promise':
        return Promise.resolve({
          then: metaToValue(meta.then)
        })
      case 'object': {
        let ret = {}
        Object.defineProperty(ret.constructor, 'name', { value: meta.name })

        ref = meta.members
        for (i = 0, len = ref.length; i < len; i++) {
          member = ref[i]
          ret[member.name] = metaToValue(member.value)
        }
        return ret
      }
      case 'function-with-return-value':
        returnValue = metaToValue(meta.value)
        return function () {
          return returnValue
        }
      case 'function': {
        // Merge webContentsId and meta.id, since meta.id can be the same in
        // different webContents.
        const webContentsId = sender.getId()
        const objectId = [webContentsId, meta.id]

        // Cache the callbacks in renderer.
        if (rendererFunctions.has(objectId)) {
          return rendererFunctions.get(objectId)
        }

        let callIntoRenderer = function (...args) {
          if (!sender.isDestroyed() && webContentsId === sender.getId()) {
            sender.send('ELECTRON_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args))
          } else {
            console.warn(removeRemoteListenersAndLogWarning(meta, args, callIntoRenderer))
          }
        }

        v8Util.setRemoteCallbackFreer(callIntoRenderer, meta.id, sender)
        rendererFunctions.set(objectId, callIntoRenderer)
        return callIntoRenderer
      }
      default:
        throw new TypeError(`Unknown type: ${meta.type}`)
    }
  }
  return args.map(metaToValue)
}

// Call a function and send reply asynchronously if it's a an asynchronous
// style function and the caller didn't pass a callback.
const callFunction = function (event, func, caller, args) {
  let funcMarkedAsync, funcName, funcPassedCallback, ref, ret
  funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous')
  funcPassedCallback = typeof args[args.length - 1] === 'function'
  try {
    if (funcMarkedAsync && !funcPassedCallback) {
      args.push(function (ret) {
        event.returnValue = valueToMeta(event.sender, ret, true)
      })
      func.apply(caller, args)
    } else {
      ret = func.apply(caller, args)
      event.returnValue = valueToMeta(event.sender, ret, true)
    }
  } catch (error) {
    // Catch functions thrown further down in function invocation and wrap
    // them with the function name so it's easier to trace things like
    // `Error processing argument -1.`
    funcName = ((ref = func.name) != null) ? ref : 'anonymous'
    throw new Error(`Could not call remote function '${funcName}'. Check that the function signature is correct. Underlying error: ${error.message}`)
  }
}

ipcMain.on('ELECTRON_BROWSER_REQUIRE', function (event, module) {
  try {
    event.returnValue = valueToMeta(event.sender, process.mainModule.require(module))
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_READ_FILE', function (event, file) {
  fs.readFile(file, (err, data) => {
    if (err) event.returnValue = {err: err.message}
    else event.returnValue = {data: data.toString()}
  })
})

ipcMain.on('ELECTRON_BROWSER_GET_BUILTIN', function (event, module) {
  try {
    event.returnValue = valueToMeta(event.sender, electron[module])
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_GLOBAL', function (event, name) {
  try {
    event.returnValue = valueToMeta(event.sender, global[name])
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_CURRENT_WINDOW', function (event) {
  try {
    event.returnValue = valueToMeta(event.sender, event.sender.getOwnerBrowserWindow())
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_CURRENT_WEB_CONTENTS', function (event) {
  event.returnValue = valueToMeta(event.sender, event.sender)
})

ipcMain.on('ELECTRON_BROWSER_CONSTRUCTOR', function (event, id, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let constructor = objectsRegistry.get(id)

    if (constructor == null) {
      throwRPCError(`Cannot call constructor on missing remote object ${id}`)
    }

    // Call new with array of arguments.
    // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
    let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)))()
    event.returnValue = valueToMeta(event.sender, obj)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_FUNCTION_CALL', function (event, id, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let func = objectsRegistry.get(id)

    if (func == null) {
      throwRPCError(`Cannot call function on missing remote object ${id}`)
    }

    callFunction(event, func, global, args)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let object = objectsRegistry.get(id)

    if (object == null) {
      throwRPCError(`Cannot call constructor '${method}' on missing remote object ${id}`)
    }

    // Call new with array of arguments.
    let constructor = object[method]
    let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)))()
    event.returnValue = valueToMeta(event.sender, obj)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_CALL', function (event, id, method, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let obj = objectsRegistry.get(id)

    if (obj == null) {
      throwRPCError(`Cannot call function '${method}' on missing remote object ${id}`)
    }

    callFunction(event, obj[method], obj, args)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_SET', function (event, id, name, value) {
  try {
    let obj = objectsRegistry.get(id)

    if (obj == null) {
      throwRPCError(`Cannot set property '${name}' on missing remote object ${id}`)
    }

    obj[name] = value
    event.returnValue = null
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_GET', function (event, id, name) {
  try {
    let obj = objectsRegistry.get(id)

    if (obj == null) {
      throwRPCError(`Cannot get property '${name}' on missing remote object ${id}`)
    }

    event.returnValue = valueToMeta(event.sender, obj[name])
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_DEREFERENCE', function (event, id) {
  objectsRegistry.remove(event.sender.getId(), id)
})

ipcMain.on('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) {
  try {
    let guestViewManager = require('./guest-view-manager')
    event.returnValue = valueToMeta(event.sender, guestViewManager.getGuest(guestInstanceId))
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, ...args) {
  try {
    let guestViewManager = require('./guest-view-manager')
    let guest = guestViewManager.getGuest(guestInstanceId)
    if (requestId) {
      const responseCallback = function (result) {
        event.sender.send(`ELECTRON_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result)
      }
      args.push(responseCallback)
    }
    guest[method].apply(guest, args)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_SEND_TO', function (event, sendToAll, webContentsId, channel, ...args) {
  let contents = webContents.fromId(webContentsId)
  if (!contents) {
    console.error(`Sending message to WebContents with unknown ID ${webContentsId}`)
    return
  }

  if (sendToAll) {
    contents.sendToAll(channel, ...args)
  } else {
    contents.send(channel, ...args)
  }
})

// Implements window.alert(message, title)
ipcMain.on('ELECTRON_BROWSER_WINDOW_ALERT', function (event, message, title) {
  if (message == null) message = ''
  if (title == null) title = ''

  event.returnValue = electron.dialog.showMessageBox(event.sender.getOwnerBrowserWindow(), {
    message: `${message}`,
    title: `${title}`,
    buttons: ['OK']
  })
})

// Implements window.confirm(message, title)
ipcMain.on('ELECTRON_BROWSER_WINDOW_CONFIRM', function (event, message, title) {
  if (message == null) message = ''
  if (title == null) title = ''

  event.returnValue = !electron.dialog.showMessageBox(event.sender.getOwnerBrowserWindow(), {
    message: `${message}`,
    title: `${title}`,
    buttons: ['OK', 'Cancel'],
    cancelId: 1
  })
})

// Implements window.close()
ipcMain.on('ELECTRON_BROWSER_WINDOW_CLOSE', function (event) {
  event.sender.getOwnerBrowserWindow().close()
  event.returnValue = null
})
<commit_msg>Move console.warn inside the helper method.<commit_after>'use strict'

const {Buffer} = require('buffer')
const electron = require('electron')
const v8Util = process.atomBinding('v8_util')
const {ipcMain, isPromise, webContents} = electron

const fs = require('fs')

const objectsRegistry = require('./objects-registry')

const hasProp = {}.hasOwnProperty

// The internal properties of Function.
const FUNCTION_PROPERTIES = [
  'length', 'name', 'arguments', 'caller', 'prototype'
]

// The remote functions in renderer processes.
// id => Function
let rendererFunctions = v8Util.createDoubleIDWeakMap()

// Return the description of object's members:
let getObjectMembers = function (object) {
  let names = Object.getOwnPropertyNames(object)
  // For Function, we should not override following properties even though they
  // are "own" properties.
  if (typeof object === 'function') {
    names = names.filter((name) => {
      return !FUNCTION_PROPERTIES.includes(name)
    })
  }
  // Map properties to descriptors.
  return names.map((name) => {
    let descriptor = Object.getOwnPropertyDescriptor(object, name)
    let member = {name, enumerable: descriptor.enumerable, writable: false}
    if (descriptor.get === undefined && typeof object[name] === 'function') {
      member.type = 'method'
    } else {
      if (descriptor.set || descriptor.writable) member.writable = true
      member.type = 'get'
    }
    return member
  })
}

// Return the description of object's prototype.
let getObjectPrototype = function (object) {
  let proto = Object.getPrototypeOf(object)
  if (proto === null || proto === Object.prototype) return null
  return {
    members: getObjectMembers(proto),
    proto: getObjectPrototype(proto)
  }
}

// Convert a real value into meta data.
let valueToMeta = function (sender, value, optimizeSimpleObject = false) {
  // Determine the type of value.
  const meta = { type: typeof value }
  if (meta.type === 'object') {
    // Recognize certain types of objects.
    if (value === null) {
      meta.type = 'value'
    } else if (ArrayBuffer.isView(value)) {
      meta.type = 'buffer'
    } else if (Array.isArray(value)) {
      meta.type = 'array'
    } else if (value instanceof Error) {
      meta.type = 'error'
    } else if (value instanceof Date) {
      meta.type = 'date'
    } else if (isPromise(value)) {
      meta.type = 'promise'
    } else if (hasProp.call(value, 'callee') && value.length != null) {
      // Treat the arguments object as array.
      meta.type = 'array'
    } else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) {
      // Treat simple objects as value.
      meta.type = 'value'
    }
  }

  // Fill the meta object according to value's type.
  if (meta.type === 'array') {
    meta.members = value.map((el) => valueToMeta(sender, el))
  } else if (meta.type === 'object' || meta.type === 'function') {
    meta.name = value.constructor ? value.constructor.name : ''

    // Reference the original value if it's an object, because when it's
    // passed to renderer we would assume the renderer keeps a reference of
    // it.
    meta.id = objectsRegistry.add(sender, value)
    meta.members = getObjectMembers(value)
    meta.proto = getObjectPrototype(value)
  } else if (meta.type === 'buffer') {
    meta.value = Buffer.from(value)
  } else if (meta.type === 'promise') {
    // Add default handler to prevent unhandled rejections in main process
    // Instead they should appear in the renderer process
    value.then(function () {}, function () {})

    meta.then = valueToMeta(sender, function (onFulfilled, onRejected) {
      value.then(onFulfilled, onRejected)
    })
  } else if (meta.type === 'error') {
    meta.members = plainObjectToMeta(value)

    // Error.name is not part of own properties.
    meta.members.push({
      name: 'name',
      value: value.name
    })
  } else if (meta.type === 'date') {
    meta.value = value.getTime()
  } else {
    meta.type = 'value'
    meta.value = value
  }
  return meta
}

// Convert object to meta by value.
const plainObjectToMeta = function (obj) {
  return Object.getOwnPropertyNames(obj).map(function (name) {
    return {
      name: name,
      value: obj[name]
    }
  })
}

// Convert Error into meta data.
const exceptionToMeta = function (error) {
  return {
    type: 'exception',
    message: error.message,
    stack: error.stack || error
  }
}

const throwRPCError = function (message) {
  const error = new Error(message)
  error.code = 'EBADRPC'
  error.errno = -72
  throw error
}

const removeRemoteListenersAndLogWarning = (meta, args, callIntoRenderer) => {
  let message = `Attempting to call a function in a renderer window that has been closed or released.` +
    `\nFunction provided here: ${meta.location}`

  if (args.length > 0 && args[0].sender && args[0].sender.eventNames) {
    const sender = args[0].sender
    const remoteEvents = sender.eventNames().filter((eventName) => {
      return sender.listeners(eventName).includes(callIntoRenderer)
    })

    if (remoteEvents.length > 0) {
      message += `\nRemote event names: ${remoteEvents.join(', ')}`
      remoteEvents.forEach((eventName) => {
        sender.removeListener(eventName, callIntoRenderer)
      })
    }
  }

  console.warn(message)
}

// Convert array of meta data from renderer into array of real values.
const unwrapArgs = function (sender, args) {
  const metaToValue = function (meta) {
    let i, len, member, ref, returnValue
    switch (meta.type) {
      case 'value':
        return meta.value
      case 'remote-object':
        return objectsRegistry.get(meta.id)
      case 'array':
        return unwrapArgs(sender, meta.value)
      case 'buffer':
        return Buffer.from(meta.value)
      case 'date':
        return new Date(meta.value)
      case 'promise':
        return Promise.resolve({
          then: metaToValue(meta.then)
        })
      case 'object': {
        let ret = {}
        Object.defineProperty(ret.constructor, 'name', { value: meta.name })

        ref = meta.members
        for (i = 0, len = ref.length; i < len; i++) {
          member = ref[i]
          ret[member.name] = metaToValue(member.value)
        }
        return ret
      }
      case 'function-with-return-value':
        returnValue = metaToValue(meta.value)
        return function () {
          return returnValue
        }
      case 'function': {
        // Merge webContentsId and meta.id, since meta.id can be the same in
        // different webContents.
        const webContentsId = sender.getId()
        const objectId = [webContentsId, meta.id]

        // Cache the callbacks in renderer.
        if (rendererFunctions.has(objectId)) {
          return rendererFunctions.get(objectId)
        }

        let callIntoRenderer = function (...args) {
          if (!sender.isDestroyed() && webContentsId === sender.getId()) {
            sender.send('ELECTRON_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args))
          } else {
            removeRemoteListenersAndLogWarning(meta, args, callIntoRenderer)
          }
        }

        v8Util.setRemoteCallbackFreer(callIntoRenderer, meta.id, sender)
        rendererFunctions.set(objectId, callIntoRenderer)
        return callIntoRenderer
      }
      default:
        throw new TypeError(`Unknown type: ${meta.type}`)
    }
  }
  return args.map(metaToValue)
}

// Call a function and send reply asynchronously if it's a an asynchronous
// style function and the caller didn't pass a callback.
const callFunction = function (event, func, caller, args) {
  let funcMarkedAsync, funcName, funcPassedCallback, ref, ret
  funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous')
  funcPassedCallback = typeof args[args.length - 1] === 'function'
  try {
    if (funcMarkedAsync && !funcPassedCallback) {
      args.push(function (ret) {
        event.returnValue = valueToMeta(event.sender, ret, true)
      })
      func.apply(caller, args)
    } else {
      ret = func.apply(caller, args)
      event.returnValue = valueToMeta(event.sender, ret, true)
    }
  } catch (error) {
    // Catch functions thrown further down in function invocation and wrap
    // them with the function name so it's easier to trace things like
    // `Error processing argument -1.`
    funcName = ((ref = func.name) != null) ? ref : 'anonymous'
    throw new Error(`Could not call remote function '${funcName}'. Check that the function signature is correct. Underlying error: ${error.message}`)
  }
}

ipcMain.on('ELECTRON_BROWSER_REQUIRE', function (event, module) {
  try {
    event.returnValue = valueToMeta(event.sender, process.mainModule.require(module))
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_READ_FILE', function (event, file) {
  fs.readFile(file, (err, data) => {
    if (err) event.returnValue = {err: err.message}
    else event.returnValue = {data: data.toString()}
  })
})

ipcMain.on('ELECTRON_BROWSER_GET_BUILTIN', function (event, module) {
  try {
    event.returnValue = valueToMeta(event.sender, electron[module])
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_GLOBAL', function (event, name) {
  try {
    event.returnValue = valueToMeta(event.sender, global[name])
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_CURRENT_WINDOW', function (event) {
  try {
    event.returnValue = valueToMeta(event.sender, event.sender.getOwnerBrowserWindow())
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_CURRENT_WEB_CONTENTS', function (event) {
  event.returnValue = valueToMeta(event.sender, event.sender)
})

ipcMain.on('ELECTRON_BROWSER_CONSTRUCTOR', function (event, id, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let constructor = objectsRegistry.get(id)

    if (constructor == null) {
      throwRPCError(`Cannot call constructor on missing remote object ${id}`)
    }

    // Call new with array of arguments.
    // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
    let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)))()
    event.returnValue = valueToMeta(event.sender, obj)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_FUNCTION_CALL', function (event, id, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let func = objectsRegistry.get(id)

    if (func == null) {
      throwRPCError(`Cannot call function on missing remote object ${id}`)
    }

    callFunction(event, func, global, args)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let object = objectsRegistry.get(id)

    if (object == null) {
      throwRPCError(`Cannot call constructor '${method}' on missing remote object ${id}`)
    }

    // Call new with array of arguments.
    let constructor = object[method]
    let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)))()
    event.returnValue = valueToMeta(event.sender, obj)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_CALL', function (event, id, method, args) {
  try {
    args = unwrapArgs(event.sender, args)
    let obj = objectsRegistry.get(id)

    if (obj == null) {
      throwRPCError(`Cannot call function '${method}' on missing remote object ${id}`)
    }

    callFunction(event, obj[method], obj, args)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_SET', function (event, id, name, value) {
  try {
    let obj = objectsRegistry.get(id)

    if (obj == null) {
      throwRPCError(`Cannot set property '${name}' on missing remote object ${id}`)
    }

    obj[name] = value
    event.returnValue = null
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_MEMBER_GET', function (event, id, name) {
  try {
    let obj = objectsRegistry.get(id)

    if (obj == null) {
      throwRPCError(`Cannot get property '${name}' on missing remote object ${id}`)
    }

    event.returnValue = valueToMeta(event.sender, obj[name])
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_DEREFERENCE', function (event, id) {
  objectsRegistry.remove(event.sender.getId(), id)
})

ipcMain.on('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) {
  try {
    let guestViewManager = require('./guest-view-manager')
    event.returnValue = valueToMeta(event.sender, guestViewManager.getGuest(guestInstanceId))
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, ...args) {
  try {
    let guestViewManager = require('./guest-view-manager')
    let guest = guestViewManager.getGuest(guestInstanceId)
    if (requestId) {
      const responseCallback = function (result) {
        event.sender.send(`ELECTRON_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result)
      }
      args.push(responseCallback)
    }
    guest[method].apply(guest, args)
  } catch (error) {
    event.returnValue = exceptionToMeta(error)
  }
})

ipcMain.on('ELECTRON_BROWSER_SEND_TO', function (event, sendToAll, webContentsId, channel, ...args) {
  let contents = webContents.fromId(webContentsId)
  if (!contents) {
    console.error(`Sending message to WebContents with unknown ID ${webContentsId}`)
    return
  }

  if (sendToAll) {
    contents.sendToAll(channel, ...args)
  } else {
    contents.send(channel, ...args)
  }
})

// Implements window.alert(message, title)
ipcMain.on('ELECTRON_BROWSER_WINDOW_ALERT', function (event, message, title) {
  if (message == null) message = ''
  if (title == null) title = ''

  event.returnValue = electron.dialog.showMessageBox(event.sender.getOwnerBrowserWindow(), {
    message: `${message}`,
    title: `${title}`,
    buttons: ['OK']
  })
})

// Implements window.confirm(message, title)
ipcMain.on('ELECTRON_BROWSER_WINDOW_CONFIRM', function (event, message, title) {
  if (message == null) message = ''
  if (title == null) title = ''

  event.returnValue = !electron.dialog.showMessageBox(event.sender.getOwnerBrowserWindow(), {
    message: `${message}`,
    title: `${title}`,
    buttons: ['OK', 'Cancel'],
    cancelId: 1
  })
})

// Implements window.close()
ipcMain.on('ELECTRON_BROWSER_WINDOW_CLOSE', function (event) {
  event.sender.getOwnerBrowserWindow().close()
  event.returnValue = null
})
<|endoftext|>


<commit_before>(function() {
  var g = ('undefined' === typeof window ? global : window) || {}
  var foolBrowserify = function (r) {
    try { return require(r) } catch (_) { }
  }
  _crypto = (
    g.crypto || g.msCrypto || foolBrowserify('crypto')
  )
  module.exports = function(size) {
    // Modern Browsers
    if(_crypto.getRandomValues) {
      var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
      /* This will not work in older browsers.
       * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
       */

      _crypto.getRandomValues(bytes);
      return bytes;
    }
    else if (_crypto.randomBytes) {
      return _crypto.randomBytes(size)
    }
    else
      throw new Error(
        'secure random number generation not supported by this browser\n'+
        'use chrome, FireFox or Internet Explorer 11'
      )
  }
}())
<commit_msg>ensure a helpful error message in browsers without randomValues<commit_after>(function() {
  var g = ('undefined' === typeof window ? global : window) || {}
  var foolBrowserify = function (r) {
    try { return require(r) } catch (_) { }
  }
  _crypto = (
    g.crypto || g.msCrypto || foolBrowserify('crypto') || {}
  )
  module.exports = function(size) {
    // Modern Browsers
    if(_crypto.getRandomValues) {
      var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
      /* This will not work in older browsers.
       * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
       */

      _crypto.getRandomValues(bytes);
      return bytes;
    }
    else if (_crypto.randomBytes) {
      return _crypto.randomBytes(size)
    }
    else
      throw new Error(
        'secure random number generation not supported by this browser\n'+
        'use chrome, FireFox or Internet Explorer 11'
      )
  }
}())
<|endoftext|>