<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';

window['requirejs'].config({
    map: {
        '*': {
            'jupyter-js-widgets': 'nbextensions/jupyter-js-widgets/extension',
        },
    }
});

var MIME_TYPE = 'application/vnd.jupyter.widget-view+json';
var CLASS_NAME = 'jupyter-widgets-view';

var mngr = require("./manager");
require("./save_state");
require("./embed_widgets");
var PhosphorWidget = require("@phosphor/widgets");

/**
 * Create a widget manager for a kernel instance.
 */
var handle_kernel = function(Jupyter, kernel) {
    if (kernel.comm_manager && kernel.widget_manager === undefined) {

        // Create a widget manager instance. Use the global
        // Jupyter.notebook handle.
        var manager = new mngr.WidgetManager(kernel.comm_manager, Jupyter.notebook);

        // For backwards compatibility and interactive use.
        Jupyter.WidgetManager = mngr.WidgetManager;

        // Store a handle to the manager so we know not to
        // another for this kernel. This also is a convenience
        // for the user.
        kernel.widget_manager = manager;
    }
};

function register_events(Jupyter, events, outputarea) {
    // If a kernel already exists, create a widget manager.
    if (Jupyter.notebook && Jupyter.notebook.kernel) {
        handle_kernel(Jupyter, Jupyter.notebook.kernel);
    }
    // When the kernel is created, create a widget manager.
    events.on('kernel_created.Kernel kernel_created.Session', function(event, data) {
        handle_kernel(Jupyter, data.kernel);
    });

    /**
     * The views on this page. We keep this list so that we can call the view.remove()
     * method when a view is removed from the page.
     */
    var views = {};
    var removeView = function(event, data) {
        var output = data.cell.output_area;
        var viewids = (output && output._jupyterWidgetViews) || void 0;
        if (viewids) {
            viewids.forEach(function(id) {
                // this may be called after the widget is pulled off the page
                // so we temporarily put it back on the page as a kludge
                // so that phosphor can trigger the appropriate detach signals
                var view = views[id];
                view.el.style.display="none";
                document.body.appendChild(view.el);
                view.remove();
                delete views[id];
            });
            output._jupyterWidgetViews = [];
        }
    }

    events.on('delete.Cell', removeView);
    events.on('execute.CodeCell', removeView);
    events.on('clear_output.CodeCell', removeView);
    events.on('clear_output.OutputArea', removeView);

    /**
     * Render data to the output area.
     *
     * `this` is the output area
     */
    function render(output, data, node) {
        // data is a model id
        var manager = Jupyter.notebook.kernel.widget_manager;
        if (!manager) {
            node.textContent = "Missing widget manager";
            return;
        }

        var model = manager.get_model(data.model_id);
        if (model) {
            model.then(function(model) {
                return manager.display_model(void 0, model, void 0);
            }).then(function(view) {
                var id = view.cid;
                output._jupyterWidgetViews = output._jupyterWidgetViews || [];
                output._jupyterWidgetViews.push(id);
                views[id] = view;
                PhosphorWidget.Widget.attach(view.pWidget, node);
            });
        } else {
            node.textContent = "Widget not found: "+JSON.stringify(data);
        }
    }

    // `this` is the output area we are appending to
    var append_mime = function(json, md, element) {
        var toinsert = this.create_output_subarea(md, CLASS_NAME, MIME_TYPE);
        this.keyboard_manager.register_events(toinsert);
        render(this, json, toinsert[0]);
        element.append(toinsert);
        return toinsert;
    };
    // Register mime type with the output area
    outputarea.OutputArea.prototype.register_mime_type(MIME_TYPE, append_mime, {
        // An output widget could contain arbitrary user javascript
        safe: false,
        // Index of renderer in `output_area.display_order`
        index: 0
    });
}

function load_ipython_extension () {
    return new Promise(function(resolve) {
        requirejs([
            "base/js/namespace",
            "base/js/events",
            "notebook/js/outputarea"
        ], function(Jupyter, events, outputarea) {
            require("@phosphor/widgets/style/index.css")
            require('jupyter-js-widgets/css/widgets.css');
            register_events(Jupyter, events, outputarea);
            resolve();
        });
    });
}

var _ = require('underscore');
module.exports = _.extend({
  load_ipython_extension: load_ipython_extension,
}, require('jupyter-js-widgets'), require('./widget_output'));
<commit_msg>Fix calling .remove() on views.<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';

window['requirejs'].config({
    map: {
        '*': {
            'jupyter-js-widgets': 'nbextensions/jupyter-js-widgets/extension',
        },
    }
});

var MIME_TYPE = 'application/vnd.jupyter.widget-view+json';
var CLASS_NAME = 'jupyter-widgets-view';

var mngr = require("./manager");
require("./save_state");
require("./embed_widgets");
var PhosphorWidget = require("@phosphor/widgets");

/**
 * Create a widget manager for a kernel instance.
 */
var handle_kernel = function(Jupyter, kernel) {
    if (kernel.comm_manager && kernel.widget_manager === undefined) {

        // Create a widget manager instance. Use the global
        // Jupyter.notebook handle.
        var manager = new mngr.WidgetManager(kernel.comm_manager, Jupyter.notebook);

        // For backwards compatibility and interactive use.
        Jupyter.WidgetManager = mngr.WidgetManager;

        // Store a handle to the manager so we know not to
        // another for this kernel. This also is a convenience
        // for the user.
        kernel.widget_manager = manager;
    }
};

function register_events(Jupyter, events, outputarea) {
    // If a kernel already exists, create a widget manager.
    if (Jupyter.notebook && Jupyter.notebook.kernel) {
        handle_kernel(Jupyter, Jupyter.notebook.kernel);
    }
    // When the kernel is created, create a widget manager.
    events.on('kernel_created.Kernel kernel_created.Session', function(event, data) {
        handle_kernel(Jupyter, data.kernel);
    });

    /**
     * The views on this page. We keep this list so that we can call the view.remove()
     * method when a view is removed from the page.
     */
    var views = {};
    var removeView = function(event, data) {
        var output = data.cell ? data.cell.output_area : data.output_area;
        var viewids = output ? output._jupyterWidgetViews : void 0;
        if (viewids) {
            viewids.forEach(function(id) {
                // this may be called after the widget is pulled off the page
                // so we temporarily put it back on the page as a kludge
                // so that phosphor can trigger the appropriate detach signals
                var view = views[id];
                view.el.style.display="none";
                document.body.appendChild(view.el);
                view.remove();
                delete views[id];
            });
            output._jupyterWidgetViews = [];
        }
    }

    // Deleting a cell does *not* clear the outputs first.
    events.on('delete.Cell', removeView);
    // add an event to the notebook element for *any* outputs that are cleared.
    Jupyter.notebook.container.on('clearing', '.output', removeView);

    // For before https://github.com/jupyter/notebook/pull/2411 is merged and
    // released. This does not handle the case where an empty cell is executed
    // to clear input.
    events.on('execute.CodeCell', removeView);
    events.on('clear_output.CodeCell', removeView);
    events.on('clear_output.OutputArea', removeView);

    /**
     * Render data to the output area.
     */
    function render(output, data, node) {
        // data is a model id
        var manager = Jupyter.notebook.kernel.widget_manager;
        if (!manager) {
            node.textContent = "Missing widget manager";
            return;
        }

        var model = manager.get_model(data.model_id);
        if (model) {
            model.then(function(model) {
                return manager.display_model(void 0, model, void 0);
            }).then(function(view) {
                var id = view.cid;
                output._jupyterWidgetViews = output._jupyterWidgetViews || [];
                output._jupyterWidgetViews.push(id);
                views[id] = view;
                PhosphorWidget.Widget.attach(view.pWidget, node);
            });
        } else {
            node.textContent = "Widget not found: "+JSON.stringify(data);
        }
    }

    // `this` is the output area we are appending to
    var append_mime = function(json, md, element) {
        var toinsert = this.create_output_subarea(md, CLASS_NAME, MIME_TYPE);
        this.keyboard_manager.register_events(toinsert);
        render(this, json, toinsert[0]);
        element.append(toinsert);
        return toinsert;
    };
    // Register mime type with the output area
    outputarea.OutputArea.prototype.register_mime_type(MIME_TYPE, append_mime, {
        // An output widget could contain arbitrary user javascript
        safe: false,
        // Index of renderer in `output_area.display_order`
        index: 0
    });
}

function load_ipython_extension () {
    return new Promise(function(resolve) {
        requirejs([
            "base/js/namespace",
            "base/js/events",
            "notebook/js/outputarea"
        ], function(Jupyter, events, outputarea) {
            require("@phosphor/widgets/style/index.css")
            require('jupyter-js-widgets/css/widgets.css');
            register_events(Jupyter, events, outputarea);
            resolve();
        });
    });
}

var _ = require('underscore');
module.exports = _.extend({
  load_ipython_extension: load_ipython_extension,
}, require('jupyter-js-widgets'), require('./widget_output'));
<|endoftext|>


<commit_before>// @flow
import path from 'path';
import { execSync } from 'child_process';

const electronRebuildCmd =
  '../node_modules/.bin/electron-rebuild --parallel --force --types prod,dev,optional --module-dir .';

