<commit_before>/*jslint indent:2, node:true, sloppy:true, browser:true */
var Consumer = require('./consumer');
var util = require('./util');

/**
 * A freedom port for a user-accessable provider.
 * @class Provider
 * @implements Port
 * @uses handleEvents
 * @param {Object} def The interface of the provider.
 * @param {Debug} debug The debugger to use for logging.
 * @contructor
 */
var Provider = function (def, debug) {
  this.id = Consumer.nextId();
  util.handleEvents(this);
  this.debug = debug;

  this.definition = def;
  this.mode = Provider.mode.synchronous;
  this.channels = {};
  this.iface = null;
  this.providerCls = null;
  this.providerInstances = {};
};

/**
 * Provider modes of operation.
 * @property mode
 * @static
 * @type number
 */
Provider.mode = {
  synchronous: 0,
  asynchronous: 1,
  promises: 2
};

/**
 * Receive external messages for the provider.
 * @method onMessage
 * @param {String} source the source identifier of the message.
 * @param {Object} message The received message.
 */
Provider.prototype.onMessage = function (source, message) {
  if (source === 'control' && message.reverse) {
    this.channels[message.name] = message.channel;
    this.emit(message.channel, {
      type: 'channel announcement',
      channel: message.reverse
    });
    this.emit('start');
  } else if (source === 'control' && message.type === 'setup') {
    this.controlChannel = message.channel;
  } else if (source === 'control' && message.type === 'close') {
    if (message.channel === this.controlChannel) {
      delete this.controlChannel;
    }
    this.close();
  } else {
    if (!this.channels[source] && message.channel) {
      this.channels[source] = message.channel;
      this.emit('start');
      return;
    } else if (!this.channels[source]) {
      this.debug.warn('Message from unconfigured source: ' + source);
      return;
    }

    if (message.type === 'close' && message.to) {
      delete this.providerInstances[source][message.to];
    } else if (message.to && this.providerInstances[source] &&
               this.providerInstances[source][message.to]) {
      message.message.to = message.to;
      this.providerInstances[source][message.to](message.message);
    } else if (message.to && message.message &&
        message.message.type === 'construct') {
      var args = Consumer.portableToMessage(
          (this.definition.constructor && this.definition.constructor.value) ?
              this.definition.constructor.value : [],
          message.message,
          this.debug
        );
      if (!this.providerInstances[source]) {
        this.providerInstances[source] = {};
      }
      this.providerInstances[source][message.to] = this.getProvider(source, message.to, args);
    } else {
      this.debug.warn(this.toString() + ' dropping message ' +
          JSON.stringify(message));
    }
  }
};

/**
 * Close / teardown the flow this provider terminates.
 * @method close
 */
Provider.prototype.close = function () {
  if (this.controlChannel) {
    this.emit(this.controlChannel, {
      type: 'Provider Closing',
      request: 'close'
    });
    delete this.controlChannel;
  }
  this.emit('close');

  this.providerInstances = {};
  this.emitChannel = null;
};

/**
 * Get an interface to expose externally representing this port.
 * Providers are registered with the port using either
 * provideSynchronous or provideAsynchronous depending on the desired
 * return interface.
 * @method getInterface
 * @return {Object} The external interface of this Provider.
 */
Provider.prototype.getInterface = function () {
  if (this.iface) {
    return this.iface;
  } else {
    this.iface = {
      provideSynchronous: function (prov) {
        this.providerCls = prov;
        this.mode = Provider.mode.synchronous;
      }.bind(this),
      provideAsynchronous: function (prov) {
        this.providerCls = prov;
        this.mode = Provider.mode.asynchronous;
      }.bind(this),
      providePromises: function (prov) {
        this.providerCls = prov;
        this.mode = Provider.mode.promises;
      }.bind(this),
      close: function () {
        this.close();
      }.bind(this)
    };

    util.eachProp(this.definition, function (prop, name) {
      switch (prop.type) {
      case "constant":
        Object.defineProperty(this.iface, name, {
          value: Consumer.recursiveFreezeObject(prop.value),
          writable: false
        });
        break;
      }
    }.bind(this));

    return this.iface;
  }
};

/**
 * Create a function that can be used to get interfaces from this provider from
 * a user-visible point.
 * @method getProxyInterface
 */
Provider.prototype.getProxyInterface = function () {
  var func = function (p) {
    return p.getInterface();
  }.bind({}, this);

  func.close = function (iface) {
    if (iface) {
      util.eachProp(this.ifaces, function (candidate, id) {
        if (candidate === iface) {
          this.teardown(id);
          this.emit(this.emitChannel, {
            type: 'close',
            to: id
          });
          return true;
        }
      }.bind(this));
    } else {
      // Close the channel.
      this.close();
    }
  }.bind(this);

  func.onClose = function (iface, handler) {
    if (typeof iface === 'function' && handler === undefined) {
      // Add an on-channel-closed handler.
      this.once('close', iface);
      return;
    }

    util.eachProp(this.ifaces, function (candidate, id) {
      if (candidate === iface) {
        if (this.handlers[id]) {
          this.handlers[id].push(handler);
        } else {
          this.handlers[id] = [handler];
        }
        return true;
      }
    }.bind(this));
  }.bind(this);

  return func;
};

/**
 * Get a new instance of the registered provider.
 * @method getProvider
 * @param {String} source The port this instance is interactign with.
 * @param {String} identifier the messagable address for this provider.
 * @param {Array} args Constructor arguments for the provider.
 * @return {Function} A function to send messages to the provider.
 */
Provider.prototype.getProvider = function (source, identifier, args) {
  if (!this.providerCls) {
    this.debug.warn('Cannot instantiate provider, since it is not provided');
    return null;
  }

  var events = {},
    dispatchEvent,
    BoundClass,
    instance;

  util.eachProp(this.definition, function (prop, name) {
    if (prop.type === 'event') {
      events[name] = prop;
    }
  });

  dispatchEvent = function (src, ev, id, name, value) {
    if (ev[name]) {
      var streams = Consumer.messageToPortable(ev[name].value, value,
                                                   this.debug);
      this.emit(this.channels[src], {
        type: 'message',
        to: id,
        message: {
          name: name,
          type: 'event',
          text: streams.text,
          binary: streams.binary
        }
      });
    }
  }.bind(this, source, events, identifier);

  // this is all to say: new providerCls(dispatchEvent, args[0], args[1],...)
  BoundClass = this.providerCls.bind.apply(this.providerCls,
      [this.providerCls, dispatchEvent].concat(args || []));
  instance = new BoundClass();

  return function (port, src, msg) {
    if (msg.action === 'method') {
      if (typeof this[msg.type] !== 'function') {
        this.debug.warn("Provider does not implement " + msg.type + "()!");
        return;
      }
      var prop = port.definition[msg.type],
        debug = this.debug,
        args = Consumer.portableToMessage(prop.value, msg, debug),
        ret = function (src, msg, prop, resolve, reject) {
          var streams = Consumer.messageToPortable(prop.ret, resolve,
                                                       debug);
          this.emit(this.channels[src], {
            type: 'method',
            to: msg.to,
            message: {
              to: msg.to,
              type: 'method',
              reqId: msg.reqId,
              name: msg.type,
              text: streams.text,
              binary: streams.binary,
              error: reject
            }
          });
        }.bind(port, src, msg, prop);
      if (!Array.isArray(args)) {
        args = [args];
      }
      if (port.mode === Provider.mode.synchronous) {
        try {
          ret(this[msg.type].apply(this, args));
        } catch (e) {
          ret(undefined, e.message);
        }
      } else if (port.mode === Provider.mode.asynchronous) {
        this[msg.type].apply(instance, args.concat(ret));
      } else if (port.mode === Provider.mode.promises) {
        this[msg.type].apply(this, args).then(ret, ret.bind({}, undefined));
      }
    }
  }.bind(instance, this, source);
};

/**
 * Get a textual description of this port.
 * @method toString
 * @return {String} the description of this port.
 */
Provider.prototype.toString = function () {
  if (this.emitChannel) {
    return "[Provider " + this.emitChannel + "]";
  } else {
    return "[unbound Provider]";
  }
};

module.exports = Provider;
<commit_msg>bind debug correctly on provider conform<commit_after>/*jslint indent:2, node:true, sloppy:true, browser:true */
var Consumer = require('./consumer');
var util = require('./util');

/**
 * A freedom port for a user-accessable provider.
 * @class Provider
 * @implements Port
 * @uses handleEvents
 * @param {Object} def The interface of the provider.
 * @param {Debug} debug The debugger to use for logging.
 * @contructor
 */
var Provider = function (def, debug) {
  this.id = Consumer.nextId();
  util.handleEvents(this);
  this.debug = debug;

  this.definition = def;
  this.mode = Provider.mode.synchronous;
  this.channels = {};
  this.iface = null;
  this.providerCls = null;
  this.providerInstances = {};
};

/**
 * Provider modes of operation.
 * @property mode
 * @static
 * @type number
 */
Provider.mode = {
  synchronous: 0,
  asynchronous: 1,
  promises: 2
};

/**
 * Receive external messages for the provider.
 * @method onMessage
 * @param {String} source the source identifier of the message.
 * @param {Object} message The received message.
 */
