<commit_before>/*---------------------------------------------------------
 * OpenERP web_gantt
 *---------------------------------------------------------*/
openerp.web_gantt = function (openerp) {
var _t = openerp.web._t,
   _lt = openerp.web._lt;
var QWeb = openerp.web.qweb;
openerp.web.views.add('gantt', 'openerp.web_gantt.GanttView');

openerp.web_gantt.GanttView = openerp.web.View.extend({
    display_name: _lt('Gantt'),
    template: "GanttView",
    init: function() {
        this._super.apply(this, arguments);
        this.has_been_loaded = $.Deferred();
        this.chart_id = _.uniqueId();
    },
    start: function() {
        return $.when(this.rpc("/web/view/load", {"model": this.dataset.model, "view_id": this.view_id, "view_type": "gantt"}),
            this.rpc("/web/searchview/fields_get", {"model": this.dataset.model})).pipe(this.on_loaded);
    },
    on_loaded: function(fields_view, fields_get) {
        this.fields_view = fields_view[0];
        this.fields = fields_get[0].fields;
        this.field_name = 'name';

        this.has_been_loaded.resolve();
    },
    do_search: function (domains, contexts, group_bys) {
        var self = this;
        self.last_domains = domains;
        self.last_contexts = contexts;
        self.last_group_bys = group_bys;
        // select the group by
        var n_group_bys = [];
        if (this.fields_view.arch.attrs.default_group_by) {
            n_group_bys = this.fields_view.arch.attrs.default_group_by.split(',');
        }
        if (group_bys.length) {
            n_group_bys = group_bys;
        }
        // gather the fields to get
        var fields = _.compact(_.map(["date_start", "date_delay", "date_stop", "color", "colors"], function(key) {
            return self.fields_view.arch.attrs[key] || '';
        }));
        fields = _.uniq(fields.concat([this.field_name], n_group_bys));

        return $.when(this.has_been_loaded).pipe(function() {
            return self.dataset.read_slice(fields, {
                domain: domains,
                context: contexts
            }).pipe(function(data) {
                return self.on_data_loaded(data, n_group_bys);
            });
        });
    },
    reload: function() {
        if (this.last_domains !== undefined)
            return this.do_search(this.last_domains, this.last_contexts, this.last_group_bys);
    },
    on_data_loaded: function(tasks, group_bys) {
        var self = this;
        $(".oe-gantt-view-view", this.$element).html("");

        //prevent more that 1 group by
        if (group_bys.length > 0) {
            group_bys = [group_bys[0]];
        }
        // if there is no group by, simulate it
        if (group_bys.length == 0) {
            group_bys = ["_pseudo_group_by"];
            _.each(tasks, function(el) {
                el._pseudo_group_by = "Gantt View";
            });
            this.fields._pseudo_group_by = {type: "string"};
        }

        // get the groups
        var split_groups = function(tasks, group_bys) {
            if (group_bys.length === 0)
                return tasks;
            var groups = [];
            _.each(tasks, function(task) {
                var group_name = task[_.first(group_bys)];
                var group = _.find(groups, function(group) { return _.isEqual(group.name, group_name); });
                if (group === undefined) {
                    group = {name:group_name, tasks: [], __is_group: true};
                    groups.push(group);
                }
                group.tasks.push(task);
            });
            _.each(groups, function(group) {
                group.tasks = split_groups(group.tasks, _.rest(group_bys));
            });
            return groups;
        }
        var groups = split_groups(tasks, group_bys);

        // track ids of task items for context menu
        var task_ids = {};
        // creation of the chart
        var generate_task_info = function(task, plevel) {
            var level = plevel || 0;
            if (task.__is_group) {
                var task_infos = _.compact(_.map(task.tasks, function(sub_task) {
                    return generate_task_info(sub_task, level + 1);
                }));
                if (task_infos.length == 0)
                    return;
                var task_start = _.reduce(_.pluck(task_infos, "task_start"), function(date, memo) {
                    return memo === undefined || date < memo ? date : memo;
                }, undefined);
                var task_stop = _.reduce(_.pluck(task_infos, "task_stop"), function(date, memo) {
                    return memo === undefined || date > memo ? date : memo;
                }, undefined);
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var group_name = openerp.web.format_value(task.name, self.fields[group_bys[level]]);
                if (level == 0) {
                    var group = new GanttProjectInfo(_.uniqueId("gantt_project_"), group_name, task_start);
                    _.each(task_infos, function(el) {
                        group.addTask(el.task_info);
                    });
                    return group;
                } else {
                    var group = new GanttTaskInfo(_.uniqueId("gantt_project_task_"), group_name, task_start, duration, 100);
                    _.each(task_infos, function(el) {
                        group.addChildTask(el.task_info);
                    });
                    return {task_info: group, task_start: task_start, task_stop: task_stop};
                }
            } else {
                var task_name = openerp.web.format_value(task[self.field_name], self.fields[self.field_name]);
                var task_start = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_start]);
                if (!task_start)
                    return;
                var task_stop;
                if (self.fields_view.arch.attrs.date_stop) {
                    task_stop = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_stop]);
                    if (!task_stop)
                        return;
                } else { // we assume date_duration is defined
                    var tmp = openerp.web.format_value(task[self.fields_view.arch.attrs.date_delay],
                        self.fields[self.fields_view.arch.attrs.date_delay]);
                    if (!tmp)
                        return;
                    task_stop = task_start.clone().addMilliseconds(tmp * 60 * 60 * 1000);
                }
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var id = _.uniqueId("gantt_task_");
                var task_info = new GanttTaskInfo(id, task_name, task_start, ((duration / 24) * 8), 100);
                task_info.internal_task = task;
                task_ids[id] = task_info;
                return {task_info: task_info, task_start: task_start, task_stop: task_stop};
            }
        }
        var gantt = new GanttChart();
        _.each(_.compact(_.map(groups, function(e) {return generate_task_info(e, 0);})), function(project) {
            gantt.addProject(project);
        });
        gantt.setEditable(true);
        gantt.setImagePath("/web_gantt/static/lib/dhtmlxGantt/codebase/imgs/");
        gantt.attachEvent("onTaskEndDrag", function(task) {
            self.on_task_changed(task);
        });
        gantt.attachEvent("onTaskEndResize", function(task) {
            self.on_task_changed(task);
        });
        gantt.create(this.chart_id);

        // bind event to display task when we click the item in the tree
        $(".taskNameItem", self.$element).click(function(event) {
            var task_info = task_ids[event.target.id];
            if (task_info) {
                self.on_task_display(task_info.internal_task);
            }
        });

        // insertion of create button
        var td = $($("table td", self.$element)[0]);
        var rendered = QWeb.render("GanttView-create-button");
        $(rendered).prependTo(td);
        $(".oe-gantt-view-create", this.$element).click(this.on_task_create);
    },
    on_task_changed: function(task_obj) {
        var self = this;
        var itask = task_obj.TaskInfo.internal_task;
        var start = task_obj.getEST();
        var duration = (task_obj.getDuration() / 8) * 24;
        var end = start.clone().addMilliseconds(duration * 60 * 60 * 1000);
        var data = {};
        data[self.fields_view.arch.attrs.date_start] =
            openerp.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type);
        if (self.fields_view.arch.attrs.date_stop) {
            data[self.fields_view.arch.attrs.date_stop] =
                openerp.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type);
        } else { // we assume date_duration is defined
            data[self.fields_view.arch.attrs.date_delay] = duration;
        }
        this.dataset.write(itask.id, data).then(function() {
            console.log("task edited");
        });
    },
    on_task_display: function(task) {
        var self = this;
        var pop = new openerp.web.form.FormOpenPopup(self);
        pop.on_write_completed.add_last(function() {
            self.reload();
        });
        pop.show_element(
            self.dataset.model,
            task.id,
            null,
            {}
        );
    },
    on_task_create: function() {
        var self = this;
        var pop = new openerp.web.form.SelectCreatePopup(this);
        pop.on_select_elements.add_last(function() {
            self.reload();
        });
        pop.select_element(
            self.dataset.model,
            {
                initial_view: "form",
            }
        );
    },
});

};
<commit_msg>[fix] problem in gantt view, now does a name_get for all models<commit_after>/*---------------------------------------------------------
 * OpenERP web_gantt
 *---------------------------------------------------------*/