const cmd = process.platform === 'win32'
  ? electronRebuildCmd.replace(/\//g, '\\')
  : electronRebuildCmd;

execSync(cmd, {
  cwd: path.join(__dirname, '..', '..', 'app')
});
<commit_msg>Fix electron-rebuild script (#1370)<commit_after>// @flow
import path from 'path';
import { execSync } from 'child_process';
import fs from 'fs';
import dependencies from '../../app/package.json';

const nodeModulesPath =
  path.join(__dirname, '..', '..', 'app', 'node_modules');

if (Object.keys(dependencies || {}).length > 0 && fs.existsSync(nodeModulesPath)) {
  const electronRebuildCmd =
  '../node_modules/.bin/electron-rebuild --parallel --force --types prod,dev,optional --module-dir .';

  const cmd = process.platform === 'win32'
    ? electronRebuildCmd.replace(/\//g, '\\')
    : electronRebuildCmd;

  execSync(cmd, {
    cwd: path.join(__dirname, '..', '..', 'app')
  });
}
<|endoftext|>


<commit_before>require('../support/test_helper');

var assert = require('../support/assert');
var geojsonValue = require('../support/geojson_value').multilayer;
var TestClient = require('../support/test_client');

describe('Rendering multiple geojson layers', function() {
    var cartocssVersion = '2.3.0';
    var cartocss = '#layer { line-width:16; }';

    var mapnikLayer1 = {
        type: 'mapnik',
        options: {
            sql: 'select * from test_table limit 2',
            cartocss_version: cartocssVersion,
            cartocss: cartocss
        }
    };

    var mapnikLayer2 = {
        type: 'mapnik',
        options: {
            sql: 'select * from test_table_2 limit 4',
            cartocss_version: cartocssVersion,
            cartocss: cartocss
        }
    };

    var mapnikLayer3 = {
        type: 'mapnik',
        options: {
            sql: 'select * from test_table_3 limit 3',
            cartocss_version: cartocssVersion,
            cartocss: cartocss
        }
    };

    beforeEach(function () {
        this.testClient = new TestClient({
            version: '1.4.0',
            layers: [
                mapnikLayer1,
                mapnikLayer2,
                mapnikLayer3
            ]
        });
        this.options = { format: 'geojson'};
    });

    it('for all layers should return a multilayer geojson', function (done) {
        this.options.layer = undefined;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue);
            done();
        });
    });

    it('for "mapnik" layer param should return a multilayer geojson', function (done) {
        this.options.layer = 'mapnik';

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue);
            done();
        });
    });

    it('for layers 0 and 2 should return a multilayer geojson using the requested layers', function (done) {
        this.options.layer = '0,2';
        var geojsonExpected = {
            type: "FeatureCollection",
            features: [
                geojsonValue.features[0],
                geojsonValue.features[2]
            ]
        };

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonExpected);
            done();
        });
    });

    it('for layers 1 and 2 should return a multilayer geojson using the requested layers', function (done) {
        this.options.layer = '1,2';
        var geojsonExpected = {
            type: "FeatureCollection",
            features: [
                geojsonValue.features[1],
                geojsonValue.features[2]
            ]
        };

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonExpected);
            done();
        });
    });

    it('for layer 0 should return a geojson with points', function (done) {
        this.options.layer = 0;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue.features[0]);
            done();
        });
    });

    it('for layer 1 should return a geojson with points', function (done) {
        this.options.layer = 1;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue.features[1]);
            done();
        });
    });

    it('for layer 3 (out of range) should return a specific error', function (done) {
        this.options.layer = 3;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(err);
            assert.equal(err.message, "Layer '3' not found in layergroup");
            assert.ok(!geojsonTile);

            done();
        });
    });

    it('for layer 0 and 3 (one is out of range) should return a specific error', function (done) {
        this.options.layer = '0,3';

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(err);
            assert.equal(err.message, "Invalid layer filtering");
            assert.ok(!geojsonTile);

            done();
        });
    });

    it('for layer 3 and 2 (invalid layer filtering) should return a specific error', function (done) {
        this.options.layer = '3,2';

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(err);
            assert.equal(err.message, "Invalid layer filtering");
            assert.ok(!geojsonTile);

            done();
        });
    });
});
<commit_msg>Add cartodb_id to be able to use deepEqualGeoJSON<commit_after>require('../support/test_helper');

var assert = require('../support/assert');
var geojsonValue = require('../support/geojson_value').multilayer;
var TestClient = require('../support/test_client');