Provider.prototype.onMessage = function (source, message) {
  if (source === 'control' && message.reverse) {
    this.channels[message.name] = message.channel;
    this.emit(message.channel, {
      type: 'channel announcement',
      channel: message.reverse
    });
    this.emit('start');
  } else if (source === 'control' && message.type === 'setup') {
    this.controlChannel = message.channel;
  } else if (source === 'control' && message.type === 'close') {
    if (message.channel === this.controlChannel) {
      delete this.controlChannel;
    }
    this.close();
  } else {
    if (!this.channels[source] && message.channel) {
      this.channels[source] = message.channel;
      this.emit('start');
      return;
    } else if (!this.channels[source]) {
      this.debug.warn('Message from unconfigured source: ' + source);
      return;
    }

    if (message.type === 'close' && message.to) {
      delete this.providerInstances[source][message.to];
    } else if (message.to && this.providerInstances[source] &&
               this.providerInstances[source][message.to]) {
      message.message.to = message.to;
      this.providerInstances[source][message.to](message.message);
    } else if (message.to && message.message &&
        message.message.type === 'construct') {
      var args = Consumer.portableToMessage(
          (this.definition.constructor && this.definition.constructor.value) ?
              this.definition.constructor.value : [],
          message.message,
          this.debug
        );
      if (!this.providerInstances[source]) {
        this.providerInstances[source] = {};
      }
      this.providerInstances[source][message.to] = this.getProvider(source, message.to, args);
    } else {
      this.debug.warn(this.toString() + ' dropping message ' +
          JSON.stringify(message));
    }
  }
};

/**
 * Close / teardown the flow this provider terminates.
 * @method close
 */
Provider.prototype.close = function () {
  if (this.controlChannel) {
    this.emit(this.controlChannel, {
      type: 'Provider Closing',
      request: 'close'
    });
    delete this.controlChannel;
  }
  this.emit('close');

  this.providerInstances = {};
  this.emitChannel = null;
};

/**
 * Get an interface to expose externally representing this port.
 * Providers are registered with the port using either
 * provideSynchronous or provideAsynchronous depending on the desired
 * return interface.
 * @method getInterface
 * @return {Object} The external interface of this Provider.
 */
Provider.prototype.getInterface = function () {
  if (this.iface) {
    return this.iface;
  } else {
    this.iface = {
      provideSynchronous: function (prov) {
        this.providerCls = prov;
        this.mode = Provider.mode.synchronous;
      }.bind(this),
      provideAsynchronous: function (prov) {
        this.providerCls = prov;
        this.mode = Provider.mode.asynchronous;
      }.bind(this),
      providePromises: function (prov) {
        this.providerCls = prov;
        this.mode = Provider.mode.promises;
      }.bind(this),
      close: function () {
        this.close();
      }.bind(this)
    };

    util.eachProp(this.definition, function (prop, name) {
      switch (prop.type) {
      case "constant":
        Object.defineProperty(this.iface, name, {
          value: Consumer.recursiveFreezeObject(prop.value),
          writable: false
        });
        break;
      }
    }.bind(this));

    return this.iface;
  }
};

/**
 * Create a function that can be used to get interfaces from this provider from
 * a user-visible point.
 * @method getProxyInterface
 */
Provider.prototype.getProxyInterface = function () {
  var func = function (p) {
    return p.getInterface();
  }.bind({}, this);

  func.close = function (iface) {
    if (iface) {
      util.eachProp(this.ifaces, function (candidate, id) {
        if (candidate === iface) {
          this.teardown(id);
          this.emit(this.emitChannel, {
            type: 'close',
            to: id
          });
          return true;
        }
      }.bind(this));
    } else {
      // Close the channel.
      this.close();
    }
  }.bind(this);

  func.onClose = function (iface, handler) {
    if (typeof iface === 'function' && handler === undefined) {
      // Add an on-channel-closed handler.
      this.once('close', iface);
      return;
    }

    util.eachProp(this.ifaces, function (candidate, id) {
      if (candidate === iface) {
        if (this.handlers[id]) {
          this.handlers[id].push(handler);
        } else {
          this.handlers[id] = [handler];
        }
        return true;
      }
    }.bind(this));
  }.bind(this);

  return func;
};

/**
 * Get a new instance of the registered provider.
 * @method getProvider
 * @param {String} source The port this instance is interactign with.
 * @param {String} identifier the messagable address for this provider.
 * @param {Array} args Constructor arguments for the provider.
 * @return {Function} A function to send messages to the provider.
 */
Provider.prototype.getProvider = function (source, identifier, args) {
  if (!this.providerCls) {
    this.debug.warn('Cannot instantiate provider, since it is not provided');
    return null;
  }

  var events = {},
    dispatchEvent,
    BoundClass,
    instance;

  util.eachProp(this.definition, function (prop, name) {
    if (prop.type === 'event') {
      events[name] = prop;
    }
  });

  dispatchEvent = function (src, ev, id, name, value) {
    if (ev[name]) {
      var streams = Consumer.messageToPortable(ev[name].value, value,
                                                   this.debug);
      this.emit(this.channels[src], {
        type: 'message',
        to: id,
        message: {
          name: name,
          type: 'event',
          text: streams.text,
          binary: streams.binary
        }
      });
    }
  }.bind(this, source, events, identifier);

  // this is all to say: new providerCls(dispatchEvent, args[0], args[1],...)
  BoundClass = this.providerCls.bind.apply(this.providerCls,
      [this.providerCls, dispatchEvent].concat(args || []));
  instance = new BoundClass();

  return function (port, src, msg) {
    if (msg.action === 'method') {
      if (typeof this[msg.type] !== 'function') {
        this.debug.warn("Provider does not implement " + msg.type + "()!");
        return;
      }
      var prop = port.definition[msg.type],
        debug = port.debug,
        args = Consumer.portableToMessage(prop.value, msg, debug),
        ret = function (src, msg, prop, resolve, reject) {
          var streams = Consumer.messageToPortable(prop.ret, resolve,
                                                       debug);
          this.emit(this.channels[src], {
            type: 'method',
            to: msg.to,
            message: {
              to: msg.to,
              type: 'method',
              reqId: msg.reqId,
              name: msg.type,
              text: streams.text,
              binary: streams.binary,
              error: reject
            }
          });
        }.bind(port, src, msg, prop);
      if (!Array.isArray(args)) {
        args = [args];
      }
      if (port.mode === Provider.mode.synchronous) {
        try {
          ret(this[msg.type].apply(this, args));
        } catch (e) {
          ret(undefined, e.message);
        }
      } else if (port.mode === Provider.mode.asynchronous) {
        this[msg.type].apply(instance, args.concat(ret));
      } else if (port.mode === Provider.mode.promises) {
        this[msg.type].apply(this, args).then(ret, ret.bind({}, undefined));
      }
    }
  }.bind(instance, this, source);
};

/**
 * Get a textual description of this port.
 * @method toString
 * @return {String} the description of this port.
 */
Provider.prototype.toString = function () {
  if (this.emitChannel) {
    return "[Provider " + this.emitChannel + "]";
  } else {
    return "[unbound Provider]";
  }
};

module.exports = Provider;
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const dbConfig = require('./db.js');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const blogController = require('./controllers/blog-controller');
const postController = require('./controllers/post-controller');
const userController = require('./controllers/user-controller');
const sessionController = require('./controllers/session-controller');
const cookieController = require('./controllers/cookie-controller');
const collectionController = require('./controllers/collection-controller');
const collectionItemController = require('./controllers/collection-item-controller');
const pluginController = require('./controllers/plugin-controller');
const pluginItemController = require('./controllers/plugin-item-controller');
var nodemailer = require("nodemailer");

//connecting to the database
mongoose.connect(dbConfig.url, function(err) {
  if (err) return console.error(err);
  console.log('connected to mongoDB @ mlab');
});

// handling cookies for all requests
app.use(cookieParser());
//using bodyParser for json
app.use(bodyParser.json());
// serving static from client folder
app.use((req, res, next) => {
  // Cors
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
  next();
});
app.use(express.static('admin'));
app.use(express.static('dist'));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + './../../index.html'));
});

app.get('/dashboard.html', sessionController.isLoggedIn, (req, res) => {
    res.sendFile(path.join(__dirname + './../client/components/dashboard.html'));
});

// ** authentication - authorized routes **
// login
app.post('/login', userController.verifyUser);

// ** blog **
// blog creation route
app.post('/api/blog', blogController.createBlog);

// listing all the blogs
app.get('/api/blogs', blogController.getAllBlogs);

// listing a specific blog
app.get('/api/blog/:blog_id', blogController.getBlogById);

// updating a specific blog
app.put('/api/blog/:blog_id', blogController.updateBlogById);

// deleting a specific blog
app.delete('/api/blog/:blog_id', blogController.deleteBlogById);

// ** post **
// post creation route
app.post('/api/post', postController.createPost);

// listing all the posts
app.get('/api/posts', (req, res, next) => {
  console.log('redirect', req.url);
  next();
}, postController.getAllPosts);

// listing a specific post
app.get('/api/post/:post_id', postController.getPostById);

// updating a specific post
app.put('/api/post/:post_id', postController.updatePostById);

// deleting a specific post
app.delete('/api/post/:post_id', postController.deletePostById);

// ** user **
// user creation route
app.post('/api/user', userController.createUser);

// listing all the users
app.get('/api/users', userController.getAllUsers);

// listing all the users
app.get('/api/user/:user_id', userController.getUserById);

// updating a specific user
app.put('/api/user/:user_id', userController.updateUserById);

// deleting a specific user
app.delete('/api/user/:user_id', userController.deleteUserById);

// ** collection **
// collection creation route
app.post('/api/collection', collectionController.createCollection);
// listing all the collections
app.get('/api/collections', collectionController.getAllCollections);
// deleting a specific collection
app.delete('/api/collection/:collection_id', collectionController.deleteCollectionById);

