<commit_before>'use strict';

const EventEmitter = require('events').EventEmitter;

const utils = require('./utils');

const Message = require('./Message');
const Metric = require('./Metric');
const Stream = require('./Stream');
const serializerFactory = require('./serializer/factory');

const LEVELS = {
  TRACE: 10,
  DEBUG: 20,
  INFO: 30,
  WARN: 40,
  ERROR: 50,
  FATAL: 60
}

class Logger extends EventEmitter {
  constructor(options) {
    super(options);

    // Initialize the logger:
    this.init(options);

    // Bind the process handler to the message
    // event emission:
    this.on('write', this.write);
    this.on('read', this.read);
  }

  init(options) {
    options = options || {};

    // Keep original configuration parameters:
    this._options = options;

    // Streams:
    if (!this.options().streams) {
      this._options.streams = [new Stream({
        name: 'default',
        stream: process.stdout,
        serializer: serializerFactory.create('bunyan')
      })];
    }

    // Streams normalization:
    for (const i in this.options().streams) {
      const stream = this.options().streams[i];
      if (!(stream instanceof Stream)) {
        // Change the serializer string definition by its instance:
        if (typeof stream.serializer === 'string') {
          stream.serializer = serializerFactory.create(stream.serializer);
        }

        this._options.streams[i] = new Stream(stream);
      }
    }
  }

  // Create a logger child:
  child(options) {
    return new Logger(utils.extend(options, this._options));
  }

  write(message) {
    if (message instanceof Message) {
      for (var stream of this.streams()) {
        stream.write(message);
      }
    }
  }

  read(message) {
    for (var stream of this.streams()) {
      const entry = stream.read(message);
      if (entry !== false) {
        this.log(entry.level, entry.error, entry.context, entry.message);
      }
    }
  }

  log(level, error, context, message) {
    if (this.withStats()) {
      context.stats = utils.stats();
    }
    const log = new Message(this, level, error,
      utils.extend(this.context(), context), message);
    // this.toStack(log);
    this.emit('write', log);
  }

  // LEVEL METHODS

  fatal(error, context, message) {
    this.log(LEVELS.FATAL, error, context, message);
  }

  error(error, context, message) {
    this.log(LEVELS.ERROR, error, context, message);
  }

  warn(error, context, message) {
    this.log(LEVELS.WARN, error, context, message);
  }

  info(context, message) {
    this.log(LEVELS.INFO, null, context, message);
  }

  debug(context, message) {
    this.log(LEVELS.DEBUG, null, context, message);
  }

  trace(context, message) {
    this.log(LEVELS.TRACE, null, context, message);
  }

  metric(type, value, sampleRate, tags) {
    const metric = new Metric(this, type, value, sampleRate, tags);
    this.emit('metric', metric);
  }

  // GETTERS

  options() {
    return this._options || {};
  }

  streams() {
    return this._options.streams || [];
  }

  context() {
    return this.options().context || {};
  }

  withStats() {
    return this.options().withStats || false;
  }

  getName() {
    return this.options().name || 'logger';
  }
}

Logger.prototype.LEVELS = LEVELS;

module.exports = Logger;
<commit_msg>Add parent.child chain<commit_after>'use strict';

const EventEmitter = require('events').EventEmitter;

const utils = require('./utils');

const Message = require('./Message');
const Metric = require('./Metric');
const Stream = require('./Stream');
const serializerFactory = require('./serializer/factory');

const LEVELS = {
  TRACE: 10,
  DEBUG: 20,
  INFO: 30,
  WARN: 40,
  ERROR: 50,
  FATAL: 60
}

class Logger extends EventEmitter {
  constructor(options) {
    super(options);

    // Initialize the logger:
    this.init(options);

    // Bind the process handler to the message
    // event emission:
    this.on('write', this.write);
    this.on('read', this.read);
  }

  init(options) {
    options = options || {};

    // Keep original configuration parameters:
    this._options = options;

    // Streams:
    if (!this.options().streams) {
      this._options.streams = [new Stream({
        name: 'default',
        stream: process.stdout,
        serializer: serializerFactory.create('bunyan')
      })];
    }

    // Streams normalization:
    for (const i in this.options().streams) {
      const stream = this.options().streams[i];
      if (!(stream instanceof Stream)) {
        // Change the serializer string definition by its instance:
        if (typeof stream.serializer === 'string') {
          stream.serializer = serializerFactory.create(stream.serializer);
        }

        this._options.streams[i] = new Stream(stream);
      }
    }
  }

  // Create a logger child:
  child(options) {
    options.parent = this;
    return new Logger(utils.extend(options, this._options));
  }

  parent() {
    return this.options().parent;
  }

  write(message) {
    if (message instanceof Message) {
      for (var stream of this.streams()) {
        stream.write(message);
      }
    }
  }

  read(message) {
    for (var stream of this.streams()) {
      const entry = stream.read(message);
      if (entry !== false) {
        this.log(entry.level, entry.error, entry.context, entry.message);
      }
    }
  }

  log(level, error, context, message) {
    if (this.withStats()) {
      context.stats = utils.stats();
    }
    const log = new Message(this, level, error,
      utils.extend(this.context(), context), message);
    // this.toStack(log);
    this.emit('write', log);
  }

  // LEVEL METHODS

  fatal(error, context, message) {
    this.log(LEVELS.FATAL, error, context, message);
  }

  error(error, context, message) {
    this.log(LEVELS.ERROR, error, context, message);
  }

  warn(error, context, message) {
    this.log(LEVELS.WARN, error, context, message);
  }

  info(context, message) {
    this.log(LEVELS.INFO, null, context, message);
  }

  debug(context, message) {
    this.log(LEVELS.DEBUG, null, context, message);
  }

  trace(context, message) {
    this.log(LEVELS.TRACE, null, context, message);
  }

  metric(type, value, sampleRate, tags) {
    const metric = new Metric(this, type, value, sampleRate, tags);
    this.emit('metric', metric);
  }

  // GETTERS

  options() {
    return this._options || {};
  }

  streams() {
    return this._options.streams || [];
  }

  context() {
    return this.options().context || {};
  }

  withStats() {
    return this.options().withStats || false;
  }

  getName() {
    return this.options().name || 'logger';
  }
}

Logger.prototype.LEVELS = LEVELS;

module.exports = Logger;
<|endoftext|>


<commit_before>'use babel';

import path from 'path';
import fs from 'fs-plus';

import fileTypes from './file-types';

const iconBinary = 'icon-file-binary';
const iconCode = 'icon-file-code';
const iconMedia = 'icon-file-media';
const iconPdf = 'icon-file-pdf';
const iconSymlink = 'icon-file-symlink-file';
const iconText = 'icon-file-text';
const iconZip = 'icon-file-zip';
const iconDatabase = 'icon-database';

export default class File {
  constructor(filePath) {
    this.filePath = filePath || '';
    this.extension = path.extname(this.filePath);
    this.fileName = path.basename(this.filePath, this.extension);
    this.fileType = this.extension.substring(1) || this.fileName;
  }

  iconClass() {
    if (fs.isSymbolicLinkSync(this.filePath)) {
      return iconSymlink;
    } else if (fs.isCompressedExtension(this.extension)) {
      return iconZip;
    } else if (fs.isImageExtension(this.extension)) {
      return iconMedia;
    } else if (fs.isPdfExtension(this.extension)) {
      return iconPdf;
    } else if (fs.isBinaryExtension(this.extension)) {
      return iconBinary;
    } else if (fs.isMarkdownExtension(this.extension)) {
      return iconText;
    } else if (this.isDatabase()) {
      return iconDatabase;
    } else if (this.isCodeExtension()) {
      return iconCode;
    }
    return iconText;
  }

  isCodeExtension() {
    return fileTypes.source.includes(this.fileType);
  }

  isDatabase() {
    return fileTypes.database.includes(this.fileType);
  }
}
<commit_msg>Add "book" icon for MD files<commit_after>'use babel';

import path from 'path';
import fs from 'fs-plus';

import fileTypes from './file-types';

const iconBinary = 'icon-file-binary';
const iconCode = 'icon-file-code';
const iconMedia = 'icon-file-media';
const iconPdf = 'icon-file-pdf';
const iconSymlink = 'icon-file-symlink-file';
const iconText = 'icon-file-text';
const iconZip = 'icon-file-zip';
const iconDatabase = 'icon-database';
const iconBook = 'icon-book';

export default class File {
  constructor(filePath) {
    this.filePath = filePath || '';
    this.extension = path.extname(this.filePath);
    this.fileName = path.basename(this.filePath, this.extension);
    this.fileType = this.extension.substring(1) || this.fileName;
  }

  iconClass() {
    if (fs.isSymbolicLinkSync(this.filePath)) {
      return iconSymlink;
    } else if (fs.isCompressedExtension(this.extension)) {
      return iconZip;
    } else if (fs.isImageExtension(this.extension)) {
      return iconMedia;
    } else if (fs.isPdfExtension(this.extension)) {
      return iconPdf;
    } else if (fs.isBinaryExtension(this.extension)) {
      return iconBinary;
    } else if (fs.isMarkdownExtension(this.extension)) {
      return iconBook;
    } else if (this.isDatabase()) {
      return iconDatabase;
    } else if (this.isCodeExtension()) {
      return iconCode;
    }
    return iconText;
  }

  isCodeExtension() {
    return fileTypes.source.includes(this.fileType);
  }

  isDatabase() {
    return fileTypes.database.includes(this.fileType);
  }
}
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const EventEmitter = require('events');
const path = require('path');
const utils = require('./utils');

class Method extends EventEmitter {
  constructor(name, options, fn) {
    super();

    this.name = name || options.name || utils.getName(fn);
    assert(typeof this.name === 'string', 'Method name must be a valid string');
    assert(typeof fn === 'function', 'Method fn must be a valid function');

    // Parent reference
    this.parent = null;

    this.stack = null;
    this.fn = fn;
    this.options = options || {};

    // Skip beforeHooks and afterHooks or not, default is false
    this.skipHooks = this.options.skipHooks === true;

    this.accepts = options.accepts || [];
    this.description = options.description || options.desc || name;
    this.notes = options.notes;
    this.documented = options.documented !== false;

    this.http = options.http || {};
    if (!this.http.verb) this.http.verb = 'all';
    this.http.verb = String(this.http.verb).toLowerCase();
    if (!this.http.path) this.http.path = '/';

    this.multipart = options.multipart || {};

    // if accepts is not a array, then wrap it as an array
    if (this.accepts && !Array.isArray(this.accepts)) {
      this.accepts = [this.accepts];
    }
  }

  fullPath() {
    let segments = ['/'];
    if (this.parent) segments.push(this.parent.fullPath());
    segments.push(this.http.path);
    return path.join.apply(path, segments);
  }