describe('Rendering multiple geojson layers', function() {
    var cartocssVersion = '2.3.0';
    var cartocss = '#layer { line-width:16; }';

    var mapnikLayer1 = {
        type: 'mapnik',
        options: {
            sql: 'select * from test_table limit 2',
            cartocss_version: cartocssVersion,
            cartocss: cartocss,
            interactivity: 'cartodb_id'
        }
    };

    var mapnikLayer2 = {
        type: 'mapnik',
        options: {
            sql: 'select * from test_table_2 limit 4',
            cartocss_version: cartocssVersion,
            cartocss: cartocss,
            interactivity: 'cartodb_id'
        }
    };

    var mapnikLayer3 = {
        type: 'mapnik',
        options: {
            sql: 'select * from test_table_3 limit 3',
            cartocss_version: cartocssVersion,
            cartocss: cartocss,
            interactivity: 'cartodb_id'
        }
    };

    beforeEach(function () {
        this.testClient = new TestClient({
            version: '1.4.0',
            layers: [
                mapnikLayer1,
                mapnikLayer2,
                mapnikLayer3
            ]
        });
        this.options = { format: 'geojson'};
    });

    it('for all layers should return a multilayer geojson', function (done) {
        this.options.layer = undefined;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue);
            done();
        });
    });

    it('for "mapnik" layer param should return a multilayer geojson', function (done) {
        this.options.layer = 'mapnik';

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue);
            done();
        });
    });

    it('for layers 0 and 2 should return a multilayer geojson using the requested layers', function (done) {
        this.options.layer = '0,2';
        var geojsonExpected = {
            type: "FeatureCollection",
            features: [
                geojsonValue.features[0],
                geojsonValue.features[2]
            ]
        };

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonExpected);
            done();
        });
    });

    it('for layers 1 and 2 should return a multilayer geojson using the requested layers', function (done) {
        this.options.layer = '1,2';
        var geojsonExpected = {
            type: "FeatureCollection",
            features: [
                geojsonValue.features[1],
                geojsonValue.features[2]
            ]
        };

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonExpected);
            done();
        });
    });

    it('for layer 0 should return a geojson with points', function (done) {
        this.options.layer = 0;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue.features[0]);
            done();
        });
    });

    it('for layer 1 should return a geojson with points', function (done) {
        this.options.layer = 1;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(!err);
            assert.deepEqualGeoJSON(geojsonTile, geojsonValue.features[1]);
            done();
        });
    });

    it('for layer 3 (out of range) should return a specific error', function (done) {
        this.options.layer = 3;

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(err);
            assert.equal(err.message, "Layer '3' not found in layergroup");
            assert.ok(!geojsonTile);

            done();
        });
    });

    it('for layer 0 and 3 (one is out of range) should return a specific error', function (done) {
        this.options.layer = '0,3';

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(err);
            assert.equal(err.message, "Invalid layer filtering");
            assert.ok(!geojsonTile);

            done();
        });
    });

    it('for layer 3 and 2 (invalid layer filtering) should return a specific error', function (done) {
        this.options.layer = '3,2';

        this.testClient.getTile(13, 4011, 3088, this.options, function (err, geojsonTile) {
            assert.ok(err);
            assert.equal(err.message, "Invalid layer filtering");
            assert.ok(!geojsonTile);

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


<commit_before>import { isArray, isStringOrNumber, isFunction, isNullOrUndefined, addChildrenToProps, isStatefulComponent, isString, isInvalidNode, isPromise, replaceInArray } from '../core/utils';
import { recyclingEnabled, recycle } from './recycling';
import { appendText, createElement, SVGNamespace, MathNamespace, createVirtualFragment, insertOrAppend, createEmptyTextNode } from './utils';
import { patchAttribute, patchStyle } from './patching';
import { addEventToRegistry, addEventToNode, isFocusOrBlur } from './events';
import { diffNodes } from './diffing';
import { selectValue } from './utils';

function appendPromise(child, parentDom, domChildren, namespace, lifecycle, context, instance) {
	const placeholder = createEmptyTextNode();
	domChildren && domChildren.push(placeholder);

	child.then(node => {
		// TODO check for text nodes and arrays
		const dom = mountNode(node, null, namespace, lifecycle, context, instance);

		parentDom.replaceChild(dom, placeholder);
		domChildren && replaceInArray(domChildren, placeholder, dom);
	});
	parentDom.appendChild(placeholder);
}

export function mountChildren(node, children, parentDom, namespace, lifecycle, context, instance) {
	const domChildren = [];
	let isNonKeyed = false;
	let hasKeyedAssumption = false;

	if (isArray(children)) {
		for (let i = 0; i < children.length; i++) {
			const child = children[i];

			if (isStringOrNumber(child)) {

				isNonKeyed = true;
				domChildren.push(appendText(child, parentDom, false));
			} else if (!isNullOrUndefined(child) && isArray(child)) {
				const virtualFragment = createVirtualFragment();

				isNonKeyed = true;
				mountChildren(node, child, virtualFragment, namespace, lifecycle, context, instance);
				insertOrAppend(parentDom, virtualFragment);
				domChildren.push(virtualFragment);
			} else if (isPromise(child)) {
				appendPromise(child, parentDom, domChildren, namespace, lifecycle, context, instance);
			} else {
				const domNode = mountNode(child, parentDom, namespace, lifecycle, context, instance);

				if (isNonKeyed || (!hasKeyedAssumption && child && isNullOrUndefined(child.key))) {
					isNonKeyed = true;
					domChildren.push(domNode);
				} else if (isInvalidNode(child)) {
					isNonKeyed = true;
					domChildren.push(domNode);
				} else if (hasKeyedAssumption === false) {
					// this will be true if a single node comes back with a key, if it does, we assume the rest have keys for a perf boost
					hasKeyedAssumption = true;
				}
			}
		}
	} else {
		if (isStringOrNumber(children)) {
			appendText(children, parentDom, true);

		} else if (isPromise(children)) {
			appendPromise(children, parentDom, null, namespace, lifecycle, context, instance);

		} else {
			mountNode(children, parentDom, namespace, lifecycle, context, instance);
		}
	}
	if (domChildren.length > 1 && isNonKeyed === true) {
		node.domChildren = domChildren;
	}
}

function mountRef(instance, value, dom) {
	if (!isNullOrUndefined(instance) && isString(value)) {
		instance.refs[value] = dom;
	}
}

function mountComponent(parentNode, Component, props, hooks, children, parentDom, lifecycle, context) {
	props = addChildrenToProps(children, props);

	let dom;
	if (isStatefulComponent(Component)) {
		const instance = new Component(props);
		instance._diffNodes = diffNodes;

		const childContext = instance.getChildContext();
		if (!isNullOrUndefined(childContext)) {
			context = { ...context, ...childContext };
		}
		instance.context = context;

		// Block setting state - we should render only once, using latest state
		instance._pendingSetState = true;
		instance.componentWillMount();
		const shouldUpdate = instance.shouldComponentUpdate();
		if (shouldUpdate) {
			instance.componentWillUpdate();
			const pendingState = instance._pendingState;
			const oldState = instance.state;
			instance.state = { ...oldState, ...pendingState };
		}
		const node = instance.render();
		instance._pendingSetState = false;

		if (!isNullOrUndefined(node)) {
			dom = mountNode(node, null, null, lifecycle, context, instance);
			instance._lastNode = node;
			if (parentDom !== null) { // avoid DEOPT
				parentDom.appendChild(dom);
			}
			instance.componentDidMount();
			instance.componentDidUpdate();
		}

		parentNode.dom = dom;
		parentNode.instance = instance;
		return dom;
	}
	if (!isNullOrUndefined(hooks)) {
		if (!isNullOrUndefined(hooks.componentWillMount)) {
			hooks.componentWillMount(null, props);
		}
		if (!isNullOrUndefined(hooks.componentDidMount)) {
			lifecycle.addListener(() => {
				hooks.componentDidMount(dom, props);
			});
		}
	}

	/* eslint new-cap: 0 */
	const node = Component(props);
	dom = mountNode(node, null, null, lifecycle, context, null);

	parentNode.instance = node;

	if (parentDom !== null) { // avoid DEOPT
		parentDom.appendChild(dom);
	}
	parentNode.dom = dom;
	return dom;
}

function mountEvents(events, node) {
	const allEvents = Object.keys(events);

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

		if (isFocusOrBlur(event)) {
			addEventToNode(event, node, events[event]);
		} else if (isString(event)) {
			addEventToRegistry(event, node, events[event]);
		}
	}
}

function placeholder(node, parentDom) {
	const dom = createEmptyTextNode();

	if (parentDom !== null) {
		parentDom.appendChild(dom);
	}
	if (!isNullOrUndefined(node)) {
		node.dom = dom;
	}
	return dom;
}

export function mountNode(node, parentDom, namespace, lifecycle, context, instance) {
	if (isInvalidNode(node) || isArray(node)) {
		return placeholder(node, parentDom);
	}

	let dom;
	if (isStringOrNumber(node)) {
		dom = document.createTextNode(node);

		if (parentDom !== null) {
			parentDom.appendChild(dom);
		}
		return dom;
	}
	if (recyclingEnabled) {
		dom = recycle(node, lifecycle, context);
		if (dom) {
			if (parentDom) {
				parentDom.appendChild(dom);
			}
			return dom;
		}
	}
	const tag = node.tag;

	if (tag === null) {
		return placeholder(node, parentDom);
	}
	if (isFunction(tag)) {
		return mountComponent(node, tag, node.attrs || {}, node.hooks, node.children, parentDom, lifecycle, context);
	}
	namespace = namespace || tag === 'svg' ? SVGNamespace : tag === 'math' ? MathNamespace : null;

	const tpl = node.tpl;
	if (!isNullOrUndefined(tpl) && !isNullOrUndefined(tpl.dom)) {
		dom = tpl.dom.cloneNode(true);
	} else {
		if (!isString(tag) || tag === '') {
			throw Error('Inferno Error: Expected function or string for element tag type');
		}
		dom = createElement(tag, namespace);
	}
	const children = node.children;
	const attrs = node.attrs;
	const events = node.events;
	const hooks = node.hooks;
	const className = node.className;
	const style = node.style;

	node.dom = dom;
	if (!isNullOrUndefined(hooks)) {
		if (!isNullOrUndefined(hooks.created)) {
			hooks.created(dom);
		}
		if (!isNullOrUndefined(hooks.attached)) {
			lifecycle.addListener(() => {
				hooks.attached(dom);
			});
		}
	}
	if (!isNullOrUndefined(events)) {
		mountEvents(events, node);
	}
	if (!isInvalidNode(children)) {
		mountChildren(node, children, dom, namespace, lifecycle, context, instance);
	}
	if (!isNullOrUndefined(attrs)) {
		mountAttributes(attrs, dom, instance);
	}
	if (!isNullOrUndefined(className)) {
		dom.className = className;
	}
	if (!isNullOrUndefined(style)) {
		patchStyle(null, style, dom);
	}
	if (parentDom !== null) {
		parentDom.appendChild(dom);
	}
	return dom;
}

function mountAttributes(attrs, dom, instance) {

	// TODO! Activate this when vdom object is found!

//	if (vdomObject.tag === "select") {
//		selectValue(vdomObject);
	//}

	const attrsKeys = Object.keys(attrs);

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

		if (attr === 'ref') {
			mountRef(instance, attrs[attr], dom);
		} else {
			patchAttribute(attr, attrs[attr], dom);
		}
	}
}
<commit_msg>added node to mountAttrs<commit_after>import { isArray, isStringOrNumber, isFunction, isNullOrUndefined, addChildrenToProps, isStatefulComponent, isString, isInvalidNode, isPromise, replaceInArray } from '../core/utils';
import { recyclingEnabled, recycle } from './recycling';
import { appendText, createElement, SVGNamespace, MathNamespace, createVirtualFragment, insertOrAppend, createEmptyTextNode } from './utils';
import { patchAttribute, patchStyle } from './patching';
import { addEventToRegistry, addEventToNode, isFocusOrBlur } from './events';
import { diffNodes } from './diffing';
import { selectValue } from './utils';

function appendPromise(child, parentDom, domChildren, namespace, lifecycle, context, instance) {
	const placeholder = createEmptyTextNode();
	domChildren && domChildren.push(placeholder);

	child.then(node => {
		// TODO check for text nodes and arrays
		const dom = mountNode(node, null, namespace, lifecycle, context, instance);

		parentDom.replaceChild(dom, placeholder);
		domChildren && replaceInArray(domChildren, placeholder, dom);
	});
	parentDom.appendChild(placeholder);
}

export function mountChildren(node, children, parentDom, namespace, lifecycle, context, instance) {
	const domChildren = [];
	let isNonKeyed = false;
	let hasKeyedAssumption = false;

	if (isArray(children)) {
		for (let i = 0; i < children.length; i++) {
			const child = children[i];

			if (isStringOrNumber(child)) {

				isNonKeyed = true;
				domChildren.push(appendText(child, parentDom, false));
			} else if (!isNullOrUndefined(child) && isArray(child)) {
				const virtualFragment = createVirtualFragment();

				isNonKeyed = true;
				mountChildren(node, child, virtualFragment, namespace, lifecycle, context, instance);
				insertOrAppend(parentDom, virtualFragment);
				domChildren.push(virtualFragment);
			} else if (isPromise(child)) {
				appendPromise(child, parentDom, domChildren, namespace, lifecycle, context, instance);
			} else {
				const domNode = mountNode(child, parentDom, namespace, lifecycle, context, instance);

				if (isNonKeyed || (!hasKeyedAssumption && child && isNullOrUndefined(child.key))) {
					isNonKeyed = true;
					domChildren.push(domNode);
				} else if (isInvalidNode(child)) {
					isNonKeyed = true;
					domChildren.push(domNode);
				} else if (hasKeyedAssumption === false) {
					// this will be true if a single node comes back with a key, if it does, we assume the rest have keys for a perf boost
					hasKeyedAssumption = true;
				}
			}
		}
	} else {
		if (isStringOrNumber(children)) {
			appendText(children, parentDom, true);

		} else if (isPromise(children)) {
			appendPromise(children, parentDom, null, namespace, lifecycle, context, instance);

		} else {
			mountNode(children, parentDom, namespace, lifecycle, context, instance);
		}
	}
	if (domChildren.length > 1 && isNonKeyed === true) {
		node.domChildren = domChildren;
	}
}

function mountRef(instance, value, dom) {
	if (!isNullOrUndefined(instance) && isString(value)) {
		instance.refs[value] = dom;
	}
}

function mountComponent(parentNode, Component, props, hooks, children, parentDom, lifecycle, context) {
	props = addChildrenToProps(children, props);

	let dom;
	if (isStatefulComponent(Component)) {
		const instance = new Component(props);
		instance._diffNodes = diffNodes;

		const childContext = instance.getChildContext();
		if (!isNullOrUndefined(childContext)) {
			context = { ...context, ...childContext };
		}
		instance.context = context;

		// Block setting state - we should render only once, using latest state
		instance._pendingSetState = true;
		instance.componentWillMount();
		const shouldUpdate = instance.shouldComponentUpdate();
		if (shouldUpdate) {
			instance.componentWillUpdate();
			const pendingState = instance._pendingState;
			const oldState = instance.state;
			instance.state = { ...oldState, ...pendingState };
		}
		const node = instance.render();
		instance._pendingSetState = false;

		if (!isNullOrUndefined(node)) {
			dom = mountNode(node, null, null, lifecycle, context, instance);
			instance._lastNode = node;
			if (parentDom !== null) { // avoid DEOPT
				parentDom.appendChild(dom);
			}
			instance.componentDidMount();
			instance.componentDidUpdate();
		}

		parentNode.dom = dom;
		parentNode.instance = instance;
		return dom;
	}
	if (!isNullOrUndefined(hooks)) {
		if (!isNullOrUndefined(hooks.componentWillMount)) {
			hooks.componentWillMount(null, props);
		}
		if (!isNullOrUndefined(hooks.componentDidMount)) {
			lifecycle.addListener(() => {
				hooks.componentDidMount(dom, props);
			});
		}
	}

	/* eslint new-cap: 0 */
	const node = Component(props);
	dom = mountNode(node, null, null, lifecycle, context, null);

	parentNode.instance = node;

	if (parentDom !== null) { // avoid DEOPT
		parentDom.appendChild(dom);
	}
	parentNode.dom = dom;
	return dom;
}

function mountEvents(events, node) {
	const allEvents = Object.keys(events);

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

		if (isFocusOrBlur(event)) {
			addEventToNode(event, node, events[event]);
		} else if (isString(event)) {
			addEventToRegistry(event, node, events[event]);
		}
	}
}

function placeholder(node, parentDom) {
	const dom = createEmptyTextNode();

	if (parentDom !== null) {
		parentDom.appendChild(dom);
	}
	if (!isNullOrUndefined(node)) {
		node.dom = dom;
	}
	return dom;
}

export function mountNode(node, parentDom, namespace, lifecycle, context, instance) {
	if (isInvalidNode(node) || isArray(node)) {
		return placeholder(node, parentDom);
	}

	let dom;
	if (isStringOrNumber(node)) {
		dom = document.createTextNode(node);

		if (parentDom !== null) {
			parentDom.appendChild(dom);
		}
		return dom;
	}
	if (recyclingEnabled) {
		dom = recycle(node, lifecycle, context);
		if (dom) {
			if (parentDom) {
				parentDom.appendChild(dom);
			}
			return dom;
		}
	}
	const tag = node.tag;

	if (tag === null) {
		return placeholder(node, parentDom);
	}
	if (isFunction(tag)) {
		return mountComponent(node, tag, node.attrs || {}, node.hooks, node.children, parentDom, lifecycle, context);
	}
	namespace = namespace || tag === 'svg' ? SVGNamespace : tag === 'math' ? MathNamespace : null;

	const tpl = node.tpl;
	if (!isNullOrUndefined(tpl) && !isNullOrUndefined(tpl.dom)) {
		dom = tpl.dom.cloneNode(true);
	} else {
		if (!isString(tag) || tag === '') {
			throw Error('Inferno Error: Expected function or string for element tag type');
		}
		dom = createElement(tag, namespace);
	}
	const children = node.children;
	const attrs = node.attrs;
	const events = node.events;
	const hooks = node.hooks;
	const className = node.className;
	const style = node.style;

	node.dom = dom;
	if (!isNullOrUndefined(hooks)) {
		if (!isNullOrUndefined(hooks.created)) {
			hooks.created(dom);
		}
		if (!isNullOrUndefined(hooks.attached)) {
			lifecycle.addListener(() => {
				hooks.attached(dom);
			});
		}
	}
	if (!isNullOrUndefined(events)) {
		mountEvents(events, node);
	}
	if (!isInvalidNode(children)) {
		mountChildren(node, children, dom, namespace, lifecycle, context, instance);
	}
	if (!isNullOrUndefined(attrs)) {
		mountAttributes(node, attrs, dom, instance);
	}
	if (!isNullOrUndefined(className)) {
		dom.className = className;
	}
	if (!isNullOrUndefined(style)) {
		patchStyle(null, style, dom);
	}
	if (parentDom !== null) {
		parentDom.appendChild(dom);
	}
	return dom;
}

function mountAttributes(node, attrs, dom, instance) {

	// TODO! Activate this when vdom object is found!

//	if (vdomObject.tag === "select") {
//		selectValue(vdomObject);
	//}

	const attrsKeys = Object.keys(attrs);

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

		if (attr === 'ref') {
			mountRef(instance, attrs[attr], dom);
		} else {
			patchAttribute(attr, attrs[attr], dom);
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>cast args to numbers<commit_after><|endoftext|>


<commit_before>/**
 * Created by Alex Bol on 4/1/2017.
 */

let Interval = class Interval {
    constructor(low, high) {
        this.low = low;
        this.high = high;
    }

    get max() {
        return this.high;
    }

    interval(low, high) {
        return new Interval(low, high);
    }

    clone() {
        return new Interval(this.low, this.high);
    }

    less_than(other_interval) {
        return this.low < other_interval.low ||
            this.low == other_interval.low && this.high < other_interval.high;
    }

    equal_to(other_interval) {
        return this.low == other_interval.low && this.high == other_interval.high;
    }

    intersect(other_interval) {
        return !this.not_intersect(other_interval);
    }

    not_intersect(other_interval) {
        return (this.high < other_interval.low || other_interval.high < this.low);
    }

    output() {
        return [this.low, this.high];
    }

    maximal_val(val1, val2) {
        return Math.max(val1, val2);
    }

    val_less_than(val1, val2 ) {     // trait to compare max property with item ?
        return val1 < val2;
    }
};

module.exports = Interval;<commit_msg>make interval toArray function name clearer<commit_after>/**
 * Created by Alex Bol on 4/1/2017.
 */

let Interval = class Interval {
    constructor(low, high) {
        this.low = low;
        this.high = high;
    }

    get max() {
        return this.high;
    }

    interval(low, high) {
        return new Interval(low, high);
    }

    clone() {
        return new Interval(this.low, this.high);
    }

    less_than(other_interval) {
        return this.low < other_interval.low ||
            this.low == other_interval.low && this.high < other_interval.high;
    }

    equal_to(other_interval) {
        return this.low == other_interval.low && this.high == other_interval.high;
    }

    intersect(other_interval) {
        return !this.not_intersect(other_interval);
    }

    not_intersect(other_interval) {
        return (this.high < other_interval.low || other_interval.high < this.low);
    }

    toArray() {
        return [this.low, this.high];
    }

    maximal_val(val1, val2) {
        return Math.max(val1, val2);
    }

    val_less_than(val1, val2 ) {     // trait to compare max property with item ?
        return val1 < val2;
    }
};

module.exports = Interval;
<|endoftext|>


<commit_before><commit_msg>Revert "Getting data from server (broken)"<commit_after><|endoftext|>


<commit_before>// Mozilla Firefox User Preferences

// -----------------------------------------------------------------------------
// General
// -----------------------------------------------------------------------------

// Show a blank page when Firefox starts
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.page", 0);
user_pref("browser.rights.3.shown", true);
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("startup.homepage_welcome_url", "");
user_pref("startup.homepage_welcome_url.additional", "");
user_pref("startup.homepage_override_url", "");
user_pref("browser.laterrun.enabled", false);

// Show a blank page when opening new tab
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtabpage.enhanced", false);
user_pref("browser.newtab.preload", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.newtabpage.directory.ping", "data:text/plain,");
user_pref("browser.newtabpage.directory.source", "data:text/plain,");
user_pref("browser.newtabpage.activity-stream.enabled", false); // Firefox 54+

// Always ask me where to save download files
user_pref("browser.download.useDownloadDir", false);

// Disable downloading on desktop
user_pref("browser.download.folderList", 2);

// -----------------------------------------------------------------------------
// Search
// -----------------------------------------------------------------------------

// Set default region for search engines
user_pref("browser.search.region", "JP");
user_pref("browser.search.countryCode", "JP");
user_pref("browser.search.isUS", false);

// Disable geographically specific results/search engines
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");

// -----------------------------------------------------------------------------
// Content
// -----------------------------------------------------------------------------

// Set minimum font size
user_pref("font.minimum-size.ja", 10);
user_pref("font.minimum-size.ko", 10);
user_pref("font.minimum-size.zh-CN", 10);
user_pref("font.minimum-size.zh-HK", 10);
user_pref("font.minimum-size.zh-TW", 10);

// Choose preferred language for displaying pages
user_pref("intl.accept_languages", "ja, zh-tw, zh, en-us, en");

// Disable Geolocation
user_pref("geo.enabled", false);
user_pref("geo.wifi.uri", "https://127.0.0.1");
user_pref("geo.wifi.logging.enabled", false);
user_pref("geo.wifi.xhr.timeout", 1);
user_pref("geo.security.allowinsecure", false);
user_pref("browser.search.geoip.url", "");
user_pref("browser.search.geoip.timeout", 1);

// Disable WebRTC
user_pref("media.peerconnection.enabled", false);
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("media.peerconnection.video.enabled", false);
user_pref("media.peerconnection.identity.enabled", false);
user_pref("media.peerconnection.identity.timeout", 1);
user_pref("media.peerconnection.turn.disable", true);
user_pref("media.peerconnection.ice.tcp", false);
user_pref("media.navigator.video.enabled", false);

// Improve WebRTC IP leak issue
user_pref("media.peerconnection.ice.default_address_only", true);
user_pref("media.peerconnection.ice.no_host", true);

// Disable audio auto-play in non-active tabs
user_pref("media.block-autoplay-until-in-foreground", true);

// Disable link prefetching
user_pref("network.prefetch-next", false);

// Disable DNS prefetching
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);

// Disable opening connection to links when mouseover
user_pref("network.http.speculative-parallel-limit", 0);

// Disable Beacon
user_pref("beacon.enabled", false);

// Ignore the `ping` attribute for `<a>` elements
user_pref("browser.send_pings", false);
user_pref("browser.send_pings.require_same_host", true);

// Disable camera controlling
user_pref("camera.control.face_detection.enabled", false);

// Decrease the maximum number of popups from a single non-click event (Default is 20)
user_pref("dom.popup_maximum", 2);

// Disallow JavaScript to raise or lower windows
user_pref("dom.disable_window_flip", true);

// Disallow JavaScript to move or resize existing windows
user_pref("dom.disable_window_move_resize", true);

// Disable web notifications
user_pref("dom.webnotifications.enabled", false);
user_pref("dom.webnotifications.serviceworker.enabled", false);

// Disable Flyweb
user_pref("dom.flyweb.enabled", false);

// Disable SPDY (SPDY would be deprecated in 2016)
user_pref("network.http.spdy.enabled", false);
user_pref("network.http.spdy.enabled.deps", false);

// -----------------------------------------------------------------------------
// Privacy
// -----------------------------------------------------------------------------

// Request that sites not track me
user_pref("privacy.donottrackheader.enabled", true);

// Use Tracking Protection in Private Windows
user_pref("privacy.trackingprotection.enabled", true);
user_pref("privacy.trackingprotection.pbmode.enabled", true);
user_pref("privacy.trackingprotection.introCount", 20);
user_pref("privacy.trackingprotection.ui.enabled", true);

// Never accept third-party cookies
user_pref("network.cookie.cookieBehavior", 1);

// Set the maximum number of pages to be retained in the history database
user_pref("places.history.expiration.max_pages", 10000);
user_pref("places.history.expiration.transient_current_max_pages", 10000);

// -----------------------------------------------------------------------------
// Security
// -----------------------------------------------------------------------------

// Block reported attack sites
user_pref("browser.safebrowsing.malware.enabled", true);

// Block reported web forgeries
user_pref("browser.safebrowsing.enabled", true);

// Do not remember passwords for sites
user_pref("signon.rememberSignons", false);

// -----------------------------------------------------------------------------
// Advanced
// -----------------------------------------------------------------------------

// Disable Firefox Health Report
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.documentServerURI", "");
user_pref("datareporting.healthreport.about.reportUrl", "data:text/plain,");
user_pref("datareporting.healthreport.about.reportUrlInified", "data:text/plain,");
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled.v2", false);

// Disable Crash Reporter
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false); // Added in Firefox 44
user_pref("browser.crashReports.unsubmittedCheck.enabled", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);

// Disable Telemetry
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.unifiedIsOptIn", true);
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.cachedClientID", "");
user_pref("toolkit.telemetry.server", "");

// Disable Telemetry Experiments
user_pref("experiments.enabled", false);
user_pref("experiments.supported", false);
user_pref("experiments.activeExperiment", false);
user_pref("experiments.manifest.uri", "");
user_pref("network.allow-experiments", false);

// Enable OCSP stapling
user_pref("security.ssl.enable_ocsp_stapling", true);

// Query OCSP responder servers to confirm current validity of certificates
user_pref("security.OCSP.enabled", 1);

// -----------------------------------------------------------------------------
// Add-ons and Plugins
// -----------------------------------------------------------------------------

// Disable enforced add-on signing since Firefox 43
user_pref("xpinstall.signatures.required", false);

// Hide the "Get Add-ons" pane in the Add-ons page
user_pref("extensions.getAddons.showPane", false);

// Disable extension discovery
user_pref("extensions.webservice.discoverURL", "http://127.0.0.1");

// Lock down allowed extension directories
user_pref("extensions.enabledScopes", 1);

// Clear localStorage and UUID when a WebExtension is uninstalled
user_pref("extensions.webextensions.keepStorageOnUninstall", false);
user_pref("extensions.webextensions.keepUuidOnUninstall", false);

// Ask me to activate plugins by default
user_pref("plugin.default.state", 1);
user_pref("plugin.defaultXpi.state", 1);

// Enable click-to-play and set the session permission
user_pref("plugins.click_to_play", true);
user_pref("plugin.sessionPermissionNow.intervalInMinutes", 0);

// Click to play Adobe Flash
user_pref("plugin.state.flash", 1);

// Disable all GMP (Gecko Media Plugins)
user_pref("media.gmp-provider.enabled", false);
user_pref("media.gmp.trial-create.enabled", false);

// Disable widevine CDM
user_pref("media.gmp-widevinecdm.visible", false);
user_pref("media.gmp-widevinecdm.enabled", false);
user_pref("media.gmp-widevinecdm.autoupdate", false);

// Disable all DRM content
user_pref("media.eme.enabled", false);
user_pref("browser.eme.ui.enabled", false);

// Disable OpenH264 Video Codec by Cisco
user_pref("media.gmp-gmpopenh264.enabled", false);
user_pref("media.gmp-gmpopenh264.autoupdate", false);
user_pref("media.gmp-manager.url", "data:text/plain,");

// -----------------------------------------------------------------------------
// Others
// -----------------------------------------------------------------------------

// Disable Heartbeat
user_pref("browser.selfsupport.enabled", false);
user_pref("browser.selfsupport.url", "");

// Disable Shield (Telemetry system)
user_pref("extensions.shield-recipe-client.enabled", false);
user_pref("extensions.shield-recipe-client.api_url", "");

// Disable Pocket
user_pref("extensions.pocket.enabled", false);
user_pref("extensions.pocket.api", "");
user_pref("extensions.pocket.site", "");
user_pref("extensions.pocket.oAuthConsumerKey", "");

// Disable Reader View
user_pref("reader.parse-on-load.enabled", false);

// Disable capturing page thumbnails
user_pref("browser.pagethumbnails.capturing_disabled", true);

// Disable Taskbar Jump List in Windows 7 and above
user_pref("browser.taskbar.lists.frequent.enabled", false);
user_pref("browser.taskbar.lists.recent.enabled", false);

// Disable "Slow startup" warnings
user_pref("browser.slowStartup.notificationDisabled", true);
user_pref("browser.slowStartup.maxSamples", 0);
user_pref("browser.slowStartup.samples", 0);

// Disable `about:config` warnings
user_pref("general.warnOnAboutConfig", false);

// Skip the installation delay
user_pref("security.dialog_enable_delay", 0);

// Disable closing browser with last tab
user_pref("browser.tabs.closeWindowWithLastTab", false);

// Disable UI animation
user_pref("browser.fullscreen.animate", false);
user_pref("browser.tabs.animate", false);

// Disable site specific zoom
user_pref("browser.zoom.siteSpecific", false);

// Disable search suggestions in URL bar
user_pref("browser.urlbar.suggest.searches", false);
user_pref("browser.urlbar.userMadeSearchSuggestionsChoice", true);
user_pref("browser.urlbar.oneOffSearches", false);

// Disable preloading top websites in URL bar (Firefox 54+)
user_pref("browser.urlbar.usepreloadedtopurls.enabled", false);

// Display the raw Punycode in URL bar.
user_pref("network.IDN_show_punycode", true);

// Disable WebIDE to prevent remote debugging and addon downloads
user_pref("devtools.webide.enabled", false);
user_pref("devtools.webide.autoinstallADBHelper", false);
user_pref("devtools.webide.autoinstallFxdtAdapters", false);
user_pref("devtools.debugger.remote-enabled", false);

// Disable UI tour
user_pref("browser.uitour.enabled", false);
user_pref("browser.uitour.url", "");

// Prevent links from launching Windows Store (Windows 8+)
user_pref("network.protocol-handler.external.ms-windows-store", false);

// Disable Microsoft Family Safety cert (Winodws 8+)
user_pref("security.family_safety.mode", 0);

// Set the cache directory location
// user_pref("browser.cache.disk.parent_directory", "");
<commit_msg>Update user.js for Firefox 55<commit_after>// Mozilla Firefox User Preferences

// -----------------------------------------------------------------------------
// General
// -----------------------------------------------------------------------------

// Show a blank page when Firefox starts
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.page", 0);
user_pref("browser.rights.3.shown", true);
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("startup.homepage_welcome_url", "");
user_pref("startup.homepage_welcome_url.additional", "");
user_pref("startup.homepage_override_url", "");
user_pref("browser.laterrun.enabled", false);

// Show a blank page when opening new tab
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtabpage.enhanced", false);
user_pref("browser.newtab.preload", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.newtabpage.directory.source", "data:text/plain,");
user_pref("browser.newtabpage.activity-stream.enabled", false);

// Always ask me where to save download files
user_pref("browser.download.useDownloadDir", false);

// Disable downloading on desktop
user_pref("browser.download.folderList", 2);

// -----------------------------------------------------------------------------
// Search
// -----------------------------------------------------------------------------

// Set default region for search engines
user_pref("browser.search.region", "JP");
user_pref("browser.search.countryCode", "JP");
user_pref("browser.search.isUS", false);

// Disable geographically specific results/search engines
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");

// -----------------------------------------------------------------------------
// Content
// -----------------------------------------------------------------------------

// Set minimum font size
user_pref("font.minimum-size.ja", 10);
user_pref("font.minimum-size.ko", 10);
user_pref("font.minimum-size.zh-CN", 10);
user_pref("font.minimum-size.zh-HK", 10);
user_pref("font.minimum-size.zh-TW", 10);

// Choose preferred language for displaying pages
user_pref("intl.accept_languages", "ja, zh-tw, zh, en-us, en");

// Disable Geolocation
user_pref("geo.enabled", false);
user_pref("geo.wifi.uri", "");
user_pref("geo.wifi.logging.enabled", false);
user_pref("geo.wifi.xhr.timeout", 1);
user_pref("browser.search.geoip.url", "");
user_pref("browser.search.geoip.timeout", 1);

// Disable WebRTC
user_pref("media.peerconnection.enabled", false);
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("media.peerconnection.video.enabled", false);
user_pref("media.peerconnection.identity.enabled", false);
user_pref("media.peerconnection.identity.timeout", 1);
user_pref("media.peerconnection.turn.disable", true);
user_pref("media.peerconnection.ice.tcp", false);
user_pref("media.navigator.video.enabled", false);

// Improve WebRTC IP leak issue
user_pref("media.peerconnection.ice.default_address_only", true);
user_pref("media.peerconnection.ice.no_host", true);

// Disable audio auto-play in non-active tabs
user_pref("media.block-autoplay-until-in-foreground", true);

// Disable link prefetching
user_pref("network.prefetch-next", false);

// Disable DNS prefetching
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);

// Disable opening connection to links when mouseover
user_pref("network.http.speculative-parallel-limit", 0);

// Disable Beacon
user_pref("beacon.enabled", false);

// Ignore the `ping` attribute for `<a>` elements
user_pref("browser.send_pings", false);
user_pref("browser.send_pings.require_same_host", true);

// Disable camera controlling
user_pref("camera.control.face_detection.enabled", false);

// Decrease the maximum number of popups from a single non-click event (Default is 20)
user_pref("dom.popup_maximum", 2);

// Disallow JavaScript to raise or lower windows
user_pref("dom.disable_window_flip", true);

// Disallow JavaScript to move or resize existing windows
user_pref("dom.disable_window_move_resize", true);

// Disable web notifications
user_pref("dom.webnotifications.enabled", false);
user_pref("dom.webnotifications.serviceworker.enabled", false);

// Disable Flyweb
user_pref("dom.flyweb.enabled", false);

// Disable SPDY (SPDY would be deprecated in 2016)
user_pref("network.http.spdy.enabled", false);
user_pref("network.http.spdy.enabled.deps", false);

// -----------------------------------------------------------------------------
// Privacy
// -----------------------------------------------------------------------------

// Request that sites not track me
user_pref("privacy.donottrackheader.enabled", true);

// Use Tracking Protection in Private Windows
user_pref("privacy.trackingprotection.enabled", true);
user_pref("privacy.trackingprotection.pbmode.enabled", true);
user_pref("privacy.trackingprotection.introCount", 20);
user_pref("privacy.trackingprotection.ui.enabled", true);

// Never accept third-party cookies
user_pref("network.cookie.cookieBehavior", 1);

// Set the maximum number of pages to be retained in the history database
user_pref("places.history.expiration.max_pages", 10000);
user_pref("places.history.expiration.transient_current_max_pages", 10000);

// -----------------------------------------------------------------------------
// Security
// -----------------------------------------------------------------------------

// Block reported attack sites
user_pref("browser.safebrowsing.malware.enabled", true);

// Block reported web forgeries
user_pref("browser.safebrowsing.enabled", true);

// Do not remember passwords for sites
user_pref("signon.rememberSignons", false);

// -----------------------------------------------------------------------------
// Advanced
// -----------------------------------------------------------------------------

// Disable Firefox Health Report
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.healthreport.about.reportUrl", "data:text/plain,");
user_pref("datareporting.policy.dataSubmissionEnabled", false);

// Disable Crash Reporter
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false);
user_pref("browser.crashReports.unsubmittedCheck.enabled", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);

// Disable Telemetry
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.cachedClientID", "");
user_pref("toolkit.telemetry.server", "");
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);