openerp.web_gantt = function (openerp) {
var _t = openerp.web._t,
   _lt = openerp.web._lt;
var QWeb = openerp.web.qweb;
openerp.web.views.add('gantt', 'openerp.web_gantt.GanttView');

openerp.web_gantt.GanttView = openerp.web.View.extend({
    display_name: _lt('Gantt'),
    template: "GanttView",
    init: function() {
        this._super.apply(this, arguments);
        this.has_been_loaded = $.Deferred();
        this.chart_id = _.uniqueId();
    },
    start: function() {
        return $.when(this.rpc("/web/view/load", {"model": this.dataset.model, "view_id": this.view_id, "view_type": "gantt"}),
            this.rpc("/web/searchview/fields_get", {"model": this.dataset.model})).pipe(this.on_loaded);
    },
    on_loaded: function(fields_view, fields_get) {
        this.fields_view = fields_view[0];
        this.fields = fields_get[0].fields;

        this.has_been_loaded.resolve();
    },
    do_search: function (domains, contexts, group_bys) {
        var self = this;
        self.last_domains = domains;
        self.last_contexts = contexts;
        self.last_group_bys = group_bys;
        // select the group by
        var n_group_bys = [];
        if (this.fields_view.arch.attrs.default_group_by) {
            n_group_bys = this.fields_view.arch.attrs.default_group_by.split(',');
        }
        if (group_bys.length) {
            n_group_bys = group_bys;
        }
        // gather the fields to get
        var fields = _.compact(_.map(["date_start", "date_delay", "date_stop"], function(key) {
            return self.fields_view.arch.attrs[key] || '';
        }));
        fields = _.uniq(fields.concat(n_group_bys));

        return $.when(this.has_been_loaded).pipe(function() {
            return self.dataset.read_slice(fields, {
                domain: domains,
                context: contexts
            }).pipe(function(data) {
                return self.on_data_loaded(data, n_group_bys);
            });
        });
    },
    reload: function() {
        if (this.last_domains !== undefined)
            return this.do_search(this.last_domains, this.last_contexts, this.last_group_bys);
    },
    on_data_loaded: function(tasks, group_bys) {
        var self = this;
        var ids = _.pluck(tasks, "id");
        return this.dataset.name_get(ids).pipe(function(names) {
            var ntasks = _.map(tasks, function(task) {
                return _.extend({__name: _.detect(names, function(name) { return name[0] == task.id; })[1]}, task);
            });
            return self.on_data_loaded_2(ntasks, group_bys);
        });
    },
    on_data_loaded_2: function(tasks, group_bys) {
        var self = this;
        $(".oe-gantt-view-view", this.$element).html("");

        //prevent more that 1 group by
        if (group_bys.length > 0) {
            group_bys = [group_bys[0]];
        }
        // if there is no group by, simulate it
        if (group_bys.length == 0) {
            group_bys = ["_pseudo_group_by"];
            _.each(tasks, function(el) {
                el._pseudo_group_by = "Gantt View";
            });
            this.fields._pseudo_group_by = {type: "string"};
        }

        // get the groups
        var split_groups = function(tasks, group_bys) {
            if (group_bys.length === 0)
                return tasks;
            var groups = [];
            _.each(tasks, function(task) {
                var group_name = task[_.first(group_bys)];
                var group = _.find(groups, function(group) { return _.isEqual(group.name, group_name); });
                if (group === undefined) {
                    group = {name:group_name, tasks: [], __is_group: true};
                    groups.push(group);
                }
                group.tasks.push(task);
            });
            _.each(groups, function(group) {
                group.tasks = split_groups(group.tasks, _.rest(group_bys));
            });
            return groups;
        }
        var groups = split_groups(tasks, group_bys);

        // track ids of task items for context menu
        var task_ids = {};
        // creation of the chart
        var generate_task_info = function(task, plevel) {
            var level = plevel || 0;
            if (task.__is_group) {
                var task_infos = _.compact(_.map(task.tasks, function(sub_task) {
                    return generate_task_info(sub_task, level + 1);
                }));
                if (task_infos.length == 0)
                    return;
                var task_start = _.reduce(_.pluck(task_infos, "task_start"), function(date, memo) {
                    return memo === undefined || date < memo ? date : memo;
                }, undefined);
                var task_stop = _.reduce(_.pluck(task_infos, "task_stop"), function(date, memo) {
                    return memo === undefined || date > memo ? date : memo;
                }, undefined);
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var group_name = openerp.web.format_value(task.name, self.fields[group_bys[level]]);
                if (level == 0) {
                    var group = new GanttProjectInfo(_.uniqueId("gantt_project_"), group_name, task_start);
                    _.each(task_infos, function(el) {
                        group.addTask(el.task_info);
                    });
                    return group;
                } else {
                    var group = new GanttTaskInfo(_.uniqueId("gantt_project_task_"), group_name, task_start, duration, 100);
                    _.each(task_infos, function(el) {
                        group.addChildTask(el.task_info);
                    });
                    return {task_info: group, task_start: task_start, task_stop: task_stop};
                }
            } else {
                var task_name = task.__name;
                var task_start = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_start]);
                if (!task_start)
                    return;
                var task_stop;
                if (self.fields_view.arch.attrs.date_stop) {
                    task_stop = openerp.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_stop]);
                    if (!task_stop)
                        return;
                } else { // we assume date_duration is defined
                    var tmp = openerp.web.format_value(task[self.fields_view.arch.attrs.date_delay],
                        self.fields[self.fields_view.arch.attrs.date_delay]);
                    if (!tmp)
                        return;
                    task_stop = task_start.clone().addMilliseconds(tmp * 60 * 60 * 1000);
                }
                var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var id = _.uniqueId("gantt_task_");
                var task_info = new GanttTaskInfo(id, task_name, task_start, ((duration / 24) * 8), 100);
                task_info.internal_task = task;
                task_ids[id] = task_info;
                return {task_info: task_info, task_start: task_start, task_stop: task_stop};
            }
        }
        var gantt = new GanttChart();
        _.each(_.compact(_.map(groups, function(e) {return generate_task_info(e, 0);})), function(project) {
            gantt.addProject(project);
        });
        gantt.setEditable(true);
        gantt.setImagePath("/web_gantt/static/lib/dhtmlxGantt/codebase/imgs/");
        gantt.attachEvent("onTaskEndDrag", function(task) {
            self.on_task_changed(task);
        });
        gantt.attachEvent("onTaskEndResize", function(task) {
            self.on_task_changed(task);
        });
        gantt.create(this.chart_id);

        // bind event to display task when we click the item in the tree
        $(".taskNameItem", self.$element).click(function(event) {
            var task_info = task_ids[event.target.id];
            if (task_info) {
                self.on_task_display(task_info.internal_task);
            }
        });

        // insertion of create button
        var td = $($("table td", self.$element)[0]);
        var rendered = QWeb.render("GanttView-create-button");
        $(rendered).prependTo(td);
        $(".oe-gantt-view-create", this.$element).click(this.on_task_create);
    },
    on_task_changed: function(task_obj) {
        var self = this;
        var itask = task_obj.TaskInfo.internal_task;
        var start = task_obj.getEST();
        var duration = (task_obj.getDuration() / 8) * 24;
        var end = start.clone().addMilliseconds(duration * 60 * 60 * 1000);
        var data = {};
        data[self.fields_view.arch.attrs.date_start] =
            openerp.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type);
        if (self.fields_view.arch.attrs.date_stop) {
            data[self.fields_view.arch.attrs.date_stop] =
                openerp.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type);
        } else { // we assume date_duration is defined
            data[self.fields_view.arch.attrs.date_delay] = duration;
        }
        this.dataset.write(itask.id, data).then(function() {
            console.log("task edited");
        });
    },
    on_task_display: function(task) {
        var self = this;
        var pop = new openerp.web.form.FormOpenPopup(self);
        pop.on_write_completed.add_last(function() {
            self.reload();
        });
        pop.show_element(
            self.dataset.model,
            task.id,
            null,
            {}
        );
    },
    on_task_create: function() {
        var self = this;
        var pop = new openerp.web.form.SelectCreatePopup(this);
        pop.on_select_elements.add_last(function() {
            self.reload();
        });
        pop.select_element(
            self.dataset.model,
            {
                initial_view: "form",
            }
        );
    },
});

};
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
module.exports =
{
    initSpawnQue: function()
    {
        if(Memory.spawnQue == undefined)
            Memory.spawnQue = [ ];
    },

    addToQue: function(creep, unshift)
    {
        this.initSpawnQue();

        if(unshift != undefined && unshift === true)
            Memory.spawnQue.unshift(creep);
        else
            Memory.spawnQue.push(creep);
    },

    spawnNextInQue: function()
    {

        this.initSpawnQue();

        if(!Memory.spawnQue.length)
            return;

        var spawns = Game.rooms['W2N48'].find(FIND_MY_SPAWNS, {
            filter: function(spawn)
            {
                return spawn.spawning === undefined || spawn.spawning === null;
            }
        });
        //console.log(spawns);

        if(!spawns.length)
            return;
        console.log("getting here1");
        var role = Memory.spawnQue[0];

        if(typeof role == "string")
        {
            role = { type: role, memory: { } };
        }

        var me = this;
        var toSpawnAt = spawns.filter(function(spawn)
        {
            return me.canSpawn(spawn, role.type);
        });

        if(! toSpawnAt.length)
            return;

        toSpawnAt = toSpawnAt[0];
        this.spawn(role.type, role.memory, toSpawnAt);

        Memory.spawnQue.shift();
    },

    spawn: function(role, memory, spawnPoint)
    {
        if(!spawnPoint)
            spawnPoint = Game.spawns['Harmony'];

        var manager = require('roleManager');

        if(!manager.roleExists(role))
        {
            return;
        }

        if(!this.canSpawn(spawnPoint, role))
        {
            return;
        }

        if(memory == undefined)
            memory = { };

        memory['role'] = role;

        var nameCount = 0;
        var name = null;
        while(name == null)
        {
            nameCount++;
            var tryName = role + nameCount;
            if(Game.creeps[tryName] == undefined)
                name = tryName;
        }

        console.log('Spawning ' + role);
        console.log(spawnPoint.createCreep(manager.getRoleBodyParts(role), name, memory));
    },

    canSpawn: function(spawnPoint, role)
    {
        if(typeof spawnPoint == "string" && role == undefined)
        {
            role = spawnPoint;
            spawnPoint = Game.spawns['Harmony'];
        }
        //console.log(role);
        return spawnPoint.energy >= this.spawnCost(role)
            && (spawnPoint.spawning == null
            || spawnPoint.spawning == undefined);
    },

    spawnCost: function(role)
    {
        var manager = require('roleManager');
        var parts = manager.getRoleBodyParts(role);

        var total = 0;
        for(var index in parts)
        {
            var part = parts[index];
            switch(part)
            {
                case MOVE:
                    total += 50
                    break;

                case WORK:
                    total += 100
                    break;

                case CARRY:
                    total += 50
                    break;

                case ATTACK:
                    total += 80
                    break;

                case RANGED_ATTACK:
                    total += 150
                    break;

                case HEAL:
                    total += 250
                    break;

                case TOUGH:
                    total += 10
                    break;

                case CLAIM:
                    total += 600
            }
        }
        //console.log("total cost: " + total);
        return total;
    },

    killAll: function(role)
    {
        for(var i in Game.creeps) {
            if(role == undefined || Game.creeps[i].memory.role == role)
                Game.creeps[i].suicide();
        }
    }
}<commit_msg>Fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
module.exports =
{
    initSpawnQue: function()
    {
        if(Memory.spawnQue == undefined)
            Memory.spawnQue = [ ];
    },

    addToQue: function(creep, unshift)
    {
        this.initSpawnQue();

        if(unshift != undefined && unshift === true)
            Memory.spawnQue.unshift(creep);
        else
            Memory.spawnQue.push(creep);
    },

    spawnNextInQue: function()
    {

        this.initSpawnQue();

        if(!Memory.spawnQue.length)
            return;

        var spawns = Game.rooms['W2N48'].find(FIND_MY_SPAWNS, {
            filter: function(spawn)
            {
                return spawn.spawning === undefined || spawn.spawning === null;
            }
        });
        //console.log(spawns);

        if(!spawns.length)
            return;

        var role = Memory.spawnQue[0];

        if(typeof role == "string")
        {
            role = { type: role, memory: { } };
        }

        var me = this;
        var toSpawnAt = spawns.filter(function(spawn)
        {
            return me.canSpawn(spawn, role.type);
        });
        console.log("getting here");
        if(! toSpawnAt.length)
            return;

        toSpawnAt = toSpawnAt[0];
        this.spawn(role.type, role.memory, toSpawnAt);

        Memory.spawnQue.shift();
    },

    spawn: function(role, memory, spawnPoint)
    {
        if(!spawnPoint)
            spawnPoint = Game.spawns['Harmony'];

        var manager = require('roleManager');

        if(!manager.roleExists(role))
        {
            return;
        }

        if(!this.canSpawn(spawnPoint, role))
        {
            return;
        }

        if(memory == undefined)
            memory = { };

        memory['role'] = role;

        var nameCount = 0;
        var name = null;
        while(name == null)
        {
            nameCount++;
            var tryName = role + nameCount;
            if(Game.creeps[tryName] == undefined)
                name = tryName;
        }

        console.log('Spawning ' + role);
        console.log(spawnPoint.createCreep(manager.getRoleBodyParts(role), name, memory));
    },

    canSpawn: function(spawnPoint, role)
    {
        if(typeof spawnPoint == "string" && role == undefined)
        {
            role = spawnPoint;
            spawnPoint = Game.spawns['Harmony'];
        }
        //console.log(role);
        return spawnPoint.energy >= this.spawnCost(role)
            && (spawnPoint.spawning == null
            || spawnPoint.spawning == undefined);
    },

    spawnCost: function(role)
    {
        var manager = require('roleManager');
        var parts = manager.getRoleBodyParts(role);

        var total = 0;
        for(var index in parts)
        {
            var part = parts[index];
            switch(part)
            {
                case MOVE:
                    total += 50
                    break;

                case WORK:
                    total += 100
                    break;

                case CARRY:
                    total += 50
                    break;

                case ATTACK:
                    total += 80
                    break;

                case RANGED_ATTACK:
                    total += 150
                    break;

                case HEAL:
                    total += 250
                    break;

                case TOUGH:
                    total += 10
                    break;

                case CLAIM:
                    total += 600
            }
        }
        //console.log("total cost: " + total);
        return total;
    },

    killAll: function(role)
    {
        for(var i in Game.creeps) {
            if(role == undefined || Game.creeps[i].memory.role == role)
                Game.creeps[i].suicide();
        }
    }
}<|endoftext|>