  clone() {
    let method = new Method(
      this.name,
      Object.assign({}, this.options),
      this.fn
    );

    method.stack = null;
    method.skipHooks = this.skipHooks;
    method.parent = this.parent;
    method.accepts = this.accepts.slice();
    method.description = this.description;
    method.notes = this.notes;
    method.documented = this.documented;
    method.http = Object.assign({}, this.http);
    method.multipart = Object.assign({}, this.multipart);

    return method;
  }

  fullName() {
    return this.parent ? `${this.parent.fullName()}.${this.name}` : this.name;
  }

  invoke() {
    assert(this.stack, `Method: '${this.fullName()}' is not composed before invoking`);

    return this.stack.apply(null, arguments);
  }

  compose(beforeStack, afterStack, afterErrorStack) {
    let stack = [].concat(this.skipHooks ? [] : (beforeStack || []))
                  .concat(this.fn)
                  .concat(this.skipHooks ? [] : (afterStack || []));

    let afterError = utils.compose(afterErrorStack || []);

    this.stack = utils.compose(stack, afterError);
  }
}

Method.create = function(name, options, fn) {
  return new Method(name, options, fn);
};

module.exports = Method;
<commit_msg>default skipHooks when http.verb is use and allow manual overwrite<commit_after>'use strict';

const assert = require('assert');
const EventEmitter = require('events');
const path = require('path');
const utils = require('./utils');

class Method extends EventEmitter {
  constructor(name, options, fn) {
    super();

    this.name = name || options.name || utils.getName(fn);
    assert(typeof this.name === 'string', 'Method name must be a valid string');
    assert(typeof fn === 'function', 'Method fn must be a valid function');

    // Parent reference
    this.parent = null;

    this.stack = null;
    this.fn = fn;
    this.options = options || {};

    this.accepts = options.accepts || [];
    this.description = options.description || options.desc || name;
    this.notes = options.notes;
    this.documented = options.documented !== false;

    this.http = options.http || {};
    if (!this.http.verb) this.http.verb = 'all';
    this.http.verb = String(this.http.verb).toLowerCase();
    if (!this.http.path) this.http.path = '/';

    this.multipart = options.multipart || {};

    // if accepts is not a array, then wrap it as an array
    if (this.accepts && !Array.isArray(this.accepts)) {
      this.accepts = [this.accepts];
    }

    // Skip beforeHooks and afterHooks or not, default is `true` when http.verb is `use` otherwise `false`
    this.skipHooks = this.http.verb === 'use';
    if (this.options.skipHooks === true) {
      this.skipHooks = true;
    } else if (this.options.skipHooks === false) {
      this.skipHooks = false;
    }
  }

  fullPath() {
    let segments = ['/'];
    if (this.parent) segments.push(this.parent.fullPath());
    segments.push(this.http.path);
    return path.join.apply(path, segments);
  }

  clone() {
    let method = new Method(
      this.name,
      Object.assign({}, this.options),
      this.fn
    );

    method.stack = null;
    method.skipHooks = this.skipHooks;
    method.parent = this.parent;
    method.accepts = this.accepts.slice();
    method.description = this.description;
    method.notes = this.notes;
    method.documented = this.documented;
    method.http = Object.assign({}, this.http);
    method.multipart = Object.assign({}, this.multipart);

    return method;
  }

  fullName() {
    return this.parent ? `${this.parent.fullName()}.${this.name}` : this.name;
  }

  invoke() {
    assert(this.stack, `Method: '${this.fullName()}' is not composed before invoking`);

    return this.stack.apply(null, arguments);
  }

  compose(beforeStack, afterStack, afterErrorStack) {
    let stack = [].concat(this.skipHooks ? [] : (beforeStack || []))
                  .concat(this.fn)
                  .concat(this.skipHooks ? [] : (afterStack || []));

    let afterError = utils.compose(afterErrorStack || []);

    this.stack = utils.compose(stack, afterError);
  }
}

Method.create = function(name, options, fn) {
  return new Method(name, options, fn);
};

module.exports = Method;
<|endoftext|>


<commit_before>self.onmessage = function(e) {
    self.clients.getServiced().then(function(clients) {
        clients.forEach(function(client) {
            client.postMessage('Sending message via clients');
            client.postMessage('quit');
        });
    });
};
<commit_msg>ServiceWorker: Ensure getServiced() resolved with JS array<commit_after>self.onmessage = function(e) {
    self.clients.getServiced().then(function(clients) {
        clients.forEach(function(client) {
            client.postMessage('Sending message via clients');
            if (!Array.isArray(clients))
                client.postMessage('clients is not an array');
            client.postMessage('quit');
        });
    });
};
<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import Webiny from 'webiny';

class Auth {
    constructor() {
        this.loginRoute = 'Login';
        this.forbiddenRoute = 'Forbidden';
        this.routerEvent = null;
    }

    init() {
        Webiny.Router.addRoute(new Webiny.Route(this.loginRoute, '/login', this.renderLogin(), 'Login').setLayout('empty'));
        Webiny.Router.addRoute(new Webiny.Route(this.forbiddenRoute, '/forbidden', this.renderForbidden(), 'Forbidden'));

        Webiny.Router.onBeforeStart(routerEvent => {
            Webiny.Http.addRequestInterceptor(http => {
                http.addHeader('X-Webiny-Authorization', Webiny.Cookies.get(this.getCookieName()));
            });

            // Watch if we got a forbidden request - then log out
            Webiny.Http.addResponseInterceptor(this.getResponseInterceptor());

            return this.checkUser(routerEvent);
        });
        Webiny.Router.onRouteWillChange(this.checkUser.bind(this));
    }

    getResponseInterceptor() {
        return response => {
            if (response.getStatus() === 403) {
                this.onForbidden(response);
            }
        };
    }

    /**
     * Check if user is authenticated and authorized to visit requested route.
     * This method is the main "entry point" into the verification process.
     *
     * @param routerEvent
     * @returns {*}
     */
    checkUser(routerEvent) {
        this.routerEvent = routerEvent;

        if (Webiny.Model.get('User')) {
            return this.checkRouteRole(routerEvent);
        }

        const token = Webiny.Cookies.get(this.getCookieName());

        // Check if token exists on client side
        if (!token) {
            return this.onNoToken(routerEvent);
        }

        // Try fetching user data
        return this.getUser().then(() => this.checkRouteRole(routerEvent));
    }

    checkRouteRole(routerEvent) {
        if (Webiny.Config.Js.CheckUserRoles && _.has(routerEvent.route, 'role')) {
            return new Promise((resolve) => {
                const user = Webiny.Model.get('User');

                if (user && _.isArray(routerEvent.route.role) && this.hasRole(routerEvent.route.role)) {
                    return resolve(routerEvent);
                }

                if (user && _.isFunction(routerEvent.route.role)) {
                    return Promise.resolve(routerEvent.route.role(routerEvent.route)).then(allowed => {
                        if (!allowed) {
                            routerEvent.stop();
                            routerEvent.goToRoute(this.forbiddenRoute);
                        }
                        resolve(routerEvent);
                    });
                }

                routerEvent.stop();
                routerEvent.goToRoute(this.forbiddenRoute);
                resolve(routerEvent);
            });
        }
        return Promise.resolve(routerEvent);
    }

    /**
     * This method checks if current target route is already a login route and redirects (or not) properly.
     *
     * @param routerEvent
     * @returns {*}
     */
    goToLogin(routerEvent) {
        localStorage.loginRedirect = window.location.href;

        const isLoginRoute = _.get(routerEvent.route, 'name') === this.loginRoute;

        if (!isLoginRoute) {
            routerEvent.stop();
            routerEvent.goToRoute(this.loginRoute);
        }

        return routerEvent;
    }

    onNoToken(routerEvent) {
        return this.goToLogin(routerEvent);
    }

    /**
     * Use the given user data to check if the user is authorized to be in this app.
     * This logic is completely specific to your application. Implement this as you see fit.
     *
     * This method is used by `verifyUser` and Login forms to check authorization of logged in user.
     *
     * @param user
     * @returns {boolean}
     */
    isAuthorized(user) {
        return !!_.find(user.roles, {slug: 'administrator'});
    }

    getUserFields() {
        return '*,roles.slug,roleGroups[id,name,roles.slug],gravatar';
    }

    /**
     * Fetch user profile and verify the returned data.
     *
     * @returns Promise
     */
    getUser() {
        return this.getApiEndpoint().get('/me', {_fields: this.getUserFields()}).then(apiResponse => {
            return Promise.resolve(this.verifyUser(apiResponse)).then(() => apiResponse);
        });
    }

    /**
     * Get cookie name
     * @returns {string}
     */
    getCookieName() {
        return 'webiny-token';
    }

    getApiEndpoint() {
        if (!this.authApi) {
            this.authApi = new Webiny.Api.Endpoint('/entities/webiny/users')
        }
        return this.authApi;
    }

    refresh() {
        return this.getUser();
    }

    logout(redirect = true) {
        let logout = Promise.resolve().then(() => {
            Webiny.Model.set('User', null);
            Webiny.Cookies.remove(this.getCookieName());
        });

        if (redirect) {
            logout = logout.then(() => Webiny.Router.goToRoute(this.loginRoute));
        }

        return logout;
    }

    /**
     * This method determines if the given response from the API is valid user data.
     * It also executes `isAuthorized` to see if given user is allowed to be in this app.
     *
     * This method can be overridden to suit your app's needs.
     * It is up to the developer to handle both `verified` and `unverified` cases as he sees fit.
     *
     * @param apiResponse
     * @returns {*}
     */
    verifyUser(apiResponse) {
        const data = apiResponse.getData();
        if (apiResponse.isError() || !this.isAuthorized(data)) {
            // We need to stop router event to prevent him from rendering the route he initially intended
            this.routerEvent && this.routerEvent.stop();
            return this.logout();
        }
        Webiny.Model.set('User', data);
    }

    /**
     * Check if current user has any of the requested roles (checks both roles and roleGroups)
     * @param role
     */
    hasRole(role) {
        if (_.isString(role)) {
            role = [role];
        }

        const user = Webiny.Model.get('User');
        // First check user roles
        let hasRole = _.find(user.roles, r => role.indexOf(r.slug) > -1);
        if (!hasRole) {
            // Check user role groups
            _.each(user.roleGroups, group => {
                hasRole = _.find(group.roles, r => role.indexOf(r.slug) > -1);
                if (hasRole) {
                    return false;
                }
            });
        }

        return hasRole;
    }

    /**
     * Triggered when user is not authorized to perform the HTTP request.
     */
    onForbidden(httpResponse) {
        // Implement whatever logic you see fit
    }

    renderLogin() {
        return null;
    }

    renderForbidden() {
        return null;
    }
}