// Disable Telemetry Experiments
user_pref("experiments.enabled", false);
user_pref("experiments.supported", false);
user_pref("experiments.activeExperiment", false);
user_pref("experiments.manifest.uri", "");
user_pref("network.allow-experiments", false);

// Enable OCSP stapling
user_pref("security.ssl.enable_ocsp_stapling", true);

// Query OCSP responder servers to confirm current validity of certificates
user_pref("security.OCSP.enabled", 1);

// -----------------------------------------------------------------------------
// Add-ons and Plugins
// -----------------------------------------------------------------------------

// Disable enforced add-on signing since Firefox 43
user_pref("xpinstall.signatures.required", false);

// Hide the "Get Add-ons" pane in the Add-ons page
user_pref("extensions.getAddons.showPane", false);

// Disable extension discovery
user_pref("extensions.webservice.discoverURL", "http://127.0.0.1");

// Lock down allowed extension directories
user_pref("extensions.enabledScopes", 1);

// Clear localStorage and UUID when a WebExtension is uninstalled
user_pref("extensions.webextensions.keepStorageOnUninstall", false);
user_pref("extensions.webextensions.keepUuidOnUninstall", false);

// Ask me to activate plugins by default
user_pref("plugin.default.state", 1);
user_pref("plugin.defaultXpi.state", 1);