<commit_before>import React from 'react'
import {compose} from 'recompose'
import {connect} from 'react-redux'
import {push} from 'react-router-redux'
import {reduxForm, Field, SubmissionError, getFormValues} from 'redux-form'
import {RaisedButton, MenuItem} from 'material-ui'
import {
  TextField,
  Toggle,
  SelectField,
} from 'redux-form-material-ui'
import {omit, isEmpty, map, get, reject, pickBy, forEach} from 'lodash'
import {graphql, gql} from 'react-apollo'
import {humanize} from 'inflection'
import DropzoneS3Uploader from 'react-dropzone-s3-uploader'
import {showNotification} from '../actions'
import upsertPage from '../graphql/upsertPage.gql'
import deletePage from '../graphql/deletePage.gql'
import siteQuery from '../graphql/site.gql'
import {t} from '../common/utils'
import common from '../common.scss'
import {RedactorField as Redactor} from '../components/redactor'

const required = value => isEmpty(value) && 'Cannot be blank'

class PageEditorGeneral extends React.Component {
  constructor(p) {
    super(p)
    this.state = {}
  }

  onSubmit(data) {
    const page = omit(data, '__typename', 'sections')
    const newPage = !data.id
    console.log(this.props);
    return this.props.upsertPage({variables: {page, locale: this.props.locale}})
      .then(({data}) => {
        this.props.showNotification("Page saved")
        if (newPage) {
          this.props.push(`/site/page/${data.upsertPage.id}`)
        }
      })
      .catch((error) => {
        throw new SubmissionError(error.graphQLErrors[0].errors)
      })
  }

  get properties() {
    return get(this.props.siteData, ['site', 'layouts', this.props.page.layout, 'properties'], [])
  }

  render() {
    if (this.props.data.loading || this.props.siteData.loading) {
      return null
    }
    const {handleSubmit, pristine, submitting, locale, data: {pages}, siteData: {site}} = this.props
    const layouts = site.layouts
    const validParents = reject(pages, parent => parent.id === get(this.props.page, 'id'))
    return (
      <form onSubmit={handleSubmit((data) => this.onSubmit(data))}>
        <Field name="title" component={TextField} hintText="Page title" floatingLabelText="Title" validate={required} floatingLabelFixed
          fullWidth className={common.formControl} />
        <Field name="slug" component={TextField} hintText="Page URL" floatingLabelText="Slug"
          fullWidth floatingLabelFixed className={common.formControl} />
        <Field
          name="layout"
          component={SelectField}
          hintText="Page base layout"
          floatingLabelText="Layout"
          validate={required}
          className={common.formControl}
          fullWidth
        >
          {map(layouts, ({name}, key) => <MenuItem value={key} primaryText={name} key={key} />)}
        </Field>
        <Field
          name="parent"
          component={SelectField}
          hintText="Parent page"
          floatingLabelText="Parent page"
          className={common.formControl}
          fullWidth
        >
          <MenuItem value={null} primaryText={Root} />
          {map(validParents, ({title, id}) => <MenuItem value={id} primaryText={t(title, locale)} key={id} />)}
        </Field>
        <Field name="published" component={Toggle} label="Published" />
        {map(this.properties, prop => this.renderPropetyField(prop))}

          <RaisedButton label="Save" primary disabled={pristine || submitting} type="submit" />
          {this.props.page.id &&
            <RaisedButton style={{float: 'right'}} label="Delete" secondary onTouchTap={() => this.deletePage()} />
          }

      </form>)
  }

  deletePage() {
    this.props.deletePage({variables: {id: this.props.page.id}})
      .then(() => {
        this.props.showNotification("Page deleted")
        // this.props.push(`/site`)
      })
      .catch((error) => {
        throw new SubmissionError(error.graphQLErrors[0].errors)
      })
  }

  renderPropetyField(prop) {
    const {key} = prop
    if (prop.type === 'text') {
      return (
        <Field
          name={`properties.${key}`}
          key={key}
          component={TextField}
          floatingLabelText={humanize(key)}
          fullWidth floatingLabelFixed
          multiLine
          rows={2}
          className={common.formControl}
        />
      )
    } else if (prop.type === 'html') {
      return (
        <Field
          name={`properties.${key}`}
          key={key}
          component={Redactor}
          label={humanize(key)}
        />
      )
    } else if (prop.type === 'boolean') {
      return <Field key={key} name={`properties.${key}`} component={Toggle} label={humanize(key)} />
    } else if (prop.type === 'image') {
      const val = get(this.props.formValues, ['properties', key])
      return (

        {humanize(key)}
        <DropzoneS3Uploader
          onFinish={params => {
            this.props.change(`properties.${key}`, `https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com/${params.fileKey}`)
          }}
          s3Url={`https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com`}
          maxSize={1024 * 1024 * 5}
          upload={{
            signingUrl: '/admin/api/s3/sign',
            signingUrlWithCredentials: true,
          }}
          passChildrenProps={false}
        >
          {!isEmpty(val) &&

          }
          {isEmpty(val) &&

Drop an image here

          }
        </DropzoneS3Uploader>
        {!isEmpty(val) &&  this.props.change(`properties.${key}`, '')}
        />}

)
    } else if (prop.type === 'file') {
      const val = get(this.props.formValues, ['properties', key])
      return (

        {humanize(key)}
        <DropzoneS3Uploader
          onFinish={params => {
            this.props.change(`properties.${key}`, {
              url: params.fileKey,
              name: params.file.name,
              type: params.file.type,
              size: params.file.size,
            })
          }}
          s3Url={`https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com`}
          maxSize={1024 * 1024 * 50}
          upload={{
            signingUrl: '/admin/api/s3/sign',
            signingUrlWithCredentials: true,
          }}
          passChildrenProps={false}
        >
          {!isEmpty(val) &&
            <a href={`https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com/${val.url}`} style={{display: 'block', height: '100%', textAlign: 'center', lineHeight: '200px'}}>

          }
          {isEmpty(val) &&

Drop an file here

          }
        </DropzoneS3Uploader>
        {!isEmpty(val) &&  this.props.change(`properties.${key}`, null)}
        />}

)
    } else {
      return (
        <Field
          name={`properties.${key}`}
          key={key}
          component={TextField}
          floatingLabelText={humanize(key)}
          fullWidth floatingLabelFixed
          className={common.formControl}
        />
      )
    }

  }
}