export default Auth;<commit_msg>Added roleGroups to `isAuthorized` check of Auth class for cases when `administrator` role is exposed via `roleGroups` attribute.<commit_after>import React from 'react';
import _ from 'lodash';
import Webiny from 'webiny';

class Auth {
    constructor() {
        this.loginRoute = 'Login';
        this.forbiddenRoute = 'Forbidden';
        this.routerEvent = null;
    }

    init() {
        Webiny.Router.addRoute(new Webiny.Route(this.loginRoute, '/login', this.renderLogin(), 'Login').setLayout('empty'));
        Webiny.Router.addRoute(new Webiny.Route(this.forbiddenRoute, '/forbidden', this.renderForbidden(), 'Forbidden'));

        Webiny.Router.onBeforeStart(routerEvent => {
            Webiny.Http.addRequestInterceptor(http => {
                http.addHeader('X-Webiny-Authorization', Webiny.Cookies.get(this.getCookieName()));
            });

            // Watch if we got a forbidden request - then log out
            Webiny.Http.addResponseInterceptor(this.getResponseInterceptor());

            return this.checkUser(routerEvent);
        });
        Webiny.Router.onRouteWillChange(this.checkUser.bind(this));
    }

    getResponseInterceptor() {
        return response => {
            if (response.getStatus() === 403) {
                this.onForbidden(response);
            }
        };
    }

    /**
     * Check if user is authenticated and authorized to visit requested route.
     * This method is the main "entry point" into the verification process.
     *
     * @param routerEvent
     * @returns {*}
     */
    checkUser(routerEvent) {
        this.routerEvent = routerEvent;

        if (Webiny.Model.get('User')) {
            return this.checkRouteRole(routerEvent);
        }

        const token = Webiny.Cookies.get(this.getCookieName());

        // Check if token exists on client side
        if (!token) {
            return this.onNoToken(routerEvent);
        }

        // Try fetching user data
        return this.getUser().then(() => this.checkRouteRole(routerEvent));
    }

    checkRouteRole(routerEvent) {
        if (Webiny.Config.Js.CheckUserRoles && _.has(routerEvent.route, 'role')) {
            return new Promise((resolve) => {
                const user = Webiny.Model.get('User');

                if (user && _.isArray(routerEvent.route.role) && this.hasRole(routerEvent.route.role)) {
                    return resolve(routerEvent);
                }

                if (user && _.isFunction(routerEvent.route.role)) {
                    return Promise.resolve(routerEvent.route.role(routerEvent.route)).then(allowed => {
                        if (!allowed) {
                            routerEvent.stop();
                            routerEvent.goToRoute(this.forbiddenRoute);
                        }
                        resolve(routerEvent);
                    });
                }

                routerEvent.stop();
                routerEvent.goToRoute(this.forbiddenRoute);
                resolve(routerEvent);
            });
        }
        return Promise.resolve(routerEvent);
    }

    /**
     * This method checks if current target route is already a login route and redirects (or not) properly.
     *
     * @param routerEvent
     * @returns {*}
     */
    goToLogin(routerEvent) {
        localStorage.loginRedirect = window.location.href;

        const isLoginRoute = _.get(routerEvent.route, 'name') === this.loginRoute;

        if (!isLoginRoute) {
            routerEvent.stop();
            routerEvent.goToRoute(this.loginRoute);
        }

        return routerEvent;
    }

    onNoToken(routerEvent) {
        return this.goToLogin(routerEvent);
    }

    /**
     * Use the given user data to check if the user is authorized to be in this app.
     * This logic is completely specific to your application. Implement this as you see fit.
     *
     * This method is used by `verifyUser` and Login forms to check authorization of logged in user.
     *
     * @param user
     * @returns {boolean}
     */
    isAuthorized(user) {
        if (!!_.find(user.roles, {slug: 'administrator'})) {
            return true;
        }

        return !!_.find(user.roleGroups, rg => !!_.find(rg.roles, {slug: 'administrator'}));
    }

    getUserFields() {
        return '*,roles.slug,roleGroups[id,name,roles.slug],gravatar';
    }

    /**
     * Fetch user profile and verify the returned data.
     *
     * @returns Promise
     */
    getUser() {
        return this.getApiEndpoint().get('/me', {_fields: this.getUserFields()}).then(apiResponse => {
            return Promise.resolve(this.verifyUser(apiResponse)).then(() => apiResponse);
        });
    }

    /**
     * Get cookie name
     * @returns {string}
     */
    getCookieName() {
        return 'webiny-token';
    }

    getApiEndpoint() {
        if (!this.authApi) {
            this.authApi = new Webiny.Api.Endpoint('/entities/webiny/users')
        }
        return this.authApi;
    }

    refresh() {
        return this.getUser();
    }

    logout(redirect = true) {
        let logout = Promise.resolve().then(() => {
            Webiny.Model.set('User', null);
            Webiny.Cookies.remove(this.getCookieName());
        });

        if (redirect) {
            logout = logout.then(() => Webiny.Router.goToRoute(this.loginRoute));
        }

        return logout;
    }

    /**
     * This method determines if the given response from the API is valid user data.
     * It also executes `isAuthorized` to see if given user is allowed to be in this app.
     *
     * This method can be overridden to suit your app's needs.
     * It is up to the developer to handle both `verified` and `unverified` cases as he sees fit.
     *
     * @param apiResponse
     * @returns {*}
     */
    verifyUser(apiResponse) {
        const data = apiResponse.getData();
        if (apiResponse.isError() || !this.isAuthorized(data)) {
            // We need to stop router event to prevent him from rendering the route he initially intended
            this.routerEvent && this.routerEvent.stop();
            return this.logout();
        }
        Webiny.Model.set('User', data);
    }

    /**
     * Check if current user has any of the requested roles (checks both roles and roleGroups)
     * @param role
     */
    hasRole(role) {
        if (_.isString(role)) {
            role = [role];
        }

        const user = Webiny.Model.get('User');
        // First check user roles
        let hasRole = _.find(user.roles, r => role.indexOf(r.slug) > -1);
        if (!hasRole) {
            // Check user role groups
            _.each(user.roleGroups, group => {
                hasRole = _.find(group.roles, r => role.indexOf(r.slug) > -1);
                if (hasRole) {
                    return false;
                }
            });
        }

        return hasRole;
    }

    /**
     * Triggered when user is not authorized to perform the HTTP request.
     */
    onForbidden(httpResponse) {
        // Implement whatever logic you see fit
    }

    renderLogin() {
        return null;
    }

    renderForbidden() {
        return null;
    }
}

export default Auth;<|endoftext|>


<commit_before>'use strict';

var _ = require('nitro-tools'),
    fs = require('fs'),
    joinPaths = require('./join-paths'),
    mkdirp = require('mkdirp'),
    mmatch = require('minimatch'),
    deasync = require('deasync'),
    RE_filepath = /(.*)[\\\/](.*)/,
    YAML = require('js-yaml');

function parsePath (filepath) {
  var matches = filepath.match(RE_filepath);

  return {
    filename: ( matches && matches[2] ) || filepath,
    filepath: ( matches && matches[1] ) || null
  };
}

var file = {
  exists: function (filepath, done) {
    filepath = joinPaths.root(filepath);
    try {
      return fs[done ? 'stat' : 'statSync'](filepath, done);
    } catch(err) {
      if( done ) done(err);
      return false;
    }
  },
  read: function (paths) {
    return fs.readFileSync( joinPaths.root(paths), { encoding: 'utf8' });
  },
  readJSON: function () {
    return JSON.parse( file.read.apply(this, arguments) );
  },
  readYAML: function () {
    return YAML.safeLoad( file.read.apply(this, arguments) );
  },
  write: function (paths, content, options) {
    var dest = joinPaths(paths),
        filepath = parsePath(dest).filepath;

    if( filepath ) mkdirp.sync(filepath);
    return fs.writeFileSync( joinPaths.root(dest) , content, _.extend({ encoding: 'utf8' }, options || {}) );
  },
  writeJSON: function (paths, data, indentation) {
    return file.write( paths, JSON.stringify(data, null, indentation || '\t') );
  },
  writeYAML: function (paths, data) {
    return file.write( paths, YAML.safeDump(data) );
  },
  copy: function (src, dest) {
    var filepath = parsePath(dest).filepath;
    if( filepath && !file.exists(filepath) ) {
      mkdirp.sync( joinPaths.root(filepath) );
    }
    deasync(function (done) {
      fs.createReadStream(joinPaths.root(src))
        .pipe( fs.createWriteStream( joinPaths.root(dest) ).on('close', done) );
    })();
    return file;
  },
  parsePath: parsePath,
  filter: function (filter) {
    if( typeof filter === 'string' ) {
      return mmatch.filter(filter);
    } else if( filter instanceof Array ) {
      var filters = filter.map(file.filter);

      return function (filepath) {
        return filters.every(function (fileFilter) {
          return fileFilter(filepath);
        });
      };
    }
    return null;
  }
};

module.exports = file;
<commit_msg>removed async IO for now<commit_after>'use strict';

var _ = require('nitro-tools'),
    fs = require('fs'),
    joinPaths = require('./join-paths'),
    mkdirp = require('mkdirp'),
    mmatch = require('minimatch'),
    deasync = require('deasync'),
    RE_filepath = /(.*)[\\\/](.*)/,
    YAML = require('js-yaml');

function parsePath (filepath) {
  var matches = filepath.match(RE_filepath);

  return {
    filename: ( matches && matches[2] ) || filepath,
    filepath: ( matches && matches[1] ) || null
  };
}

var file = {
  exists: function (filepath) {
    filepath = joinPaths.root(filepath);
    try {
      return fs.statSync(filepath);
    } catch(err) {
      return false;
    }
  },
  read: function (paths) {
    return fs.readFileSync( joinPaths.root(paths), { encoding: 'utf8' });
  },
  readJSON: function () {
    return JSON.parse( file.read.apply(this, arguments) );
  },
  readYAML: function () {
    return YAML.safeLoad( file.read.apply(this, arguments) );
  },
  write: function (paths, content, options) {
    var dest = joinPaths(paths),
        filepath = parsePath(dest).filepath;

    if( filepath ) mkdirp.sync(filepath);
    return fs.writeFileSync( joinPaths.root(dest) , content, _.extend({ encoding: 'utf8' }, options || {}) );
  },
  writeJSON: function (paths, data, indentation) {
    return file.write( paths, JSON.stringify(data, null, indentation || '\t') );
  },
  writeYAML: function (paths, data) {
    return file.write( paths, YAML.safeDump(data) );
  },
  copy: function (src, dest) {
    var filepath = parsePath(dest).filepath;
    if( filepath && !file.exists(filepath) ) {
      mkdirp.sync( joinPaths.root(filepath) );
    }
    deasync(function (done) {
      fs.createReadStream(joinPaths.root(src))
        .pipe( fs.createWriteStream( joinPaths.root(dest) ).on('close', done) );
    })();
    return file;
  },
  parsePath: parsePath,
  filter: function (filter) {
    if( typeof filter === 'string' ) {
      return mmatch.filter(filter);
    } else if( filter instanceof Array ) {
      var filters = filter.map(file.filter);

      return function (filepath) {
        return filters.every(function (fileFilter) {
          return fileFilter(filepath);
        });
      };
    }
    return null;
  }
};