// Enable click-to-play and set the session permission
user_pref("plugins.click_to_play", true);
user_pref("plugin.sessionPermissionNow.intervalInMinutes", 0);

// Click to play Adobe Flash
user_pref("plugin.state.flash", 1);

// Disable all GMP (Gecko Media Plugins)
user_pref("media.gmp-provider.enabled", false);
user_pref("media.gmp.trial-create.enabled", false);
user_pref("media.gmp-manager.url", "data:text/plain,");
user_pref("media.gmp-manager.url.override", "data:text/plain,");
user_pref("media.gmp-manager.updateEnabled", false);

// Disable widevine CDM
user_pref("media.gmp-widevinecdm.visible", false);
user_pref("media.gmp-widevinecdm.enabled", false);
user_pref("media.gmp-widevinecdm.autoupdate", false);

// Disable all DRM content
user_pref("media.eme.enabled", false);
user_pref("media.eme.chromium-api.enabled", false);
user_pref("browser.eme.ui.enabled", false);

// Disable OpenH264 Video Codec by Cisco
user_pref("media.gmp-gmpopenh264.enabled", false);
user_pref("media.gmp-gmpopenh264.autoupdate", false);

// -----------------------------------------------------------------------------
// Others
// -----------------------------------------------------------------------------

// Disable Shield (Telemetry system)
user_pref("extensions.shield-recipe-client.enabled", false);
user_pref("extensions.shield-recipe-client.api_url", "");