// ** collection items **
// collection item creation route
app.post('/api/collection_item', collectionItemController.createCollectionItem);
// getting all the collection items
app.get('/api/collection_items', collectionItemController.getAllCollectionItems);
// deleting a specific item
app.delete('/api/collection_item/:item_id', collectionItemController.deleteCollectionItemById);
// delete all items in collection
app.delete('/api/collection_items/:collection_id', collectionItemController.deleteCollectionItemsById);

// ** plugins **
// plugin item creation route
app.post('/api/plugin', pluginController.createPlugin);
// getting all the plugin s
app.get('/api/plugins', pluginController.getAllPlugins);
// deleting a specific plugin
app.delete('/api/plugin/:plugin_id', pluginController.deletePluginById);
// delete all s in plugin
app.delete('/api/plugin/:plugin_id', pluginController.deletePluginById);

// ** plugin items **
// plugin item creation route
app.post('/api/plugin_item', pluginItemController.createPluginItem);
// getting all the plugin items
app.get('/api/plugin_items', pluginItemController.getAllPluginItems);
// deleting a specific item
app.delete('/api/plugin_item/:plugin_item_id', pluginItemController.deletePluginItemById);
// delete all items in plugin
app.delete('/api/plugin_item/:plugin_item_id', pluginItemController.deletePluginItemById);

// const pluginsRoutes = require('./plugins');

// ** PLUGINS ** DO NOT EDIT BELOW vvv
// this section is going to be automatically edited by de CLI

//%%begin%%
require('../../plugins/Comments/server/routes')(app);
//%%end%%

// ** PLUGINS ** DO NOT EDIT ABOVE ^^^

// get list of plugins from plugin directory
app.get('/api/stored-plugins', (req, res) => {
  let plugins = fs.readdirSync('plugins').filter(file =>{
    return fs.statSync(path.join('plugins', file)).isDirectory();
  });
  res.send(plugins)
})

// configuring env production port
const PORT = process.env.PORT || 3000

// spinning up the server
app.listen(PORT, function () {
  console.log('react synthesis listening on port %s!', PORT);
});

module.exports = app;
<commit_msg>detecting environment for mongoDB<commit_after>const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const dbConfig = require('./db.js');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const blogController = require('./controllers/blog-controller');
const postController = require('./controllers/post-controller');
const userController = require('./controllers/user-controller');
const sessionController = require('./controllers/session-controller');
const cookieController = require('./controllers/cookie-controller');
const collectionController = require('./controllers/collection-controller');
const collectionItemController = require('./controllers/collection-item-controller');
const pluginController = require('./controllers/plugin-controller');
const pluginItemController = require('./controllers/plugin-item-controller');
var nodemailer = require("nodemailer");

//connecting to the database
if (process.env.NODE_ENV === 'test') dbConfig.url = 'mongodb://localhost/synthesis-test';
mongoose.connect(dbConfig.url, function(err) {
  if (err) return console.error(err);
  console.log('connected to mongoDB', dbConfig.url);
});

// handling cookies for all requests
app.use(cookieParser());
//using bodyParser for json
app.use(bodyParser.json());
// serving static from client folder
app.use((req, res, next) => {
  // Cors
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
  next();
});
app.use(express.static('admin'));
app.use(express.static('dist'));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + './../../index.html'));
});

app.get('/dashboard.html', sessionController.isLoggedIn, (req, res) => {
    res.sendFile(path.join(__dirname + './../client/components/dashboard.html'));
});

// ** authentication - authorized routes **
// login
app.post('/login', userController.verifyUser);

// ** blog **
// blog creation route
app.post('/api/blog', blogController.createBlog);

// listing all the blogs
app.get('/api/blogs', blogController.getAllBlogs);

// listing a specific blog
app.get('/api/blog/:blog_id', blogController.getBlogById);

// updating a specific blog
app.put('/api/blog/:blog_id', blogController.updateBlogById);

// deleting a specific blog
app.delete('/api/blog/:blog_id', blogController.deleteBlogById);

// ** post **
// post creation route
app.post('/api/post', postController.createPost);

// listing all the posts
app.get('/api/posts', (req, res, next) => {
  console.log('redirect', req.url);
  next();
}, postController.getAllPosts);

// listing a specific post
app.get('/api/post/:post_id', postController.getPostById);

// updating a specific post
app.put('/api/post/:post_id', postController.updatePostById);

// deleting a specific post
app.delete('/api/post/:post_id', postController.deletePostById);

// ** user **
// user creation route
app.post('/api/user', userController.createUser);

// listing all the users
app.get('/api/users', userController.getAllUsers);

// listing all the users
app.get('/api/user/:user_id', userController.getUserById);

// updating a specific user
app.put('/api/user/:user_id', userController.updateUserById);

// deleting a specific user
app.delete('/api/user/:user_id', userController.deleteUserById);

// ** collection **
// collection creation route
app.post('/api/collection', collectionController.createCollection);
// listing all the collections
app.get('/api/collections', collectionController.getAllCollections);
// deleting a specific collection
app.delete('/api/collection/:collection_id', collectionController.deleteCollectionById);

// ** collection items **
// collection item creation route
app.post('/api/collection_item', collectionItemController.createCollectionItem);
// getting all the collection items
app.get('/api/collection_items', collectionItemController.getAllCollectionItems);
// deleting a specific item
app.delete('/api/collection_item/:item_id', collectionItemController.deleteCollectionItemById);
// delete all items in collection
app.delete('/api/collection_items/:collection_id', collectionItemController.deleteCollectionItemsById);

// ** plugins **
// plugin item creation route
app.post('/api/plugin', pluginController.createPlugin);
// getting all the plugin s
app.get('/api/plugins', pluginController.getAllPlugins);
// deleting a specific plugin
app.delete('/api/plugin/:plugin_id', pluginController.deletePluginById);
// delete all s in plugin
app.delete('/api/plugin/:plugin_id', pluginController.deletePluginById);

// ** plugin items **
// plugin item creation route
app.post('/api/plugin_item', pluginItemController.createPluginItem);
// getting all the plugin items
app.get('/api/plugin_items', pluginItemController.getAllPluginItems);
// deleting a specific item
app.delete('/api/plugin_item/:plugin_item_id', pluginItemController.deletePluginItemById);
// delete all items in plugin
app.delete('/api/plugin_item/:plugin_item_id', pluginItemController.deletePluginItemById);

// const pluginsRoutes = require('./plugins');

// ** PLUGINS ** DO NOT EDIT BELOW vvv
// this section is going to be automatically edited by de CLI

//%%begin%%
require('../../plugins/Comments/server/routes')(app);
//%%end%%

// ** PLUGINS ** DO NOT EDIT ABOVE ^^^

// get list of plugins from plugin directory
app.get('/api/stored-plugins', (req, res) => {
  let plugins = fs.readdirSync('plugins').filter(file =>{
    return fs.statSync(path.join('plugins', file)).isDirectory();
  });
  res.send(plugins)
})

// configuring env production port
const PORT = process.env.PORT || 3000

// spinning up the server
app.listen(PORT, function () {
  console.log('react synthesis listening on port %s!', PORT);
});

module.exports = app;
<|endoftext|>


<commit_before>/**!
 ** @name gulp-sass-pedigree
 ** @version 2.1.6
 ** @author Giuseppe Mandato <gius.mand.developer@gmail.com> (https://github.com/hitmands)
 ** @contributors ["Luca Volta <luca.volta@gmail.com> (https://github.com/lucavolta)"]
 ** @url https://github.com/hitmands/gulp-sass-pedigree#readme
 ** @description Incremental Caching System for Gulp and NodeSass
 ** @keywords [gulpplugin, sass, libsass, gulp, cache, incremental cache]
 ** @entry build/GulpSassPedigree.js
 ** @license MIT License
***/

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 8);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PLUGIN_NAME = undefined;
exports.create = create;

var _through = __webpack_require__(7);

var _through2 = _interopRequireDefault(_through);

var _path = __webpack_require__(4);

var _path2 = _interopRequireDefault(_path);

var _fs = __webpack_require__(2);

var _fs2 = _interopRequireDefault(_fs);

var _gulpUtil = __webpack_require__(3);

var _gulpUtil2 = _interopRequireDefault(_gulpUtil);

var _DependenciesGraph = __webpack_require__(5);

var _Helpers = __webpack_require__(1);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var PLUGIN_NAME = exports.PLUGIN_NAME = 'gulp-sass-pedigree';
var getFileChangedArgs = function getFileChangedArgs(graph, file) {
  var dir = _path2.default.dirname(file.path);
  var dirs = [dir];

  if (_path2.default.relative(dir, file.base)) {
    dirs.push(file.base);
  }

  return [file, file.contents.toString(), dirs.concat(graph.options.includePaths)];
};