const mapStateToProps = ({app, ...state}, {page, siteData}) => {
  const initialValues = {
    ...page,
    parent: get(page.parent, 'id'),
    title: t(page.title, app.locale),
    properties: {...page.properties} || {},
  }

  if (page.layout) {
    const localizedProperties = pickBy(siteData.site.layouts[page.layout].properties, 'localized')
    forEach(localizedProperties, (prop, key) => {
      initialValues.properties[key] = t(get(page.properties, key), app.locale)
    })
  }

  return {
    locale: app.locale,
    formValues: {...initialValues, ...getFormValues('page')(state)},
    initialValues
  }
}

const listAllPages = gql`
  query {
    pages {
      id
      title
    }
  }
`

const enhance = compose(
  graphql(siteQuery, {name: 'siteData'}),
  graphql(listAllPages),
  graphql(upsertPage, {
    options: {
      refetchQueries: [
        'pages',
      ],
    },
    name: 'upsertPage',
  }),
  graphql(deletePage, {
    options: {
      refetchQueries: [
        'pages',
      ],
    },
    name: 'deletePage',
  }),
  connect(mapStateToProps, {showNotification, push}),
  reduxForm({form: 'page', enableReinitialize: true, keepDirtyOnReinitialize: true}),
)

export default enhance(PageEditorGeneral)
<commit_msg>allow setting content disposition on DropzoneS3Uploader<commit_after>import React from 'react'
import {compose} from 'recompose'
import {connect} from 'react-redux'
import {push} from 'react-router-redux'
import {reduxForm, Field, SubmissionError, getFormValues} from 'redux-form'
import {RaisedButton, MenuItem} from 'material-ui'
import {
  TextField,
  Toggle,
  SelectField,
} from 'redux-form-material-ui'
import {omit, isEmpty, map, get, reject, pickBy, forEach} from 'lodash'
import {graphql, gql} from 'react-apollo'
import {humanize} from 'inflection'
import DropzoneS3Uploader from 'react-dropzone-s3-uploader'
import {showNotification} from '../actions'
import upsertPage from '../graphql/upsertPage.gql'
import deletePage from '../graphql/deletePage.gql'
import siteQuery from '../graphql/site.gql'
import {t} from '../common/utils'
import common from '../common.scss'
import {RedactorField as Redactor} from '../components/redactor'

const required = value => isEmpty(value) && 'Cannot be blank'

class PageEditorGeneral extends React.Component {
  constructor(p) {
    super(p)
    this.state = {}
  }

  onSubmit(data) {
    const page = omit(data, '__typename', 'sections')
    const newPage = !data.id
    console.log(this.props);
    return this.props.upsertPage({variables: {page, locale: this.props.locale}})
      .then(({data}) => {
        this.props.showNotification("Page saved")
        if (newPage) {
          this.props.push(`/site/page/${data.upsertPage.id}`)
        }
      })
      .catch((error) => {
        throw new SubmissionError(error.graphQLErrors[0].errors)
      })
  }

  get properties() {
    return get(this.props.siteData, ['site', 'layouts', this.props.page.layout, 'properties'], [])
  }

  render() {
    if (this.props.data.loading || this.props.siteData.loading) {
      return null
    }
    const {handleSubmit, pristine, submitting, locale, data: {pages}, siteData: {site}} = this.props
    const layouts = site.layouts
    const validParents = reject(pages, parent => parent.id === get(this.props.page, 'id'))
    return (
      <form onSubmit={handleSubmit((data) => this.onSubmit(data))}>
        <Field name="title" component={TextField} hintText="Page title" floatingLabelText="Title" validate={required} floatingLabelFixed
          fullWidth className={common.formControl} />
        <Field name="slug" component={TextField} hintText="Page URL" floatingLabelText="Slug"
          fullWidth floatingLabelFixed className={common.formControl} />
        <Field
          name="layout"
          component={SelectField}
          hintText="Page base layout"
          floatingLabelText="Layout"
          validate={required}
          className={common.formControl}
          fullWidth
        >
          {map(layouts, ({name}, key) => <MenuItem value={key} primaryText={name} key={key} />)}
        </Field>
        <Field
          name="parent"
          component={SelectField}
          hintText="Parent page"
          floatingLabelText="Parent page"
          className={common.formControl}
          fullWidth
        >
          <MenuItem value={null} primaryText={Root} />
          {map(validParents, ({title, id}) => <MenuItem value={id} primaryText={t(title, locale)} key={id} />)}
        </Field>
        <Field name="published" component={Toggle} label="Published" />
        {map(this.properties, prop => this.renderPropetyField(prop))}

          <RaisedButton label="Save" primary disabled={pristine || submitting} type="submit" />
          {this.props.page.id &&
            <RaisedButton style={{float: 'right'}} label="Delete" secondary onTouchTap={() => this.deletePage()} />
          }

      </form>)
  }

  deletePage() {
    this.props.deletePage({variables: {id: this.props.page.id}})
      .then(() => {
        this.props.showNotification("Page deleted")
        // this.props.push(`/site`)
      })
      .catch((error) => {
        throw new SubmissionError(error.graphQLErrors[0].errors)
      })
  }

  renderPropetyField(prop) {
    const {key} = prop
    if (prop.type === 'text') {
      return (
        <Field
          name={`properties.${key}`}
          key={key}
          component={TextField}
          floatingLabelText={humanize(key)}
          fullWidth floatingLabelFixed
          multiLine
          rows={2}
          className={common.formControl}
        />
      )
    } else if (prop.type === 'html') {
      return (
        <Field
          name={`properties.${key}`}
          key={key}
          component={Redactor}
          label={humanize(key)}
        />
      )
    } else if (prop.type === 'boolean') {
      return <Field key={key} name={`properties.${key}`} component={Toggle} label={humanize(key)} />
    } else if (prop.type === 'image') {
      const val = get(this.props.formValues, ['properties', key])
      return (

        {humanize(key)}
        <DropzoneS3Uploader
          onFinish={params => {
            this.props.change(`properties.${key}`, `https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com/${params.fileKey}`)
          }}
          s3Url={`https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com`}
          maxSize={1024 * 1024 * 5}
          upload={{
            signingUrl: '/admin/api/s3/sign',
            signingUrlWithCredentials: true,
          }}
          passChildrenProps={false}
        >
          {!isEmpty(val) &&

          }
          {isEmpty(val) &&

Drop an image here

          }
        </DropzoneS3Uploader>
        {!isEmpty(val) &&  this.props.change(`properties.${key}`, '')}
        />}

)
    } else if (prop.type === 'file') {
      const val = get(this.props.formValues, ['properties', key])
      return (

        {humanize(key)}
        <DropzoneS3Uploader
          onFinish={params => {
            this.props.change(`properties.${key}`, {
              url: params.fileKey,
              name: params.file.name,
              type: params.file.type,
              size: params.file.size,
            })
          }}
          s3Url={`https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com`}
          maxSize={1024 * 1024 * 50}
          upload={{
            signingUrl: '/admin/api/s3/sign',
            signingUrlWithCredentials: true,
            contentDisposition: prop.disposition || 'auto',
          }}
          passChildrenProps={false}
        >
          {!isEmpty(val) &&
            <a href={`https://${process.env.REACT_APP_S3_BUCKET}.s3.amazonaws.com/${val.url}`} style={{display: 'block', height: '100%', textAlign: 'center', lineHeight: '200px'}}>

          }
          {isEmpty(val) &&

Drop an file here

          }
        </DropzoneS3Uploader>
        {!isEmpty(val) &&  this.props.change(`properties.${key}`, null)}
        />}

)
    } else {
      return (
        <Field
          name={`properties.${key}`}
          key={key}
          component={TextField}
          floatingLabelText={humanize(key)}
          fullWidth floatingLabelFixed
          className={common.formControl}
        />
      )
    }

  }
}

const mapStateToProps = ({app, ...state}, {page, siteData}) => {
  const initialValues = {
    ...page,
    parent: get(page.parent, 'id'),
    title: t(page.title, app.locale),
    properties: {...page.properties} || {},
  }

  if (page.layout) {
    const localizedProperties = pickBy(siteData.site.layouts[page.layout].properties, 'localized')
    forEach(localizedProperties, (prop, key) => {
      initialValues.properties[key] = t(get(page.properties, key), app.locale)
    })
  }

  return {
    locale: app.locale,
    formValues: {...initialValues, ...getFormValues('page')(state)},
    initialValues
  }
}

const listAllPages = gql`
  query {
    pages {
      id
      title
    }
  }
`

const enhance = compose(
  graphql(siteQuery, {name: 'siteData'}),
  graphql(listAllPages),
  graphql(upsertPage, {
    options: {
      refetchQueries: [
        'pages',
      ],
    },
    name: 'upsertPage',
  }),
  graphql(deletePage, {
    options: {
      refetchQueries: [
        'pages',
      ],
    },
    name: 'deletePage',
  }),
  connect(mapStateToProps, {showNotification, push}),
  reduxForm({form: 'page', enableReinitialize: true, keepDirtyOnReinitialize: true}),
)

export default enhance(PageEditorGeneral)
<|endoftext|>