// Disable Pocket
user_pref("extensions.pocket.enabled", false);
user_pref("extensions.pocket.api", "");
user_pref("extensions.pocket.site", "");
user_pref("extensions.pocket.oAuthConsumerKey", "");

// Disable Reader View
user_pref("reader.parse-on-load.enabled", false);

// Disable capturing page thumbnails
user_pref("browser.pagethumbnails.capturing_disabled", true);

// Disable Taskbar Jump List in Windows 7 and above
user_pref("browser.taskbar.lists.frequent.enabled", false);
user_pref("browser.taskbar.lists.recent.enabled", false);

// Disable "Slow startup" warnings
user_pref("browser.slowStartup.notificationDisabled", true);
user_pref("browser.slowStartup.maxSamples", 0);
user_pref("browser.slowStartup.samples", 0);

// Disable `about:config` warnings
user_pref("general.warnOnAboutConfig", false);

// Skip the installation delay
user_pref("security.dialog_enable_delay", 0);

// Disable closing browser with last tab
user_pref("browser.tabs.closeWindowWithLastTab", false);

// Disable UI animation
user_pref("toolkit.cosmeticAnimations.enabled", false);

// Disable site specific zoom
user_pref("browser.zoom.siteSpecific", false);

// Disable search suggestions in URL bar
user_pref("browser.urlbar.suggest.searches", false);
user_pref("browser.urlbar.userMadeSearchSuggestionsChoice", true);
user_pref("browser.urlbar.oneOffSearches", false);

// Disable preloading top websites in URL bar (Firefox 54+)
user_pref("browser.urlbar.usepreloadedtopurls.enabled", false);

// Display the raw Punycode in URL bar.
user_pref("network.IDN_show_punycode", true);

// Disable WebIDE to prevent remote debugging and addon downloads
user_pref("devtools.webide.enabled", false);
user_pref("devtools.webide.autoinstallADBHelper", false);
user_pref("devtools.webide.autoinstallFxdtAdapters", false);
user_pref("devtools.debugger.remote-enabled", false);

// Disable Onboarding
user_pref("browser.onboarding.enabled", false);

// Disable UI tour
user_pref("browser.uitour.enabled", false);
user_pref("browser.uitour.url", "");

// Prevent links from launching Windows Store (Windows 8+)
user_pref("network.protocol-handler.external.ms-windows-store", false);

// Disable Microsoft Family Safety cert (Winodws 8+)
user_pref("security.family_safety.mode", 0);
<|endoftext|>


<commit_before>const express = require('express')
// @ts-ignore
const Grant = require('grant-express')
const grantConfig = require('./config/grant')()
const providerManager = require('./server/provider')
const controllers = require('./server/controllers')
const s3 = require('./server/controllers/s3')
const url = require('./server/controllers/url')
const SocketServer = require('ws').Server
const emitter = require('./server/emitter')
const merge = require('lodash.merge')
const redis = require('./server/redis')
const cookieParser = require('cookie-parser')
const { jsonStringify, getURLBuilder } = require('./server/helpers/utils')
const jobs = require('./server/jobs')
const interceptor = require('express-interceptor')
const logger = require('./server/logger')
const { STORAGE_PREFIX } = require('./server/Uploader')
const middlewares = require('./server/middlewares')

const providers = providerManager.getDefaultProviders()
const defaultOptions = {
  server: {
    protocol: 'http',
    path: ''
  },
  providerOptions: {
    s3: {
      acl: 'public-read',
      endpoint: 'https://{service}.{region}.amazonaws.com',
      conditions: [],
      getKey: (req, filename) => filename
    }
  },
  debug: true
}

/**
 * Entry point into initializing the Companion app.
 *
 * @param {object} options
 */
module.exports.app = (options = {}) => {
  options = merge({}, defaultOptions, options)
  providerManager.addProviderOptions(options, grantConfig)

  const customProviders = options.customProviders
  if (customProviders) {
    providerManager.addCustomProviders(customProviders, providers, grantConfig)
  }

  // create singleton redis client
  if (options.redisUrl) {
    redis.client(merge({ url: options.redisUrl }, options.redisOptions || {}))
  }
  emitter(options.multipleInstances && options.redisUrl)

  const app = express()
  app.use(cookieParser()) // server tokens are added to cookies

  app.use(interceptGrantErrorResponse)
  app.use(new Grant(grantConfig))
  app.use((req, res, next) => {
    res.header(
      'Access-Control-Allow-Headers',
      [res.get('Access-Control-Allow-Headers'), 'uppy-auth-token'].join(', ')
    )
    next()
  })
  if (options.sendSelfEndpoint) {
    app.use('*', (req, res, next) => {
      const { protocol } = options.server
      res.header('i-am', `${protocol}://${options.sendSelfEndpoint}`)
      // add it to the exposed custom headers.
      res.header('Access-Control-Expose-Headers', [res.get('Access-Control-Expose-Headers'), 'i-am'].join(', '))
      next()
    })
  }

  // add uppy options to the request object so it can be accessed by subsequent handlers.
  app.use('*', getOptionsMiddleware(options))
  app.use('/s3', s3(options.providerOptions.s3))
  app.use('/url', url())

  app.get('/:providerName/callback', middlewares.hasSessionAndProvider, controllers.callback)
  app.get('/:providerName/connect', middlewares.hasSessionAndProvider, controllers.connect)
  app.get('/:providerName/redirect', middlewares.hasSessionAndProvider, controllers.redirect)
  app.get('/:providerName/logout', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.logout)
  app.get('/:providerName/authorized', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.authorized)
  app.get('/:providerName/list/:id?', middlewares.hasSessionAndProvider, middlewares.verifyToken, controllers.list)
  app.post('/:providerName/get/:id', middlewares.hasSessionAndProvider, middlewares.verifyToken, controllers.get)
  app.get('/:providerName/thumbnail/:id', middlewares.hasSessionAndProvider, middlewares.cookieAuthToken, middlewares.verifyToken, controllers.thumbnail)

  app.param('providerName', providerManager.getProviderMiddleware(providers))

  if (app.get('env') !== 'test') {
    jobs.startCleanUpJob(options.filePath)
  }

  return app
}

/**
 * the socket is used to send progress events during an upload
 *
 * @param {object} server
 */