module.exports = file;
<|endoftext|>


<commit_before>const wrapCall = require('promise-toolbox/wrapCall')

/**
 * Similar to Promise.all + Array#map but supports all iterables and does not trigger ESLint array-callback-return
 *
 * WARNING: Does not handle plain objects
 *
 * @template Item,This
 * @param {Iterable<Item>} arrayLike
 * @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
 * @param {This} [thisArg]
 * @returns {Promise<Item[]>}
 */
exports.asyncMap = function asyncMap(iterable, mapFn, thisArg = iterable) {
  return Promise.all(Array.from(iterable, mapFn, thisArg))
}

/**
 * Like `asyncMap` but wait for all promises to settle before rejecting
 *
 * @template Item,This
 * @param {Iterable<Item>} iterable
 * @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
 * @param {This} [thisArg]
 * @returns {Promise<Item[]>}
 */
exports.asyncMapSettled = function asyncMapSettled(iterable, mapFn, thisArg = iterable) {
  return new Promise((resolve, reject) => {
    const onError = e => {
      if (result !== undefined) {
        error = e
        result = undefined
      }
      if (--n === 0) {
        this.reject(error)
      }
    }
    const onValue = (i, value) => {
      const hasError = result !== undefined
      if (!hasError) {
        result[i] = value
      }
      if (--n === 0) {
        if (hasError) {
          reject(error)
        } else {
          resolve(result)
        }
      }
    }

    let n = 0
    for (const item of iterable) {
      const i = n++
      wrapCall(mapFn, item, thisArg).then(value => onValue(i, value), onError)
    }

    if (n === 0) {
      return resolve([])
    }

    let error
    let result = new Array(n)
  })
}
<commit_msg>fix(async-map/asyncMapSettled): fix hasError condition<commit_after>const wrapCall = require('promise-toolbox/wrapCall')

/**
 * Similar to Promise.all + Array#map but supports all iterables and does not trigger ESLint array-callback-return
 *
 * WARNING: Does not handle plain objects
 *
 * @template Item,This
 * @param {Iterable<Item>} arrayLike
 * @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
 * @param {This} [thisArg]
 * @returns {Promise<Item[]>}
 */
exports.asyncMap = function asyncMap(iterable, mapFn, thisArg = iterable) {
  return Promise.all(Array.from(iterable, mapFn, thisArg))
}

/**
 * Like `asyncMap` but wait for all promises to settle before rejecting
 *
 * @template Item,This
 * @param {Iterable<Item>} iterable
 * @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
 * @param {This} [thisArg]
 * @returns {Promise<Item[]>}
 */
exports.asyncMapSettled = function asyncMapSettled(iterable, mapFn, thisArg = iterable) {
  return new Promise((resolve, reject) => {
    const onError = e => {
      if (result !== undefined) {
        error = e
        result = undefined
      }
      if (--n === 0) {
        this.reject(error)
      }
    }
    const onValue = (i, value) => {
      const hasError = result === undefined
      if (!hasError) {
        result[i] = value
      }
      if (--n === 0) {
        if (hasError) {
          reject(error)
        } else {
          resolve(result)
        }
      }
    }

    let n = 0
    for (const item of iterable) {
      const i = n++
      wrapCall(mapFn, item, thisArg).then(value => onValue(i, value), onError)
    }

    if (n === 0) {
      return resolve([])
    }

    let error
    let result = new Array(n)
  })
}
<|endoftext|>


<commit_before>var methods = {
  parse: require('./parse'),
  request: require('./request')
};

function Parser (filter) {
  this.filter = filter;
}

Parser.prototype.parse = function (html, callback) {
  return methods.parse(html, this.filter, callback);
};

Parser.prototype.request = function (options, callback) {
  return methods.request(options, this.filter, callback);
};

module.exports = Parser;
<commit_msg>Add Parser#helper method<commit_after>var methods = {
  parse: require('./parse'),
  request: require('./request')
};

function Parser (filter) {
  this.filter = filter;
}

Parser.prototype.parse = function (html, callback) {
  return methods.parse(html, this.filter, callback);
};

Parser.prototype.method = function () {
  var _this = this;

  return function (html, callback) {
    return _this.parse(html, callback);
  };
};

Parser.prototype.request = function (options, callback) {
  return methods.request(options, this.filter, callback);
};

module.exports = Parser;
<|endoftext|>


<commit_before>"use strict";

const pathUtil = require("path");
const treeWalker = require("./utils/tree_walker");
const inspect = require("./inspect");
const matcher = require("./utils/matcher");
const validate = require("./utils/validate");

const validateInput = (methodName, path, options) => {
  const methodSignature = `${methodName}([path], options)`;
  validate.argument(methodSignature, "path", path, ["string"]);
  validate.options(methodSignature, "options", options, {
    matching: ["string", "array of string"],
    files: ["boolean"],
    directories: ["boolean"],
    recursive: ["boolean"],
    ignoreCase: ["boolean"]
  });
};

const normalizeOptions = options => {
  const opts = options || {};
  // defaults:
  if (opts.files === undefined) {
    opts.files = true;
  }
  if (opts.ignoreCase === undefined) {
    opts.ignoreCase = false;
  }
  if (opts.directories === undefined) {
    opts.directories = false;
  }
  if (opts.recursive === undefined) {
    opts.recursive = true;
  }
  return opts;
};

const processFoundObjects = (foundObjects, cwd) => {
  return foundObjects.map(inspectObj => {
    return pathUtil.relative(cwd, inspectObj.absolutePath);
  });
};

const generatePathDoesntExistError = path => {
  const err = new Error(`Path you want to find stuff in doesn't exist ${path}`);
  err.code = "ENOENT";
  return err;
};

const generatePathNotDirectoryError = path => {
  const err = new Error(
    `Path you want to find stuff in must be a directory ${path}`
  );
  err.code = "ENOTDIR";
  return err;
};

// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------

const findSync = (path, options) => {
  const foundInspectObjects = [];
  const matchesAnyOfGlobs = matcher.create(
    path,
    options.matching,
    options.ignoreCase
  );

  let maxLevelsDeep = Infinity;
  if (options.recursive === false) {
    maxLevelsDeep = 1;
  }

  treeWalker.sync(
    path,
    {
      maxLevelsDeep,
      inspectOptions: {
        absolutePath: true,
        symlinks: "follow"
      }
    },
    (itemPath, item) => {
      if (item && itemPath !== path && matchesAnyOfGlobs(itemPath)) {
        if (
          (item.type === "file" && options.files === true) ||
          (item.type === "dir" && options.directories === true)
        ) {
          foundInspectObjects.push(item);
        }
      }
    }
  );

  return processFoundObjects(foundInspectObjects, options.cwd);
};

const findSyncInit = (path, options) => {
  const entryPointInspect = inspect.sync(path, { symlinks: "follow" });
  if (entryPointInspect === undefined) {
    throw generatePathDoesntExistError(path);
  } else if (entryPointInspect.type !== "dir") {
    throw generatePathNotDirectoryError(path);
  }

  return findSync(path, normalizeOptions(options));
};

// ---------------------------------------------------------
// Async
// ---------------------------------------------------------

const findAsync = (path, options) => {
  return new Promise((resolve, reject) => {
    const foundInspectObjects = [];
    const matchesAnyOfGlobs = matcher.create(
      path,
      options.matching,
      options.ignoreCase
    );

    let maxLevelsDeep = Infinity;
    if (options.recursive === false) {
      maxLevelsDeep = 1;
    }

    const walker = treeWalker
      .stream(path, {
        maxLevelsDeep,
        inspectOptions: {
          absolutePath: true,
          symlinks: "follow"
        }
      })
      .on("readable", () => {
        const data = walker.read();
        if (data && data.path !== path && matchesAnyOfGlobs(data.path)) {
          const item = data.item;
          if (
            (item.type === "file" && options.files === true) ||
            (item.type === "dir" && options.directories === true)
          ) {
            foundInspectObjects.push(item);
          }
        }
      })
      .on("error", reject)
      .on("end", () => {
        resolve(processFoundObjects(foundInspectObjects, options.cwd));
      });
  });
};

const findAsyncInit = (path, options) => {
  return inspect.async(path, { symlinks: "follow" }).then(entryPointInspect => {
    if (entryPointInspect === undefined) {
      throw generatePathDoesntExistError(path);
    } else if (entryPointInspect.type !== "dir") {
      throw generatePathNotDirectoryError(path);
    }
    return findAsync(path, normalizeOptions(options));
  });
};

// ---------------------------------------------------------
// API
// ---------------------------------------------------------

exports.validateInput = validateInput;
exports.sync = findSyncInit;
exports.async = findAsyncInit;
<commit_msg>findAsync no longer crashes on ENOENT<commit_after>"use strict";

const pathUtil = require("path");
const treeWalker = require("./utils/tree_walker");
const inspect = require("./inspect");
const matcher = require("./utils/matcher");
const validate = require("./utils/validate");

const validateInput = (methodName, path, options) => {
  const methodSignature = `${methodName}([path], options)`;
  validate.argument(methodSignature, "path", path, ["string"]);
  validate.options(methodSignature, "options", options, {
    matching: ["string", "array of string"],
    files: ["boolean"],
    directories: ["boolean"],
    recursive: ["boolean"],
    ignoreCase: ["boolean"]
  });
};

const normalizeOptions = options => {
  const opts = options || {};
  // defaults:
  if (opts.files === undefined) {
    opts.files = true;
  }
  if (opts.ignoreCase === undefined) {
    opts.ignoreCase = false;
  }
  if (opts.directories === undefined) {
    opts.directories = false;
  }
  if (opts.recursive === undefined) {
    opts.recursive = true;
  }
  return opts;
};

const processFoundObjects = (foundObjects, cwd) => {
  return foundObjects.map(inspectObj => {
    return pathUtil.relative(cwd, inspectObj.absolutePath);
  });
};

const generatePathDoesntExistError = path => {
  const err = new Error(`Path you want to find stuff in doesn't exist ${path}`);
  err.code = "ENOENT";
  return err;
};

const generatePathNotDirectoryError = path => {
  const err = new Error(
    `Path you want to find stuff in must be a directory ${path}`
  );
  err.code = "ENOTDIR";
  return err;
};

// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------