<commit_before>var XWiki = (function(XWiki) {
  // Start XWiki augmentation
  var widgets = XWiki.widgets = XWiki.widgets || {};

  widgets.DuplicateValidator = Class.create({
    initialize : function(input, selector, message) {
      this.input = input;
      this.valid = true;
      this.state = 'NEW';
      this.value = input.value;
      this.selector = selector;
      this.message = message;

      if (!this.input.__validation) {
        try {
          this.input.__validation = new LiveValidation(this.input, {validMessage: '', wait : 500});
        }
        catch(err) {
          //console.log(err);
        }
      }
      if (this.input.__validation)
        this.input.__validation.add(this.validate.bind(this));
    },
    check : function() {
      if (this.input.value != this.value) {
        this.value = this.input.value;
        this.state = 'CHECKING';
        var el = this.input;
        var allItems = [];
        $$(this.selector).each( function (item) {
          if (item != el) {
            allItems.push(item.value);
          }
        });
        if (allItems.indexOf(el.value) > -1) {
          this.invalid();
        } else {
          this.available();
        }
        this.responded();
      }
    },
    validate : function(value) {
      if (value.blank()) {
        return true;
      }
      if (this.state == 'DONE' &&
          this.value == value &&
          !this.valid) {
        Validate.fail(this.message);
      }
      this.check();
      return true;
    },

    available : function() {
      this.valid = true;
    },
    invalid : function() {
      this.valid = false;
    },
    responded : function() {
      this.state = 'DONE';
      this.input.__validation.validate();
    },
  });

  var init = function(event) {
    ((event && event.memo.elements) || [$('body')]).each(function(element) {
      element.select('input.gene-name').each(function(input) {
        if (!input.__Gene_validator) {
          input.__Gene_validator = new XWiki.widgets.DuplicateValidator(input, 'input.gene-name', "$services.localization.render('PhenoTips.GeneClass.geneAlreadyExist')");
        }
      });
      element.select('.variant.cdna input').each(function(input) {
        if (!input.__Variant_validator) {
          input.__Variant_validator = new XWiki.widgets.DuplicateValidator(input, '.variant.cdna input', "$services.localization.render('PhenoTips.GeneVariantClass.variantAlreadyExist')");
        }
      });
    });
    return true;
  };

  (XWiki.domIsLoaded && init()) || document.observe("xwiki:dom:loaded", init);
  document.observe('xwiki:dom:updated', init);

  // End XWiki augmentation.
  return XWiki;
}(XWiki || {}));<commit_msg>[misc] No validation of hidden inputs<commit_after>var XWiki = (function(XWiki) {
  // Start XWiki augmentation
  var widgets = XWiki.widgets = XWiki.widgets || {};

  widgets.DuplicateValidator = Class.create({
    initialize : function(input, selector, message) {
      this.input = input;
      this.valid = true;
      this.state = 'NEW';
      this.value = input.value;
      this.selector = selector;
      this.message = message;

      if (!this.input.__validation && !this.input.type == "hidden") {
        try {
          this.input.__validation = new LiveValidation(this.input, {validMessage: '', wait : 500});
        }
        catch(err) {
          //console.log(err);
        }
      }
      if (this.input.__validation)
        this.input.__validation.add(this.validate.bind(this));
    },
    check : function() {
      if (this.input.value != this.value) {
        this.value = this.input.value;
        this.state = 'CHECKING';
        var el = this.input;
        var allItems = [];
        $$(this.selector).each( function (item) {
          if (item != el) {
            allItems.push(item.value);
          }
        });
        if (allItems.indexOf(el.value) > -1) {
          this.invalid();
        } else {
          this.available();
        }
        this.responded();
      }
    },
    validate : function(value) {
      if (value.blank()) {
        return true;
      }
      if (this.state == 'DONE' &&
          this.value == value &&
          !this.valid) {
        Validate.fail(this.message);
      }
      this.check();
      return true;
    },

    available : function() {
      this.valid = true;
    },
    invalid : function() {
      this.valid = false;
    },
    responded : function() {
      this.state = 'DONE';
      this.input.__validation.validate();
    },
  });

  var init = function(event) {
    ((event && event.memo.elements) || [$('body')]).each(function(element) {
      element.select('input.gene-name').each(function(input) {
        if (!input.__Gene_validator) {
          input.__Gene_validator = new XWiki.widgets.DuplicateValidator(input, 'input.gene-name', "$services.localization.render('PhenoTips.GeneClass.geneAlreadyExist')");
        }
      });
      element.select('.variant.cdna input').each(function(input) {
        if (!input.__Variant_validator) {
          input.__Variant_validator = new XWiki.widgets.DuplicateValidator(input, '.variant.cdna input', "$services.localization.render('PhenoTips.GeneVariantClass.variantAlreadyExist')");
        }
      });
    });
    return true;
  };

  (XWiki.domIsLoaded && init()) || document.observe("xwiki:dom:loaded", init);
  document.observe('xwiki:dom:updated', init);

  // End XWiki augmentation.
  return XWiki;
}(XWiki || {}));
<|endoftext|>


<commit_before>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
require('./event_emitter');
require('./service_interface/json');
require('./service_interface/query');
require('./service_interface/rest');
require('./service_interface/rest_xml');

/**
 * @api private
 */
AWS.EventListeners = {
  Core: new AWS.EventEmitter().addNamedListeners(function(add) {
    add('VALIDATE_CREDENTIALS', 'validate',
        function VALIDATE_CREDENTIALS(req) {
      if (!req.client.config.credentials.accessKeyId ||
          !req.client.config.credentials.secretAccessKey) {
        throw AWS.util.error(new Error(),
          {code: 'SigningError', message: 'Missing credentials in config'});
      }
    });

    add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
      if (!req.client.config.region) {
        throw AWS.util.error(new Error(),
          {code: 'SigningError', message: 'Missing region in config'});
      }
    });

    add('SIGN', 'sign', function SIGN(req, resp) {
      var date = AWS.util.date.getDate();
      var credentials = AWS.util.copy(req.client.config.credentials);
      var SignerClass = req.client.signatureVersion;
      var signer = new SignerClass(resp.httpRequest, req.client.serviceName);

      // clear old authorization headers
      delete resp.httpRequest.headers['Authorization'];
      delete resp.httpRequest.headers['Date'];
      delete resp.httpRequest.headers['X-Amz-Date'];

      // add new authorization
      signer.addAuthorization(credentials, date);
    });

    add('SETUP_ERROR', 'extractError', function SETUP_ERROR(req, resp) {
      if (req.client.successfulResponse(req, resp)) {
        // throwing null will stop the error extraction chain
        // but will not set an error for data extraction
        throw null;
      }

      resp.error = AWS.util.error(new Error(),
        {code: 'UnknownError', message: 'An unknown error occurred.'});
      resp.data = null;
    });

    add('SETUP_DATA', 'extractData', function SETUP_DATA(req, resp) {
      resp.data = {};
      resp.error = null;
    });

    add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(req, resp) {
      resp.error.statusCode = resp.httpResponse.statusCode;
      resp.error.retryable = req.client.retryableError(resp.error, req);
    });
  }),

  Http: new AWS.EventEmitter().addNamedListeners(function(add) {
    add('SEND', 'send', function SEND(req, resp) {
      AWS.HttpClient.getInstance().handleRequest(req, resp);
    });

    add('HTTP_HEADERS', 'httpHeaders',
        function HTTP_HEADERS(req, resp, statusCode, headers) {
      resp.httpResponse.statusCode = statusCode;
      resp.httpResponse.headers = headers;
      resp.httpResponse.body = '';
    });

    add('HTTP_DATA', 'httpData', function HTTP_DONE(req, resp, chunk) {
      resp.httpResponse.body += chunk;
    });

    add('HTTP_DONE', 'httpDone', function HTTP_DONE(req) {
      req.completeRequest();
    });

    add('HTTP_ERROR', 'httpError', function HTTP_ERROR(req, error) {
      req.response.error = error;
      req.completeRequest();
    });

    add('REDIRECT', 'retry', function REDIRECT(req, resp) {
      if (resp.error && resp.error.statusCode == 307) {
        resp.httpRequest.endpoint =
          new AWS.Endpoint(resp.httpResponse.headers['location']);
        resp.error = null;
      }
    });

    add('RETRY_CHECK', 'retry', function RETRY_CHECK(req, resp) {
      if (resp.error) {
        if (!resp.error.retryable)
          throw resp.error;
        if (resp.retryCount >= req.client.numRetries())
          throw resp.error;

        resp.retryCount++;
      }
    });

    add('RETRY_SIGN', 'retry', function RETRY_SIGN(req) {
      req.emitEvents('sign');
    });

    add('RETRY_DELAY_SEND', 'retry', function RETRY_DELAY_SEND(req, resp) {
      var delay = 0;
      if (resp.error) {
        delay = req.client.retryDelays()[resp.retryCount] || 0;
      }
      setTimeout(function() {
        resp.error = null;
        resp.data = null;
        req.emitEvents('send');
      }, delay);
    });
  }),

  Json: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.Json;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  }),

  Rest: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.Rest;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  }),

  RestXml: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.RestXml;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  }),

  Query: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.Query;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  })
};
<commit_msg>Move FINALIZE_ERROR listener with other retry events<commit_after>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
require('./event_emitter');
require('./service_interface/json');
require('./service_interface/query');
require('./service_interface/rest');
require('./service_interface/rest_xml');

/**
 * @api private
 */