module.exports.socket = (server) => {
  const wss = new SocketServer({ server })
  const redisClient = redis.client()

  // A new connection is usually created when an upload begins,
  // or when connection fails while an upload is on-going and,
  // client attempts to reconnect.
  wss.on('connection', (ws) => {
    // @ts-ignore
    const fullPath = ws.upgradeReq.url
    // the token identifies which ongoing upload's progress, the socket
    // connection wishes to listen to.
    const token = fullPath.replace(/^.*\/api\//, '')
    logger.info(`connection received from ${token}`, 'socket.connect')

    /**
     *
     * @param {{action: string, payload: object}} data
     */
    function sendProgress (data) {
      ws.send(jsonStringify(data), (err) => {
        if (err) logger.error(err, 'socket.progress.error')
      })
    }

    // if the redisClient is available, then we attempt to check the storage
    // if we have any already stored progress data on the upload.
    if (redisClient) {
      redisClient.get(`${STORAGE_PREFIX}:${token}`, (err, data) => {
        if (err) logger.error(err, 'socket.redis.error')
        if (data) {
          const dataObj = JSON.parse(data.toString())
          if (dataObj.action) sendProgress(dataObj)
        }
      })
    }

    emitter().emit(`connection:${token}`)
    emitter().on(token, sendProgress)

    ws.on('message', (jsonData) => {
      const data = JSON.parse(jsonData.toString())
      // whitelist triggered actions
      if (data.action === 'pause' || data.action === 'resume') {
        emitter().emit(`${data.action}:${token}`)
      }
    })

    ws.on('close', () => {
      emitter().removeListener(token, sendProgress)
    })
  })
}

// intercepts grantJS' default response error when something goes
// wrong during oauth process.
const interceptGrantErrorResponse = interceptor((req, res) => {
  return {
    isInterceptable: () => {
      // match grant.js' callback url
      return /^\/connect\/\w+\/callback/.test(req.path)
    },
    intercept: (body, send) => {
      const unwantedBody = 'error=Grant%3A%20missing%20session%20or%20misconfigured%20provider'
      if (body === unwantedBody) {
        logger.error(`grant.js responded with error: ${body}`, 'grant.oauth.error')
        send([
          'Companion was unable to complete the OAuth process :(',
          '(Hint, try clearing your cookies and try again)'
        ].join('\n'))
      } else {
        send(body)
      }
    }
  }
})

/**
 *
 * @param {object} options
 */
const getOptionsMiddleware = (options) => {
  let s3Client = null
  if (options.providerOptions.s3) {
    const S3 = require('aws-sdk/clients/s3')
    const AWS = require('aws-sdk')
    const config = options.providerOptions.s3
    // Use credentials to allow assumed roles to pass STS sessions in.
    // If the user doesn't specify key and secret, the default credentials (process-env)
    // will be used by S3 in calls below.
    let credentials
    if (config.key && config.secret) {
      credentials = new AWS.Credentials(config.key, config.secret, config.sessionToken)
    }
    s3Client = new S3({
      region: config.region,
      endpoint: config.endpoint,
      credentials,
      signatureVersion: 'v4'
    })
  }

  /**
   *
   * @param {object} req
   * @param {object} res
   * @param {function} next
   */
  const middleware = (req, res, next) => {
    req.uppy = {
      options,
      s3Client,
      authToken: req.header('uppy-auth-token'),
      buildURL: getURLBuilder(options)
    }
    next()
  }

  return middleware
}
<commit_msg>Update uppy.js<commit_after>const express = require('express')
// @ts-ignore
const Grant = require('grant-express')
const grantConfig = require('./config/grant')()
const providerManager = require('./server/provider')
const controllers = require('./server/controllers')
const s3 = require('./server/controllers/s3')
const url = require('./server/controllers/url')
const SocketServer = require('ws').Server
const emitter = require('./server/emitter')
const merge = require('lodash.merge')
const redis = require('./server/redis')
const cookieParser = require('cookie-parser')
const { jsonStringify, getURLBuilder } = require('./server/helpers/utils')
const jobs = require('./server/jobs')
const interceptor = require('express-interceptor')
const logger = require('./server/logger')
const { STORAGE_PREFIX } = require('./server/Uploader')
const middlewares = require('./server/middlewares')

const providers = providerManager.getDefaultProviders()
const defaultOptions = {
  server: {
    protocol: 'http',
    path: ''
  },
  providerOptions: {
    s3: {
      acl: 'public-read',
      endpoint: 'https://{service}.{region}.amazonaws.com',
      conditions: [],
      getKey: (req, filename) => filename
    }
  },
  debug: true
}

/**
 * Entry point into initializing the Companion app.
 *
 * @param {object} options
 */
module.exports.app = (options = {}) => {
  options = merge({}, defaultOptions, options)
  providerManager.addProviderOptions(options, grantConfig)

  const customProviders = options.customProviders
  if (customProviders) {
    providerManager.addCustomProviders(customProviders, providers, grantConfig)
  }

  // create singleton redis client
  if (options.redisUrl) {
    redis.client(merge({ url: options.redisUrl }, options.redisOptions || {}))
  }
  emitter(options.multipleInstances && options.redisUrl)

  const app = express()
  app.use(cookieParser()) // server tokens are added to cookies

  app.use(interceptGrantErrorResponse)
  app.use(new Grant(grantConfig))
  app.use((req, res, next) => {
    res.header(
      'Access-Control-Allow-Headers',
      [res.get('Access-Control-Allow-Headers'), 'uppy-auth-token'].join(', ')
    )
    next()
  })
  if (options.sendSelfEndpoint) {
    app.use('*', (req, res, next) => {
      const { protocol } = options.server
      res.header('i-am', `${protocol}://${options.sendSelfEndpoint}`)
      // add it to the exposed custom headers.
      res.header('Access-Control-Expose-Headers', [res.get('Access-Control-Expose-Headers'), 'i-am'].join(', '))
      next()
    })
  }

  // add uppy options to the request object so it can be accessed by subsequent handlers.
  app.use('*', getOptionsMiddleware(options))
  app.use('/s3', s3(options.providerOptions.s3))
  app.use('/url', url())

  app.get('/:providerName/callback', middlewares.hasSessionAndProvider, controllers.callback)
  app.get('/:providerName/connect', middlewares.hasSessionAndProvider, controllers.connect)
  app.get('/:providerName/redirect', middlewares.hasSessionAndProvider, controllers.redirect)
  app.get('/:providerName/logout', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.logout)
  app.get('/:providerName/authorized', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.authorized)
  app.get('/:providerName/list/:id?', middlewares.hasSessionAndProvider, middlewares.verifyToken, controllers.list)
  app.post('/:providerName/get/:id', middlewares.hasSessionAndProvider, middlewares.gentleVerifyToken, controllers.get)
  app.get('/:providerName/thumbnail/:id', middlewares.hasSessionAndProvider, middlewares.cookieAuthToken, middlewares.verifyToken, controllers.thumbnail)

  app.param('providerName', providerManager.getProviderMiddleware(providers))

  if (app.get('env') !== 'test') {
    jobs.startCleanUpJob(options.filePath)
  }

  return app
}

/**
 * the socket is used to send progress events during an upload
 *
 * @param {object} server
 */
module.exports.socket = (server) => {
  const wss = new SocketServer({ server })
  const redisClient = redis.client()

  // A new connection is usually created when an upload begins,
  // or when connection fails while an upload is on-going and,
  // client attempts to reconnect.
  wss.on('connection', (ws) => {
    // @ts-ignore
    const fullPath = ws.upgradeReq.url
    // the token identifies which ongoing upload's progress, the socket
    // connection wishes to listen to.
    const token = fullPath.replace(/^.*\/api\//, '')
    logger.info(`connection received from ${token}`, 'socket.connect')

    /**
     *
     * @param {{action: string, payload: object}} data
     */
    function sendProgress (data) {
      ws.send(jsonStringify(data), (err) => {
        if (err) logger.error(err, 'socket.progress.error')
      })
    }

    // if the redisClient is available, then we attempt to check the storage
    // if we have any already stored progress data on the upload.
    if (redisClient) {
      redisClient.get(`${STORAGE_PREFIX}:${token}`, (err, data) => {
        if (err) logger.error(err, 'socket.redis.error')
        if (data) {
          const dataObj = JSON.parse(data.toString())
          if (dataObj.action) sendProgress(dataObj)
        }
      })
    }

    emitter().emit(`connection:${token}`)
    emitter().on(token, sendProgress)

    ws.on('message', (jsonData) => {
      const data = JSON.parse(jsonData.toString())
      // whitelist triggered actions
      if (data.action === 'pause' || data.action === 'resume') {
        emitter().emit(`${data.action}:${token}`)
      }
    })

    ws.on('close', () => {
      emitter().removeListener(token, sendProgress)
    })
  })
}

// intercepts grantJS' default response error when something goes
// wrong during oauth process.
const interceptGrantErrorResponse = interceptor((req, res) => {
  return {
    isInterceptable: () => {
      // match grant.js' callback url
      return /^\/connect\/\w+\/callback/.test(req.path)
    },
    intercept: (body, send) => {
      const unwantedBody = 'error=Grant%3A%20missing%20session%20or%20misconfigured%20provider'
      if (body === unwantedBody) {
        logger.error(`grant.js responded with error: ${body}`, 'grant.oauth.error')
        send([
          'Companion was unable to complete the OAuth process :(',
          '(Hint, try clearing your cookies and try again)'
        ].join('\n'))
      } else {
        send(body)
      }
    }
  }
})

/**
 *
 * @param {object} options
 */
const getOptionsMiddleware = (options) => {
  let s3Client = null
  if (options.providerOptions.s3) {
    const S3 = require('aws-sdk/clients/s3')
    const AWS = require('aws-sdk')
    const config = options.providerOptions.s3
    // Use credentials to allow assumed roles to pass STS sessions in.
    // If the user doesn't specify key and secret, the default credentials (process-env)
    // will be used by S3 in calls below.
    let credentials
    if (config.key && config.secret) {
      credentials = new AWS.Credentials(config.key, config.secret, config.sessionToken)
    }
    s3Client = new S3({
      region: config.region,
      endpoint: config.endpoint,
      credentials,
      signatureVersion: 'v4'
    })
  }

  /**
   *
   * @param {object} req
   * @param {object} res
   * @param {function} next
   */
  const middleware = (req, res, next) => {
    req.uppy = {
      options,
      s3Client,
      authToken: req.header('uppy-auth-token'),
      buildURL: getURLBuilder(options)
    }
    next()
  }

  return middleware
}
<|endoftext|>


<commit_before>(function () {

  var template = chrome.extension.getURL('bar.html');
  $.ajax({
    url: template,
    async: false,
    success: function (html) {
      var nimbleBar = $(html);
      $('body').append(nimbleBar);
      window.nimbleBar = nimbleBar;
      bindInputDropdown();
    }
  });

  var dropdownItems;
  var filteredItems;
  var selectedOptionIndex;
  var shown = false;
  var pipeline;

  function initialize () {
    dropdownItems = [];
    filteredItems = [];
    selectedOptionIndex = -1;
    pipeline = [];
    $('.nimble-pipeline').html('');
    $('.nimble-options').html('');
    console.log('initialize')
  }

  function populateDropdown (items) {
    $('.nimble-options').html('');
    selectedOptionIndex = -1;
    _.each(items, function (item) {
      var $nimbleOption = $('
');
      var content = item.extras.title;
      $nimbleOption.html('
' + content + '
');
      $('.nimble-options').append($nimbleOption);
    })
  }

  function showNimbleBar () {
    initialize();
    window.nimbleBar.addClass('visible animated bounceInUp');
    setTimeout(function (argument) {
      nimbleBar.removeClass('bounceInUp');
      $('.nimble-input').val('');
      this.nimble.getData(function (data) {
        $('.nimble-input').focus();
        dropdownItems = data;
        filteredItems = dropdownItems;
        populateDropdown(dropdownItems);
      });
    }, 750);
  }

  function hideNimbleBar () {
    $('.nimble-pipeline').empty();
    nimbleBar.addClass('bounceOutDown');
    setTimeout(function () {
      $('.nimble-input').blur();
      $('.nimble-input').val('');
      $('.nimble-options').html('');
      nimbleBar.removeClass('visible animated bounceOutDown');
    }, 750);
  }

  function bindInputDropdown () {
    $('.nimble-input').on('keyup', function (ev) {
      if (ev.keyCode == 38 || ev.keyCode == 40) {
        return;
      }
      var input = $('.nimble-input').val();
      filteredItems = _.filter(dropdownItems, function (text) {
        return text.queryPattern.test(input.toLowerCase())
        || text.extras.title.toLowerCase().indexOf(input) > -1;
      });
      if (filteredItems.length > 0) {
        populateDropdown(filteredItems);
      } else {
        populateDropdown([{
          extras: {
            title: 'No results found'
          }
        }]);
      }
      selectedOptionIndex = -1;
    });
  }

  Mousetrap.bind('n', function(e) {
    if (!shown) {
      e.preventDefault();
      showNimbleBar();
      shown = true;
    }
  });

  Mousetrap.bind('esc', function(e) {
    if (shown) {
      e.preventDefault();
      hideNimbleBar();
      shown = false;
    }
  });

  function highlightSelectedItem (index) {
    var options = document.querySelectorAll('.nimble-options li');
    $(options).removeClass('selected');
    $(options[index]).addClass('selected');
  }

  function updateInputQueryString () {
    var selectedItem = filteredItems[selectedOptionIndex];
    if (selectedItem && 'extras' in selectedItem && 'title' in selectedItem.extras) {
      $('.nimble-input').val(selectedItem.extras.title);
    }
  }

  Mousetrap.bind('down', function (e) {
    if (shown) {
      selectedOptionIndex++;
      highlightSelectedItem(selectedOptionIndex);
      updateInputQueryString();
    }
  });

  Mousetrap.bind('up', function (e) {
    if (shown) {
      selectedOptionIndex--;
      selectedOptionIndex = Math.max(selectedOptionIndex, 0);
      highlightSelectedItem(selectedOptionIndex);
      updateInputQueryString();
    }
  });

  Mousetrap.bind('tab', function (e) {
    e.preventDefault();
    $('.nimble-input').val('');
    var selectedObj = filteredItems[selectedOptionIndex];
    pipeline.push(selectedObj);
    var $nimblePipelineItem = $('
');
    var content = selectedObj.extras.title;
    if (content) {
      $nimblePipelineItem.html('' + content + '');
      $('.nimble-pipeline').append($nimblePipelineItem);
    }

    var filterCriteria = selectedObj.output !== undefined ?
      selectedObj.output : selectedObj;
    var matchResults = router.matchObject(filterCriteria);
    dropdownItems = matchResults;
    filteredItems = dropdownItems;
    populateDropdown(dropdownItems);
  });

  Mousetrap.bind('enter', function (e) {
    e.preventDefault();

    // Temp. hack to test execution code.
    var obj = pipeline[0];
    obj.extras.telno = '+14255022351';

    this.nimble.chainPromise(pipeline.slice(1), obj);
    hideNimbleBar();
    shown = false;
  });

  initialize();

  var plugins = [
    'Googl',
    'PluginFacebook',
    'PluginDropbox',
    'Twilio'
  ];

  /* Creates instances of recipe workers for each entry in a recipe manifest.
   */
  var initPlugins = function (plugins) {
    var recipes = [];
    for (var i = 0; i < plugins.length; i++) {
      var construct = plugins[i] + '()';
      var pluginRef = eval(construct);
      var supportedRecipes = pluginRef.getRecipes();
      recipes = recipes.concat(supportedRecipes);
    }
    return recipes;
  };

  var recipes = initPlugins(plugins);
  var router = Router(recipes);
  console.log('Nimble finish loading');
})();
<commit_msg>Fixed issue where selectedOptionIndex resets when typed<commit_after>(function () {

  var template = chrome.extension.getURL('bar.html');
  $.ajax({
    url: template,
    async: false,
    success: function (html) {
      var nimbleBar = $(html);
      $('body').append(nimbleBar);
      window.nimbleBar = nimbleBar;
      bindInputDropdown();
    }
  });

  var dropdownItems;
  var filteredItems;
  var selectedOptionIndex;
  var shown = false;
  var pipeline;

  function initialize () {
    dropdownItems = [];
    filteredItems = [];
    selectedOptionIndex = -1;
    pipeline = [];
    $('.nimble-pipeline').html('');
    $('.nimble-options').html('');
    console.log('initialize')
  }

  function populateDropdown (items) {
    $('.nimble-options').html('');
    selectedOptionIndex = -1;
    _.each(items, function (item) {
      var $nimbleOption = $('
');
      var content = item.extras.title;
      $nimbleOption.html('
' + content + '
');
      $('.nimble-options').append($nimbleOption);
    })
  }

  function showNimbleBar () {
    initialize();
    window.nimbleBar.addClass('visible animated bounceInUp');
    setTimeout(function (argument) {
      nimbleBar.removeClass('bounceInUp');
      $('.nimble-input').val('');
      this.nimble.getData(function (data) {
        $('.nimble-input').focus();
        dropdownItems = data;
        filteredItems = dropdownItems;
        populateDropdown(dropdownItems);
        selectedOptionIndex = 0;
        highlightSelectedItem(selectedOptionIndex);
      });
    }, 750);
  }

  function hideNimbleBar () {
    $('.nimble-pipeline').empty();
    nimbleBar.addClass('bounceOutDown');
    setTimeout(function () {
      $('.nimble-input').blur();
      $('.nimble-input').val('');
      $('.nimble-options').html('');
      nimbleBar.removeClass('visible animated bounceOutDown');
    }, 750);
  }

  function bindInputDropdown () {
    $('.nimble-input').on('keyup', function (ev) {
      if (ev.keyCode == 38 || ev.keyCode == 40) {
        return;
      }
      var input = $('.nimble-input').val();
      filteredItems = _.filter(dropdownItems, function (text) {
        return text.queryPattern.test(input.toLowerCase())
        || text.extras.title.toLowerCase().indexOf(input) > -1;
      });
      if (filteredItems.length > 0) {
        populateDropdown(filteredItems);
        selectedOptionIndex = 0;
        highlightSelectedItem(selectedOptionIndex);
      } else {
        populateDropdown([{
          extras: {
            title: 'No results found'
          }
        }]);
        selectedOptionIndex = -1;
      }
    });
  }

  Mousetrap.bind('n', function(e) {
    if (!shown) {
      e.preventDefault();
      showNimbleBar();
      shown = true;
    }
  });

  Mousetrap.bind('esc', function(e) {
    if (shown) {
      e.preventDefault();
      hideNimbleBar();
      shown = false;
    }
  });

  function highlightSelectedItem (index) {
    var options = document.querySelectorAll('.nimble-options li');
    $(options).removeClass('selected');
    $(options[index]).addClass('selected');
  }

  function updateInputQueryString () {
    var selectedItem = filteredItems[selectedOptionIndex];
    if (selectedItem && 'extras' in selectedItem && 'title' in selectedItem.extras) {
      $('.nimble-input').val(selectedItem.extras.title);
    }
  }

  Mousetrap.bind('down', function (e) {
    if (shown) {
      selectedOptionIndex++;
      highlightSelectedItem(selectedOptionIndex);
      updateInputQueryString();
    }
  });

  Mousetrap.bind('up', function (e) {
    if (shown) {
      selectedOptionIndex--;
      selectedOptionIndex = Math.max(selectedOptionIndex, 0);
      highlightSelectedItem(selectedOptionIndex);
      updateInputQueryString();
    }
  });

  Mousetrap.bind('tab', function (e) {
    e.preventDefault();
    $('.nimble-input').val('');
    var selectedObj = filteredItems[selectedOptionIndex];
    pipeline.push(selectedObj);
    var $nimblePipelineItem = $('
');
    var content = selectedObj.extras.title;
    if (content) {
      $nimblePipelineItem.html('' + content + '');
      $('.nimble-pipeline').append($nimblePipelineItem);
    }

    var filterCriteria = selectedObj.output !== undefined ?
      selectedObj.output : selectedObj;
    var matchResults = router.matchObject(filterCriteria);
    dropdownItems = matchResults;
    filteredItems = dropdownItems;
    populateDropdown(dropdownItems);
  });

  Mousetrap.bind('enter', function (e) {
    e.preventDefault();

    // Temp. hack to test execution code.
    var obj = pipeline[0];
    obj.extras.telno = '+14255022351';

    this.nimble.chainPromise(pipeline.slice(1), obj);
    hideNimbleBar();
    shown = false;
  });

  initialize();

  var plugins = [
    'Googl',
    'PluginFacebook',
    'PluginDropbox',
    'Twilio'
  ];

  /* Creates instances of recipe workers for each entry in a recipe manifest.
   */
  var initPlugins = function (plugins) {
    var recipes = [];
    for (var i = 0; i < plugins.length; i++) {
      var construct = plugins[i] + '()';
      var pluginRef = eval(construct);
      var supportedRecipes = pluginRef.getRecipes();
      recipes = recipes.concat(supportedRecipes);
    }
    return recipes;
  };

  var recipes = initPlugins(plugins);
  var router = Router(recipes);
  console.log('Nimble finish loading');
})();
<|endoftext|>