const findSync = (path, options) => {
  const foundInspectObjects = [];
  const matchesAnyOfGlobs = matcher.create(
    path,
    options.matching,
    options.ignoreCase
  );

  let maxLevelsDeep = Infinity;
  if (options.recursive === false) {
    maxLevelsDeep = 1;
  }

  treeWalker.sync(
    path,
    {
      maxLevelsDeep,
      inspectOptions: {
        absolutePath: true,
        symlinks: "follow"
      }
    },
    (itemPath, item) => {
      if (item && itemPath !== path && matchesAnyOfGlobs(itemPath)) {
        if (
          (item.type === "file" && options.files === true) ||
          (item.type === "dir" && options.directories === true)
        ) {
          foundInspectObjects.push(item);
        }
      }
    }
  );

  return processFoundObjects(foundInspectObjects, options.cwd);
};

const findSyncInit = (path, options) => {
  const entryPointInspect = inspect.sync(path, { symlinks: "follow" });
  if (entryPointInspect === undefined) {
    throw generatePathDoesntExistError(path);
  } else if (entryPointInspect.type !== "dir") {
    throw generatePathNotDirectoryError(path);
  }

  return findSync(path, normalizeOptions(options));
};

// ---------------------------------------------------------
// Async
// ---------------------------------------------------------

const findAsync = (path, options) => {
  return new Promise((resolve, reject) => {
    const foundInspectObjects = [];
    const matchesAnyOfGlobs = matcher.create(
      path,
      options.matching,
      options.ignoreCase
    );

    let maxLevelsDeep = Infinity;
    if (options.recursive === false) {
      maxLevelsDeep = 1;
    }

    const walker = treeWalker
      .stream(path, {
        maxLevelsDeep,
        inspectOptions: {
          absolutePath: true,
          symlinks: "follow"
        }
      })
      .on("readable", () => {
        const data = walker.read();
        if (
          data &&
          data.item &&
          data.path !== path &&
          matchesAnyOfGlobs(data.path)
        ) {
          const item = data.item;
          if (
            (item.type === "file" && options.files === true) ||
            (item.type === "dir" && options.directories === true)
          ) {
            foundInspectObjects.push(item);
          }
        }
      })
      .on("error", reject)
      .on("end", () => {
        resolve(processFoundObjects(foundInspectObjects, options.cwd));
      });
  });
};

const findAsyncInit = (path, options) => {
  return inspect.async(path, { symlinks: "follow" }).then(entryPointInspect => {
    if (entryPointInspect === undefined) {
      throw generatePathDoesntExistError(path);
    } else if (entryPointInspect.type !== "dir") {
      throw generatePathNotDirectoryError(path);
    }
    return findAsync(path, normalizeOptions(options));
  });
};

// ---------------------------------------------------------
// API
// ---------------------------------------------------------

exports.validateInput = validateInput;
exports.sync = findSyncInit;
exports.async = findAsyncInit;
<|endoftext|>


<commit_before>var child = require('child_process');
var spawn = child.spawn;
var exec = child.exec;
var execSync = child.execSync;

var path = require('path');
var fs = require('fs');

var fmppName = process.platform === 'win32' ? 'fmpp.bat' : 'fmpp';
var fmpp = path.join(__dirname, '../fmpp', fmppName);
function run(args, done) {

  var output = '';

  try {
    var s = spawn(fmpp, args);

    s.stdout.on('data', function(d) {
      output += d;
    });

    s.stderr.on('data', function(d) {
      output += d;
    });

    s.on('error', function(e) {
      done(e);
    });

    s.on('close', function(code) {
      done(code, output);
    });
  } catch(e) {
    done(e);
  }
}

function run(args, done) {

  var command = fmpp + ' ' + args.join(' ');

  exec(command,
    function(error, stdout, stderr) {

      done(error || stderr, stdout);

    });
}

function runSync(args) {
  var command = fmpp + ' ' + args.join(' ');

  if(execSync) {
    // On node.js v0.12, there comes execSync() method which exactly we want
    return execSync(command);
  } else {
    // Here is inefficiency and ugliness hack for older version of node.js
    exec(command + ' 2>&1 1>output && echo done! > done');
    while(!fs.existsSync('done')) {}

    var output = fs.readFileSync('output');
    fs.unlinkSync('output');
    fs.unlinkSync('done');

    return '' + output;
  }
}

exports.run = run;
exports.runSync = runSync;
<commit_msg>remove useless code<commit_after>var child = require('child_process');
var spawn = child.spawn;
var exec = child.exec;
var execSync = child.execSync;

var path = require('path');
var fs = require('fs');

var fmppName = process.platform === 'win32' ? 'fmpp.bat' : 'fmpp';
var fmpp = path.join(__dirname, '../fmpp', fmppName);

function run(args, done) {

  var command = fmpp + ' ' + args.join(' ');

  exec(command,
    function(error, stdout, stderr) {

      done(error || stderr, stdout);

    });
}

function runSync(args) {
  var command = fmpp + ' ' + args.join(' ');

  if(execSync) {
    // On node.js v0.12, there comes execSync() method which exactly we want
    return execSync(command);
  } else {
    // Here is inefficiency and ugliness hack for older version of node.js
    exec(command + ' 2>&1 1>output && echo done! > done');
    while(!fs.existsSync('done')) {}

    var output = fs.readFileSync('output');
    fs.unlinkSync('output');
    fs.unlinkSync('done');

    return '' + output;
  }
}

exports.run = run;
exports.runSync = runSync;
<|endoftext|>


<commit_before>'use strict';

module.exports = function func() {
    var name = arguments[0],
        args = [].join.call([].slice.call(arguments, 1), ', '),
        tab = '  ',
        lines = [],
        vars = [],
        ind = 1,
        bs = '{[',  // block start
        be = '}]',  // block end
        space = function () {
            var sp = tab, i = 0;
            while (i++ < ind - 1) { sp += tab; }
            return sp;
        },
        builder = function (line) {
            var first = line[0],
                last = line[line.length - 1];

            if (be.indexOf(first) > -1 && bs.indexOf(last) > -1) {
                ind--;
                lines.push(space() + line);
                ind++;
            }
            else if (bs.indexOf(last) > -1) {
                lines.push(space() + line);
                ind++;
            }
            else if (be.indexOf(first) > -1) {
                ind--;
                lines.push(space() + line);
            }
            else {
                lines.push(space() + line);
            }

            return builder;
        };

    builder.def = function (id, def) {
        vars.push(id + (def !== undefined ? ' = ' + def : ''));
        return builder;
    };

    builder.toSource = function () {
        return 'function ' + name + '(' + args + ') {\n' +
            tab + '"use strict"' + '\n' +
            tab + 'var ' + vars.join(',\n' + tab + '    ') + '\n' +
            lines.join('\n') + '\n}';
    };

    builder.compile = function (scope) {
        var src = 'return (' + builder.toSource() + ')',
            scp = scope || {},
            keys = Object.keys(scp),
            vals = keys.map(function (key) { return scp[key]; });

        return Function.apply(null, keys.concat(src)).apply(null, vals);
    };

    return builder;
};<commit_msg>Optimize func generator<commit_after>'use strict';

module.exports = function func() {
    var name = arguments[0],
        args = [].join.call([].slice.call(arguments, 1), ', '),
        tab = '  ',
        lines = '',
        vars = '',
        ind = 1,    // indentation
        bs = '{[',  // block start
        be = '}]',  // block end
        space = function () {
            var sp = tab, i = 0;
            while (i++ < ind - 1) { sp += tab; }
            return sp;
        },
        add = function (line) {
            lines += space() + line + '\n';
        },
        builder = function (line) {
            var first = line[0],
                last = line[line.length - 1];

            if (be.indexOf(first) > -1 && bs.indexOf(last) > -1) {
                ind--;
                add(line);
                ind++;
            }
            else if (bs.indexOf(last) > -1) {
                add(line);
                ind++;
            }
            else if (be.indexOf(first) > -1) {
                ind--;
                add(line);
            }
            else {
                add(line);
            }

            return builder;
        };

    builder.def = function (id, def) {
        vars += (vars ? ',\n' + tab + '    ' : '') + id + (def !== undefined ? ' = ' + def : '');
        return builder;
    };

    builder.toSource = function () {
        return 'function ' + name + '(' + args + ') {\n' +
            tab + '"use strict"' + '\n' +
            tab + 'var ' + vars + ';\n' +
            lines + '\n}';
    };

    builder.compile = function (scope) {
        var src = 'return (' + builder.toSource() + ')',
            scp = scope || {},
            keys = Object.keys(scp),
            vals = keys.map(function (key) { return scp[key]; });

        return Function.apply(null, keys.concat(src)).apply(null, vals);
    };

    return builder;
};<|endoftext|>