AWS.EventListeners = {
  Core: new AWS.EventEmitter().addNamedListeners(function(add) {
    add('VALIDATE_CREDENTIALS', 'validate',
        function VALIDATE_CREDENTIALS(req) {
      if (!req.client.config.credentials.accessKeyId ||
          !req.client.config.credentials.secretAccessKey) {
        throw AWS.util.error(new Error(),
          {code: 'SigningError', message: 'Missing credentials in config'});
      }
    });

    add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
      if (!req.client.config.region) {
        throw AWS.util.error(new Error(),
          {code: 'SigningError', message: 'Missing region in config'});
      }
    });

    add('SIGN', 'sign', function SIGN(req, resp) {
      var date = AWS.util.date.getDate();
      var credentials = AWS.util.copy(req.client.config.credentials);
      var SignerClass = req.client.signatureVersion;
      var signer = new SignerClass(resp.httpRequest, req.client.serviceName);

      // clear old authorization headers
      delete resp.httpRequest.headers['Authorization'];
      delete resp.httpRequest.headers['Date'];
      delete resp.httpRequest.headers['X-Amz-Date'];

      // add new authorization
      signer.addAuthorization(credentials, date);
    });

    add('SETUP_ERROR', 'extractError', function SETUP_ERROR(req, resp) {
      if (req.client.successfulResponse(req, resp)) {
        // throwing null will stop the error extraction chain
        // but will not set an error for data extraction
        throw null;
      }

      resp.error = AWS.util.error(new Error(),
        {code: 'UnknownError', message: 'An unknown error occurred.'});
      resp.data = null;
    });

    add('SETUP_DATA', 'extractData', function SETUP_DATA(req, resp) {
      resp.data = {};
      resp.error = null;
    });
  }),

  Http: new AWS.EventEmitter().addNamedListeners(function(add) {
    add('SEND', 'send', function SEND(req, resp) {
      AWS.HttpClient.getInstance().handleRequest(req, resp);
    });

    add('HTTP_HEADERS', 'httpHeaders',
        function HTTP_HEADERS(req, resp, statusCode, headers) {
      resp.httpResponse.statusCode = statusCode;
      resp.httpResponse.headers = headers;
      resp.httpResponse.body = '';
    });

    add('HTTP_DATA', 'httpData', function HTTP_DONE(req, resp, chunk) {
      resp.httpResponse.body += chunk;
    });

    add('HTTP_DONE', 'httpDone', function HTTP_DONE(req) {
      req.completeRequest();
    });

    add('HTTP_ERROR', 'httpError', function HTTP_ERROR(req, error) {
      req.response.error = error;
      req.completeRequest();
    });

    add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(req, resp) {
      resp.error.statusCode = resp.httpResponse.statusCode;
      if (resp.error.retryable === undefined) {
        resp.error.retryable = req.client.retryableError(resp.error, req);
      }
    });

    add('REDIRECT', 'retry', function REDIRECT(req, resp) {
      if (resp.error && resp.error.statusCode == 307) {
        resp.httpRequest.endpoint =
          new AWS.Endpoint(resp.httpResponse.headers['location']);
        resp.error = null;
      }
    });

    add('RETRY_CHECK', 'retry', function RETRY_CHECK(req, resp) {
      if (resp.error) {
        if (!resp.error.retryable)
          throw resp.error;
        if (resp.retryCount >= req.client.numRetries())
          throw resp.error;

        resp.retryCount++;
      }
    });

    add('RETRY_SIGN', 'retry', function RETRY_SIGN(req) {
      req.emitEvents('sign');
    });

    add('RETRY_DELAY_SEND', 'retry', function RETRY_DELAY_SEND(req, resp) {
      var delay = 0;
      if (resp.error) {
        delay = req.client.retryDelays()[resp.retryCount] || 0;
      }
      setTimeout(function() {
        resp.error = null;
        resp.data = null;
        req.emitEvents('send');
      }, delay);
    });
  }),

  Json: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.Json;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  }),

  Rest: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.Rest;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  }),

  RestXml: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.RestXml;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  }),

  Query: new AWS.EventEmitter().addNamedListeners(function(add) {
    var svc = AWS.ServiceInterface.Query;
    add('BUILD', 'build', svc.buildRequest);
    add('EXTRACT_DATA', 'extractData', svc.extractData);
    add('EXTRACT_ERROR', 'extractError', svc.extractError);
  })
};
<|endoftext|>


<commit_before>var bodyParser = require('body-parser');
var express = require('express');
var multer = require('multer');

module.exports = function createDynamicRouter (keystone) {

	// ensure keystone nav has been initialised
	// TODO: move this elsewhere (on demand generation, or client-side?)
	if (!keystone.nav) {
		keystone.nav = keystone.initNav();
	}

	var router = express.Router();

	// Use bodyParser and multer to parse request bodies and file uploads
	router.use(bodyParser.json({}));
	router.use(bodyParser.urlencoded({ extended: true }));
	router.use(multer({ includeEmptyFields: true }));

	// #1: Session API
	// TODO: this should respect keystone auth options
	router.get('/api/session', require('../api/session/get'));
	router.post('/api/session/signin', require('../api/session/signin'));
	router.post('/api/session/signout', require('../api/session/signout'));

	// #2: Session Routes
	// Bind auth middleware (generic or custom) to * routes, allowing
	// access to the generic signin page if generic auth is used
	if (keystone.get('auth') === true) {
		// TODO: poor separation of concerns; settings should be defaulted elsewhere
		if (!keystone.get('signout url')) {
			keystone.set('signout url', '/' + keystone.get('admin path') + '/signout');
		}
		if (!keystone.get('signin url')) {
			keystone.set('signin url', '/' + keystone.get('admin path') + '/signin');
		}
		if (!keystone.nativeApp || !keystone.get('session')) {
			router.all('*', keystone.session.persist);
		}
		router.all('/signin', require('../routes/signin'));
		router.all('/signout', require('../routes/signout'));
		router.use(keystone.session.keystoneAuth);
	} else if (typeof keystone.get('auth') === 'function') {
		router.use(keystone.get('auth'));
	}

	// #3: Home route
	router.get('/', require('../routes/home'));

	// #4: Cloudinary and S3 specific APIs
	// TODO: poor separation of concerns; should / could this happen elsewhere?
	if (keystone.get('cloudinary config')) {
		router.get('/api/cloudinary/get', require('../api/cloudinary').get);
		router.get('/api/cloudinary/autocomplete', require('../api/cloudinary').autocomplete);
		router.post('/api/cloudinary/upload', require('../api/cloudinary').upload);
	}
	if (keystone.get('s3 config')) {
		router.post('/api/s3/upload', require('../api/s3').upload);
	}

	// #5: Core Lists API

	// Init API request helpers
	router.use('/api', require('../middleware/apiError'));
	router.use('/api', require('../middleware/logError'));

	// Init req with list
	var initList = require('../middleware/initList')(keystone);
	// lists
	router.all('/api/counts', require('../api/counts'));
	router.get('/api/:list', initList(), require('../api/list/get'));
	router.get('/api/:list/:format(export.csv|export.json)', initList(), require('../api/list/download'));
	router.post('/api/:list/create', initList(), require('../api/list/create'));
	router.post('/api/:list/update', initList(), require('../api/list/update'));
	router.post('/api/:list/delete', initList(), require('../api/list/delete'));
	// items
	router.get('/api/:list/:id', initList(), require('../api/item/get'));
	router.post('/api/:list/:id', initList(), require('../api/item/update'));
	router.post('/api/:list/:id/delete', initList(), require('../api/list/delete'));
	router.post('/api/:list/:id/sortOrder/:sortOrder/:newOrder', initList(), require('../api/item/sortOrder'));
	// #6: List Routes
	router.all('/:list/:page([0-9]{1,5})?', initList(true), require('../routes/list'));
	router.all('/:list/:item', initList(true), require('../routes/item'));

	// TODO: catch 404s and errors with Admin-UI specific handlers

	return router;
};
<commit_msg>Routing to legacy API endpoints in express stack<commit_after>var bodyParser = require('body-parser');
var express = require('express');
var multer = require('multer');

module.exports = function createDynamicRouter (keystone) {

	// ensure keystone nav has been initialised
	// TODO: move this elsewhere (on demand generation, or client-side?)
	if (!keystone.nav) {
		keystone.nav = keystone.initNav();
	}

	var router = express.Router();

	// Use bodyParser and multer to parse request bodies and file uploads
	router.use(bodyParser.json({}));
	router.use(bodyParser.urlencoded({ extended: true }));
	router.use(multer({ includeEmptyFields: true }));

	// #1: Session API
	// TODO: this should respect keystone auth options
	router.get('/api/session', require('../api/session/get'));
	router.post('/api/session/signin', require('../api/session/signin'));
	router.post('/api/session/signout', require('../api/session/signout'));

	// #2: Session Routes
	// Bind auth middleware (generic or custom) to * routes, allowing
	// access to the generic signin page if generic auth is used
	if (keystone.get('auth') === true) {
		// TODO: poor separation of concerns; settings should be defaulted elsewhere
		if (!keystone.get('signout url')) {
			keystone.set('signout url', '/' + keystone.get('admin path') + '/signout');
		}
		if (!keystone.get('signin url')) {
			keystone.set('signin url', '/' + keystone.get('admin path') + '/signin');
		}
		if (!keystone.nativeApp || !keystone.get('session')) {
			router.all('*', keystone.session.persist);
		}
		router.all('/signin', require('../routes/signin'));
		router.all('/signout', require('../routes/signout'));
		router.use(keystone.session.keystoneAuth);
	} else if (typeof keystone.get('auth') === 'function') {
		router.use(keystone.get('auth'));
	}

	// #3: Home route
	router.get('/', require('../routes/home'));

	// #4: Cloudinary and S3 specific APIs
	// TODO: poor separation of concerns; should / could this happen elsewhere?
	if (keystone.get('cloudinary config')) {
		router.get('/api/cloudinary/get', require('../api/cloudinary').get);
		router.get('/api/cloudinary/autocomplete', require('../api/cloudinary').autocomplete);
		router.post('/api/cloudinary/upload', require('../api/cloudinary').upload);
	}
	if (keystone.get('s3 config')) {
		router.post('/api/s3/upload', require('../api/s3').upload);
	}

	// #5: Core Lists API
	var initList = require('../middleware/initList')(keystone);

	// Init API request helpers
	router.use('/api', require('../middleware/apiError'));
	router.use('/api', require('../middleware/logError'));

	// Legacy API endpoints
	router.post('/api/legacy/:list/create', initList(), require('../api/list/legacyCreate'));
	router.post('/api/legacy/:list/:id', initList(), require('../api/item/legacyUpdate'));

	// lists
	router.all('/api/counts', require('../api/counts'));
	router.get('/api/:list', initList(), require('../api/list/get'));
	router.get('/api/:list/:format(export.csv|export.json)', initList(), require('../api/list/download'));
	router.post('/api/:list/create', initList(), require('../api/list/create'));
	router.post('/api/:list/update', initList(), require('../api/list/update'));
	router.post('/api/:list/delete', initList(), require('../api/list/delete'));
	// items
	router.get('/api/:list/:id', initList(), require('../api/item/get'));
	router.post('/api/:list/:id', initList(), require('../api/item/update'));
	router.post('/api/:list/:id/delete', initList(), require('../api/list/delete'));
	router.post('/api/:list/:id/sortOrder/:sortOrder/:newOrder', initList(), require('../api/item/sortOrder'));

	// #6: List Routes
	router.all('/:list/:page([0-9]{1,5})?', initList(true), require('../routes/list'));
	router.all('/:list/:item', initList(true), require('../routes/item'));

	// TODO: catch 404s and errors with Admin-UI specific handlers

	return router;
};
<|endoftext|>