function create() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var graph = new _DependenciesGraph.DependenciesGraph();
  graph.options = options;
  graph.options.verbose = !!graph.options.verbose;

  return {
    graph: graph,
    study: function study() {

      return _through2.default.obj(function studyProjectStructure(file, enc, cb) {
        if (file && !file.isNull()) {
          void graph.onFileChange.apply(graph, _toConsumableArray(getFileChangedArgs(graph, file)));
        }

        return cb(null, file);
      });
    },
    getAncestors: function getAncestors() {

      return _through2.default.obj(function getAncestorsFromFile(file, enc, cb) {
        if (file && !file.isNull()) {
          var start = Date.now();

          void graph.onFileChange.apply(graph, _toConsumableArray(getFileChangedArgs(graph, file)));
          var parents = graph.get(file.path).parents;

          if (parents.length) {
            var ancestors = void 0;

            try {
              ancestors = graph.ascend(parents.slice());
            } catch (e) {

              (0, _Helpers.log)('warn', 'possible circular dependency at ' + (0, _Helpers.green)(file.path));
              if (graph.options.verbose) {
                (0, _Helpers.log)('error', e);
              }
            }

            if (ancestors) {
              for (var i = 0; i < ancestors.length; i++) {
                var p = ancestors[i];

                this.push(
                /* eslint object-property-newline: 0 */
                new _gulpUtil2.default.File({
                  path: p, cwd: file.cwd, base: _path2.default.dirname(p),
                  contents: file.type === 'stream' ? _fs2.default.createReadStream(p) : _fs2.default.readFileSync(p)
                }));
              }

              var filename = (0, _Helpers.green)(JSON.stringify(_path2.default.basename(file.path)));
              var info = [(0, _Helpers.green)(ancestors.length) + ' ancestors for ' + filename];

              if (graph.options.verbose) {
                info.push((0, _Helpers.green)(JSON.stringify(ancestors, null, 2)));
              }

              _Helpers.log.apply(undefined, ['info'].concat(info, [_gulpUtil2.default.colors.magenta(Date.now() - start + ' ms')]));
            }
          }
        }

        return cb(null, file);
      });
    }
  };
}

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.green = undefined;
exports.prune = prune;
exports.fileExists = fileExists;
exports.log = log;

var _gulpUtil = __webpack_require__(3);

var _gulpUtil2 = _interopRequireDefault(_gulpUtil);

var _fs = __webpack_require__(2);

var _fs2 = _interopRequireDefault(_fs);

var _GulpSassPedigree = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function prune(arr) {
  return arr.filter(function (child, i, list) {
    return child && i === list.lastIndexOf(child);
  });
}

function fileExists(path) {
  return _fs2.default.existsSync(path);
}

function log(type) {
  var color = void 0;

  switch (type) {
    case 'warn':
      color = 'yellow';
      break;

    case 'error':
      color = 'red';
      break;

    default:
      color = 'cyan';
  }

  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  return _gulpUtil2.default.log.apply(_gulpUtil2.default, [_gulpUtil2.default.colors[color](_GulpSassPedigree.PLUGIN_NAME + '::' + type)].concat(args));
}

var green = exports.green = function green(msg) {
  return _gulpUtil2.default.colors.green(msg);
};

/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = require("fs");

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = require("gulp-util");

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = require("path");

/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DependenciesGraph = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _path = __webpack_require__(4);

var _path2 = _interopRequireDefault(_path);

var _Helpers = __webpack_require__(1);

var _stripScssImports = __webpack_require__(6);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DependenciesGraph = exports.DependenciesGraph = function () {
  function DependenciesGraph() {
    _classCallCheck(this, DependenciesGraph);

    this.cache = Object.create(null);
    this._options = Object.assign(Object.create(null), {
      includePaths: [],
      ext: '.scss',
      verbose: false
    });

    this.log = _Helpers.log;
    this.fileExists = _Helpers.fileExists;
  }

  _createClass(DependenciesGraph, [{
    key: 'get',
    value: function get(path) {

      return this.cache[path] || null;
    }
  }, {
    key: 'has',
    value: function has(path) {

      return path in this.cache;
    }
  }, {
    key: 'set',
    value: function set(path) {
      var children = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var parents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

      this.cache[path] = Object.assign(Object.create(null), { children: children, parents: parents });
    }
  }, {
    key: 'onFileChange',
    value: function onFileChange(file) {
      var content = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
      var dirs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

      var imports = this.updateKeys((0, _stripScssImports.stripScssImports)(content), dirs, file.path);

      this.has(file.path) || this.set(file.path);
      this.get(file.path).children = imports;
      void this.updateParents();
    }
  }, {
    key: 'updateParents',
    value: function updateParents() {
      var _this = this;

      for (var k in this.cache) {
        // noinspection JSUnfilteredForInLoop
        this.get(k).parents = [];
      }

      var _loop = function _loop(_k) {
        // noinspection JSUnfilteredForInLoop
        _this.get(_k).children.forEach(function (file) {
          var parents = _this.get(file).parents;

          // noinspection JSUnfilteredForInLoop
          ~parents.indexOf(_k) || parents.push(_k);
        });
      };

      for (var _k in this.cache) {
        _loop(_k);
      }
    }
  }, {
    key: 'updateKeys',
    value: function updateKeys(files, dirs, importer) {
      var _this2 = this;

      return files.reduce(function (res, filename) {
        for (var i = 0; i < dirs.length; i++) {
          var a = _path2.default.resolve(dirs[i], filename);
          var paths = [a, a.replace(/([^/\\]*$)/, '_$1')];

          for (var j = 0; j < paths.length; j++) {
            var p = paths[j];

            if (_this2.has(p)) {
              return res.concat(p);
            }

            if (_this2.fileExists(p)) {
              _this2.set(p);
              return res.concat(p);
            }
          }
        }

        var log = function log() {
          return (0, _Helpers.green)(JSON.stringify.apply(JSON, arguments));
        };
        _this2.log('warn', log(filename) + ' not found in ' + log(dirs, null, 2) + ' of ' + log(_path2.default.basename(importer)));

        return res;
      }, []);
    }
  }, {
    key: 'ascend',
    value: function ascend(list) {
      var res = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

      if (!list.length) {
        return (0, _Helpers.prune)(res);
      }

      var p = list.shift();
      var parents = this.get(p).parents;

      return parents.length ? this.ascend(list.concat(parents), res) : this.ascend(list, res.concat(p));
    }
  }, {
    key: 'options',
    set: function set(v) {

      this._options = Object.assign(this._options, v || {});
    },
    get: function get() {

      return this._options;
    }
  }, {
    key: 'length',
    get: function get() {

      return Object.keys(this.cache).length;
    }
  }]);

  return DependenciesGraph;
}();

/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.stripScssImports = stripScssImports;
function stripScssImports(textContent) {

  return (
  // TODO: Handle comments //@import ""; or /* @import ""; */
  textContent.match(/(?:@import\s+)([^;]*)/g) || []).reduce(function (res, filename) {
    return res.concat(filename.replace(/@import|["'\s]/g, '').split(/,/).map(function (p) {
      return p.replace(/\.scss$/, '') + '.scss';
    }));
  }, []);
}

/***/ }),
/* 7 */
/***/ (function(module, exports) {

module.exports = require("through2");

/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(0);

/***/ })
/******/ ]);
//# sourceMappingURL=GulpSassPedigree.js.map<commit_msg>build with a new version code<commit_after>/**!
 ** @name gulp-sass-pedigree
 ** @version 2.1.7
 ** @author Giuseppe Mandato <gius.mand.developer@gmail.com> (https://github.com/hitmands)
 ** @contributors ["Luca Volta <luca.volta@gmail.com> (https://github.com/lucavolta)"]
 ** @url https://github.com/hitmands/gulp-sass-pedigree#readme
 ** @description Incremental Caching System for Gulp and NodeSass
 ** @keywords [gulpplugin, sass, libsass, gulp, cache, incremental cache]
 ** @entry build/GulpSassPedigree.js
 ** @license MIT License
***/

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 8);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PLUGIN_NAME = undefined;
exports.create = create;

var _through = __webpack_require__(7);

var _through2 = _interopRequireDefault(_through);

var _path = __webpack_require__(4);

var _path2 = _interopRequireDefault(_path);

var _fs = __webpack_require__(2);

var _fs2 = _interopRequireDefault(_fs);

var _gulpUtil = __webpack_require__(3);

var _gulpUtil2 = _interopRequireDefault(_gulpUtil);

var _DependenciesGraph = __webpack_require__(5);

var _Helpers = __webpack_require__(1);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var PLUGIN_NAME = exports.PLUGIN_NAME = 'gulp-sass-pedigree';
var getFileChangedArgs = function getFileChangedArgs(graph, file) {
  var dir = _path2.default.dirname(file.path);
  var dirs = [dir];

  if (_path2.default.relative(dir, file.base)) {
    dirs.push(file.base);
  }

  return [file, file.contents.toString(), dirs.concat(graph.options.includePaths)];
};

function create() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var graph = new _DependenciesGraph.DependenciesGraph();
  graph.options = options;
  graph.options.verbose = !!graph.options.verbose;

  return {
    graph: graph,
    study: function study() {

      return _through2.default.obj(function studyProjectStructure(file, enc, cb) {
        if (file && !file.isNull()) {
          void graph.onFileChange.apply(graph, _toConsumableArray(getFileChangedArgs(graph, file)));
        }

        return cb(null, file);
      });
    },
    getAncestors: function getAncestors() {

      return _through2.default.obj(function getAncestorsFromFile(file, enc, cb) {
        if (file && !file.isNull()) {
          var start = Date.now();

          void graph.onFileChange.apply(graph, _toConsumableArray(getFileChangedArgs(graph, file)));
          var parents = graph.get(file.path).parents;

          if (parents.length) {
            var ancestors = void 0;

            try {
              ancestors = graph.ascend(parents.slice());
            } catch (e) {

              (0, _Helpers.log)('warn', 'possible circular dependency at ' + (0, _Helpers.green)(file.path));
              if (graph.options.verbose) {
                (0, _Helpers.log)('error', e);
              }
            }

            if (ancestors) {
              for (var i = 0; i < ancestors.length; i++) {
                var p = ancestors[i];

                this.push(
                /* eslint object-property-newline: 0 */
                new _gulpUtil2.default.File({
                  path: p, cwd: file.cwd, base: _path2.default.dirname(p),
                  contents: file.type === 'stream' ? _fs2.default.createReadStream(p) : _fs2.default.readFileSync(p)
                }));
              }

              var filename = (0, _Helpers.green)(JSON.stringify(_path2.default.basename(file.path)));
              var info = [(0, _Helpers.green)(ancestors.length) + ' ancestors for ' + filename];

              if (graph.options.verbose) {
                info.push((0, _Helpers.green)(JSON.stringify(ancestors, null, 2)));
              }

              _Helpers.log.apply(undefined, ['info'].concat(info, [_gulpUtil2.default.colors.magenta(Date.now() - start + ' ms')]));
            }
          }
        }

        return cb(null, file);
      });
    }
  };
}

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.green = undefined;
exports.prune = prune;
exports.fileExists = fileExists;
exports.log = log;