<commit_before>/*The MIT License (MIT)

Copyright (c) 2015 Jens Malmborg

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

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

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

var Color = require("/color.js").Color;

function Game(options) {
    options = options || {};
    this.window = new Window(options);
    this.screenCenter = {
        x: this.window.width / 2,
        y: this.window.height / 2,
    };
    if (options.isFixedTimeStep === false) {
        this.isFixedTimeStep = false;
    } else {
        this.isFixedTimeStep = true;
    }
    this.targetElapsedTime = options.targetElapsedTime || 1.0 / 60.0;
    this.backgroundColor = Color.cornflowerBlue();
    this.graphics = this.window.graphics;
    this.mouse = new Mouse(this.window);
    this.keyboard = new Keyboard(this.window);
    this.timer = new Timer();
};

Game.prototype.run = function () {
    var last = 0;
    var accumulator = 0;
    while (!this.window.isClosing()) {
        this.window.pollEvents();
        this.keyboard.updateState();
        this.mouse.updateState();
        var current = this.timer.elapsed();
        var frame = current - last;
        var updated = false;
        last = current;
        if (this.isFixedTimeStep) {
            accumulator += frame;
            while (accumulator >= this.targetElapsedTime) {
                this.update(this.targetElapsedTime);
                accumulator -= this.targetElapsedTime;
                if (accumulator <= this.targetElapsedTime / 2) {
                    // Lock updates exactly to the monitor refresh (in order to
                    // avoid endlessly accumulating small time deltas, which
                    // would eventually add up enough to cause a dropped frame).
                    accumulator = 0;
                }
                updated = true;
            }
        } else {
            this.update(frame);
            updated = true;
        }
        if (updated) {
            this.graphics.clear(this.backgroundColor);
            this.draw();
            this.graphics.present();
        }
    }
};

Game.prototype.update = function () {
};

Game.prototype.draw = function () {
};

Game.prototype.exit = function () {
    this.window.close();
};

module.exports.Game = Game;<commit_msg>Refactoring and added properties for Game.<commit_after>/*The MIT License (MIT)

Copyright (c) 2015 Jens Malmborg

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

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

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

var Color = require("/color.js").Color;
var Utils = require("/utils.js").Utils;

function Game(options) {

    options = Utils.options(options, this);
    options.value('targetElapsedTime', 1.0 / 60.0);
    options.value('isFixedTimeStep', true);
    options.value('backgroundColor', Color.cornflowerBlue());

    this.window = new Window(options);
    this.graphics = this.window.graphics;
    this.mouse = new Mouse(this.window);
    this.keyboard = new Keyboard(this.window);
    this.timer = new Timer();

    Object.defineProperty(Game, 'window', {
        value: this.window, writable: false
    });

    Object.defineProperty(Game, 'graphics', {
        value: this.graphics, writable: false
    });

    Object.defineProperty(Game, 'keyboard', {
        value: this.keyboard, writable: false
    });

    Object.defineProperty(Game, 'mouse', {
        value: this.mouse, writable: false
    });
}

Game.prototype.run = function () {
    var last = 0;
    var accumulator = 0;
    while (!this.window.isClosing()) {
        this.window.pollEvents();
        this.keyboard.updateState();
        this.mouse.updateState();
        var current = this.timer.elapsed();
        var frame = current - last;
        var updated = false;
        last = current;
        if (this.isFixedTimeStep) {
            accumulator += frame;
            while (accumulator >= this.targetElapsedTime) {
                this.update(this.targetElapsedTime);
                accumulator -= this.targetElapsedTime;
                if (accumulator <= this.targetElapsedTime / 2) {
                    // Lock updates exactly to the monitor refresh (in order to
                    // avoid endlessly accumulating small time deltas, which
                    // would eventually add up enough to cause a dropped frame).
                    accumulator = 0;
                }
                updated = true;
            }
        } else {
            this.update(frame);
            updated = true;
        }
        if (updated) {
            this.graphics.clear(this.backgroundColor);
            this.draw();
            this.graphics.present();
        }
    }
};

Game.prototype.update = function () {
};

Game.prototype.draw = function () {
};

Game.prototype.exit = function () {
    this.window.close();
};

module.exports.Game = Game;<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import Immutable from 'immutable';
import _ from 'lodash';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import { EntityEventProcessorManager, DataManager } from '../../redux';
import * as Utils from '../../utils';
import SearchParameters from '../../domain/SearchParameters';

const UIKEY = 'entity-event-processors';
const manager = new EntityEventProcessorManager();

/**
 * BE event precessors
 *
 * @author Radek Tomiška
 */
class EntityEventProcessors extends Advanced.AbstractTableContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      filterOpened: true
    };
  }

  getContentKey() {
    return 'content.system.entity-event-processors';
  }

  getNavigationKey() {
    return 'entity-event-processors';
  }

  getManager() {
    return manager;
  }

  componentDidMount() {
    super.componentDidMount();
    //
    this.reload();
    this.context.store.dispatch(manager.fetchRegisteredProcessors());
    this.refs.text.focus();
  }

  reload() {
    const { _searchParameters } = this.props;
    //
    this.fetchEntities(_searchParameters);
  }

  useFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchEntities(SearchParameters.getSearchParameters(SearchParameters.getFilterData(this.refs.filterForm), this.props._searchParameters));
  }

  cancelFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchEntities(null);
    this.refs.filterForm.setData({});
  }

  fetchEntities(searchParameters) {
    this.context.store.dispatch(this.getManager().fetchEntities(searchParameters, UIKEY));
  }

  onEnable(entity, enable, event) {
    if (event) {
      event.preventDefault();
    }
    this.refs[`confirm-${enable ? '' : 'de'}activate`].show(
      this.i18n(`action.${enable ? '' : 'de'}activate.message`, { count: 1, record: entity.name }),
      this.i18n(`action.${enable ? '' : 'de'}activate.header`, { count: 1 })
    ).then(() => {
      this.context.store.dispatch(this.getManager().setEnabled(entity.id, enable, (patchedEntity, error) => {
        if (!error) {
          this.addMessage({ message: this.i18n(`action.${enable ? '' : 'de'}activate.success`, { count: 1, record: entity.name }) });
          // refresh table with processors
          this.reload();
        } else {
          this.addError(error);
        }
      }));
    }, () => {
      // rejected
    });
  }

  render() {
    const { processors, registeredProcessors, showLoading, _searchParameters } = this.props;
    const { filterOpened } = this.state;
    //
    // all entity types and event types for select boxes
    let _registeredEntityTypes = new Immutable.OrderedSet();
    let _registeredEventTypes = new Immutable.OrderedSet();
    if (registeredProcessors) {
      registeredProcessors.forEach(processor => {
        _registeredEntityTypes = _registeredEntityTypes.add(processor.entityType);
        processor.eventTypes.forEach(e => {
          _registeredEventTypes = _registeredEventTypes.add(e);
        });
      });
      // sort _entityTypes
      _registeredEntityTypes = _registeredEntityTypes.sort((one, two) => {
        return one > two;
      });
    }
    //
    // filtered processors and entity types
    let _processors = new Immutable.OrderedMap();
    let _entityTypes = new Immutable.OrderedSet();
    if (processors) {
      processors.forEach(processor => {
        if (!_processors.has(processor.entityType)) {
          _processors = _processors.set(processor.entityType, []);
        }
        const entityProcessors = _processors.get(processor.entityType);
        entityProcessors.push(processor);
        _processors = _processors.set(processor.entityType, entityProcessors);
        _entityTypes = _entityTypes.add(processor.entityType);
      });
    }
    //
    return (

        <Helmet title={this.i18n('title')} />
        <Basic.Confirm ref="confirm-deactivate" level="warning"/>
        <Basic.Confirm ref="confirm-activate" level="success"/>

        <Basic.Toolbar>

              <Advanced.Filter.ToogleButton
                filterOpen={ (open)=> this.setState({ filterOpened: open }) }
                filterOpened={ filterOpened }
                style={{ marginLeft: 3 }}
                searchParameters={ _searchParameters }/>
              <Advanced.RefreshButton
                onClick={ this.fetchEntities.bind(this, _searchParameters) }
                title={ this.i18n('button.refresh') }
                showLoading={ showLoading }/>

          <Basic.Collapse in={filterOpened}>

              <Advanced.Filter onSubmit={this.useFilter.bind(this)}>
                <Basic.AbstractForm ref="filterForm">
                  <Basic.Row>
                    <Basic.Col lg={ 8 }>
                      <Advanced.Filter.TextField
                        ref="text"
                        placeholder={this.i18n('filter.text.placeholder')}/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 } className="text-right">
                      <Advanced.Filter.FilterButtons cancelFilter={this.cancelFilter.bind(this)}/>
                    </Basic.Col>
                  </Basic.Row>
                  <Basic.Row className="last">
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.TextField
                        ref="module"
                        placeholder={this.i18n('filter.module.placeholder')}/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.EnumSelectBox
                        ref="entityType"
                        placeholder={ this.i18n('filter.entityType.placeholder') }
                        options={ _registeredEntityTypes.toArray().map(value => { return { value, niceLabel: value }; }) }
                        searchable/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.EnumSelectBox
                        ref="eventTypes"
                        placeholder={ this.i18n('filter.eventTypes.placeholder') }
                        options={ _registeredEventTypes.toArray().map(value => { return { value, niceLabel: value }; }) }
                        multiSelect
                        searchable/>
                    </Basic.Col>
                  </Basic.Row>
                </Basic.AbstractForm>
              </Advanced.Filter>

          </Basic.Collapse>
        </Basic.Toolbar>

        <Basic.Loading isStatic show={ showLoading }/>
        <Basic.Alert level="info" text={ this.i18n('component.basic.Table.noData') } style={{ margin: 15 }} rendered={ !showLoading && _processors.size === 0 } />

        {
          showLoading || _processors.size === 0
          ||

            {
              _entityTypes.map((entityType) => {
                const entityProcessors = _processors.get(entityType);
                entityProcessors.sort((one, two) => {
                  return one.order > two.order;
                });
                return (

                    <Basic.ContentHeader text={entityType}/>

                    <Basic.Table
                      data={ entityProcessors }
                      showLoading={ showLoading }
                      noData={ this.i18n('component.basic.Table.noData') }
                      rowClass={({ rowIndex, data }) => { return Utils.Ui.getRowClass(data[rowIndex]); }}>
                      <Basic.Column property="module" header={this.i18n('entity.EntityEventProcessor.module')} width={75} />
                      <Basic.Column property="name" header={this.i18n('entity.EntityEventProcessor.name')} width="30%"/>
                      <Basic.Column
                        property="description"
                        header={this.i18n('entity.EntityEventProcessor.description')}
                        cell={
                          ({ rowIndex, data, property }) => {
                            const values = [];
                            _.keys(data[rowIndex].configurationProperties).map(configurationProperty => {
                              const value = data[rowIndex].configurationProperties[configurationProperty];
                              if (value) {
                                values.push({ configurationProperty, value });
                              }
                            });
                            return (

{data[rowIndex][property]}

                                {
                                  values.length === 0
                                  ||

Configuration:

                                    {
                                      values.map(value => {
                                        return (
{ `- ${value.configurationProperty}: ${value.value}` }
);
                                      })
                                    }

                                }

                            );
                          }
                        }/>
                      <Basic.Column
                        property="eventTypes"
                        header={this.i18n('entity.EntityEventProcessor.eventTypes')}
                        width={125}
                        cell={
                          ({ rowIndex, data, property }) => {
                            if (!data[rowIndex][property]) {
                              return null;
                            }
                            return data[rowIndex][property].join(', ');
                          }
                        }/>
                      <Basic.Column property="order" header={this.i18n('entity.EntityEventProcessor.order')} width={100}/>
                      <Basic.Column
                        property="disabled"
                        header={<Basic.Cell className="column-face-bool">{this.i18n('entity.EntityEventProcessor.disabled')}</Basic.Cell>}
                        cell={<Basic.BooleanCell className="column-face-bool"/>}
                        width={ 100 }/>
                      <Basic.Column
                        header={ this.i18n('entity.id.label') }
                        property="id"
                        rendered={ this.isDevelopment() }
                        className="text-center"
                        width={ 100 }
                        cell={
                          ({rowIndex, data, property}) => {
                            return (
                              <Advanced.UuidInfo value={data[rowIndex][property]}/>
                            );
                          }
                        }/>
                      <Basic.Column
                        header={this.i18n('label.action')}
                        className="action"
                        cell={
                          ( {rowIndex, data} ) => {
                            if (!data[rowIndex].disabled) {
                              return (
                                <Basic.Button
                                  level="warning"
                                  onClick={this.onEnable.bind(this, data[rowIndex], false)}
                                  className="btn-xs"
                                  title={this.i18n('button.deactivate')}
                                  titlePlacement="bottom"
                                  rendered={data[rowIndex].disableable}>
                                  {this.i18n('button.deactivate')}
                                </Basic.Button>
                              );
                            }
                            return (
                              <Basic.Button
                                level="success"
                                onClick={this.onEnable.bind(this, data[rowIndex], true)}
                                className="btn-xs"
                                title={this.i18n('button.activate')}
                                titlePlacement="bottom">
                                {this.i18n('button.activate')}
                              </Basic.Button>
                            );
                          }
                        }/>
                    </Basic.Table>

                );
              })
            }
            <Basic.Pagination total={ processors.length } />

        }

    );
  }
}