<commit_before>// Load in requirements
var fs = require('fs');
var path = require('path');
var deepClone = require('clone');
var mkdirp = require('mkdirp');

/**
 * Filesystem storage system with in-memory cache
 * @param options {Object} Required container for options
 * @param [options.ext='.json'] {String} Optional extension to save values under
 * @param [options.stringify=JSON.stringify] {Function} Optional stringifier to pass values through
 * @param [options.parse=JSON.parse] {Function} Optional parser to load values through
 */
function Store(options) {
  this.dir = options.directory;
  this.memoryCache = {};
  this.ext = options.ext || '.json';
  this.stringify = options.stringify || JSON.stringify;
  this.parse = options.parse || JSON.parse;
}
Store.prototype = {
  getFilepath: function (key) {
    return path.join(this.dir, key + '.json');
  },
  get: function (key, cb) {
    var memoryCache = this.memoryCache;
    var cachedData = memoryCache[key];
    if (cachedData) {
      process.nextTick(function () {
        // DEV: Technically, this clone is not necessary since res.send serializes
        // However, it is good to future proof against internal changes
        cb(null, deepClone(cachedData));
      });
    } else {
      fs.readFile(this.getFilepath(key), function parseResponse (err, content) {
        // If there was an error
        if (err) {
          // If the file was not found, send back nothing
          if (err.code === 'ENOENT') {
            return cb(null, null);
          // Otherwise, send back the error
          } else {
            return cb(err);
          }
        }

        // Otherwise, parse the file
        // DEV: We use a try/catch in case the JSON is invalid
        var data;
        try {
          data = JSON.parse(content);
        } catch (err) {
          return cb(err);
        }
        memoryCache[key] = data;
        cb(null, deepClone(data));
      });
    }
  },
  set: function (key, data, cb) {
    var filepath = this.getFilepath(key);
    var that = this;
    mkdirp(path.dirname(filepath), function (err) {
      if (err) {
        return cb(err);
      }
      that.memoryCache[key] = data;
      fs.writeFile(filepath, JSON.stringify(data, null, 2), cb);
    });
  }
};

// Export the store
module.exports = Store;
<commit_msg>Moved internals to new options<commit_after>// Load in requirements
var fs = require('fs');
var path = require('path');
var deepClone = require('clone');
var mkdirp = require('mkdirp');

/**
 * Filesystem storage system with in-memory cache
 * @param options {Object} Required container for options
 * @param [options.ext='.json'] {String} Optional extension to save values under
 * @param [options.stringify=JSON.stringify] {Function} Optional stringifier to pass values through
 * @param [options.parse=JSON.parse] {Function} Optional parser to load values through
 */
function Store(options) {
  this.dir = options.directory;
  this.memoryCache = {};
  this.ext = options.ext || '.json';
  this.stringify = options.stringify || JSON.stringify;
  this.parse = options.parse || JSON.parse;
}
Store.prototype = {
  getFilepath: function (key) {
    return path.join(this.dir, key + this.ext);
  },
  get: function (key, cb) {
    var memoryCache = this.memoryCache;
    var cachedData = memoryCache[key];
    if (cachedData) {
      process.nextTick(function () {
        // Deep clone the data to prevent mutation of internal cache
        cb(null, deepClone(cachedData));
      });
    } else {
      fs.readFile(this.getFilepath(key), function parseResponse (err, content) {
        // If there was an error
        if (err) {
          // If the file was not found, send back nothing
          if (err.code === 'ENOENT') {
            return cb(null, null);
          // Otherwise, send back the error
          } else {
            return cb(err);
          }
        }

        // Otherwise, parse the file
        // DEV: We use a try/catch in case the JSON is invalid
        var data;
        try {
          data = this.parse(content);
        } catch (err) {
          return cb(err);
        }
        memoryCache[key] = data;
        cb(null, deepClone(data));
      });
    }
  },
  set: function (key, data, cb) {
    var filepath = this.getFilepath(key);
    var that = this;
    mkdirp(path.dirname(filepath), function (err) {
      if (err) {
        return cb(err);
      }
      that.memoryCache[key] = data;
      fs.writeFile(filepath, this.stringify(data), cb);
    });
  }
};

// Export the store
module.exports = Store;
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const vm = require('vm');
const _ = require('lodash');
const EXEC_TIMEOUT = 2000;
const pouch = require('../pouch-graphql/pouchdb');

module.exports = {
  exec: exec,
};

function exec(args) {
  let logOutput = '';
  let implementation = args.implementation;
  if(_.isFunction(implementation)) implementation = `module.exports=${implementation.toString()}`;

  try {
    const scriptSandbox = {
      require: require,
      module: module,
      exports: module.exports,
      setTimeout: setTimeout,
      clearTimeout: clearTimeout,
      setInterval: setInterval,
      clearInterval: clearInterval,
      console: console,
      Buffer: Buffer,
    };

    const moduleExecutionContext = {
      pouchdb: envName => pouch.createPouchDB(envName || 'default'),
      log: value => {
        logOutput += `${JSON.stringify(value, null, 4)}\\r\\n`;
      },
    };

    const done = new Promise((resolve, reject) => {
      moduleExecutionContext.success = resolve;
      moduleExecutionContext.failure = reject;
    });

    scriptSandbox.moduleExecutionContext = moduleExecutionContext;
    scriptSandbox.data = args.input;
    scriptSandbox.context = args.context;
    vm.createContext(scriptSandbox);
    setTimeout(() => moduleExecutionContext.failure(new Error('Time out')), EXEC_TIMEOUT);
    vm.runInContext(`${implementation}\r\nmodule.exports(moduleExecutionContext, data);`, scriptSandbox, {filename: args.name, displayErrors: false, timeout: EXEC_TIMEOUT});

    return done
      .then(output => Object.assign(output, {log:logOutput}));

  } catch(error) {
    console.log(error)
    return Object.assign({message: error.message ? error.message : error}, {log:logOutput});
  }
}
<commit_msg>Increase function execution timeout<commit_after>const fs = require('fs');
const path = require('path');
const vm = require('vm');
const _ = require('lodash');
const EXEC_TIMEOUT = 60000;
const pouch = require('../pouch-graphql/pouchdb');

module.exports = {
  exec: exec,
};

function exec(args) {
  let logOutput = '';
  let implementation = args.implementation;
  if(_.isFunction(implementation)) implementation = `module.exports=${implementation.toString()}`;

  try {
    const scriptSandbox = {
      require: require,
      module: module,
      exports: module.exports,
      setTimeout: setTimeout,
      clearTimeout: clearTimeout,
      setInterval: setInterval,
      clearInterval: clearInterval,
      console: console,
      Buffer: Buffer,
    };

    const moduleExecutionContext = {
      pouchdb: envName => pouch.createPouchDB(envName || 'default'),
      log: value => {
        logOutput += `${JSON.stringify(value, null, 4)}\\r\\n`;
      },
    };

    const done = new Promise((resolve, reject) => {
      moduleExecutionContext.success = resolve;
      moduleExecutionContext.failure = reject;
    });

    scriptSandbox.moduleExecutionContext = moduleExecutionContext;
    scriptSandbox.data = args.input;
    scriptSandbox.context = args.context;
    vm.createContext(scriptSandbox);
    setTimeout(() => moduleExecutionContext.failure(new Error('GraphQL-Pouch function execution time out')), EXEC_TIMEOUT);
    vm.runInContext(`${implementation}\r\nmodule.exports(moduleExecutionContext, data);`, scriptSandbox, {filename: args.name, displayErrors: false, timeout: EXEC_TIMEOUT});

    return done
      .then(output => Object.assign(output, {log:logOutput}));

  } catch(error) {
    console.log(error)
    return Object.assign({message: error.message ? error.message : error}, {log:logOutput});
  }
}
<|endoftext|>


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