var _gulpUtil = __webpack_require__(3);

var _gulpUtil2 = _interopRequireDefault(_gulpUtil);

var _fs = __webpack_require__(2);

var _fs2 = _interopRequireDefault(_fs);

var _GulpSassPedigree = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function prune(arr) {
  return arr.filter(function (child, i, list) {
    return child && i === list.lastIndexOf(child);
  });
}

function fileExists(path) {
  return _fs2.default.existsSync(path);
}

function log(type) {
  var color = void 0;

  switch (type) {
    case 'warn':
      color = 'yellow';
      break;

    case 'error':
      color = 'red';
      break;

    default:
      color = 'cyan';
  }

  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  return _gulpUtil2.default.log.apply(_gulpUtil2.default, [_gulpUtil2.default.colors[color](_GulpSassPedigree.PLUGIN_NAME + '::' + type)].concat(args));
}

var green = exports.green = function green(msg) {
  return _gulpUtil2.default.colors.green(msg);
};

/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = require("fs");

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = require("gulp-util");

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = require("path");

/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DependenciesGraph = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _path = __webpack_require__(4);

var _path2 = _interopRequireDefault(_path);

var _Helpers = __webpack_require__(1);

var _stripScssImports = __webpack_require__(6);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DependenciesGraph = exports.DependenciesGraph = function () {
  function DependenciesGraph() {
    _classCallCheck(this, DependenciesGraph);

    this.cache = Object.create(null);
    this._options = Object.assign(Object.create(null), {
      includePaths: [],
      ext: '.scss',
      verbose: false
    });

    this.log = _Helpers.log;
    this.fileExists = _Helpers.fileExists;
  }

  _createClass(DependenciesGraph, [{
    key: 'get',
    value: function get(path) {

      return this.cache[path] || null;
    }
  }, {
    key: 'has',
    value: function has(path) {

      return path in this.cache;
    }
  }, {
    key: 'set',
    value: function set(path) {
      var children = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var parents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

      this.cache[path] = Object.assign(Object.create(null), { children: children, parents: parents });
    }
  }, {
    key: 'onFileChange',
    value: function onFileChange(file) {
      var content = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
      var dirs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

      var imports = this.updateKeys((0, _stripScssImports.stripScssImports)(content), dirs, file.path);

      this.has(file.path) || this.set(file.path);
      this.get(file.path).children = imports;
      void this.updateParents();
    }
  }, {
    key: 'updateParents',
    value: function updateParents() {
      var _this = this;

      for (var k in this.cache) {
        // noinspection JSUnfilteredForInLoop
        this.get(k).parents = [];
      }

      var _loop = function _loop(_k) {
        // noinspection JSUnfilteredForInLoop
        _this.get(_k).children.forEach(function (file) {
          var parents = _this.get(file).parents;

          // noinspection JSUnfilteredForInLoop
          ~parents.indexOf(_k) || parents.push(_k);
        });
      };

      for (var _k in this.cache) {
        _loop(_k);
      }
    }
  }, {
    key: 'updateKeys',
    value: function updateKeys(files, dirs, importer) {
      var _this2 = this;

      return files.reduce(function (res, filename) {
        for (var i = 0; i < dirs.length; i++) {
          var a = _path2.default.resolve(dirs[i], filename);
          var paths = [a, a.replace(/([^/\\]*$)/, '_$1')];

          for (var j = 0; j < paths.length; j++) {
            var p = paths[j];

            if (_this2.has(p)) {
              return res.concat(p);
            }

            if (_this2.fileExists(p)) {
              _this2.set(p);
              return res.concat(p);
            }
          }
        }

        var log = function log() {
          return (0, _Helpers.green)(JSON.stringify.apply(JSON, arguments));
        };
        _this2.log('warn', log(filename) + ' not found in ' + log(dirs, null, 2) + ' of ' + log(_path2.default.basename(importer)));

        return res;
      }, []);
    }
  }, {
    key: 'ascend',
    value: function ascend(list) {
      var res = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

      if (!list.length) {
        return (0, _Helpers.prune)(res);
      }

      var p = list.shift();
      var parents = this.get(p).parents;

      return parents.length ? this.ascend(list.concat(parents), res) : this.ascend(list, res.concat(p));
    }
  }, {
    key: 'options',
    set: function set(v) {

      this._options = Object.assign(this._options, v || {});
    },
    get: function get() {

      return this._options;
    }
  }, {
    key: 'length',
    get: function get() {

      return Object.keys(this.cache).length;
    }
  }]);

  return DependenciesGraph;
}();

/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.stripScssImports = stripScssImports;
function stripScssImports(textContent) {

  return (
  // TODO: Handle comments //@import ""; or /* @import ""; */
  textContent.match(/(?:@import\s+)([^;]*)/g) || []).reduce(function (res, filename) {
    return res.concat(filename.replace(/@import|["'\s]/g, '').split(/,/).map(function (p) {
      return p.replace(/\.scss$/, '') + '.scss';
    }));
  }, []);
}

/***/ }),
/* 7 */
/***/ (function(module, exports) {

module.exports = require("through2");

/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(0);

/***/ })
/******/ ]);
//# sourceMappingURL=GulpSassPedigree.js.map<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    bemConfig = require('bem-config'),
    scheme = require('bem-fs-scheme'),
    bemNaming = require('bem-naming'),
    braceExpansion = require('brace-expansion'),
    createEntity = require('./create-entity'),
    getTemplate = require('./template'),
    uniq = require('uniq'),
    flatten = require('flatten'),
    Promise = require('pinkie-promise');

module.exports = function create(entities, levels, techs, options) {
    options || (options = {});
    techs || (techs = []);
    var config = bemConfig(options),
        cwd = options.cwd || process.cwd();

    if (!levels || !levels.length) {
        var levelsMap = config.levelMapSync(),
            levelList = Object.keys(levelsMap);

        var defaultLevels = levelList.filter(function(level) {
            return levelsMap[level].default;
        });

        var levelByCwd = levelList.filter(function(level) {
            return cwd.indexOf(level) === 0;
        }).sort().reverse()[0];

        levels = levelByCwd || (defaultLevels.length ? defaultLevels : cwd);
    }

    Array.isArray(entities) || (entities = [entities]);
    Array.isArray(levels) || (levels = [levels]);

    return Promise.all(entities.map(function(input) {
        var isFileGlob = typeof input === 'string';

        return Promise.all((isFileGlob ? braceExpansion(input) : [input]).map(function(filepathOrInput) {
            var currentLevels = levels;

            if (typeof filepathOrInput === 'string'){
                var currentLevel = path.dirname(filepathOrInput);
                currentLevel !== '.' && (currentLevels = [currentLevel]);
            }

            return Promise.all(currentLevels.map(function(relLevel) {
                var level = path.resolve(config.rootSync() || cwd, relLevel);

                return config.module('bem-tools')
                    .then(function(bemToolsConf) {
                        var pluginConf = bemToolsConf && bemToolsConf.plugins && bemToolsConf.plugins.create || {};

                        return config.level(level).then(function(levelOptions) {
                            levelOptions || (levelOptions = {});

                            var namingOpts = levelOptions.naming,
                                levelScheme = levelOptions.scheme,
                                buildPath = scheme(levelScheme).path,
                                entity = filepathOrInput,

                                pluginConfLevels = pluginConf.levels || {},
                                pluginConfLevel = pluginConfLevels[level] || {},
                                pluginConfLevelTechs = pluginConfLevel.techs,

                                pluginTechs = pluginConf.techs || [],
                                currentTechs = uniq([].concat(pluginConfLevelTechs || pluginTechs, techs)),
                                templatesOpts = Object.assign({}, pluginConf, pluginConfLevel);

                            if (isFileGlob) {
                                var file = path.basename(filepathOrInput),
                                    splitted = file.split('.');

                                entity = bemNaming(namingOpts).parse(splitted.shift());
                                if (splitted.join('.')) {
                                    currentTechs = uniq(techs.concat(splitted.join('.')));
                                }
                            }

                            options.onlyTech && (currentTechs = options.onlyTech);

                            return Promise.all(currentTechs.map(function(tech) {
                                var pathToFile = buildPath(entity, tech, { naming: namingOpts }),
                                    absPathToFile = path.join(path.resolve(level), pathToFile),
                                    template = getTemplate(tech, templatesOpts);

                                return createEntity(entity, absPathToFile, template, { naming: namingOpts });
                            }));
                        });
                    });
            }));

        }));
    })).then(flatten);
};
<commit_msg>Add ability to pass cwd as options.cwd #11 (#16)<commit_after>'use strict';

var path = require('path'),
    bemConfig = require('bem-config'),
    scheme = require('bem-fs-scheme'),
    bemNaming = require('bem-naming'),
    braceExpansion = require('brace-expansion'),
    createEntity = require('./create-entity'),
    getTemplate = require('./template'),
    uniq = require('uniq'),
    flatten = require('flatten'),
    Promise = require('pinkie-promise');

