<commit_before>var path = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec,
    argv = require('minimist')(process.argv.slice(2)),
    gulp = require('gulp'),
    gutil = require('gulp-util');

var create = function(generatorPath, options) {
  if (argv._.length < 2) {
    gutil.log(gutil.colors.red("[-Error:] Missing directory name."), "ex: em new my-app");
    gutil.log(gutil.colors.red("[-Error:]"), "See 'em new --help'");
    process.exit(0);
  }
  // checking the url prefix
  var re = /^http(?:s)?:\/\//,
      userInputPath = options.path,
      // check for the mode, is running test or not
      isRunningTest = options.test || false,
      // check for remote URL path
      remoteUrl = ( userInputPath ) ? ( re.test(userInputPath) ) ? userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath(),
      // get the full path to the ember application or take the generator from github or an URL
      // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
      skeletonsAppPath = getSkeletonsAppPath();

  if (fs.existsSync(generatorPath)) {
    gutil.log(gutil.colors.red('[-Error:]'), 'The folder name', gutil.colors.red(generatorPath), 'has existed in this directory tree!' );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  var currentAppPath = path.resolve(generatorPath);
  // Setup gulp task, copy the source files into the newly create folder
  setupTask (skeletonsCorePath, skeletonsAppPath, currentAppPath, isRunningTest);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;

function setupTask (coreSrcPath, appSrcPath, dest, isRunningTest) {
  gutil.log(gutil.colors.gray("[-log:]"), "Starting to generate an application at", gutil.colors.cyan(dest));

  var coreSrc = [ coreSrcPath + '/**', coreSrcPath + '/**/.*' ],
      appSrc = [ appSrcPath + '/**' ];

  return gulp.task('generator', function (callback) {
      gulp.src(coreSrc)
          .on('end', function() {
              gutil.log(gutil.colors.green('[-done:] A new'),  gutil.colors.cyan('Node.js'),  gutil.colors.green('web server have been successfully created!') );
          })
          .pipe(gulp.dest(dest));

      gulp.src(appSrc)
          .on('end', function() {
              gutil.log(gutil.colors.green('[-done:] A new'),  gutil.colors.cyan('Ember.js'),  gutil.colors.green('mvc application have been successfully created!') );
              if( !isRunningTest ) {
                installNpm( dest, callback );
              } else {
                callback();
              }
          })
          .pipe(gulp.dest(dest+'/client/app'));
  });
}

function installNpm (rootPath, callback) {
  installer ( rootPath, 'npm install', 'NPM is installing node packages...', installBower, callback );
}

function installBower (rootPath, callback) {
  installer ( rootPath, 'bower install', 'Bower is installing javascript packages...', gitInit, callback );
}

function gitInit(rootPath, callback) {
    gutil.log(gutil.colors.gray("[-log:]"), gutil.colors.cyan('em-cli'), 'is doing REALLY hard to initialize your repo ...');

    rootPath = rootPath || process.cwd();
    process.chdir(rootPath);
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        today = new Date(),
        todayDate = today.getDate(),
        todayMonth = month[today.getMonth()],
        todayYear = today.getFullYear(),
        command = 'git init && git add . && git commit -m "Initial Commit @ ' + todayMonth + ' ' + todayDate + ', ' + todayYear + '"';
    return exec(command, function(error, stdout, stderr) {
        if (error !== null) {
          var log = stderr.toString();
          gutil.log( gutil.colors.red('[-Error:] ' + log) );
          return callback(log);
        }
        gutil.log(gutil.colors.green("[-done:] Initialized a new git repo and did a first commit") );
        gutil.log(gutil.colors.bold("[-copy:] =>"), gutil.colors.cyan('cd ' + argv._[1]), gutil.colors.gray('# navigate to the newly created application') );
        callback();
    });
}

// installer plugins to handle the npm and bower packages installation
function installer ( rootPath, command, description, nextStepFn, callback ) {
  rootPath = rootPath || process.cwd();
  gutil.log(gutil.colors.gray("[-log:]"), description);
  process.chdir(rootPath);
  return exec(command, function(error, stdout, stderr) {
    //process.chdir(rootPath);
    if (error !== null) {
      var log = stderr.toString();
      gutil.log( gutil.colors.red('[-Error:] ' + log) );
      return callback(log);
    }
    nextStepFn(rootPath, callback);
  });
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}
<commit_msg>add a relative path cleanup for the dest folder path<commit_after>var path = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec,
    argv = require('minimist')(process.argv.slice(2)),
    tildify = require('tildify'),
    gulp = require('gulp'),
    gutil = require('gulp-util');

var create = function(generatorPath, options) {
  if (argv._.length < 2) {
    gutil.log(gutil.colors.red("[-Error:] Missing directory name."), "ex: em new my-app");
    gutil.log(gutil.colors.red("[-Error:]"), "See 'em new --help'");
    process.exit(0);
  }
  // checking the url prefix
  var re = /^http(?:s)?:\/\//,
      userInputPath = options.path,
      // check for the mode, is running test or not
      isRunningTest = options.test || false,
      // check for remote URL path
      remoteUrl = ( userInputPath ) ? ( re.test(userInputPath) ) ? userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath(),
      // get the full path to the ember application or take the generator from github or an URL
      // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
      skeletonsAppPath = getSkeletonsAppPath();

  if (fs.existsSync(generatorPath)) {
    gutil.log(gutil.colors.red('[-Error:]'), 'The folder name', gutil.colors.red(generatorPath), 'has existed in this directory tree!' );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  var currentAppPath = path.resolve(generatorPath);
  // Setup gulp task, copy the source files into the newly create folder
  setupTask (skeletonsCorePath, skeletonsAppPath, currentAppPath, isRunningTest);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;

function setupTask (coreSrcPath, appSrcPath, dest, isRunningTest) {
  gutil.log(gutil.colors.gray("[-log:]"), "Starting to generate an application at", gutil.colors.cyan( tildify(dest) ));

  var coreSrc = [ coreSrcPath + '/**', coreSrcPath + '/**/.*' ],
      appSrc = [ appSrcPath + '/**' ];

  return gulp.task('generator', function (callback) {
      gulp.src(coreSrc)
          .on('end', function() {
              gutil.log(gutil.colors.green('[-done:] A new'),  gutil.colors.cyan('Node.js'),  gutil.colors.green('web server have been successfully created!') );
          })
          .pipe(gulp.dest(dest));

      gulp.src(appSrc)
          .on('end', function() {
              gutil.log(gutil.colors.green('[-done:] A new'),  gutil.colors.cyan('Ember.js'),  gutil.colors.green('mvc application have been successfully created!') );
              if( !isRunningTest ) {
                installNpm( dest, callback );
              } else {
                callback();
              }
          })
          .pipe(gulp.dest(dest+'/client/app'));
  });
}

function installNpm (rootPath, callback) {
  installer ( rootPath, 'npm install', 'NPM is installing node packages...', installBower, callback );
}

function installBower (rootPath, callback) {
  installer ( rootPath, 'bower install', 'Bower is installing javascript packages...', gitInit, callback );
}

function gitInit(rootPath, callback) {
    gutil.log(gutil.colors.gray("[-log:]"), gutil.colors.cyan('em-cli'), 'is doing REALLY hard to initialize your repo ...');

    rootPath = rootPath || process.cwd();
    process.chdir(rootPath);
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        today = new Date(),
        todayDate = today.getDate(),
        todayMonth = month[today.getMonth()],
        todayYear = today.getFullYear(),
        command = 'git init && git add . && git commit -m "Initial Commit @ ' + todayMonth + ' ' + todayDate + ', ' + todayYear + '"';
    return exec(command, function(error, stdout, stderr) {
        if (error !== null) {
          var log = stderr.toString();
          gutil.log( gutil.colors.red('[-Error:] ' + log) );
          return callback(log);
        }
        gutil.log(gutil.colors.green("[-done:] Initialized a new git repo and did a first commit") );
        gutil.log(gutil.colors.bold("[-copy:] =>"), gutil.colors.cyan('cd ' + argv._[1]), gutil.colors.gray('# navigate to the newly created application') );
        callback();
    });
}

// installer plugins to handle the npm and bower packages installation
function installer ( rootPath, command, description, nextStepFn, callback ) {
  rootPath = rootPath || process.cwd();
  gutil.log(gutil.colors.gray("[-log:]"), description);
  process.chdir(rootPath);
  return exec(command, function(error, stdout, stderr) {
    //process.chdir(rootPath);
    if (error !== null) {
      var log = stderr.toString();
      gutil.log( gutil.colors.red('[-Error:] ' + log) );
      return callback(log);
    }
    nextStepFn(rootPath, callback);
  });
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}
<|endoftext|>


<commit_before>const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const Mainloop = imports.mainloop;
const CodeWriter = imports.codeWriter;
const Utils = imports.utils;
const NoFlo = imports.noflo;
const Fbp = require('fbp');

let normalizeName = function(name) {
    return name.replace('noflo-', '');
};

/* Module listing */

let getModuleAtPath = function(vpath, alternativeFile) {
    let path = Utils.resolvePath(vpath);

    if (!GLib.file_test(path, GLib.FileTest.IS_DIR))
        return null;

    let manifestPath = path + (alternativeFile ? alternativeFile : '/component.json');
    if (!GLib.file_test(manifestPath, GLib.FileTest.IS_REGULAR))
        return null;

    let file = Gio.File.new_for_path(manifestPath);
    let [, manifestContent] = file.load_contents(null);
    let manifest;

    let module;
    try {
        module = JSON.parse('' + manifestContent);
        module.vpath = vpath;
        module.path = path;
        module.normalizedName = normalizeName(module.name);
    } catch (e) {
        return null;
    }

    /* Quick sanity check */
    if (!module.name ||
        !module.noflo)
        return null;

    return module;
};

let getModulesInPath = function(vpath) {
    let modules = {};
    let path = Utils.resolvePath(vpath);

    if (!GLib.file_test(path, GLib.FileTest.IS_DIR))
        return modules;

    Utils.forEachInDirectory(Gio.File.new_for_path(path), false, function(child) {
        let module = getModuleAtPath(Utils.buildPath(vpath,
                                                     child.get_basename()));

        if (module)
            modules[module.name] = module;
    });

    return modules;
};

let getModules = function(paths) {
    let modules = {};
    for (let i in paths) {
        Utils.mergeProps(modules, getModulesInPath(paths[i]));
    }
    return modules;
};

/* Component loader to be injected into the runtime base */

let ComponentLoader = function(options) {
    let self = this;

    /* Ensure with have valid options */
    self.options = options;
    if (!self.options || !self.options.paths)
        self.options = { paths: [ 'library://components' ] };

    self.applicationName = null;
    self.mainGraphName = null;
    self.mainGraph = null;
    self.modules = {};
    self.components = {};

    let removeExtension = function(path) {
        let ret = path.replace(/\.coffee$/, '');
        return ret.replace(/\.js$/, '');
    };

    /* Components */

    let generateComponentInstance = function(vpath) {
        return function(metadata) {
            if (!this.implementation)
                this.implementation = require(vpath);
            let instance = this.implementation.getComponent(metadata);
            return instance;
        };
    };

    let generateComponentCodeLoader = function(path) {
        return function() {
            let file = Gio.File.new_for_path(Utils.resolvePath(path));
            let [, code] = file.load_contents(null);
            return '' + code;
        };
    };

    /* Graphs */

    let generateGraphCodeLoader = function(vpath) {
        return function() {
            try {
                let path = Utils.resolvePath(vpath);
                let source = Utils.loadTextFileContent(path);
                return source;
            } catch (e) {
                log('Failed to load graph : ' + vpath);
                throw e;
            }
            return null;
        };
    };

    let generateGraphDefinition = function(vpath) {
        return function() {
            try {
                let path = Utils.resolvePath(vpath);
                let source = Utils.loadTextFileContent(path);
                let def;
                if (path.indexOf('.fbp') >= 0)
                    def = Fbp.parse(source);
                else
                    def = JSON.parse(source);
                def.properties = {
                    name: this.name,
                    id: this.name,
                };
                return def;
            } catch (e) {
                log('Failed to load graph definition : ' + vpath + ' : ' + e.message);
                throw e;
            }
            return null;
        };
    };

    let generateGraphLoader = function() {
        return function(metadata) {
            let graph = NoFlo.NoFlo.graph.loadJSON(
                this.getDefinition(),
                function(a) { return a; },
                metadata);
            graph.baseDir = self.options.baseDir;
            return graph;
        };
    };

    /**/

    let getComponentFullPath = function(module, component) {
        return module.vpath + '/' + module.noflo.components[component];
    };

    let getGraphFullPath = function(module, component) {
        return module.vpath + '/' + module.noflo.graphs[component];
    };

    let getComponentRequirePath = function(module, component) {
        return removeExtension(getComponentFullPath(module, component));
    };

    /**/

    self._loadModule = function(module) {
        // Avoid circular dependencies
        if (module.loading || module.loaded)
            return;
        module.loading = true;

        // Try to load dependencies first
        if (module.dependencies) {
            for (let depName in module.dependencies) {
                let dep = /[^\/]+\/(.*)/.exec(depName);
                if (dep && dep[1] && self.modules[dep[1]])
                    self._loadModule(self.modules[dep[1]]);
            }
        }

        // Components
        for (let componentName in module.noflo.components) {
            let path = normalizeName(module.name + '/' + componentName);
            let fullPath = getComponentFullPath(module, componentName);
            let requirePath = removeExtension(fullPath);
            self.components[path] = {
                path: fullPath,
                isGraph: false,
                module: module,
                moduleName: normalizeName(module.name),
                name: componentName,
                create: generateComponentInstance(requirePath),
                getCode: generateComponentCodeLoader(fullPath),
                language: Utils.guessLanguageFromFilename(fullPath),
            };
        }

        // Graphs
        for (let graphName in module.noflo.graphs) {
            let path = normalizeName(module.name + '/' + graphName);
            let fullPath = getGraphFullPath(module, graphName);
            let component = {
                path: fullPath,
                isGraph: true,
                module: module,
                moduleName: normalizeName(module.name),
                name: graphName,
                getDefinition: generateGraphDefinition(fullPath),
                getCode: generateGraphCodeLoader(fullPath),
                create: generateGraphLoader(path),
                language: 'json',
            };

            if (module.name == self.applicationName &&
                graphName == self.mainGraphName)
                self.mainGraph = component;
            else
                self.components[path] = component;
        }

        // Loaders
        if (module.noflo.loader) {
            let path = module.vpath + '/' + module.noflo.loader;
            path = removeExtension(path);
            let loader = require(path);
            loader(self);
        }

        delete module.loading;
        module.loaded = true;
    };

    self.loadModules = function() {
        // Load libray modules
        self.modules = getModules(self.options.paths);
        // Load application components/graphs
        let appModule = getModuleAtPath('local://', 'manifest.json');
        self.applicationName = appModule.name;
        self.mainGraphName = appModule.noflo.main;
        self.modules[appModule.name] = appModule;

        for (let moduleName in self.modules) {
            self._loadModule(self.modules[moduleName]);
            //log('loading ' + moduleName);
        }
    };

    self.listComponents = function(callback) {
        callback(self.components);
    };

    self.load = function(name, callback, delayed, metadata) {
        //log('load name=' + name);
        let item = self.components[name];
        if (!item)
            throw new Error('Component ' + name + ' not available');

        if (item.isGraph)
            self._loadGraph(item, delayed, metadata, callback);
        else
            self._loadComponent(item, metadata, callback);
    };

    self._loadComponent = function(item, metadata, callback) {

        Mainloop.timeout_add(0, Lang.bind(this, function() {
            try {
                callback(item.create(metadata));
            } catch (e) {
                log('Cannot load component ' + item.name +
                    ' ' + item.path + ' : ' + e.message);
            }
            return false;
        }));
    }

    self._loadGraph = function(item, delayed, metadata, callback) {
        //log('loadGraph ' + item.name);
        let graph = NoFlo.Graph.getComponent(metadata);
        let graphSocket = NoFlo.internalSocket.createSocket();
        graph.loader = self;
        graph.baseDir = self.options.baseDir

        if (delayed) {
            let delaySocket = NoFlo.internalSocket.createSocket();
            graph.inPorts.start.attach(delaySocket);
        }

        graph.inPorts.graph.attach(graphSocket);

        try {
            graphSocket.send(item.create(metadata));
            graphSocket.disconnect();
            graph.inPorts.remove('graph');
            graph.inPorts.remove('start');
            graph.setIcon('sitemap');
            callback(graph);
        } catch (e) {
            log('Cannot load graph ' + item.name +
                ' ' + item.path + ' : ' + e.message);
        }
    };

    self.registerComponent = function(packageId, name, constructor) {
        let path = (packageId != '') ? (packageId + '/' + name) : name;

        if (self.components[path]) {
            log('Dismissing registration for ' + path);
            return;
        }

        self.components[path] = {
            path: 'unknown',
            module: null,
            name: name,
            create: constructor,
            getCode: function() { return ''; },
            language: 'javascript'
        };
        //log('registerComponent ' + packageId + ' / ' + name);
    };

    self.registerGraph = function(packageId, name, gPath, callback) {
        log('----------> registerGraph ' + packageId + ' / ' + name);
        throw new Error('registerGraph ' + packageId + ' / ' + name);
    };

    /**/

    self.setSource = function(packageId, name, source, language, callback) {
        log('setSource ' + packageId + ' / ' + name);
    };

    self.getSource = function(name, callback) {
        let item = self.components[name];
        if (item) {
            try {
                //log(JSON.stringify(item.getCode()));
                callback(null, { name: item.name,
                                 library: item.moduleName,
                                 code: item.getCode(),
                                 language: item.language
                               });
            } catch (e) {
                log('error loading ' + name + ' : ' + e.message);
                callback(new Error("Cannot load source code for " +
                                   name + " : " + e.message));
            }
        } else {
            log('Unknown component ' + name);
            callback(new Error('Unknown component ' + name));
        }
    };

    self.getGraphDefinition = function(name, callback) {
        let item = self.components[name];

        if (item) {
            try {
                let descr = item.getDefinition();
                callback(null, descr);
            } catch (e) {
                log('error loading ' + name + ' : ' + e.message);
                callback(new Error("Cannot load definition for " +
                                   name + " : " + e.message));
            }
        } else {
            log('Unknown graph ' + name);
            callback(new Error('Unknown graph ' + name));
        }
    };

    /**/

    self.getComponentModule = function(name) {
        let item = self.components[name];
        if (item)
            return item.module;
        return null;
    };

    self.getComponentCode = function(name) {
        //log('Looking up component : ' + name);
        let item = self.components[name];
        if (item)
            return item.getCode();
        return null;
    };

    /**/

    self.save = function(runtime) {
        log('Saving graphs!');
        for (let i in runtime.graph.graphs) {
            let graph = runtime.graph.graphs[i];
            CodeWriter.writeGraph(graph);
        }
    };

    self._saveCb = function() {
        self.save(self._runtime);
        self._saveTimeout = null;
        return false;
    };

    self._graphUpdate = function() {
        if (self._saveTimeout)
            Mainloop.source_remove(self._saveTimeout);
        self._saveTimeout =
            Mainloop.timeout_add(1000, Lang.bind(self, self._saveCb));
    };

    self.autosave = function(runtime) {
        log('autosave!');
        self._runtime = runtime;
        for (let i in runtime.graph.graphs) {
            let graph = runtime.graph.graphs[i];
            log('listening on ' + graph.name);
            graph.on('endTransaction', Lang.bind(self, self._graphUpdate));
        }
   };

    /**/

    self._installGraphs = function(runtime) {
        for (let graphName in self.modules[self.applicationName].noflo.graphs) {
            let path = self.applicationName + '/' + graphName;
            let component = self.components[path];

            if (component)
                runtime.graph.registerGraph(graphName, component.create());
        }
        runtime.graph.registerGraph(self.mainGraphName,
                                    self.mainGraph.create());
    };

    self._installNetwork = function(runtime) {
        let path = self.mainGraphName;
        let component = self.components[path];

        runtime.network.initNetwork(runtime.graph.graphs[path],
                                    { graph: path, },
                                    '');
    };

    /**/

    self.install = function(runtime) {
        self.loadModules();
        self._installGraphs(runtime);
        self._installNetwork(runtime);
    };
};
<commit_msg>runtime: componentLoader: show console error on component load problem<commit_after>const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const Mainloop = imports.mainloop;
const CodeWriter = imports.codeWriter;
const Utils = imports.utils;
const NoFlo = imports.noflo;
const Fbp = require('fbp');

let normalizeName = function(name) {
    return name.replace('noflo-', '');
};

/* Module listing */

let getModuleAtPath = function(vpath, alternativeFile) {
    let path = Utils.resolvePath(vpath);

    if (!GLib.file_test(path, GLib.FileTest.IS_DIR))
        return null;

    let manifestPath = path + (alternativeFile ? alternativeFile : '/component.json');
    if (!GLib.file_test(manifestPath, GLib.FileTest.IS_REGULAR))
        return null;

    let file = Gio.File.new_for_path(manifestPath);
    let [, manifestContent] = file.load_contents(null);
    let manifest;

    let module;
    try {
        module = JSON.parse('' + manifestContent);
        module.vpath = vpath;
        module.path = path;
        module.normalizedName = normalizeName(module.name);
    } catch (e) {
        return null;
    }

    /* Quick sanity check */
    if (!module.name ||
        !module.noflo)
        return null;

    return module;
};

let getModulesInPath = function(vpath) {
    let modules = {};
    let path = Utils.resolvePath(vpath);

    if (!GLib.file_test(path, GLib.FileTest.IS_DIR))
        return modules;

    Utils.forEachInDirectory(Gio.File.new_for_path(path), false, function(child) {
        let module = getModuleAtPath(Utils.buildPath(vpath,
                                                     child.get_basename()));

        if (module)
            modules[module.name] = module;
    });

    return modules;
};

let getModules = function(paths) {
    let modules = {};
    for (let i in paths) {
        Utils.mergeProps(modules, getModulesInPath(paths[i]));
    }
    return modules;
};

/* Component loader to be injected into the runtime base */

let ComponentLoader = function(options) {
    let self = this;

    /* Ensure with have valid options */
    self.options = options;
    if (!self.options || !self.options.paths)
        self.options = { paths: [ 'library://components' ] };

    self.applicationName = null;
    self.mainGraphName = null;
    self.mainGraph = null;
    self.modules = {};
    self.components = {};

    let removeExtension = function(path) {
        let ret = path.replace(/\.coffee$/, '');
        return ret.replace(/\.js$/, '');
    };

    /* Components */

    let generateComponentInstance = function(vpath) {
        return function(metadata) {
            if (!this.implementation)
                this.implementation = require(vpath);
            let instance = this.implementation.getComponent(metadata);
            return instance;
        };
    };

    let generateComponentCodeLoader = function(path) {
        return function() {
            let file = Gio.File.new_for_path(Utils.resolvePath(path));
            try {
                let [, code] = file.load_contents(null);
                return '' + code;
            } catch (e) {
                log('Fail to load component : ' + path);
                throw e;
            }
            return null;
        };
    };

    /* Graphs */

    let generateGraphCodeLoader = function(vpath) {
        return function() {
            try {
                let path = Utils.resolvePath(vpath);
                let source = Utils.loadTextFileContent(path);
                return source;
            } catch (e) {
                log('Failed to load graph : ' + vpath);
                throw e;
            }
            return null;
        };
    };

    let generateGraphDefinition = function(vpath) {
        return function() {
            try {
                let path = Utils.resolvePath(vpath);
                let source = Utils.loadTextFileContent(path);
                let def;
                if (path.indexOf('.fbp') >= 0)
                    def = Fbp.parse(source);
                else
                    def = JSON.parse(source);
                def.properties = {
                    name: this.name,
                    id: this.name,
                };
                return def;
            } catch (e) {
                log('Failed to load graph definition : ' + vpath + ' : ' + e.message);
                throw e;
            }
            return null;
        };
    };

    let generateGraphLoader = function() {
        return function(metadata) {
            let graph = NoFlo.NoFlo.graph.loadJSON(
                this.getDefinition(),
                function(a) { return a; },
                metadata);
            graph.baseDir = self.options.baseDir;
            return graph;
        };
    };

    /**/

    let getComponentFullPath = function(module, component) {
        return module.vpath + '/' + module.noflo.components[component];
    };

    let getGraphFullPath = function(module, component) {
        return module.vpath + '/' + module.noflo.graphs[component];
    };

    let getComponentRequirePath = function(module, component) {
        return removeExtension(getComponentFullPath(module, component));
    };

    /**/

    self._loadModule = function(module) {
        // Avoid circular dependencies
        if (module.loading || module.loaded)
            return;
        module.loading = true;

        // Try to load dependencies first
        if (module.dependencies) {
            for (let depName in module.dependencies) {
                let dep = /[^\/]+\/(.*)/.exec(depName);
                if (dep && dep[1] && self.modules[dep[1]])
                    self._loadModule(self.modules[dep[1]]);
            }
        }

        // Components
        for (let componentName in module.noflo.components) {
            let path = normalizeName(module.name + '/' + componentName);
            let fullPath = getComponentFullPath(module, componentName);
            let requirePath = removeExtension(fullPath);
            self.components[path] = {
                path: fullPath,
                isGraph: false,
                module: module,
                moduleName: normalizeName(module.name),
                name: componentName,
                create: generateComponentInstance(requirePath),
                getCode: generateComponentCodeLoader(fullPath),
                language: Utils.guessLanguageFromFilename(fullPath),
            };
        }

        // Graphs
        for (let graphName in module.noflo.graphs) {
            let path = normalizeName(module.name + '/' + graphName);
            let fullPath = getGraphFullPath(module, graphName);
            let component = {
                path: fullPath,
                isGraph: true,
                module: module,
                moduleName: normalizeName(module.name),
                name: graphName,
                getDefinition: generateGraphDefinition(fullPath),
                getCode: generateGraphCodeLoader(fullPath),
                create: generateGraphLoader(path),
                language: 'json',
            };

            if (module.name == self.applicationName &&
                graphName == self.mainGraphName)
                self.mainGraph = component;
            else
                self.components[path] = component;
        }

        // Loaders
        if (module.noflo.loader) {
            let path = module.vpath + '/' + module.noflo.loader;
            path = removeExtension(path);
            let loader = require(path);
            loader(self);
        }

        delete module.loading;
        module.loaded = true;
    };

    self.loadModules = function() {
        // Load libray modules
        self.modules = getModules(self.options.paths);
        // Load application components/graphs
        let appModule = getModuleAtPath('local://', 'manifest.json');
        self.applicationName = appModule.name;
        self.mainGraphName = appModule.noflo.main;
        self.modules[appModule.name] = appModule;

        for (let moduleName in self.modules) {
            self._loadModule(self.modules[moduleName]);
            //log('loading ' + moduleName);
        }
    };

    self.listComponents = function(callback) {
        callback(self.components);
    };

    self.load = function(name, callback, delayed, metadata) {
        //log('load name=' + name);
        let item = self.components[name];
        if (!item)
            throw new Error('Component ' + name + ' not available');

        if (item.isGraph)
            self._loadGraph(item, delayed, metadata, callback);
        else
            self._loadComponent(item, metadata, callback);
    };

    self._loadComponent = function(item, metadata, callback) {

        Mainloop.timeout_add(0, Lang.bind(this, function() {
            try {
                callback(item.create(metadata));
            } catch (e) {
                log('Cannot load component ' + item.name +
                    ' ' + item.path + ' : ' + e.message);
            }
            return false;
        }));
    }

    self._loadGraph = function(item, delayed, metadata, callback) {
        //log('loadGraph ' + item.name);
        let graph = NoFlo.Graph.getComponent(metadata);
        let graphSocket = NoFlo.internalSocket.createSocket();
        graph.loader = self;
        graph.baseDir = self.options.baseDir

        if (delayed) {
            let delaySocket = NoFlo.internalSocket.createSocket();
            graph.inPorts.start.attach(delaySocket);
        }

        graph.inPorts.graph.attach(graphSocket);

        try {
            graphSocket.send(item.create(metadata));
            graphSocket.disconnect();
            graph.inPorts.remove('graph');
            graph.inPorts.remove('start');
            graph.setIcon('sitemap');
            callback(graph);
        } catch (e) {
            log('Cannot load graph ' + item.name +
                ' ' + item.path + ' : ' + e.message);
        }
    };

    self.registerComponent = function(packageId, name, constructor) {
        let path = (packageId != '') ? (packageId + '/' + name) : name;

        if (self.components[path]) {
            log('Dismissing registration for ' + path);
            return;
        }

        self.components[path] = {
            path: 'unknown',
            module: null,
            name: name,
            create: constructor,
            getCode: function() { return ''; },
            language: 'javascript'
        };
        //log('registerComponent ' + packageId + ' / ' + name);
    };

    self.registerGraph = function(packageId, name, gPath, callback) {
        log('----------> registerGraph ' + packageId + ' / ' + name);
        throw new Error('registerGraph ' + packageId + ' / ' + name);
    };

    /**/

    self.setSource = function(packageId, name, source, language, callback) {
        log('setSource ' + packageId + ' / ' + name);
    };

    self.getSource = function(name, callback) {
        let item = self.components[name];
        if (item) {
            try {
                //log(JSON.stringify(item.getCode()));
                callback(null, { name: item.name,
                                 library: item.moduleName,
                                 code: item.getCode(),
                                 language: item.language
                               });
            } catch (e) {
                log('error loading ' + name + ' : ' + e.message);
                callback(new Error("Cannot load source code for " +
                                   name + " : " + e.message));
            }
        } else {
            log('Unknown component ' + name);
            callback(new Error('Unknown component ' + name));
        }
    };

    self.getGraphDefinition = function(name, callback) {
        let item = self.components[name];

        if (item) {
            try {
                let descr = item.getDefinition();
                callback(null, descr);
            } catch (e) {
                log('error loading ' + name + ' : ' + e.message);
                callback(new Error("Cannot load definition for " +
                                   name + " : " + e.message));
            }
        } else {
            log('Unknown graph ' + name);
            callback(new Error('Unknown graph ' + name));
        }
    };

    /**/

    self.getComponentModule = function(name) {
        let item = self.components[name];
        if (item)
            return item.module;
        return null;
    };

    self.getComponentCode = function(name) {
        //log('Looking up component : ' + name);
        let item = self.components[name];
        if (item)
            return item.getCode();
        return null;
    };

    /**/

    self.save = function(runtime) {
        log('Saving graphs!');
        for (let i in runtime.graph.graphs) {
            let graph = runtime.graph.graphs[i];
            CodeWriter.writeGraph(graph);
        }
    };

    self._saveCb = function() {
        self.save(self._runtime);
        self._saveTimeout = null;
        return false;
    };

    self._graphUpdate = function() {
        if (self._saveTimeout)
            Mainloop.source_remove(self._saveTimeout);
        self._saveTimeout =
            Mainloop.timeout_add(1000, Lang.bind(self, self._saveCb));
    };

    self.autosave = function(runtime) {
        log('autosave!');
        self._runtime = runtime;
        for (let i in runtime.graph.graphs) {
            let graph = runtime.graph.graphs[i];
            log('listening on ' + graph.name);
            graph.on('endTransaction', Lang.bind(self, self._graphUpdate));
        }
   };

    /**/

    self._installGraphs = function(runtime) {
        for (let graphName in self.modules[self.applicationName].noflo.graphs) {
            let path = self.applicationName + '/' + graphName;
            let component = self.components[path];

            if (component)
                runtime.graph.registerGraph(graphName, component.create());
        }
        runtime.graph.registerGraph(self.mainGraphName,
                                    self.mainGraph.create());
    };

    self._installNetwork = function(runtime) {
        let path = self.mainGraphName;
        let component = self.components[path];

        runtime.network.initNetwork(runtime.graph.graphs[path],
                                    { graph: path, },
                                    '');
    };

    /**/

    self.install = function(runtime) {
        self.loadModules();
        self._installGraphs(runtime);
        self._installNetwork(runtime);
    };
};
<|endoftext|>


<commit_before>angular.module('gateways', [])
.factory('gateways', function($http) {
  var defaultGateways;
  var custom;

  //load gateways list from API
  var promise = $http.get(API + '/gateways').success(function (data) {
    var normalized;
    var gateway;
    var currency;

    defaultGateways = data;
    custom = store.session.get('userGateways') ||
      store.get('userGateways') || { };

    //add or update gateways based
    //on data from api
    for (currency in defaultGateways) {

      //unknown currency,
      //add it as a default
      if (!custom[currency]) {
        custom[currency] = {
          custom  : false,
          issuers : { }
        };

      //must be a default
      //currency
      } else {
        custom[currency].custom = false;
      }

      //update gateways with the new data
      for (var i in defaultGateways[currency]) {
        gateway = defaultGateways[currency][i];

        //if its already here,
        //use the current include
        if (custom[currency].issuers[gateway.account]) {
          gateway.include = custom[currency].issuers[gateway.account].include;

        //otherwise, include it if featured
        } else {
          gateway.include = defaultGateways[currency][i].featured;
        }

        normalized     = gateway.name.toLowerCase().replace(/\W/g, '');
        gateway.assets = handleAssets(gateway.assets, normalized);
        custom[currency].issuers[gateway.account] = gateway;
      }
    }

    //ensure that non-default currencies
    //are marked as custom
    for (currency in custom) {
      if (!defaultGateways[currency]) {
        custom[currency].custom = true;
      }
    }

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  });

  //add API endpoint to asset filenames
  function handleAssets(assets, normalized) {
    var obj = { };

    if (!assets) assets = [ ];

    assets.forEach(function(a) {
      obj[a] = API + '/gateways/' + normalized + '/assets/' + a;
    });

    return obj;
  }

  /**
   * getCurrencies
   * get currencies from user defined list
   */

  var getCurrencies = function (all) {

    var currencies = [];
    var include;

    //add currencies from cusom list
    for (var currency in custom) {
      if (currency === '0158415500000000C1F76FF6ECB0BAC600000000') {
        continue;
      }

      include = null;

      //find selected currencies
      for (var issuer in custom[currency].issuers) {
        if (custom[currency].issuers[issuer].include) {
          include = {
            currency : currency,
            icon     : API + '/currencies/'+ currency +'.svg',
            include  : true,
            custom   : custom[currency].custom
          };
          break;
        }
      }

      //if none are selected, only add if all = true
      if (include)  currencies.push(include);
      else if (all) currencies.push({
        currency : currency,
        icon     : API + '/currencies/'+ currency +'.svg',
        include  : false,
        custom   : custom[currency].custom
      });
    }

    currencies.sort(function(a, b){
      if(a.currency < b.currency) return -1;
      if(a.currency > b.currency) return 1;
      return 0;
    });

    currencies.unshift({
      currency : "XRP",
      icon     : API + '/currencies/xrp.svg',
      include  : true
    });

    return currencies;
  };

  /**
   * getIssuers
   * get issuers for a given currency
   */

  var getIssuers = function (currency, all) {
    var issuers = [ ];
    var normalized;
    var assets;
    var name;

    if (!custom[currency]) return [ ];

    for (var issuer in custom[currency].issuers) {
      if (all || custom[currency].issuers[issuer].include) {
        issuers.push(custom[currency].issuers[issuer]);
      }
    }

    issuers.sort(function(a,b) {
      if (a.featured && b.featured) return 0;
      else if (a.featured) return -1;
      else if (b.featured) return 1;
      else return 0;
    });

    return issuers;
  };

  /**
   * updateCurrency
   * add/remove/include/exclude
   */

  var updateCurrency = function (options) {
    var currency = options.currency.toUpperCase();
    var featured;
    var issuer;

    //include currency, include featured
    //if there are any, otherwise include all
    if (options.include && custom[currency]) {
      featured = hasFeatured(custom[currency].issuers);

      for (issuer in custom[currency].issuers) {
        if (featured && !custom[currency].issuers[issuer].featured) {
          continue;
        }

        custom[currency].issuers[issuer].include = true;
      }

    //exclude currency, exclude all issuers
    } else if (options.exclude && custom[currency]) {
      for (issuer in custom[currency].issuers) {
        custom[currency].issuers[issuer].include = false;
      }

    //add custom
    } else if (options.add && !custom[currency]) {
      custom[currency] = {
        custom  : true,
        issuers : []
      };

    //remove custom
    } else if (options.remove && custom[currency] && custom[currency].custom) {
      delete custom[currency];

    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);

    //check for featured gateway
    function hasFeatured(issuers) {
      for (var i in issuers) {
        if (issuers[i].featured) return true;
      }

      return false;
    }
  };

  /**
   * updateIssuer
   * add/remove/include/exclude
   */

  var updateIssuer = function (options) {
    var currency = options.currency.toUpperCase();
    var issuer   = options.issuer;

    if (!custom[currency]) return;

    //include or exclude
    if (options.exclude || options.include) {
      if (!custom[currency].issuers[issuer]) return;
      custom[currency].issuers[issuer].include = options.include ? true : false;

    } else if (options.add && !custom[currency].issuers[issuer]) {
      custom[currency].issuers[issuer] = {
        account : issuer,
        name    : options.name || issuer,
        include : true,
        custom  : true
      };

    } else if (options.remove &&
               custom[currency].issuers[issuer] &&
               custom[currency].issuers[issuer].custom) {
      delete custom[currency].issuers[issuer];
    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  };

  return {
    promise        : promise,
    getCurrencies  : getCurrencies,
    getIssuers     : getIssuers,
    updateCurrency : updateCurrency,
    updateIssuer   : updateIssuer
  }
});
<commit_msg>fix bug with adding custom issuers to custom currencies<commit_after>angular.module('gateways', [])
.factory('gateways', function($http) {
  var defaultGateways;
  var custom;

  //load gateways list from API
  var promise = $http.get(API + '/gateways').success(function (data) {
    var normalized;
    var gateway;
    var currency;

    defaultGateways = data;
    custom = store.session.get('userGateways') ||
      store.get('userGateways') || { };

    //add or update gateways based
    //on data from api
    for (currency in defaultGateways) {

      //unknown currency,
      //add it as a default
      if (!custom[currency]) {
        custom[currency] = {
          custom  : false,
          issuers : { }
        };

      //must be a default
      //currency
      } else {
        custom[currency].custom = false;
      }

      //update gateways with the new data
      for (var i in defaultGateways[currency]) {
        gateway = defaultGateways[currency][i];

        //if its already here,
        //use the current include
        if (custom[currency].issuers[gateway.account]) {
          gateway.include = custom[currency].issuers[gateway.account].include;

        //otherwise, include it if featured
        } else {
          gateway.include = defaultGateways[currency][i].featured;
        }

        normalized     = gateway.name.toLowerCase().replace(/\W/g, '');
        gateway.assets = handleAssets(gateway.assets, normalized);
        custom[currency].issuers[gateway.account] = gateway;
      }
    }

    //ensure that non-default currencies
    //are marked as custom
    for (currency in custom) {
      if (!defaultGateways[currency]) {
        custom[currency].custom = true;
      }
    }

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  });

  //add API endpoint to asset filenames
  function handleAssets(assets, normalized) {
    var obj = { };

    if (!assets) assets = [ ];

    assets.forEach(function(a) {
      obj[a] = API + '/gateways/' + normalized + '/assets/' + a;
    });

    return obj;
  }

  /**
   * getCurrencies
   * get currencies from user defined list
   */

  var getCurrencies = function (all) {

    var currencies = [];
    var include;

    //add currencies from cusom list
    for (var currency in custom) {
      if (currency === '0158415500000000C1F76FF6ECB0BAC600000000') {
        continue;
      }

      include = null;

      //find selected currencies
      for (var issuer in custom[currency].issuers) {
        if (custom[currency].issuers[issuer].include) {
          include = {
            currency : currency,
            icon     : API + '/currencies/'+ currency +'.svg',
            include  : true,
            custom   : custom[currency].custom
          };
          break;
        }
      }

      //if none are selected, only add if all = true
      if (include)  currencies.push(include);
      else if (all) currencies.push({
        currency : currency,
        icon     : API + '/currencies/'+ currency +'.svg',
        include  : false,
        custom   : custom[currency].custom
      });
    }

    currencies.sort(function(a, b){
      if(a.currency < b.currency) return -1;
      if(a.currency > b.currency) return 1;
      return 0;
    });

    currencies.unshift({
      currency : "XRP",
      icon     : API + '/currencies/xrp.svg',
      include  : true
    });

    return currencies;
  };

  /**
   * getIssuers
   * get issuers for a given currency
   */

  var getIssuers = function (currency, all) {
    var issuers = [ ];
    var normalized;
    var assets;
    var name;

    if (!custom[currency]) return [ ];

    for (var issuer in custom[currency].issuers) {
      if (all || custom[currency].issuers[issuer].include) {
        issuers.push(custom[currency].issuers[issuer]);
      }
    }

    issuers.sort(function(a,b) {
      if (a.featured && b.featured) return 0;
      else if (a.featured) return -1;
      else if (b.featured) return 1;
      else return 0;
    });

    return issuers;
  };

  /**
   * updateCurrency
   * add/remove/include/exclude
   */

  var updateCurrency = function (options) {
    var currency = options.currency.toUpperCase();
    var featured;
    var issuer;

    //include currency, include featured
    //if there are any, otherwise include all
    if (options.include && custom[currency]) {
      featured = hasFeatured(custom[currency].issuers);

      for (issuer in custom[currency].issuers) {
        if (featured && !custom[currency].issuers[issuer].featured) {
          continue;
        }

        custom[currency].issuers[issuer].include = true;
      }

    //exclude currency, exclude all issuers
    } else if (options.exclude && custom[currency]) {
      for (issuer in custom[currency].issuers) {
        custom[currency].issuers[issuer].include = false;
      }

    //add custom
    } else if (options.add && !custom[currency]) {
      custom[currency] = {
        custom  : true,
        issuers : { }
      };

    //remove custom
    } else if (options.remove && custom[currency] && custom[currency].custom) {
      delete custom[currency];

    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);

    //check for featured gateway
    function hasFeatured(issuers) {
      for (var i in issuers) {
        if (issuers[i].featured) return true;
      }

      return false;
    }
  };

  /**
   * updateIssuer
   * add/remove/include/exclude
   */

  var updateIssuer = function (options) {
    var currency = options.currency.toUpperCase();
    var issuer   = options.issuer;

    if (!custom[currency]) return;

    //include or exclude
    if (options.exclude || options.include) {
      if (!custom[currency].issuers[issuer]) return;
      custom[currency].issuers[issuer].include = options.include ? true : false;

    } else if (options.add && !custom[currency].issuers[issuer]) {
      custom[currency].issuers[issuer] = {
        account : issuer,
        name    : options.name || issuer,
        include : true,
        custom  : true
      };

    } else if (options.remove &&
               custom[currency].issuers[issuer] &&
               custom[currency].issuers[issuer].custom) {
      delete custom[currency].issuers[issuer];
    } else return;

    //save
    store.session.set('userGateways', custom);
    store.set('userGateways', custom);
  };

  return {
    promise        : promise,
    getCurrencies  : getCurrencies,
    getIssuers     : getIssuers,
    updateCurrency : updateCurrency,
    updateIssuer   : updateIssuer
  }
});
<|endoftext|>


<commit_before>import { theme } from '@hackclub/design-system'
import styled, { css, keyframes } from 'styled-components'

const waveFlag = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(-5deg);
  }
`

const waveFlagScaled = keyframes`
  from {
    transform: scale(.75) rotate(0deg);
  }
  to {
    transform: scale(.75) rotate(-5deg);
  }
`

const Flag = styled.a`
  background: url(https://assets.hackclub.com/flag-orpheus-top.svg) no-repeat;
  background-position: top center;
  background-size: contain;
  flex-shrink: 0;
  width: 112px;
  height: 48px;
  transition: ${theme.transition} transform;
  transform-origin: top left;
  ${theme.mediaQueries.md} {
    width: 172px;
    height: 64px;
  }
  &:hover,
  &:focus {
    animation: ${waveFlag} 0.5s linear infinite alternate;
  }
  ${theme.mediaQueries.reduceMotion} {
    animation: none !important;
  }
  ${(props) =>
    props.scrolled &&
    css`
      transform: scale(0.875);
      height: 56px;
      &:hover,
      &:focus {
        animation: ${waveFlagScaled} 0.5s linear infinite alternate;
      }
    `};
`
Flag.defaultProps = {
  href: 'https://hackclub.com/',
  'aria-label': 'Homepage'
}

export default Flag
<commit_msg>Fix Flag animation<commit_after>import { theme } from '@hackclub/design-system'
import styled, { css, keyframes } from 'styled-components'

const waveFlag = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(-5deg);
  }
`

const waveFlagScaled = keyframes`
  from {
    transform: scale(.875) rotate(0deg);
  }
  to {
    transform: scale(.875) rotate(-5deg);
  }
`

const Flag = styled.a`
  background: url(https://assets.hackclub.com/flag-orpheus-top.svg) no-repeat;
  background-position: top center;
  background-size: contain;
  flex-shrink: 0;
  width: 112px;
  height: 48px;
  transition: ${theme.transition} transform;
  transform-origin: top left;
  ${theme.mediaQueries.md} {
    width: 172px;
    height: 64px;
  }
  &:hover,
  &:focus {
    animation: ${waveFlag} 0.5s linear infinite alternate;
  }
  ${theme.mediaQueries.reduceMotion} {
    animation: none !important;
  }
  ${(props) =>
    props.scrolled &&
    css`
      transform: scale(0.875);
      height: 56px;
      &:hover,
      &:focus {
        animation: ${waveFlagScaled} 0.5s linear infinite alternate;
      }
    `};
`
Flag.defaultProps = {
  href: 'https://hackclub.com/',
  'aria-label': 'Homepage'
}

export default Flag
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("REST API call control")
description("This will return the REST APIn call control")
base_component_id("rest_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "REST API Call",
            type:       "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    180,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    70,
            type:       "Number"
        }
        ,
        {
            id:             "callDefaultRestApi",
            pre_snippet:    `await `,
            snippet:        `callDefaultRestApi()`,
            name:           "Execute Command",
            type:           "Action"
        }
        ,
        {
            id:         "callRestApi",
            pre_snippet:    `await `,
            snippet:    `callRestApi("http://INSERT_URL_HERE")`,
            name:       "Execute Command",
            type:       "Action"
        }
        ,
        {
            id:         "stagingRoot",
            name:       "Staging response path",
            default:    "",
            type:       "String"
        }
        ,
        {
            id:         "productionRoot",
            name:       "Production response path",
            default:    "",
            type:       "String"
        }
        ,
        {
            id:         "stagingFilter",
            name:       "Staging filter",
            default:    new Object(),
            hidden:     true,
            type:       "Object"
        }
        ,
        {
            id:         "productionFilter",
            name:       "Production filter",
            default:    new Object(),
            hidden:     true,
            type:       "Object"
        }
        ,
        {
            id:         "stagingURL",
            name:       "Staging URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }
        ,
        {
            id:         "URL",
            name:       "URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }
        ,
        {
            id:         "jsonPaths",
            name:       "JSON Paths",
            default:    [],
            hidden:     true,
            type:       "Array"
        }

    ]
)//properties
logo_url("/driver_icons/rest.png")
*/

    Vue.component("rest_control",{

        props: ["meta", "args","design_mode","refresh"]

        ,

        template:

`

        {{args.text}}

        <button    class="btn btn-primary"
                   v-on:click="testDefaultRestApi()">

              Call API

        </button>

        <button    class="btn btn-primary"
                   v-on:click="filterRestApi()">

              Filter

        </button>

        <button    class="btn btn-primary"
                   v-on:click="promoteStagingToLive()">

              Promote Staging To Live

        </button>

            zzz
{{args.stagingURL}}

Root

            <select v-model="args.stagingRoot">
              <option disabled value="">Please select one</option>
              <option  v-for="jsonPath in args.jsonPaths" >{{jsonPath}}</option>
            </select>

Selected: {{ args.stagingRoot }}

List of Paths

                   <input type="checkbox" id="{{jsonPath}}" value="{{jsonPath}}" v-model="args.stagingFilter[jsonPath]">
                   {{jsonPath}}

Filtered Result

{{filteredJson}}

Result

{{tempResult}}

           {{args.text}}

{{args.URL}}

            <slot v-bind:refresh='refresh'>
            </slot>

`

        ,

        data: function() {
            return {
                    tempResult:    "",
                    filteredJson:  new Object()
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

        }
        ,

        methods: {
            callRestApiInternal: async function() {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "rest_call_service",
                    method_name: "rest_call_service"
                }
                ,
                {
                    URL:    mm.args.URL
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callJsonTraverse: async function(input) {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "json_traverse_service",
                    method_name: "json_traverse_service"
                }
                ,
                {
                    input: input
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            getJsonFiltered: async function(input) {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "json_filter_service",
                    method_name: "json_filter_service"
                }
                ,
                {
                    input: input,
                    filter: this.args.stagingFilter,
                    root:  this.args.stagingRoot

                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callDefaultRestApi: async function() {

                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callRestApi: async function(urlToCall) {

                var mm = this
                if (urlToCall) {
                    mm.args.URL = urlToCall
                }
                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            testDefaultRestApi: async function(urlToCall) {

                this.filteredJson = new Object()
                var jsonResponse  = await this.callRestApi(this.args.stagingURL)
                this.tempResult   = jsonResponse

                //alert(JSON.stringify(Object.keys(this.allPaths),null,2))

                //this.filteredJson.value = new Object()

                var aa = await this.callJsonTraverse(jsonResponse)
                this.args.jsonPaths = Object.keys(aa)

                for (var ert=0;ert<this.args.jsonPaths.length;ert++) {
                    this.args.stagingFilter[this.args.jsonPaths[ert]] = true
                }
                //alert(JSON.stringify(aa,null,2))
                //this.filteredJson = aa

            }
            ,

            promoteStagingToLive: async function(urlToCall) {

                this.filteredJson = new Object()
                var jsonResponse  = await this.callRestApi(this.args.stagingURL)
                this.tempResult   = jsonResponse

                //alert(JSON.stringify(Object.keys(this.allPaths),null,2))

                //this.filteredJson.value = new Object()

                var aa = await this.callJsonTraverse(jsonResponse)
                this.args.jsonPaths = Object.keys(aa)

                for (var ert=0;ert<this.args.jsonPaths.length;ert++) {
                    this.args.stagingFilter[this.args.jsonPaths[ert]] = true
                }
                //alert(JSON.stringify(aa,null,2))
                //this.filteredJson = aa

            }
            ,

            filterRestApi: async function(urlToCall) {

                //alert(JSON.stringify(this.filter,null,2))
                var aa = await this.getJsonFiltered(this.tempResult)
                this.filteredJson  = aa

            }
            ,

            pathToString: function (pp) {
                var s = ""
                for (  var aa = 0  ;  aa < pp.length  ;  aa ++  ) {
                    s += pp[aa]
                    if (aa < pp.length -1) {
                        s += "."
                    }
                }
                return s
            }

        }

    })
}
<commit_msg>Saved the staging REST API control response<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("REST API call control")
description("This will return the REST APIn call control")
base_component_id("rest_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "REST API Call",
            type:       "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    180,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    70,
            type:       "Number"
        }
        ,
        {
            id:             "callDefaultRestApi",
            pre_snippet:    `await `,
            snippet:        `callDefaultRestApi()`,
            name:           "Execute Command",
            type:           "Action"
        }
        ,
        {
            id:         "callRestApi",
            pre_snippet:    `await `,
            snippet:    `callRestApi("http://INSERT_URL_HERE")`,
            name:       "Execute Command",
            type:       "Action"
        }
        ,
        {
            id:         "stagingRoot",
            name:       "Staging response path",
            default:    "",
            type:       "String"
        }
        ,
        {
            id:         "productionRoot",
            name:       "Production response path",
            default:    "",
            type:       "String"
        }
        ,
        {
            id:         "stagingFilter",
            name:       "Staging filter",
            default:    new Object(),
            hidden:     true,
            type:       "Object"
        }
        ,
        {
            id:         "productionFilter",
            name:       "Production filter",
            default:    new Object(),
            hidden:     true,
            type:       "Object"
        }
        ,
        {
            id:         "stagingURL",
            name:       "Staging URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }
        ,
        {
            id:         "URL",
            name:       "URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }
        ,
        {
            id:         "jsonPaths",
            name:       "JSON Paths",
            default:    [],
            hidden:     true,
            type:       "Array"
        }
        ,
        {
            id:         "stagingResponse",
            name:       "Staging Response",
            default:    null,
            hidden:     true,
            type:       "Object"
        }

    ]
)//properties
logo_url("/driver_icons/rest.png")
*/

    Vue.component("rest_control",{

        props: ["meta", "args","design_mode","refresh"]

        ,

        template:

`

        {{args.text}}

        <button    class="btn btn-primary"
                   v-on:click="callStagingRestApi()">

              Call API

        </button>

        <button    class="btn btn-primary"
                   v-on:click="filterRestApi()">

              Filter

        </button>

        <button    class="btn btn-primary"
                   v-on:click="promoteStagingToLive()">

              Promote Staging To Live

        </button>

{{args.stagingURL}}

Root

            <select v-model="args.stagingRoot">
              <option disabled value="">Please select one</option>
              <option  v-for="jsonPath in args.jsonPaths" >{{jsonPath}}</option>
            </select>

Selected: {{ args.stagingRoot }}

List of Paths

                   <input type="checkbox" id="{{jsonPath}}" value="{{jsonPath}}" v-model="args.stagingFilter[jsonPath]">
                   {{jsonPath}}

Filtered Result

{{filteredJson}}

Result

{{args.stagingResponse}}

           {{args.text}}

{{args.URL}}

            <slot v-bind:refresh='refresh'>
            </slot>

`

        ,

        data: function() {
            return {
                    filteredJson:       new Object()
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

        }
        ,

        methods: {
            callRestApiInternal: async function() {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "rest_call_service",
                    method_name: "rest_call_service"
                }
                ,
                {
                    URL:    mm.args.URL
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callJsonTraverse: async function(input) {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "json_traverse_service",
                    method_name: "json_traverse_service"
                }
                ,
                {
                    input: input
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            getJsonFiltered: async function(input) {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "json_filter_service",
                    method_name: "json_filter_service"
                }
                ,
                {
                    input: input,
                    filter: this.args.stagingFilter,
                    root:  this.args.stagingRoot

                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callDefaultRestApi: async function() {

                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callRestApi: async function(urlToCall) {

                var mm = this
                if (urlToCall) {
                    mm.args.URL = urlToCall
                }
                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callStagingRestApi: async function( urlToCall ) {

                this.filteredJson = new Object()
                var jsonResponse  = await this.callRestApi(this.args.stagingURL)
                this.args.stagingResponse   = jsonResponse

                var aa = await this.callJsonTraverse(jsonResponse)
                this.args.jsonPaths = Object.keys(aa)

                for (var ert=0;ert<this.args.jsonPaths.length;ert++) {
                    this.args.stagingFilter[this.args.jsonPaths[ert]] = true
                }
            }
            ,

            promoteStagingToLive: async function(urlToCall) {

                this.filteredJson = new Object()
                var jsonResponse  = await this.callRestApi(this.args.stagingURL)
                this.args.stagingResponse   = jsonResponse

                //alert(JSON.stringify(Object.keys(this.allPaths),null,2))

                //this.filteredJson.value = new Object()

                var aa = await this.callJsonTraverse(jsonResponse)
                this.args.jsonPaths = Object.keys(aa)

                for (var ert=0;ert<this.args.jsonPaths.length;ert++) {
                    this.args.stagingFilter[this.args.jsonPaths[ert]] = true
                }
                //alert(JSON.stringify(aa,null,2))
                //this.filteredJson = aa

            }
            ,

            filterRestApi: async function(urlToCall) {

                //alert(JSON.stringify(this.filter,null,2))
                var aa = await this.getJsonFiltered(this.args.stagingResponse)
                this.filteredJson  = aa

            }
            ,

            pathToString: function (pp) {
                var s = ""
                for (  var aa = 0  ;  aa < pp.length  ;  aa ++  ) {
                    s += pp[aa]
                    if (aa < pp.length -1) {
                        s += "."
                    }
                }
                return s
            }

        }

    })
}
<|endoftext|>


<commit_before>import React from 'react'

import Example from './components/Example'
import Circle from './components/Circle'
import { SERIF_FONT, COLOR_A, COLOR_B, COLOR_C } from './styles'
import { withAnimatronics, withRig } from '../../src'

const COLORS = [
  COLOR_A,
  COLOR_B,
  COLOR_C,
];

class Letters extends React.Component {

  constructor(props) {
    super(props);
    this.state = { didLettersAnimate: false };
  }

  componentDidUpdate(prevProps) {
    const { didAnimate: prevDidAnimate } = prevProps;
    const { didAnimate: nextDidAnimate, playAnimation, rewindAnimation } = this.props;
    if (!prevDidAnimate && nextDidAnimate) {
      playAnimation(() => {
        this.setState({ didLettersAnimate: true });
      });
    } else if (prevDidAnimate && !nextDidAnimate) {
      rewindAnimation(() => {
        this.setState({ didLettersAnimate: false });
      });
    }
  }

  render() {
    const { text, didAnimate } = this.props;
    const { didLettersAnimate } = this.state;
    const letters = text.split('');
    const components = letters.map((letter, index) =>
       withRig(`${ letter }-${ index }`)(Circle)
    );
    return (

{
        letters.map((letter, index) => {
          const LetterCircle = components[index];
          return (
            <LetterCircle
              key={ index }
              dimension={ 80 }
              style={{
                position: 'relative',
                backgroundColor: COLORS[index % COLORS.length],
                transform: didLettersAnimate ? 'scale(1)' : 'scale(0)',
                marginLeft: '10px',
                marginTop: '10px',
              }}
            >

                { letter }

            </LetterCircle>
          );
        })
      }

    );
  }
}

const AnimatedLetters = withAnimatronics(() => [])(Letters);

class Input extends React.Component {

  constructor(props) {
    super(props);
    this._onChange = this._onChange.bind(this);
    this.state = { text: '' };
  }

  _onChange(ev) {
    const { didAnimate, rewindAnimation } = this.props;
    const text = ev.target.value;
    if (text === '' && didAnimate) {
      rewindAnimation();
    }
    this.setState({ text });
  }

  render() {
    const { didAnimate, animatronicStyles } = this.props;
    const { text } = this.state;
    return (

        <input
          type='text'
          placeholder='Type something then animate'
          value={ text }
          onChange={ this._onChange }
          style={{
            outline: 'none',
            width: '60%',
            height: '48px',
            fontSize: '24px',
            lineHeight: 1.5,
            fontFamily: SERIF_FONT,
            position: 'relative',
            paddingLeft: '0.25em',
            marginTop: '5%',
            marginLeft: '5%',
            ...animatronicStyles,
          }}
        />

          <AnimatedLetters
            didAnimate={ didAnimate }
            text={ text }
            createAnimationStages={() => [
              text.split('').reduce(
                (result, letter, index) => {{
                  result[`${ letter }-${ index }`] = {
                    duration: 250,
                    delay: index * 100,
                    start: { transform: 'scale(0)' },
                    end: { transform: 'scale(1)' }
                  }
                  return result;
                }},
                {}
              )
            ]}
          />

    );
  }

}

const RiggedInput = withRig('input')( Input );

class InputExample extends React.Component {

  render() {
    const { playAnimation, rewindAnimation } = this.props;
    return (
      <Example
        playAnimation={ playAnimation }
        rewindAnimation={ rewindAnimation }
      >
        <RiggedInput/>
      </Example>
    );
  }

}

// TODO: Better organize these example components and/or figure out a better
// way to support dynamic animatronics. Need to wrap the root element and
// have a fake animation to trigger the child Letters animation.
export default withAnimatronics(
  () => [
    {
      input: {
        duration: 0,
        start: { transform: 'scale(1)' },
        end: { transform: 'scale(1)' },
      }
    }
  ]
)( InputExample );
<commit_msg>:art: [examples] Use class expression<commit_after>import React from 'react'

import Example from './components/Example'
import Circle from './components/Circle'
import { SERIF_FONT, COLOR_A, COLOR_B, COLOR_C } from './styles'
import { withAnimatronics, withRig } from '../../src'

const COLORS = [
  COLOR_A,
  COLOR_B,
  COLOR_C,
];

const Letters = withAnimatronics(() => [])(class extends React.Component {

  constructor(props) {
    super(props);
    this.state = { didLettersAnimate: false };
  }

  componentDidUpdate(prevProps) {
    const { didAnimate: prevDidAnimate } = prevProps;
    const { didAnimate: nextDidAnimate, playAnimation, rewindAnimation } = this.props;
    if (!prevDidAnimate && nextDidAnimate) {
      playAnimation(() => {
        this.setState({ didLettersAnimate: true });
      });
    } else if (prevDidAnimate && !nextDidAnimate) {
      rewindAnimation(() => {
        this.setState({ didLettersAnimate: false });
      });
    }
  }

  render() {
    const { text, didAnimate } = this.props;
    const { didLettersAnimate } = this.state;
    const letters = text.split('');
    const components = letters.map((letter, index) =>
       withRig(`${ letter }-${ index }`)(Circle)
    );
    return (

{
        letters.map((letter, index) => {
          const LetterCircle = components[index];
          return (
            <LetterCircle
              key={ index }
              dimension={ 80 }
              style={{
                position: 'relative',
                backgroundColor: COLORS[index % COLORS.length],
                transform: didLettersAnimate ? 'scale(1)' : 'scale(0)',
                marginLeft: '10px',
                marginTop: '10px',
              }}
            >

                { letter }

            </LetterCircle>
          );
        })
      }

    );
  }

});

class Input extends React.Component {

  constructor(props) {
    super(props);
    this._onChange = this._onChange.bind(this);
    this.state = { text: '' };
  }

  _onChange(ev) {
    const { didAnimate, rewindAnimation } = this.props;
    const text = ev.target.value;
    if (text === '' && didAnimate) {
      rewindAnimation();
    }
    this.setState({ text });
  }

  render() {
    const { didAnimate, animatronicStyles } = this.props;
    const { text } = this.state;
    return (

        <input
          type='text'
          placeholder='Type something then animate'
          value={ text }
          onChange={ this._onChange }
          style={{
            outline: 'none',
            width: '60%',
            height: '48px',
            fontSize: '24px',
            lineHeight: 1.5,
            fontFamily: SERIF_FONT,
            position: 'relative',
            paddingLeft: '0.25em',
            marginTop: '5%',
            marginLeft: '5%',
            ...animatronicStyles,
          }}
        />

          <Letters
            didAnimate={ didAnimate }
            text={ text }
            createAnimationStages={() => [
              text.split('').reduce(
                (result, letter, index) => {{
                  result[`${ letter }-${ index }`] = {
                    duration: 250,
                    delay: index * 100,
                    start: { transform: 'scale(0)' },
                    end: { transform: 'scale(1)' }
                  }
                  return result;
                }},
                {}
              )
            ]}
          />

    );
  }

}

const RiggedInput = withRig('input')( Input );

class InputExample extends React.Component {

  render() {
    const { playAnimation, rewindAnimation } = this.props;
    return (
      <Example
        playAnimation={ playAnimation }
        rewindAnimation={ rewindAnimation }
      >
        <RiggedInput/>
      </Example>
    );
  }

}

// TODO: Better organize these example components and/or figure out a better
// way to support dynamic animatronics. Need to wrap the root element and
// have a fake animation to trigger the child Letters animation.
export default withAnimatronics(
  () => [
    {
      input: {
        duration: 0,
        start: { transform: 'scale(1)' },
        end: { transform: 'scale(1)' },
      }
    }
  ]
)( InputExample );
<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import serialize from 'serialize-javascript';
import config from '../config';

/* eslint-disable react/no-danger */

class Html extends Component {
  static propTypes = {
    apikey: PropTypes.string,
    app: PropTypes.object, // eslint-disable-line
    title: PropTypes.string.isRequired,
    description: PropTypes.string.isRequired,
    root: PropTypes.string,
    styles: PropTypes.arrayOf(PropTypes.shape({
      id: PropTypes.string.isRequired,
      cssText: PropTypes.string.isRequired,
    }).isRequired),
    scripts: PropTypes.arrayOf(PropTypes.string.isRequired),
    children: PropTypes.string.isRequired,
  };

  static defaultProps = {
    apikey: '',
    styles: [],
    scripts: [],
    root: ''
  };

  render() {
    const {
      apikey,
      app,
      title,
      description,
      root,
      styles,
      scripts,
      children
    } = this.props;

    return (

          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <title>{title}</title>
          <meta name="description" content={description} />
          <meta property="og:title" content={title} />
          <meta property="og:description" content={description} />
          <meta property="og:image" content={`${root}/tile.png`} />
          <meta property="og:site_name" content="Lab Zero" />
          <meta property="og:url" content={root} />
          <meta property="og:type" content="website" />
          <meta property="twitter:card" content="summary" />
          <meta property="twitter:site" content="labzero" />
          <meta property="twitter:image" content={`${root}/tile.png`} />
          <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
          <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:400,900" />
          {scripts.map(script => (
            <link key={script} rel="preload" href={script} as="script" />
          ))}
          <link rel="manifest" href="/site.webmanifest" />
          <link rel="apple-touch-icon" href="/icon.png" />
          {styles.map(style => (


<commit_before>var fs = require('fs');
var vm = require('vm');
var sandbox = vm.createContext({});

fs.readFile('./mod_sandbox-sandbox.json', function(err, data)
{
	if(err)
	{
		console.error(err);
	}
	else
	{
		JSON.parse(data, function(key, value)
		{
			try
			{
				vm.runInContext(key + '=' + value, sandbox);
			}
			catch(e)
			{
				console.log(e);
			}
		});
	}
});

process.on('message', function(m)
{
	sandbox._ =
	{
		root: sandbox,
		echoResult: false,
		output: '',
		params: m.params,
		words: m.words
	}

	var reply =
	{
		echoResult: false,
		result: result,
		output: ''
	}

	try
	{
		var result = vm.runInContext(m.js, sandbox);

		var reply =
		{
			echoResult: sandbox._.echoResult,
			result: result,
			output: sandbox._.output
		}

		delete sandbox._;

		var jsonString = JSON.stringify(sandbox, function(key, val)
		{
			if(typeof val === 'function') return val.toString();
			else return val;
		}, 2);

		fs.writeFile('./mod_sandbox-sandbox.json', jsonString, function(err)
		{
			console.log('Write error: ' + err);
		});
	}
	catch(e)
	{
		console.error(e.stack);
		reply.output += 'PRIVMSG ' + m.target + ' :JavaScript error: ' + e.message;
	}

	process.send(reply);
});
<commit_msg>Fixed strings vs functions bugs in sandbox!<commit_after>var fs = require('fs');
var vm = require('vm');
var sandbox = vm.createContext({});

fs.readFile('./mod_sandbox-sandbox.json', function(err, data)
{
	if(err)
	{
		console.error(err);
	}
	else
	{
		JSON.parse(data, function(key, val)
		{
			try
			{
				var js;

				if(typeof val === 'string' && val[0] === '\\')
				{
					js = key + '=\'' + val + '\'';
				}
				else js = key + '=' + val;

				console.log(js);
				vm.runInContext(js, sandbox);
			}
			catch(e)
			{
				console.log(e);
			}
		});
	}
});

process.on('message', function(m)
{
	sandbox._ =
	{
		root: sandbox,
		echoResult: false,
		output: '',
		params: m.params,
		words: m.words
	}

	var reply =
	{
		echoResult: false,
		result: result,
		output: ''
	}

	try
	{
		var result = vm.runInContext(m.js, sandbox);

		var reply =
		{
			echoResult: sandbox._.echoResult,
			result: result,
			output: sandbox._.output
		}

		delete sandbox._;

		var jsonString = JSON.stringify(sandbox, function(key, val)
		{
			if(typeof val === 'function') return val.toString();
			else if(typeof val === 'string') return '\\' + val.toString();
			else return val;
		}, 2);

		fs.writeFile('./mod_sandbox-sandbox.json', jsonString, function(err)
		{
			console.log('Write error: ' + err);
		});
	}
	catch(e)
	{
		console.error(e.stack);
		reply.output += 'PRIVMSG ' + m.target + ' :JavaScript error: ' + e.message;
	}

	process.send(reply);
});
<|endoftext|>


<commit_before>import React from 'react';
import Props from './Props'

const stylesheet = {
  containerStyle: {},
  tagStyle: {
    color: '#777',
  }
}

export default class Node extends React.Component {
  constructor(props){
    super(props);
  }

  render(){
    const {node, depth} = this.props;
    let {tagStyle, containerStyle} = stylesheet;

    var leftPad = {
      paddingLeft: 3 + (depth + 1) * 15,
      paddingRight: 3,
    };

    Object.assign(containerStyle, leftPad);

    const {name, text, children} = getData(node);

    // Just text
    if (!name) {
      return

        {text}

;
    }

    // Single-line tag
    if (!children) {
      return

        <{name}
          <Props node={node} singleLine />
        />

;
    }

    // Keep a copy so that further mutations to containerStyle don't impact us:
    const containerStyleCopy = Object.assign({}, containerStyle);

    // tag with children
    return (

          <{name}
            <Props node={node} />
          >

        {React.Children.map(children, childElement => (
          <Node node={childElement} depth={depth + 1} />
        ))}

          </{name}>

    );
  }
}

function getData(element) {
  const data = {
    name: null,
    text: null,
    children: null
  };

  if (typeof element == 'string') {
    data.text = element;
    return data;
  }

  data.children = element.props.children;
  const type = element.type;

  if (typeof type === 'string') {
    data.name = type;
  } else {
    data.name = type.displayName || type.name || 'Unknown';
  }

  return data;
}
<commit_msg>Check if node type is number and return it as string<commit_after>import React from 'react';
import Props from './Props'

const stylesheet = {
  containerStyle: {},
  tagStyle: {
    color: '#777',
  }
}

export default class Node extends React.Component {
  constructor(props){
    super(props);
  }

  render(){
    const {node, depth} = this.props;
    let {tagStyle, containerStyle} = stylesheet;

    var leftPad = {
      paddingLeft: 3 + (depth + 1) * 15,
      paddingRight: 3,
    };

    Object.assign(containerStyle, leftPad);

    const {name, text, children} = getData(node);

    // Just text
    if (!name) {
      return

        {text}

;
    }

    // Single-line tag
    if (!children) {
      return

        <{name}
          <Props node={node} singleLine />
        />

;
    }

    // Keep a copy so that further mutations to containerStyle don't impact us:
    const containerStyleCopy = Object.assign({}, containerStyle);

    // tag with children
    return (

          <{name}
            <Props node={node} />
          >

        {React.Children.map(children, childElement => (
          <Node node={childElement} depth={depth + 1} />
        ))}

          </{name}>

    );
  }
}

function getData(element) {
  const data = {
    name: null,
    text: null,
    children: null
  };

  if (typeof element == 'string') {
    data.text = element;
    return data;
  }

  if (typeof element === 'number') {
    data.text = String.toString(element);
    return data;
  }

  data.children = element.props.children;
  const type = element.type;

  if (typeof type === 'string') {
    data.name = type;
  } else {
    data.name = type.displayName || type.name || 'Unknown';
  }

  return data;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import PostModal from './PostModal';
import CommentModal from './CommentModal';

export default class Post extends Component {

  constructor(props) {
    super(props);

    this.state = {

      isLike: false,
      likeId: null,
      post: this.props.post || {}

    };

    this.onLike = this.onLike.bind(this);
    this.onDislike = this.onDislike.bind(this);
    this.getListLikes = this.getListLikes.bind(this);
  }

  componentDidMount() {

    this.getListLikes(this.state.post.id);

  }

  getListLikes(postId) {

    fetch("http://localhost:3001/likes?post_id=" + postId, {

      method: 'GET',

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + sessionStorage.getItem("userToken")
      }

    }).then((data) => {
      return data.json()
    }).then((data) => {

      if (data.status === "success") {

        const listLikes = data.data;

        for (let i = 0; i < listLikes.length; i++) {
          if (listLikes[i].user.id === sessionStorage.getItem("userId")) {
            console.log(listLikes[i].user.id + " " + sessionStorage.getItem("userId"))

            this.setState({

              isLike: true,
              likeId: listLikes[i].id

            });
          }
        }
      }

    }).catch((err) => {
      console.log(err)
    })

  }

  onLike(postId) {

    fetch("http://localhost:3001/likes", {

      method: 'POST',

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + sessionStorage.getItem("userToken")
      },

      body: JSON.stringify({
        "post_id": postId
      })

    }).then((data) => {
      return data.json()
    }).then((data) => {

      console.log(data)

      if (data.status === "success") {

        this.setState({ isLike: true, likeId: data.like_id });

      }

    }).catch((err) => {
      console.log(err)
    });

  }

  onDislike(likeId) {

    if (!likeId) {

      console.log("Pas de likeId");
      return ;

    }

    fetch("http://localhost:3001/likes/" + likeId, {

      method: 'DELETE',

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + sessionStorage.getItem("userToken")
      }
    }).then((data) => {
      return data.json()
    }).then((data) => {

      console.log(data)

      if (data.status === "success") {

        this.setState({ isLike: false, likeId: null });

      }

    }).catch((err) => {
      console.log(err)
    });

  }

  render() {

    const { isLike, post, likeId } = this.state;

    return (

            <PostModal
              id={post.id}
              post={post.content}

              onModify={this.props.fetchPosts}
            />
            {(post.user.firstname && post.user.lastname) ? post.user.firstname + ' ' + post.user.lastname : post.user.login}
            <CommentModal
              id={post.id}
              post={post.content}
              login={(post.user.firstname && post.user.lastname) ? post.user.firstname + ' ' + post.user.lastname : post.user.login}

              onModify={this.props.fetchPosts}
            />

              <button className={"btn btn-" + (isLike ? 'danger' : 'primary')} type="button" onClick={() => { isLike ? this.onDislike(likeId) : this.onLike(post.id)}}>

                {isLike ? 'thumb_down' : 'thumb_up'}

              </button>

              <button className="btn btn-primary" type="button" data-toggle="modal" data-target={"#myCommentModal" + post.id} style={styles.actionButton}>
                comment
              </button>

              <button className="btn btn-default" type="button" data-toggle="modal" data-target={"#myModal" + post.id} style={styles.actionButton}>
                mode_edit
              </button>

{post.content}

    );

  }

}

const styles = {

  actionButton: {

    marginRight: 10

  },

  actionButtons: {

    position: 'absolute',
    right: 10,
    top: 5

  },

  postContainer: {

    position: 'relative'

  },

  stylePostContent: {

    fontSize: 21,
    marginTop: 10,
    WebkitHyphens: 'auto',
    MozHyphens: 'auto',
    msHyphens: 'auto',
    OHyphens: 'auto',
    hyphens: 'auto',
    wordWrap: 'break-word'

  },

  stylePostLogin: {

    fontSize: 20

  }

};

Post.propTypes = {

  post: PropTypes.object.isRequired,

  fetchPosts: PropTypes.func.isRequired

};
<commit_msg>Fixed design for button<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import PostModal from './PostModal';
import CommentModal from './CommentModal';

export default class Post extends Component {

  constructor(props) {
    super(props);

    this.state = {

      isLike: false,
      likeId: null,
      post: this.props.post || {}

    };

    this.onLike = this.onLike.bind(this);
    this.onDislike = this.onDislike.bind(this);
    this.getListLikes = this.getListLikes.bind(this);
  }

  componentDidMount() {

    this.getListLikes(this.state.post.id);

  }

  getListLikes(postId) {

    fetch("http://localhost:3001/likes?post_id=" + postId, {

      method: 'GET',

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + sessionStorage.getItem("userToken")
      }

    }).then((data) => {
      return data.json()
    }).then((data) => {

      if (data.status === "success") {

        const listLikes = data.data;

        for (let i = 0; i < listLikes.length; i++) {
          if (listLikes[i].user.id === sessionStorage.getItem("userId")) {
            console.log(listLikes[i].user.id + " " + sessionStorage.getItem("userId"))

            this.setState({

              isLike: true,
              likeId: listLikes[i].id

            });
          }
        }
      }

    }).catch((err) => {
      console.log(err)
    })

  }

  onLike(postId) {

    fetch("http://localhost:3001/likes", {

      method: 'POST',

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + sessionStorage.getItem("userToken")
      },

      body: JSON.stringify({
        "post_id": postId
      })

    }).then((data) => {
      return data.json()
    }).then((data) => {

      console.log(data)

      if (data.status === "success") {

        this.setState({ isLike: true, likeId: data.like_id });

      }

    }).catch((err) => {
      console.log(err)
    });

  }

  onDislike(likeId) {

    if (!likeId) {

      console.log("Pas de likeId");
      return ;

    }

    fetch("http://localhost:3001/likes/" + likeId, {

      method: 'DELETE',

      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + sessionStorage.getItem("userToken")
      }
    }).then((data) => {
      return data.json()
    }).then((data) => {

      console.log(data)

      if (data.status === "success") {

        this.setState({ isLike: false, likeId: null });

      }

    }).catch((err) => {
      console.log(err)
    });

  }

  render() {

    const { isLike, post, likeId } = this.state;

    return (

            <PostModal
              id={post.id}
              post={post.content}

              onModify={this.props.fetchPosts}
            />
            {(post.user.firstname && post.user.lastname) ? post.user.firstname + ' ' + post.user.lastname : post.user.login}
            <CommentModal
              id={post.id}
              post={post.content}
              login={(post.user.firstname && post.user.lastname) ? post.user.firstname + ' ' + post.user.lastname : post.user.login}

              onModify={this.props.fetchPosts}
            />

              <button className={"btn btn-" + (isLike ? 'danger' : 'primary')} type="button" onClick={() => { isLike ? this.onDislike(likeId) : this.onLike(post.id)}}  style={styles.actionButton}>

                {isLike ? 'thumb_down' : 'thumb_up'}

              </button>

              <button className="btn btn-primary" type="button" data-toggle="modal" data-target={"#myCommentModal" + post.id} style={styles.actionButton}>
                comment
              </button>

              <button className="btn btn-default" type="button" data-toggle="modal" data-target={"#myModal" + post.id}>
                mode_edit
              </button>

{post.content}

    );

  }

}

const styles = {

  actionButton: {

    marginRight: 10

  },

  actionButtons: {

    position: 'absolute',
    right: 10,
    top: 5

  },

  postContainer: {

    position: 'relative'

  },

  stylePostContent: {

    fontSize: 21,
    marginTop: 10,
    WebkitHyphens: 'auto',
    MozHyphens: 'auto',
    msHyphens: 'auto',
    OHyphens: 'auto',
    hyphens: 'auto',
    wordWrap: 'break-word'

  },

  stylePostLogin: {

    fontSize: 20

  }

};

Post.propTypes = {

  post: PropTypes.object.isRequired,

  fetchPosts: PropTypes.func.isRequired

};
<|endoftext|>