EntityEventProcessors.propTypes = {
  userContext: PropTypes.object,
  registeredProcessors: PropTypes.object, // immutable
  processors: PropTypes.arrayOf(PropTypes.object),
  showLoading: PropTypes.bool
};
EntityEventProcessors.defaultProps = {
  userContext: null,
  showLoading: true,
  registeredProcessors: null
};

function select(state) {
  return {
    userContext: state.security.userContext,
    registeredProcessors: DataManager.getData(state, EntityEventProcessorManager.UI_KEY_PROCESSORS),
    processors: manager.getEntities(state, UIKEY),
    showLoading: Utils.Ui.isShowLoading(state, UIKEY)
      || Utils.Ui.isShowLoading(state, EntityEventProcessorManager.UI_KEY_PROCESSORS),
    _searchParameters: Utils.Ui.getSearchParameters(state, UIKEY)
  };
}

export default connect(select)(EntityEventProcessors);
<commit_msg>#1641 FE: fix: processors are sorted by order<commit_after>import React, { PropTypes } from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import Immutable from 'immutable';
import _ from 'lodash';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import { EntityEventProcessorManager, DataManager } from '../../redux';
import * as Utils from '../../utils';
import SearchParameters from '../../domain/SearchParameters';

const UIKEY = 'entity-event-processors';
const manager = new EntityEventProcessorManager();

/**
 * BE event precessors
 *
 * @author Radek Tomiška
 */
class EntityEventProcessors extends Advanced.AbstractTableContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      filterOpened: true
    };
  }

  getContentKey() {
    return 'content.system.entity-event-processors';
  }

  getNavigationKey() {
    return 'entity-event-processors';
  }

  getManager() {
    return manager;
  }

  componentDidMount() {
    super.componentDidMount();
    //
    this.reload();
    this.context.store.dispatch(manager.fetchRegisteredProcessors());
    this.refs.text.focus();
  }

  reload() {
    const { _searchParameters } = this.props;
    //
    this.fetchEntities(_searchParameters);
  }

  useFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchEntities(SearchParameters.getSearchParameters(SearchParameters.getFilterData(this.refs.filterForm), this.props._searchParameters));
  }

  cancelFilter(event) {
    if (event) {
      event.preventDefault();
    }
    this.fetchEntities(null);
    this.refs.filterForm.setData({});
  }

  fetchEntities(searchParameters) {
    this.context.store.dispatch(this.getManager().fetchEntities(searchParameters, UIKEY));
  }

  onEnable(entity, enable, event) {
    if (event) {
      event.preventDefault();
    }
    this.refs[`confirm-${enable ? '' : 'de'}activate`].show(
      this.i18n(`action.${enable ? '' : 'de'}activate.message`, { count: 1, record: entity.name }),
      this.i18n(`action.${enable ? '' : 'de'}activate.header`, { count: 1 })
    ).then(() => {
      this.context.store.dispatch(this.getManager().setEnabled(entity.id, enable, (patchedEntity, error) => {
        if (!error) {
          this.addMessage({ message: this.i18n(`action.${enable ? '' : 'de'}activate.success`, { count: 1, record: entity.name }) });
          // refresh table with processors
          this.reload();
        } else {
          this.addError(error);
        }
      }));
    }, () => {
      // rejected
    });
  }

  render() {
    const { processors, registeredProcessors, showLoading, _searchParameters } = this.props;
    const { filterOpened } = this.state;
    //
    // all entity types and event types for select boxes
    let _registeredEntityTypes = new Immutable.OrderedSet();
    let _registeredEventTypes = new Immutable.OrderedSet();
    if (registeredProcessors) {
      registeredProcessors.forEach(processor => {
        _registeredEntityTypes = _registeredEntityTypes.add(processor.entityType);
        processor.eventTypes.forEach(e => {
          _registeredEventTypes = _registeredEventTypes.add(e);
        });
      });
      // sort _entityTypes
      _registeredEntityTypes = _registeredEntityTypes.sort((one, two) => {
        return one > two;
      });
    }
    //
    // filtered processors and entity types
    let _processors = new Immutable.OrderedMap();
    let _entityTypes = new Immutable.OrderedSet();
    if (processors) {
      processors.forEach(processor => {
        if (!_processors.has(processor.entityType)) {
          _processors = _processors.set(processor.entityType, []);
        }
        const entityProcessors = _processors.get(processor.entityType);
        entityProcessors.push(processor);
        _processors = _processors.set(processor.entityType, entityProcessors);
        _entityTypes = _entityTypes.add(processor.entityType);
      });
    }
    //
    return (

        <Helmet title={this.i18n('title')} />
        <Basic.Confirm ref="confirm-deactivate" level="warning"/>
        <Basic.Confirm ref="confirm-activate" level="success"/>

        <Basic.Toolbar>

              <Advanced.Filter.ToogleButton
                filterOpen={ (open)=> this.setState({ filterOpened: open }) }
                filterOpened={ filterOpened }
                style={{ marginLeft: 3 }}
                searchParameters={ _searchParameters }/>
              <Advanced.RefreshButton
                onClick={ this.fetchEntities.bind(this, _searchParameters) }
                title={ this.i18n('button.refresh') }
                showLoading={ showLoading }/>

          <Basic.Collapse in={filterOpened}>

              <Advanced.Filter onSubmit={this.useFilter.bind(this)}>
                <Basic.AbstractForm ref="filterForm">
                  <Basic.Row>
                    <Basic.Col lg={ 8 }>
                      <Advanced.Filter.TextField
                        ref="text"
                        placeholder={this.i18n('filter.text.placeholder')}/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 } className="text-right">
                      <Advanced.Filter.FilterButtons cancelFilter={this.cancelFilter.bind(this)}/>
                    </Basic.Col>
                  </Basic.Row>
                  <Basic.Row className="last">
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.TextField
                        ref="module"
                        placeholder={this.i18n('filter.module.placeholder')}/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.EnumSelectBox
                        ref="entityType"
                        placeholder={ this.i18n('filter.entityType.placeholder') }
                        options={ _registeredEntityTypes.toArray().map(value => { return { value, niceLabel: value }; }) }
                        searchable/>
                    </Basic.Col>
                    <Basic.Col lg={ 4 }>
                      <Advanced.Filter.EnumSelectBox
                        ref="eventTypes"
                        placeholder={ this.i18n('filter.eventTypes.placeholder') }
                        options={ _registeredEventTypes.toArray().map(value => { return { value, niceLabel: value }; }) }
                        multiSelect
                        searchable/>
                    </Basic.Col>
                  </Basic.Row>
                </Basic.AbstractForm>
              </Advanced.Filter>

          </Basic.Collapse>
        </Basic.Toolbar>

        <Basic.Loading isStatic show={ showLoading }/>
        <Basic.Alert level="info" text={ this.i18n('component.basic.Table.noData') } style={{ margin: 15 }} rendered={ !showLoading && _processors.size === 0 } />

        {
          showLoading || _processors.size === 0
          ||

            {
              _entityTypes.map((entityType) => {
                const entityProcessors = _processors.get(entityType);
                entityProcessors.sort((one, two) => {
                  return parseInt(one.order, 10) > parseInt(two.order, 10);
                });
                return (

                    <Basic.ContentHeader text={entityType}/>

                    <Basic.Table
                      data={ entityProcessors }
                      showLoading={ showLoading }
                      noData={ this.i18n('component.basic.Table.noData') }
                      rowClass={({ rowIndex, data }) => { return Utils.Ui.getRowClass(data[rowIndex]); }}>
                      <Basic.Column property="module" header={this.i18n('entity.EntityEventProcessor.module')} width={75} />
                      <Basic.Column property="name" header={this.i18n('entity.EntityEventProcessor.name')} width="30%"/>
                      <Basic.Column
                        property="description"
                        header={this.i18n('entity.EntityEventProcessor.description')}
                        cell={
                          ({ rowIndex, data, property }) => {
                            const values = [];
                            _.keys(data[rowIndex].configurationProperties).map(configurationProperty => {
                              const value = data[rowIndex].configurationProperties[configurationProperty];
                              if (value) {
                                values.push({ configurationProperty, value });
                              }
                            });
                            return (

{data[rowIndex][property]}

                                {
                                  values.length === 0
                                  ||

Configuration:

                                    {
                                      values.map(value => {
                                        return (
{ `- ${value.configurationProperty}: ${value.value}` }
);
                                      })
                                    }

                                }

                            );
                          }
                        }/>
                      <Basic.Column
                        property="eventTypes"
                        header={this.i18n('entity.EntityEventProcessor.eventTypes')}
                        width={125}
                        cell={
                          ({ rowIndex, data, property }) => {
                            if (!data[rowIndex][property]) {
                              return null;
                            }
                            return data[rowIndex][property].join(', ');
                          }
                        }/>
                      <Basic.Column property="order" header={this.i18n('entity.EntityEventProcessor.order')} width={100}/>
                      <Basic.Column
                        property="disabled"
                        header={<Basic.Cell className="column-face-bool">{this.i18n('entity.EntityEventProcessor.disabled')}</Basic.Cell>}
                        cell={<Basic.BooleanCell className="column-face-bool"/>}
                        width={ 100 }/>
                      <Basic.Column
                        header={ this.i18n('entity.id.label') }
                        property="id"
                        rendered={ this.isDevelopment() }
                        className="text-center"
                        width={ 100 }
                        cell={
                          ({rowIndex, data, property}) => {
                            return (
                              <Advanced.UuidInfo value={data[rowIndex][property]}/>
                            );
                          }
                        }/>
                      <Basic.Column
                        header={this.i18n('label.action')}
                        className="action"
                        cell={
                          ( {rowIndex, data} ) => {
                            if (!data[rowIndex].disabled) {
                              return (
                                <Basic.Button
                                  level="warning"
                                  onClick={this.onEnable.bind(this, data[rowIndex], false)}
                                  className="btn-xs"
                                  title={this.i18n('button.deactivate')}
                                  titlePlacement="bottom"
                                  rendered={data[rowIndex].disableable}>
                                  {this.i18n('button.deactivate')}
                                </Basic.Button>
                              );
                            }
                            return (
                              <Basic.Button
                                level="success"
                                onClick={this.onEnable.bind(this, data[rowIndex], true)}
                                className="btn-xs"
                                title={this.i18n('button.activate')}
                                titlePlacement="bottom">
                                {this.i18n('button.activate')}
                              </Basic.Button>
                            );
                          }
                        }/>
                    </Basic.Table>

                );
              })
            }
            <Basic.Pagination total={ processors.length } />

        }

    );
  }
}