module.exports = function create(entities, levels, techs, options) {
    options || (options = {});
    techs || (techs = []);
    var config = bemConfig(options),
        cwd = path.resolve(options.cwd || '');

    if (!levels || !levels.length) {
        var levelsMap = config.levelMapSync(),
            levelList = Object.keys(levelsMap);

        var defaultLevels = levelList.filter(function(level) {
            return levelsMap[level].default;
        });

        var levelByCwd = levelList.filter(function(level) {
            return cwd.indexOf(level) === 0;
        }).sort().reverse()[0];

        levels = levelByCwd || (defaultLevels.length ? defaultLevels : cwd);
    }

    Array.isArray(entities) || (entities = [entities]);
    Array.isArray(levels) || (levels = [levels]);

    return Promise.all(entities.map(function(input) {
        var isFileGlob = typeof input === 'string';

        return Promise.all((isFileGlob ? braceExpansion(input) : [input]).map(function(filepathOrInput) {
            var currentLevels = levels;

            if (typeof filepathOrInput === 'string'){
                var currentLevel = path.dirname(filepathOrInput);
                currentLevel !== '.' && (currentLevels = [currentLevel]);
            }

            return Promise.all(currentLevels.map(function(relLevel) {
                var level = path.resolve(config.rootSync() || cwd, relLevel);

                return config.module('bem-tools')
                    .then(function(bemToolsConf) {
                        var pluginConf = bemToolsConf && bemToolsConf.plugins && bemToolsConf.plugins.create || {};

                        return config.level(level).then(function(levelOptions) {
                            levelOptions || (levelOptions = {});

                            var namingOpts = levelOptions.naming,
                                levelScheme = levelOptions.scheme,
                                buildPath = scheme(levelScheme).path,
                                entity = filepathOrInput,

                                pluginConfLevels = pluginConf.levels || {},
                                pluginConfLevel = pluginConfLevels[level] || {},
                                pluginConfLevelTechs = pluginConfLevel.techs,

                                pluginTechs = pluginConf.techs || [],
                                currentTechs = uniq([].concat(pluginConfLevelTechs || pluginTechs, techs)),
                                templatesOpts = Object.assign({}, pluginConf, pluginConfLevel);

                            if (isFileGlob) {
                                var file = path.basename(filepathOrInput),
                                    splitted = file.split('.');

                                entity = bemNaming(namingOpts).parse(splitted.shift());
                                if (splitted.join('.')) {
                                    currentTechs = uniq(techs.concat(splitted.join('.')));
                                }
                            }

                            options.onlyTech && (currentTechs = options.onlyTech);

                            return Promise.all(currentTechs.map(function(tech) {
                                var pathToFile = buildPath(entity, tech, { naming: namingOpts }),
                                    absPathToFile = path.join(path.resolve(level), pathToFile),
                                    template = getTemplate(tech, templatesOpts);

                                return createEntity(entity, absPathToFile, template, { naming: namingOpts });
                            }));
                        });
                    });
            }));

        }));
    })).then(flatten);
};
<|endoftext|>


<commit_before>(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as anonymous module.
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node / CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals.
    factory(jQuery);
  }
})(function ($) {

  'use strict';

  var location = window.location;
  var NAMESPACE = 'qor.filter';
  var EVENT_ENABLE = 'enable.' + NAMESPACE;
  var EVENT_DISABLE = 'disable.' + NAMESPACE;
  var EVENT_CLICK = 'click.' + NAMESPACE;
  var EVENT_CHANGE = 'change.' + NAMESPACE;

  function QorFilter(element, options) {
    this.$element = $(element);
    this.options = $.extend({}, QorFilter.DEFAULTS, $.isPlainObject(options) && options);
    this.init();
  }

  function encodeSearch(data, detached) {
    var search = location.search;
    var params;

    if ($.isArray(data)) {
      params = decodeSearch(search);

      $.each(data, function (i, param) {
        i = $.inArray(param, params);

        if (i === -1) {
          params.push(param);
        } else if (detached) {
          params.splice(i, 1);
        }
      });

      search = '?' + params.join('&');
    }

    return search;
  }

  function decodeSearch(search) {
    var data = [];

    if (search && search.indexOf('?') > -1) {
      search = search.split('?')[1];

      if (search && search.indexOf('#') > -1) {
        search = search.split('#')[0];
      }

      if (search) {
        // search = search.toLowerCase();
        data = $.map(search.split('&'), function (n) {
          var param = [];
          var value;

          n = n.split('=');
          value = n[1];
          param.push(n[0]);

          if (value) {
            value = $.trim(decodeURIComponent(value));

            if (value) {
              param.push(value);
            }
          }

          return param.join('=');
        });
      }
    }

    return data;
  }

  QorFilter.prototype = {
    constructor: QorFilter,

    init: function () {
      // this.parse();
      this.bind();
    },

    bind: function () {
      var options = this.options;

      this.$element.
        on(EVENT_CLICK, options.label, $.proxy(this.toggle, this)).
        on(EVENT_CHANGE, options.group, $.proxy(this.toggle, this));
    },

    unbind: function () {
      this.$element.
        off(EVENT_CLICK, this.toggle).
        off(EVENT_CHANGE, this.toggle);
    },

    /*parse: function () {
      var options = this.options;
      var $this = this.$element;
      var params = decodeSearch(location.search);

      $this.find(options.label).each(function () {
        var $this = $(this);

        $.each(decodeSearch($this.attr('href')), function (i, param) {
          var matched = $.inArray(param, params) > -1;

          $this.toggleClass('active', matched);

          if (matched) {
            return false;
          }
        });
      });

      $this.find(options.group).each(function () {
        var $this = $(this);
        var name = $this.attr('name');

        $this.find('option').each(function () {
          var $this = $(this),
              param = [name, $this.prop('value')].join('=');

          if ($.inArray(param, params) > -1) {
            $this.attr('selected', true);
            return false;
          }
        });
      });
    },*/

    toggle: function (e) {
      var $target = $(e.currentTarget);
      var data = {};
      var params;
      var param;
      var search;
      var name;
      var value;
      var index;
      var matched;

      if ($target.is('select')) {
        params = decodeSearch(location.search);
        name = $target.attr('name');
        value = $target.val();

        param = [name];

        if (value) {
          param.push(value);
        }

        param = param.join('=');
        data = [param];

        $target.children().each(function () {
          var $this = $(this);
          var param = [name];
          var value = $.trim($this.prop('value'));

          if (value) {
            param.push(value);
          }

          param = param.join('=');
          index = $.inArray(param, params);

          if (index > -1) {
            matched = param;
            return false;
          }
        });

        if (matched) {
          data.push(matched);
          search = encodeSearch(data, true);
        } else {
          search = encodeSearch(data);
        }
      } else if ($target.is('a')) {
        e.preventDefault();
        data = decodeSearch($target.attr('href'));

        if ($target.hasClass('active')) {
          search = encodeSearch(data, true); // set `true` to detach
        } else {
          search = encodeSearch(data);
        }
      }

      location.search = search;
    },

    destroy: function () {
      this.unbind();
      this.$element.removeData(NAMESPACE);
    },
  };

  QorFilter.DEFAULTS = {
    label: false,
    group: false
  };

  QorFilter.plugin = function (options) {
    return this.each(function () {
      var $this = $(this);
      var data = $this.data(NAMESPACE);
      var fn;

      if (!data) {
        if (/destroy/.test(options)) {
          return;
        }

        $this.data(NAMESPACE, (data = new QorFilter(this, options)));
      }

      if (typeof options === 'string' && $.isFunction(fn = data[options])) {
        fn.apply(data);
      }
    });
  };

  $(function () {
    var selector = '[data-toggle="qor.filter"]';
    var options = {
          label: '.qor-label',
          group: '.qor-label-group',
        };

    $(document).
      on(EVENT_DISABLE, function (e) {
        QorFilter.plugin.call($(selector, e.target), 'destroy');
      }).
      on(EVENT_ENABLE, function (e) {
        QorFilter.plugin.call($(selector, e.target), options);
      }).
      triggerHandler(EVENT_ENABLE);
  });

  return QorFilter;

});
<commit_msg>Clear search parameter<commit_after>(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as anonymous module.
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node / CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals.
    factory(jQuery);
  }
})(function ($) {

  'use strict';

  var location = window.location;
  var NAMESPACE = 'qor.filter';
  var EVENT_ENABLE = 'enable.' + NAMESPACE;
  var EVENT_DISABLE = 'disable.' + NAMESPACE;
  var EVENT_CLICK = 'click.' + NAMESPACE;
  var EVENT_CHANGE = 'change.' + NAMESPACE;

  function QorFilter(element, options) {
    this.$element = $(element);
    this.options = $.extend({}, QorFilter.DEFAULTS, $.isPlainObject(options) && options);
    this.init();
  }

  function encodeSearch(data, detached) {
    var search = location.search;
    var params;

    if ($.isArray(data)) {
      params = decodeSearch(search);

      $.each(data, function (i, param) {
        i = $.inArray(param, params);

        if (i === -1) {
          params.push(param);
        } else if (detached) {
          params.splice(i, 1);
        }
      });

      search = '?' + params.join('&');
    }

    return search;
  }

  function decodeSearch(search) {
    var data = [];

    if (search && search.indexOf('?') > -1) {
      search = search.split('?')[1];

      if (search && search.indexOf('#') > -1) {
        search = search.split('#')[0];
      }

      if (search) {
        // search = search.toLowerCase();
        data = $.map(search.split('&'), function (n) {
          var param = [];
          var value;

          n = n.split('=');
          value = n[1];
          param.push(n[0]);

          if (value) {
            value = $.trim(decodeURIComponent(value));

            if (value) {
              param.push(value);
            }
          }

          return param.join('=');
        });
      }
    }

    return data;
  }

  QorFilter.prototype = {
    constructor: QorFilter,

    init: function () {
      // this.parse();
      this.bind();
    },

    bind: function () {
      var options = this.options;

      this.$element.
        on(EVENT_CLICK, options.label, $.proxy(this.toggle, this)).
        on(EVENT_CHANGE, options.group, $.proxy(this.toggle, this));
    },

    unbind: function () {
      this.$element.
        off(EVENT_CLICK, this.toggle).
        off(EVENT_CHANGE, this.toggle);
    },

    /*parse: function () {
      var options = this.options;
      var $this = this.$element;
      var params = decodeSearch(location.search);

      $this.find(options.label).each(function () {
        var $this = $(this);

        $.each(decodeSearch($this.attr('href')), function (i, param) {
          var matched = $.inArray(param, params) > -1;

          $this.toggleClass('active', matched);

          if (matched) {
            return false;
          }
        });
      });

      $this.find(options.group).each(function () {
        var $this = $(this);
        var name = $this.attr('name');

        $this.find('option').each(function () {
          var $this = $(this),
              param = [name, $this.prop('value')].join('=');

          if ($.inArray(param, params) > -1) {
            $this.attr('selected', true);
            return false;
          }
        });
      });
    },*/

    toggle: function (e) {
      var $target = $(e.currentTarget);
      var data = [];
      var params;
      var param;
      var search;
      var name;
      var value;
      var index;
      var matched;

      if ($target.is('select')) {
        params = decodeSearch(location.search);
        name = $target.attr('name');
        value = $target.val();

        param = [name];

        if (value) {
          param.push(value);
        }

        param = param.join('=');

        if (value) {
          data.push(param);
        }

        $target.children().each(function () {
          var $this = $(this);
          var param = [name];
          var value = $.trim($this.prop('value'));

          if (value) {
            param.push(value);
          }

          param = param.join('=');
          index = $.inArray(param, params);

          if (index > -1) {
            matched = param;
            return false;
          }
        });

        if (matched) {
          data.push(matched);
          search = encodeSearch(data, true);
        } else {
          search = encodeSearch(data);
        }
      } else if ($target.is('a')) {
        e.preventDefault();
        data = decodeSearch($target.attr('href'));

        if ($target.hasClass('active')) {
          search = encodeSearch(data, true); // set `true` to detach
        } else {
          search = encodeSearch(data);
        }
      }

      location.search = search;
    },

    destroy: function () {
      this.unbind();
      this.$element.removeData(NAMESPACE);
    },
  };

  QorFilter.DEFAULTS = {
    label: false,
    group: false
  };

  QorFilter.plugin = function (options) {
    return this.each(function () {
      var $this = $(this);
      var data = $this.data(NAMESPACE);
      var fn;

      if (!data) {
        if (/destroy/.test(options)) {
          return;
        }

        $this.data(NAMESPACE, (data = new QorFilter(this, options)));
      }

      if (typeof options === 'string' && $.isFunction(fn = data[options])) {
        fn.apply(data);
      }
    });
  };

  $(function () {
    var selector = '[data-toggle="qor.filter"]';
    var options = {
          label: '.qor-label',
          group: '.qor-label-group',
        };

    $(document).
      on(EVENT_DISABLE, function (e) {
        QorFilter.plugin.call($(selector, e.target), 'destroy');
      }).
      on(EVENT_ENABLE, function (e) {
        QorFilter.plugin.call($(selector, e.target), options);
      }).
      triggerHandler(EVENT_ENABLE);
  });

  return QorFilter;

});
<|endoftext|>