define(function(require, exports, module) {

var Requisition = require('gcli/cli').Requisition;
var Status = require('gcli/types').Status;
var javascript = require('gcli/types/javascript');
var canon = require('gcli/canon');

var assert = require('test/assert');

var debug = false;
var requ;

var assign;
var status;
var statuses;
var tempWindow;

exports.setup = function(options) {
  tempWindow = javascript.getGlobalObject();
  javascript.setGlobalObject(options.window);

  Object.defineProperty(options.window, 'donteval', {
    get: function() {
      assert.ok(false, 'donteval should not be used');
      return { cant: '', touch: '', 'this': '' };
    },
    enumerable: true,
    configurable : true
  });
};

exports.shutdown = function(options) {
  delete options.window.donteval;

  javascript.setGlobalObject(tempWindow);
  tempWindow = undefined;
};

function input(typed) {
  if (!requ) {
    requ = new Requisition();
  }
  var cursor = { start: typed.length, end: typed.length };
  requ.update(typed);

  if (debug) {
    console.log('####### TEST: typed="' + typed +
        '" cur=' + cursor.start +
        ' cli=', requ);
  }

  status = requ.getStatus();
  statuses = requ.getInputStatusMarkup(cursor.start).map(function(s) {
    return Array(s.string.length + 1).join(s.status.toString()[0]);
  }).join('');

  if (requ.commandAssignment.value) {
    assign = requ.getAssignment(0);
  }
  else {
    assign = undefined;
  }
}

function predictionsHas(name) {
  return assign.getPredictions().some(function(prediction) {
    return name === prediction.name;
  }, this);
}

function check(expStatuses, expStatus, expAssign, expPredict) {
  assert.is('{', requ.commandAssignment.value.name, 'is exec');

  assert.is(expStatuses, statuses, 'unexpected status markup');
  assert.is(expStatus.toString(), status.toString(), 'unexpected status');
  assert.is(expAssign, assign.value, 'unexpected assignment');

  if (expPredict != null) {
    var contains;
    if (Array.isArray(expPredict)) {
      expPredict.forEach(function(p) {
        contains = predictionsHas(p);
        assert.ok(contains, 'missing prediction ' + p);
      });
    }
    else if (typeof expPredict === 'number') {
      contains = true;
      assert.is(assign.getPredictions().length, expPredict, 'prediction count');
      if (assign.getPredictions().length !== expPredict) {
        assign.getPredictions().forEach(function(prediction) {
          assert.log('actual prediction: ', prediction);
        });
      }
    }
    else {
      contains = predictionsHas(expPredict);
      assert.ok(contains, 'missing prediction ' + expPredict);
    }

    if (!contains) {
      assert.log('Predictions: ' + assign.getPredictions().map(function(p) {
        return p.name;
      }).join(', '));
    }
  }
}

exports.testBasic = function(options) {
  if (!canon.getCommand('{')) {
    assert.log('Skipping exec tests because { is not registered');
    return;
  }

  input('{');
  check('V', Status.ERROR, undefined);

  input('{ ');
  check('VV', Status.ERROR, undefined);

  input('{ w');
  check('VVI', Status.ERROR, 'w', 'window');

  input('{ windo');
  check('VVIIIII', Status.ERROR, 'windo', 'window');

  input('{ window');
  check('VVVVVVVV', Status.VALID, 'window');

  input('{ window.d');
  check('VVIIIIIIII', Status.ERROR, 'window.d', 'window.document');

  input('{ window.document.title');
  check('VVVVVVVVVVVVVVVVVVVVVVV', Status.VALID, 'window.document.title', 0);

  input('{ d');
  check('VVI', Status.ERROR, 'd', 'document');

  input('{ document.title');
  check('VVVVVVVVVVVVVVVV', Status.VALID, 'document.title', 0);

  if (!options.isJsdom) {
    // jsdom causes an eval here, maybe that's node/v8?
    assert.ok('donteval' in options.window, 'donteval exists');
  }

  input('{ don');
  check('VVIII', Status.ERROR, 'don', 'donteval');

  input('{ donteval');
  check('VVVVVVVVVV', Status.VALID, 'donteval', 0);

  /*
  // This is a controversial test - technically we can tell that it's an error
  // because 'donteval.' is a syntax error, however donteval is unsafe so we
  // are playing safe by bailing out early. It's enough of a corner case that
  // I don't think it warrants fixing
  input('{ donteval.');
  check('VVIIIIIIIII', Status.ERROR, 'donteval.', 0);
  */

  input('{ donteval.cant');
  check('VVVVVVVVVVVVVVV', Status.VALID, 'donteval.cant', 0);

  input('{ donteval.xxx');
  check('VVVVVVVVVVVVVV', Status.VALID, 'donteval.xxx', 0);
};

});
<commit_msg>asynctypes-685526: Convert testJs to use helpers<commit_after>/*
 * Copyright 2012, Mozilla Foundation and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(function(require, exports, module) {

var assert = require('test/assert');
var helpers = require('gclitest/helpers');
var javascript = require('gcli/types/javascript');
var canon = require('gcli/canon');

var tempWindow = undefined;

exports.setup = function(options) {
  helpers.setup(options);

  tempWindow = javascript.getGlobalObject();
  Object.defineProperty(options.window, 'donteval', {
    get: function() {
      assert.ok(false, 'donteval should not be used');
      return { cant: '', touch: '', 'this': '' };
    },
    enumerable: true,
    configurable : true
  });
  javascript.setGlobalObject(options.window);
};

exports.shutdown = function(options) {
  helpers.shutdown(options);

  javascript.setGlobalObject(tempWindow);
  tempWindow = undefined;
  delete options.window.donteval;
};

exports.testBasic = function(options) {
  if (!canon.getCommand('{')) {
    assert.log('Skipping exec tests because { is not registered');
    return;
  }

  helpers.setInput('{');
  helpers.check({
    input:  '{',
    hints:   '',
    markup: 'V',
    cursor: 1,
    current: 'javascript',
    status: 'ERROR',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: undefined,
        arg: '{',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.setInput('{ ');
  helpers.check({
    input:  '{ ',
    hints:    '',
    markup: 'VV',
    cursor: 2,
    current: 'javascript',
    status: 'ERROR',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: undefined,
        arg: '{ ',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.setInput('{ w');
  helpers.check({
    input:  '{ w',
    hints:     'indow',
    markup: 'VVI',
    cursor: 3,
    current: 'javascript',
    status: 'ERROR',
    predictionsContains: [ 'window' ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'w',
        arg: '{ w',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.setInput('{ windo');
  helpers.check({
    input:  '{ windo',
    hints:         'w',
    markup: 'VVIIIII',
    cursor: 7,
    current: 'javascript',
    status: 'ERROR',
    predictions: [ 'window' ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'windo',
        arg: '{ windo',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.setInput('{ window');
  helpers.check({
    input:  '{ window',
    hints:          '',
    markup: 'VVVVVVVV',
    cursor: 8,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'window',
        arg: '{ window',
        status: 'VALID',
        message: ''
      }
    }
  });

  helpers.setInput('{ window.do');
  helpers.check({
    input:  '{ window.do',
    hints:             'cument',
    markup: 'VVIIIIIIIII',
    cursor: 11,
    current: 'javascript',
    status: 'ERROR',
    predictionsContains: [ 'window.document' ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'window.do',
        arg: '{ window.do',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.setInput('{ window.document.title');
  helpers.check({
    input:  '{ window.document.title',
    hints:                         '',
    markup: 'VVVVVVVVVVVVVVVVVVVVVVV',
    cursor: 23,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'window.document.title',
        arg: '{ window.document.title',
        status: 'VALID',
        message: ''
      }
    }
  });
};

exports.testDocument = function(options) {
  helpers.setInput('{ docu');
  helpers.check({
    input:  '{ docu',
    hints:        'ment',
    markup: 'VVIIII',
    cursor: 6,
    current: 'javascript',
    status: 'ERROR',
    predictions: [ 'document' ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'docu',
        arg: '{ docu',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.pressTab();
  helpers.check({
    input:  '{ document',
    hints:            '',
    markup: 'VVVVVVVVVV',
    cursor: 10,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'document',
        arg: '{ document',
        status: 'VALID',
        message: ''
      }
    }
  });

  helpers.setInput('{ document.titl');
  helpers.check({
    input:  '{ document.titl',
    hints:                 'e',
    markup: 'VVIIIIIIIIIIIII',
    cursor: 15,
    current: 'javascript',
    status: 'ERROR',
    predictions: [ 'document.title' ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'document.titl',
        arg: '{ document.titl',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.pressTab();
  helpers.setInput('{ document.title ');
  helpers.check({
    input:  '{ document.title ',
    hints:                   '',
    markup: 'VVVVVVVVVVVVVVVVV',
    cursor: 17,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'document.title',
        arg: '{ document.title ',
        status: 'VALID',
        message: ''
      }
    }
  });

  helpers.setInput('{ document.title');
  helpers.check({
    input:  '{ document.title',
    hints:                  '',
    markup: 'VVVVVVVVVVVVVVVV',
    cursor: 16,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'document.title',
        arg: '{ document.title',
        status: 'VALID',
        message: ''
      }
    }
  });
};

exports.testDonteval = function(options) {
  if (!options.isJsdom) {
    // jsdom causes an eval here, maybe that's node/v8?
    assert.ok('donteval' in options.window, 'donteval exists');
  }

  helpers.setInput('{ don');
  helpers.check({
    input:  '{ don',
    hints:       'teval',
    markup: 'VVIII',
    cursor: 5,
    current: 'javascript',
    status: 'ERROR',
    predictions: [ 'donteval' ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'don',
        arg: '{ don',
        status: 'INCOMPLETE',
        message: ''
      }
    }
  });

  helpers.setInput('{ donteval');
  helpers.check({
    input:  '{ donteval',
    hints:            '',
    markup: 'VVVVVVVVVV',
    cursor: 10,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'donteval',
        arg: '{ donteval',
        status: 'VALID',
        message: ''
      }
    }
  });

  /*
  // This is a controversial test - technically we can tell that it's an error
  // because 'donteval.' is a syntax error, however donteval is unsafe so we
  // are playing safe by bailing out early. It's enough of a corner case that
  // I don't think it warrants fixing
  helpers.setInput('{ donteval.');
  helpers.check({
    input:  '{ donteval.',
    hints:             '',
    markup: 'VVVVVVVVVVV',
    cursor: 11,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'donteval.',
        arg: '{ donteval.',
        status: 'VALID',
        message: ''
      }
    }
  });
  */

  helpers.setInput('{ donteval.cant');
  helpers.check({
    input:  '{ donteval.cant',
    hints:                 '',
    markup: 'VVVVVVVVVVVVVVV',
    cursor: 15,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'donteval.cant',
        arg: '{ donteval.cant',
        status: 'VALID',
        message: ''
      }
    }
  });

  helpers.setInput('{ donteval.xxx');
  helpers.check({
    input:  '{ donteval.xxx',
    hints:                '',
    markup: 'VVVVVVVVVVVVVV',
    cursor: 14,
    current: 'javascript',
    status: 'VALID',
    predictions: [ ],
    unassigned: [ ],
    args: {
      command: { name: '{' },
      javascript: {
        value: 'donteval.xxx',
        arg: '{ donteval.xxx',
        status: 'VALID',
        message: ''
      }
    }
  });
};

});
<|endoftext|>