EntityEventProcessors.propTypes = {
  userContext: PropTypes.object,
  registeredProcessors: PropTypes.object, // immutable
  processors: PropTypes.arrayOf(PropTypes.object),
  showLoading: PropTypes.bool
};
EntityEventProcessors.defaultProps = {
  userContext: null,
  showLoading: true,
  registeredProcessors: null
};

function select(state) {
  return {
    userContext: state.security.userContext,
    registeredProcessors: DataManager.getData(state, EntityEventProcessorManager.UI_KEY_PROCESSORS),
    processors: manager.getEntities(state, UIKEY),
    showLoading: Utils.Ui.isShowLoading(state, UIKEY)
      || Utils.Ui.isShowLoading(state, EntityEventProcessorManager.UI_KEY_PROCESSORS),
    _searchParameters: Utils.Ui.getSearchParameters(state, UIKEY)
  };
}

export default connect(select)(EntityEventProcessors);
<|endoftext|>


<commit_before>var _ = require('underscore');
var config = require('../config/game');
var MobRepo = require('../config/mobs');
var WaveFactory = require('./wave_factory');

var Game = (function() {

	var onLastWaveEnemy;
	var _mobTypes = _.keys(MobRepo);

	var _waveInterval = config.waveInterval; // Wave trigger round mod

	function Game() {
		this.round = 1;
		this.waves = [];
		this.waveFactory = new WaveFactory();
	}

	Game.prototype.getRound = function() {
		return this.round;
	};

	Game.prototype.setupRound = function() {
		if (this.waves.length === 0 || this.round % _waveInterval === 0) {
			this.spawnEnemies();
		}
		this.round++;
	};

	Game.prototype.getEnemies = function() {
		var list = [];
		_.each(this.waves, function(enemyCollection){
			list.push(enemyCollection.list());
		});
		return _.flatten(list);
	};

	Game.prototype.spawnEnemies = function() {
		var wave = this.waveFactory.get(this.round);
		wave.onLastWaveEnemy(_.bind(onLastWaveEnemy, this));
		this.waves.push(wave);
	};

	// @deprecated
	Game.prototype.getEnemyAttackDamage = function() {
		var damage = 0;
		_.each(this.waves, function(collection){
			damage += collection.massAttack();
		});
		return damage;
	};

	/**
	 * Loops over the waves and collects information on enemy actions.
	 *
	 * Yields the player object to the enemies so that it can be inspected and/or attacked
	 * by the enemy objects.
	 *
	 * Stops processing if the player dies
	 *
	 * @param Player player
	 * @return Array
	 */
	Game.prototype.processEnemyActions = function(player){
		var waves, length, i, result;

		waves = this.waves;
		length = waves.length;
		result = [];
		for (i = 0; i <= length; i++){
			if (waves[i]){
				result.push.apply(result, waves[i].massAction(player));
			}
			if (player.health() <= 0){
				break;
			}
		}

		return result;
	};

	Game.prototype.getEnemyById = function(id) {
		var waves, length, i, enemy, result, wave;
		waves = this.waves;
		length = waves.length;
		for (i = 0; i <= length; i++){
			if((wave = waves[i])){
				enemy = wave.byId(id);
				if (enemy) {
					result = {
						enemy : enemy,
						collection : waves[i]
					};
					break;
				}
			}
		}
		return result;
	};

	Game.prototype.summary = function() {
		var summary = [];
		_.each(this.waves, function(collection){
			summary.push({
				wave : collection._id,
				enemies : collection.summary()
			});
		});
		return summary;
	};

	Game.prototype.recordGame = function(db, player, callback) {
		var resultsCollection, data;
		if (!db) {
			callback('No Mongo connection available.', this);
			return;
		}
		resultsCollection = db.collection('results');
		data = {
			username: player.name(),
			round: this.round
		};
		resultsCollection.insert(data, _.bind(function(err) {
			callback(err, this);
		}, this));
	};

	/**
	 * Retrieve the (up to) top 10 scores.
	 *
	 * @param MongoClient db
	 * @param function callback
	 * @return void
	 */
	Game.topScoreList = function(db, callback) {
		if (!db) {
			callback('DB not available.');
			return;
		}
		db.collection('results').aggregate([
			{ $sort: {round: -1} },
			{ $group: { _id: "$username", round: { $first: "$round" } } },
			{ $sort: {round: -1}}, {$limit: 10}
		], function(err, result) {
			var results = [];
			if (err) {
				callback(err, []);
			}
			_.each(result, function(entry) {
				results.push({
					username: entry._id,
					round: entry.round
				});
			});
			callback(null, results);
		});
	};

	/**
	 * Listener for when the last enemy is removed from a wave's enemy collection.
	 *
	 * @access private
	 * @param EnemyCollection collection
	 * @return void
	 */
	onLastWaveEnemy = function(collection) {
		this.waves = _.reject(this.waves, function (wave) {
			return wave._id === collection._id;
		});
	};

	return Game;

}());

module.exports = Game;
<commit_msg>Using the variable instead of doing another array lookup<commit_after>var _ = require('underscore');
var config = require('../config/game');
var MobRepo = require('../config/mobs');
var WaveFactory = require('./wave_factory');

var Game = (function() {

	var onLastWaveEnemy;
	var _mobTypes = _.keys(MobRepo);

	var _waveInterval = config.waveInterval; // Wave trigger round mod

	function Game() {
		this.round = 1;
		this.waves = [];
		this.waveFactory = new WaveFactory();
	}

	Game.prototype.getRound = function() {
		return this.round;
	};

	Game.prototype.setupRound = function() {
		if (this.waves.length === 0 || this.round % _waveInterval === 0) {
			this.spawnEnemies();
		}
		this.round++;
	};

	Game.prototype.getEnemies = function() {
		var list = [];
		_.each(this.waves, function(enemyCollection){
			list.push(enemyCollection.list());
		});
		return _.flatten(list);
	};

	Game.prototype.spawnEnemies = function() {
		var wave = this.waveFactory.get(this.round);
		wave.onLastWaveEnemy(_.bind(onLastWaveEnemy, this));
		this.waves.push(wave);
	};

	// @deprecated
	Game.prototype.getEnemyAttackDamage = function() {
		var damage = 0;
		_.each(this.waves, function(collection){
			damage += collection.massAttack();
		});
		return damage;
	};

	/**
	 * Loops over the waves and collects information on enemy actions.
	 *
	 * Yields the player object to the enemies so that it can be inspected and/or attacked
	 * by the enemy objects.
	 *
	 * Stops processing if the player dies
	 *
	 * @param Player player
	 * @return Array
	 */
	Game.prototype.processEnemyActions = function(player){
		var waves, length, i, result;

		waves = this.waves;
		length = waves.length;
		result = [];
		for (i = 0; i <= length; i++){
			if (waves[i]){
				result.push.apply(result, waves[i].massAction(player));
			}
			if (player.health() <= 0){
				break;
			}
		}

		return result;
	};

	Game.prototype.getEnemyById = function(id) {
		var waves, length, i, enemy, result, wave;
		waves = this.waves;
		length = waves.length;
		for (i = 0; i <= length; i++){
			if((wave = waves[i])){
				enemy = wave.byId(id);
				if (enemy) {
					result = {
						enemy : enemy,
						collection : wave
					};
					break;
				}
			}
		}
		return result;
	};

	Game.prototype.summary = function() {
		var summary = [];
		_.each(this.waves, function(collection){
			summary.push({
				wave : collection._id,
				enemies : collection.summary()
			});
		});
		return summary;
	};

	Game.prototype.recordGame = function(db, player, callback) {
		var resultsCollection, data;
		if (!db) {
			callback('No Mongo connection available.', this);
			return;
		}
		resultsCollection = db.collection('results');
		data = {
			username: player.name(),
			round: this.round
		};
		resultsCollection.insert(data, _.bind(function(err) {
			callback(err, this);
		}, this));
	};

	/**
	 * Retrieve the (up to) top 10 scores.
	 *
	 * @param MongoClient db
	 * @param function callback
	 * @return void
	 */
	Game.topScoreList = function(db, callback) {
		if (!db) {
			callback('DB not available.');
			return;
		}
		db.collection('results').aggregate([
			{ $sort: {round: -1} },
			{ $group: { _id: "$username", round: { $first: "$round" } } },
			{ $sort: {round: -1}}, {$limit: 10}
		], function(err, result) {
			var results = [];
			if (err) {
				callback(err, []);
			}
			_.each(result, function(entry) {
				results.push({
					username: entry._id,
					round: entry.round
				});
			});
			callback(null, results);
		});
	};

	/**
	 * Listener for when the last enemy is removed from a wave's enemy collection.
	 *
	 * @access private
	 * @param EnemyCollection collection
	 * @return void
	 */
	onLastWaveEnemy = function(collection) {
		this.waves = _.reject(this.waves, function (wave) {
			return wave._id === collection._id;
		});
	};

	return Game;

}());

module.exports = Game;
<|endoftext|>


<commit_before>require('dotenv').config();
var googleapis = require('googleapis'),
    OAuth2Client = googleapis.auth.OAuth2,
    client = '185629692675-jsqjmmqp6c11unoa18vf0ck8ibncdm99.apps.googleusercontent.com',
    redirect = 'http://localhost:3000/google/auth',
    oauth2Client = new OAuth2Client(client, process.env.GAPIS_SEC, redirect);

// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar',
  'https://www.googleapis.com/auth/userinfo.email',
  'https://www.googleapis.com/auth/contacts.readonly'
];

var url = oauth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: scopes // If you only need one scope you can pass it as string
});

exports.google = googleapis;
exports.client = oauth2Client;
exports.url = url;
<commit_msg>fix:define simpleGet module<commit_after>require('dotenv').config();
const googleapis = require('googleapis'),
    OAuth2Client = googleapis.auth.OAuth2,
    client = '185629692675-jsqjmmqp6c11unoa18vf0ck8ibncdm99.apps.googleusercontent.com',
    redirect = 'http://localhost:3000/google/auth',
    oauth2Client = new OAuth2Client(client, process.env.GAPIS_SEC, redirect),
    simpleGet = require('simple-get');

// generate a url that asks permissions for Google+ and Google Calendar scopes
const scopes = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar',
  'https://www.googleapis.com/auth/userinfo.email',
  'https://www.googleapis.com/auth/contacts.readonly'
];

const url = oauth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: scopes // If you only need one scope you can pass it as string
});

exports.google = googleapis;
exports.client = oauth2Client;
exports.url = url;
<|endoftext|>