<commit_before>'use strict';

describe('Service: trustLineService', function () {

  // load the service's module
  beforeEach(module('riwebApp'));

  // instantiate service
  var trustLineService;
  beforeEach(inject(function (_trustLineService_) {
    trustLineService = _trustLineService_;
  }));

  it('should do something', function () {
    expect(!!trustLineService).toBe(true);
  });

});
<commit_msg>Rename service var to TrustLineService just in case.<commit_after>'use strict';

describe('Service: TrustLineService', function () {

  // load the service's module
  beforeEach(module('riwebApp'));

  // instantiate service
  var TrustLineService;
  beforeEach(inject(function (_trustLineService_) {
    TrustLineService = _trustLineService_;
  }));

  it('should do something', function () {
    expect(!!TrustLineService).toBe(true);
  });

});
<|endoftext|>


<commit_before>import makeClass from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Styles from './Paper.css';

function Paper({backgroundColor, children, className, elevation, style, ...other}) {
  return (
    <div
      {...other}
      className={makeClass(className, Styles.root, Styles[`elevation${elevation}`])}
      style={Object.assign({}, style, {backgroundColor})}
    >
      {children}
    </div>
  );
}

Paper.defaultProps = {
  backgroundColor: '#fff',
  children: null,
  className: '',
  elevation: 1,
  style: {}
};

Paper.propTypes = {
  backgroundColor: PropTypes.string,
  children: PropTypes.node,
  className: PropTypes.string,
  elevation: PropTypes.number,
  style: PropTypes.object
};

export default Paper;
<commit_msg>[Paper] use class declaration (refs support)<commit_after>import makeClass from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Styles from './Paper.css';

class Paper extends React.Component {
  render() {
    const {backgroundColor, children, className, elevation, style, ...other} = this.props;
    return (
      <div
        {...other}
        className={makeClass(className, Styles.root, Styles[`elevation${elevation}`])}
        style={Object.assign({}, style, {backgroundColor})}
      >
        {children}
      </div>
    );
  }
}

Paper.defaultProps = {
  backgroundColor: '#fff',
  children: null,
  className: '',
  elevation: 1,
  style: {}
};

Paper.propTypes = {
  backgroundColor: PropTypes.string,
  children: PropTypes.node,
  className: PropTypes.string,
  elevation: PropTypes.number,
  style: PropTypes.object
};

export default Paper;
<|endoftext|>


<commit_before>// Returns fragment generator, where each returned fragment emits selected data for specified object

'use strict';

var aFrom           = require('es5-ext/array/from')
  , ensureIterable  = require('es5-ext/iterable/validate-object')
  , ensureString    = require('es5-ext/object/validate-stringifiable-value')
  , Set             = require('es6-set')
  , deferred        = require('deferred')
  , memoize         = require('memoizee/plain')
  , Fragment        = require('data-fragment')
  , resolveKeyPath  = require('dbjs/_setup/utils/resolve-key-path')
  , ensureStorage   = require('dbjs-persistence/ensure-storage')
  , assimilateEvent = require('./lib/assimilate-driver-event')
  , anyIdToStorage  = require('../utils/any-id-to-storage');

module.exports = function (storage, keyPaths) {
	var keyPathsArray, storagePromise;
	if (storage != null) storagePromise = deferred(ensureStorage(storage));

	keyPaths = new Set(aFrom(ensureIterable(keyPaths)));
	keyPathsArray = aFrom(keyPaths);

	return memoize(function (ownerId) {
		var fragment, promise;
		ownerId = ensureString(ownerId);
		fragment = new Fragment();
		if (storage) promise = storagePromise;
		else promise = anyIdToStorage(ownerId);
		fragment.promise = promise(function (storage) {
			storage.on('owner:' + ownerId, function (event) {
				if (event.type === 'reduced') return;
				if (!event.keyPath || keyPaths.has(event.path) || keyPaths.has(event.keyPath)) {
					if (event.type === 'direct') fragment.update(event.id, event.data);
					else assimilateEvent(fragment, event.id, event.data);
				}
			});
			return deferred(
				storage.getObject(ownerId)(function (data) {
					data.forEach(function (data) {
						var path = (data.id === ownerId) ? null : data.id.slice(data.id.indexOf('/') + 1)
						  , keyPath = path ? resolveKeyPath(data.id) : null;
						if (path && !keyPaths.has(path) && !keyPaths.has(keyPath)) return;
						fragment.update(data.id, data.data);
					});
				}),
				deferred.map(keyPathsArray, function (keyPath) {
					var id = ownerId + '/' + keyPath;
					return storage.getComputed(id)(function (data) {
						if (!data) return;
						assimilateEvent(fragment, id, data);
					});
				})
			);
		});
		return fragment;
	});
};
<commit_msg>Do not crash if storage was not resolved<commit_after>// Returns fragment generator, where each returned fragment emits selected data for specified object

'use strict';

var aFrom           = require('es5-ext/array/from')
  , ensureIterable  = require('es5-ext/iterable/validate-object')
  , ensureString    = require('es5-ext/object/validate-stringifiable-value')
  , Set             = require('es6-set')
  , deferred        = require('deferred')
  , memoize         = require('memoizee/plain')
  , Fragment        = require('data-fragment')
  , resolveKeyPath  = require('dbjs/_setup/utils/resolve-key-path')
  , ensureStorage   = require('dbjs-persistence/ensure-storage')
  , assimilateEvent = require('./lib/assimilate-driver-event')
  , anyIdToStorage  = require('../utils/any-id-to-storage');

module.exports = function (storage, keyPaths) {
	var keyPathsArray, storagePromise;
	if (storage != null) storagePromise = deferred(ensureStorage(storage));

	keyPaths = new Set(aFrom(ensureIterable(keyPaths)));
	keyPathsArray = aFrom(keyPaths);

	return memoize(function (ownerId) {
		var fragment, promise;
		ownerId = ensureString(ownerId);
		fragment = new Fragment();
		if (storage) promise = storagePromise;
		else promise = anyIdToStorage(ownerId);
		fragment.promise = promise(function (storage) {
			if (!storage) return; // Non existing id
			storage.on('owner:' + ownerId, function (event) {
				if (event.type === 'reduced') return;
				if (!event.keyPath || keyPaths.has(event.path) || keyPaths.has(event.keyPath)) {
					if (event.type === 'direct') fragment.update(event.id, event.data);
					else assimilateEvent(fragment, event.id, event.data);
				}
			});
			return deferred(
				storage.getObject(ownerId)(function (data) {
					data.forEach(function (data) {
						var path = (data.id === ownerId) ? null : data.id.slice(data.id.indexOf('/') + 1)
						  , keyPath = path ? resolveKeyPath(data.id) : null;
						if (path && !keyPaths.has(path) && !keyPaths.has(keyPath)) return;
						fragment.update(data.id, data.data);
					});
				}),
				deferred.map(keyPathsArray, function (keyPath) {
					var id = ownerId + '/' + keyPath;
					return storage.getComputed(id)(function (data) {
						if (!data) return;
						assimilateEvent(fragment, id, data);
					});
				})
			);
		});
		return fragment;
	});
};
<|endoftext|>


<commit_before>import configureFeatures from "./configure-features";
import withFeatures from "./with-features";
export default { configureFeatures, withFeatures };
<commit_msg>no reason to modify this file yet<commit_after>import components from "./components";
export default components;
<|endoftext|>


<commit_before>/* global soundManager */

require('./lib/soundmanager2');

/**
 * Class for loading music
 * @constructor
 */
var Assets = function() {
  /**
   * Loaded sounds
   * @type {object}
   */
  this.sounds = {};

  /**
   * default path for assets
   * @type {string}
   */
  this.basePath = 'assets/';

  /**
   * Default path for sound
   * @type {string}
   */
  this.soundsPath = 'sounds/';
};

/**
 * Method that creates sound object
 * @param {string} path - sound path (without base path)
 * @param {function} callback - callback function that is called when sound is loaded
 */
Assets.prototype.createSound = function(path, callback) {
  var self = this;

  soundManager.onload = function() {
    var sound = soundManager.createSound({
      autoLoad: true,
      autoPlay: false,
      url: self.basePath + self.soundsPath + path
    }).load({ onload: callback });

    self.sounds[path] = sound;
  };
};

/**
 * Load specified data
 * @param {object} data - data to load
 * @param {function} callback - function that is called when everything is loaded
 */
Assets.prototype.load = function(data, callback) {
  this.soundsPath = data.soundsPath || this.soundsPath;
  this.assetsPath = data.assetsPath || this.assetsPath;

  var soundsToLoad = data.sounds.length;

  var soundLoaded = function() {
    soundsToLoad -= 1;
    if (soundsToLoad <= 0) {
      callback();
    }
  };

  for (var i=0, len=data.sounds.length; i<len; i++) {
    var path = data.sounds[i];
    this.createSound(path, soundLoaded);
  }
};

/**
 * Get sound with specified name
 * @param {string} name - sound name
 * @return {object} sound object
 */
Assets.prototype.getSound = function(name) {
  return this.sounds[name];
};

module.exports = Assets;
<commit_msg>fix bug when there is no sound to load<commit_after>/* global soundManager */

require('./lib/soundmanager2');

/**
 * Class for loading music
 * @constructor
 */
var Assets = function() {
  /**
   * Loaded sounds
   * @type {object}
   */
  this.sounds = {};

  /**
   * default path for assets
   * @type {string}
   */
  this.basePath = 'assets/';

  /**
   * Default path for sound
   * @type {string}
   */
  this.soundsPath = 'sounds/';
};

/**
 * Method that creates sound object
 * @param {string} path - sound path (without base path)
 * @param {function} callback - callback function that is called when sound is loaded
 */
Assets.prototype.createSound = function(path, callback) {
  var self = this;

  soundManager.onload = function() {
    var sound = soundManager.createSound({
      autoLoad: true,
      autoPlay: false,
      url: self.basePath + self.soundsPath + path
    }).load({ onload: callback });

    self.sounds[path] = sound;
  };
};

/**
 * Load specified data
 * @param {object} data - data to load
 * @param {function} callback - function that is called when everything is loaded
 */
Assets.prototype.load = function(data, callback) {
  this.assetsPath = data.assetsPath || this.assetsPath;

  if (!data.sounds) {
    callback();
  } else {
    this.soundsPath = data.soundsPath || this.soundsPath;

    var soundsToLoad = data.sounds.length;

    var soundLoaded = function() {
      soundsToLoad -= 1;
      if (soundsToLoad <= 0) {
        callback();
      }
    };

    for (var i=0, len=data.sounds.length; i<len; i++) {
      var path = data.sounds[i];
      this.createSound(path, soundLoaded);
    }
  }
};

/**
 * Get sound with specified name
 * @param {string} name - sound name
 * @return {object} sound object
 */
Assets.prototype.getSound = function(name) {
  return this.sounds[name];
};

module.exports = Assets;
<|endoftext|>


<commit_before>var fs = require('fs');

var Critic = function(play){
	this.play = play;
	this.failures = [];
	this.successes = [];
	this.newLines = [];
}

Critic.prototype.record = function(hash){
	if(hash['type'] == 'recording'){
		this.newLines.push(hash);

	}else if(hash['type'] == 'success'){
		this.successes.push(hash);

	}else{
		this.newLines.push(hash);
	}
}

Critic.prototype.writeReview = function(callback){
	var today = new Date(),
			file = process.cwd() + '/review-play' + this.play + '_' + today.getYear() + '-' + today.getMonth() + '-' + today.getDay() + '.log';

	var review = '',
			completed = 0;

	if(_.size(this.newLines) > 0){
		review += '\r\nNEW SCENES\r\n----------------------------------------\r\n'
		_.forEach(this.newLines, function(line){
			review += '.... Scene ' + line['scene'] + ', Actor ' + line['actor'] + ': ' + line['actual'] + '\r\n';
			completed++;
		});
	}

	if(_.size(this.failures) > 0){
		review += '\r\nFAILURES\r\n----------------------------------------\r\n'
		_.forEach(this.failures, function(line){
			review += '.... Scene ' + line['scene'] + ', Actor ' + line['actor'] + ': Expected "' + line['expected'] + '" but got "' +
												line['actual'] + '"\r\n';
			completed++;
		});
	}

	if(_.size(this.successes) > 0){
		review += '\r\nSUCCESSES\r\n----------------------------------------\r\n'
		_.forEach(this.successes, function(line){
			review += '.... Scene ' + line['scene'] + ', Actor ' + line['actor'] + '\r\n';
			completed++;
		});
	}

	var waitForReview = setInterval(function(){
		if(completed >= (_.size(this.failures) + _.size(this.successes) + _.size(this.newLines))){
			clearInterval(waitForReview);

		  fs.writeFile(file, review, 'utf8', function(err){
		    if(err){
		    	console.log(err);
					console.log(err.stack);
		    }
				callback("Completed the rehearsal for Play-" + this.play + " check the critic's review at " + file + " for full details!");
		  });
		}
	}, 50);
}

module.exports = Critic;<commit_msg>Fixed issue where failures were being recorded in the new lines slot<commit_after>var fs = require('fs');

var Critic = function(play){
	this.play = play;
	this.failures = [];
	this.successes = [];
	this.newLines = [];
}

Critic.prototype.record = function(hash){
	if(hash['type'] == 'recording'){
		this.newLines.push(hash);

	}else if(hash['type'] == 'success'){
		this.successes.push(hash);

	}else{
		this.failures.push(hash);
	}
}

Critic.prototype.writeReview = function(callback){
	var today = new Date(),
			file = process.cwd() + '/review-play' + this.play + '_' + today.getYear() + '-' + today.getMonth() + '-' + today.getDay() + '.log';

	var review = '',
			completed = 0;

	if(_.size(this.newLines) > 0){
		review += '\r\nNEW SCENES\r\n----------------------------------------\r\n'
		_.forEach(this.newLines, function(line){
			review += '.... Scene ' + line['scene'] + ', Actor ' + line['actor'] + ': ' + line['actual'] + '\r\n';
			completed++;
		});
	}

	if(_.size(this.failures) > 0){
		review += '\r\nFAILURES\r\n----------------------------------------\r\n'
		_.forEach(this.failures, function(line){
			review += '.... Scene ' + line['scene'] + ', Actor ' + line['actor'] + ': Expected "' + line['expected'] + '" but got "' +
												line['actual'] + '"\r\n';
			completed++;
		});
	}

	if(_.size(this.successes) > 0){
		review += '\r\nSUCCESSES\r\n----------------------------------------\r\n'
		_.forEach(this.successes, function(line){
			review += '.... Scene ' + line['scene'] + ', Actor ' + line['actor'] + '\r\n';
			completed++;
		});
	}

	var waitForReview = setInterval(function(){
		if(completed >= (_.size(this.failures) + _.size(this.successes) + _.size(this.newLines))){
			clearInterval(waitForReview);

		  fs.writeFile(file, review, 'utf8', function(err){
		    if(err){
		    	console.log(err);
					console.log(err.stack);
		    }
				callback("Completed the rehearsal for Play-" + this.play + " check the critic's review at " + file + " for full details!");
		  });
		}
	}, 50);
}

module.exports = Critic;<|endoftext|>