<commit_before>/**
 * Module for interfacing with the Kalabox container system implementation, and
 * the provider of the container system.
 *
 * NOTE: The container system and the provider are not always the same. For
 * example using docker on a Mac would use docker as the container system,
 * however it would be provided by boot2docker.
 * @module kbox.engine
 */

'use strict';

var core = require('./core.js');
var util = require('./util.js');
var helpers = util.helpers;
var _ = require('lodash');

var provider = require('./engine/provider.js');
exports.provider = provider;

var engine = null;

var makeProviderError = function(msg) {
  var providerName = null;
  if (provider) {
    providerName = provider.getName();
  }
  var msgParts = [
    'Provider',
    providerName,
    msg
  ];
  var msg = _.filter(msgParts).join(' ');
  return new Error(msg);
};

var isProviderInstalled = false;
var verifyProviderInstalled = function(callback) {
  if (isProviderInstalled) {
    callback(null);
  } else {
    provider.isInstalled(function(err, isInstalled) {
      if (err) {
        callback(err);
      } else if (!isInstalled) {
        callback(makeProviderError('is NOT installed!'));
      } else {
        isProviderInstalled = true;
        callback(null);
      }
    });
  }
};

var isProviderUp = false;
var verifyProviderUp = function(callback) {
  if (isProviderUp) {
    callback(null);
  } else {
    provider.isUp(function(err, isUp) {
      if (err) {
        callback(err);
      } else if (!isUp) {
        callback(makeProviderError('is NOT up!'));
      } else {
        isProviderUp = true;
        callback(null);
      }
    });
  }
};

var engineHasBeenInit = false;
var verifyProviderIsReady = function(callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      verifyProviderUp(function(err) {
        if (err) {
          callback(err);
        } else {
          if (!engineHasBeenInit) {
            provider.engineConfig(function(err, config) {
              if (err) {
                callback(err);
              }
              else {
                engine.init(config);
                engineHasBeenInit = true;
                callback(null);
              }
            });
          }
          else {
            callback(null);
          }
        }
      });
    }
  });
};

/**
 * Returns the name of the configured provider.
 * @returns {string} - Name of the configured provider.
 */
exports.getProviderName = function() {
  return provider.name;
};

/**
 * Retrieves the state of the engine being up.
 * @arg {function} callback
 * @arg {error} callback.error
 * @arg {boolean} callback.isUp - Boolean representing the state of the engine being up.
 * @example
 * kbox.engine.isUp(function(err, isUp) {
 *   if (err) {
 *     throw err;
 *   } else if (isUp) {
 *     console.log('It is up!');
 *   }
 * });
 */
exports.isUp = function(callback) {
  provider.isUp(callback);
};

/**
 * Initializes kalabox engine.
 * @arg {string} globalConfig - Kalabox global config to initialize with.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * kbox.engine.init(globalConfig);
 */
exports.init = function(globalConfig) {
  if (!engine) {
    engine = require('./engine/' + globalConfig.engine + '.js');
    core.deps.register('providerModule', engine.getProviderModule());
  }
};

/**
 * Gets the engine provider into the state it needs to be in to do
 * engine things.
 * @arg {int} attempts - The amount of times to try to start the engine.
 * @arg {function} callback - Callback called when the engine has started.
 * @arg {error} callback.error
 */
exports.up = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.up(attempts, callback);
      provider.up(callback);
    }
  });
};

/**
 * Turns the engine off.
 * @arg {int} attempts - The amount of times to try to stop the engine.
 * @arg {function} callback - Callback called when the engine has been stopped.
 * @arg {error} callback.error
 */
exports.down = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.down(attempts, callback);
      provider.down(callback);
    }
  });
};

/**
 * Lists installed containers.
 * @arg {string} appName [optional] - App name to filter containers by.
 * @arg {function} callback - Callback called when the engine query completes.
 * @arg {error} callback.error
 * @arg {array} callback.containers - An array of container objects.
 * @example
 * kbox.engine.list(function(err, containers) {
 *   for (var i = 0; i < containers.length; ++i) {
 *     console.log(containers[i].name);
 *   }
 * });
 */
var list = exports.list = function(appName, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.list(appName, callback);
    }
  });
};

// @todo: document...
exports.exists = function(cid, callback) {
  list(function(err, containers) {
    if (err) {
      callback(err);
    } else {
      var exists = _.find(containers, function(container) {
        return container.id === cid || container.name === cid;
      });
      callback(null, exists !== undefined);
    }
  });
};

/**
 * Inspects a container and returns details.
 * @arg {string} containerId - Id of the container to inspect.
 * @arg {function} callback - Callback called when the container has been inspected.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the containers inspected data.
 */
exports.inspect = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.getEnsure(cid, 'inspect', function(err, container) {
        if (err) {
          callback(err);
        } else {
          engine.inspect(container, callback);
        }
      });
    }
  });
};

// @todo: document
exports.info = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.info(cid, callback);
    }
  });
};

/**
 * Creates a container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been created.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the created containers information.
 */
// @todo: find a good way to document createOptions, and possibly not make them docker specific.
exports.create = function(createOptions, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.create(createOptions, callback);
    }
  });
};

/**
 * Starts a container.
 * @arg {string} containerId - Id of the container to start.
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @todo Find a good way to document startOptions, and possibly not make them docker specific.
 */
exports.start = function(cid, startOptions, callback) {
  if (typeof startOptions === 'function' && callback === undefined) {
    callback = startOptions;
    startOptions = null;
  }
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.start(cid, startOptions, function(err) {
        // @todo: This short delay is to give redis a chance to get into a good state.
        // A better check would be bounded polling of redis until it is in a good state.
        setTimeout(function() {
          callback(err);
        }, 3000);
      });
    }
  });
};

/**
 * Runs a command in a container, in interactive mode
 * @arg {string} image - Name of image to run command in
 * @arg {string} cmd - Command to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/git:stable';
 * var cmd = ['git', 'status'];
 * kbox.engine.run(image, cmd, {}, {}, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   done();
 * });
 */
exports.run = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.run(image, cmd, process.stdin, process.stdout,
        createOpts, startOpts, callback);
    }
  });
};

// @todo: document
var query = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.query(image, cmd, createOpts, startOpts, function(err, stream) {
        callback(err, stream);
      }, function() {

      });
    }
  });
};
exports.query = query;

/**
 * Queries a container and returns a string
 * @arg {string} image - Name of image to run query in
 * @arg {string} cmd - Command (query) to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/syncthing:stable';
 * var cmd = '/bin/ls';
 * kbox.engine.queryString(image, cmd, {}, {}, function(err, data) {
 *   if (err) {
 *     throw err;
 *   } else {
 *     console.log(data);
 *   }
 * });
 */
exports.queryString = function(image, cmd, createOpts, startOpts, callback) {
  query(image, cmd, createOpts, startOpts, function(err, stream) {
    if (err) {
      callback(err);
    } else {
      var buff = null;
      stream.on('data', function(data) {
        if (!buff) {
          buff = data;
        } else {
          buff = Buffer.concat([buff, data]);
        }
      });
      stream.on('end', function() {
        if (buff) {
          callback(null, buff.toString());
        } else {
          callback();
        }
      });
    }
  });
};

/**
 * Stops a container.
 * @arg {string} containerId - Id of the container to stop.
 * @arg {function} callback - Callback called when the container has been stopped.
 * @arg {error} callback.error
 * @example
 * kbox.engine.stop(containerId, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   console.log('Container stopped!');
 * });
 */
exports.stop = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.stop(cid, callback);
    }
  });
};

/**
 * Removes a container from the engine.
 * @arg {string} containerId - Id of the container to remove.
 * @arg {function} callback - Callback called when the container has been removed.
 * @arg {error} callback.error
 */
exports.remove = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.remove(cid, callback);
    }
  });
};

/**
 * Pulls or builds the image for a container.
 * @arg {object} image - Image object to pull or build.
 * @arg {function} callback - Callback called when the image has been built.
 * @arg {error} callback.error
 */
exports.build = function(image, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      var fn = (image.build) ? 'build' : 'pull';
      engine[fn](image, callback);
    }
  });
};
<commit_msg>Code style error<commit_after>/**
 * Module for interfacing with the Kalabox container system implementation, and
 * the provider of the container system.
 *
 * NOTE: The container system and the provider are not always the same. For
 * example using docker on a Mac would use docker as the container system,
 * however it would be provided by boot2docker.
 * @module kbox.engine
 */

'use strict';

var core = require('./core.js');
var util = require('./util.js');
var helpers = util.helpers;
var _ = require('lodash');

var provider = require('./engine/provider.js');
exports.provider = provider;

var engine = null;

var makeProviderError = function(msg) {
  var providerName = null;
  if (provider) {
    providerName = provider.getName();
  }
  var msgParts = [
    'Provider',
    providerName,
    msg
  ];
  var fullErrorMsg = _.filter(msgParts).join(' ');
  return new Error(fullErrorMsg);
};

var isProviderInstalled = false;
var verifyProviderInstalled = function(callback) {
  if (isProviderInstalled) {
    callback(null);
  } else {
    provider.isInstalled(function(err, isInstalled) {
      if (err) {
        callback(err);
      } else if (!isInstalled) {
        callback(makeProviderError('is NOT installed!'));
      } else {
        isProviderInstalled = true;
        callback(null);
      }
    });
  }
};

var isProviderUp = false;
var verifyProviderUp = function(callback) {
  if (isProviderUp) {
    callback(null);
  } else {
    provider.isUp(function(err, isUp) {
      if (err) {
        callback(err);
      } else if (!isUp) {
        callback(makeProviderError('is NOT up!'));
      } else {
        isProviderUp = true;
        callback(null);
      }
    });
  }
};

var engineHasBeenInit = false;
var verifyProviderIsReady = function(callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      verifyProviderUp(function(err) {
        if (err) {
          callback(err);
        } else {
          if (!engineHasBeenInit) {
            provider.engineConfig(function(err, config) {
              if (err) {
                callback(err);
              }
              else {
                engine.init(config);
                engineHasBeenInit = true;
                callback(null);
              }
            });
          }
          else {
            callback(null);
          }
        }
      });
    }
  });
};

/**
 * Returns the name of the configured provider.
 * @returns {string} - Name of the configured provider.
 */
exports.getProviderName = function() {
  return provider.name;
};

/**
 * Retrieves the state of the engine being up.
 * @arg {function} callback
 * @arg {error} callback.error
 * @arg {boolean} callback.isUp - Boolean representing the state of the engine being up.
 * @example
 * kbox.engine.isUp(function(err, isUp) {
 *   if (err) {
 *     throw err;
 *   } else if (isUp) {
 *     console.log('It is up!');
 *   }
 * });
 */
exports.isUp = function(callback) {
  provider.isUp(callback);
};

/**
 * Initializes kalabox engine.
 * @arg {string} globalConfig - Kalabox global config to initialize with.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * kbox.engine.init(globalConfig);
 */
exports.init = function(globalConfig) {
  if (!engine) {
    engine = require('./engine/' + globalConfig.engine + '.js');
    core.deps.register('providerModule', engine.getProviderModule());
  }
};

/**
 * Gets the engine provider into the state it needs to be in to do
 * engine things.
 * @arg {int} attempts - The amount of times to try to start the engine.
 * @arg {function} callback - Callback called when the engine has started.
 * @arg {error} callback.error
 */
exports.up = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.up(attempts, callback);
      provider.up(callback);
    }
  });
};

/**
 * Turns the engine off.
 * @arg {int} attempts - The amount of times to try to stop the engine.
 * @arg {function} callback - Callback called when the engine has been stopped.
 * @arg {error} callback.error
 */
exports.down = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.down(attempts, callback);
      provider.down(callback);
    }
  });
};

/**
 * Lists installed containers.
 * @arg {string} appName [optional] - App name to filter containers by.
 * @arg {function} callback - Callback called when the engine query completes.
 * @arg {error} callback.error
 * @arg {array} callback.containers - An array of container objects.
 * @example
 * kbox.engine.list(function(err, containers) {
 *   for (var i = 0; i < containers.length; ++i) {
 *     console.log(containers[i].name);
 *   }
 * });
 */
var list = exports.list = function(appName, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.list(appName, callback);
    }
  });
};

// @todo: document...
exports.exists = function(cid, callback) {
  list(function(err, containers) {
    if (err) {
      callback(err);
    } else {
      var exists = _.find(containers, function(container) {
        return container.id === cid || container.name === cid;
      });
      callback(null, exists !== undefined);
    }
  });
};

/**
 * Inspects a container and returns details.
 * @arg {string} containerId - Id of the container to inspect.
 * @arg {function} callback - Callback called when the container has been inspected.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the containers inspected data.
 */
exports.inspect = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.getEnsure(cid, 'inspect', function(err, container) {
        if (err) {
          callback(err);
        } else {
          engine.inspect(container, callback);
        }
      });
    }
  });
};

// @todo: document
exports.info = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.info(cid, callback);
    }
  });
};

/**
 * Creates a container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been created.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the created containers information.
 */
// @todo: find a good way to document createOptions, and possibly not make them docker specific.
exports.create = function(createOptions, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.create(createOptions, callback);
    }
  });
};

/**
 * Starts a container.
 * @arg {string} containerId - Id of the container to start.
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @todo Find a good way to document startOptions, and possibly not make them docker specific.
 */
exports.start = function(cid, startOptions, callback) {
  if (typeof startOptions === 'function' && callback === undefined) {
    callback = startOptions;
    startOptions = null;
  }
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.start(cid, startOptions, function(err) {
        // @todo: This short delay is to give redis a chance to get into a good state.
        // A better check would be bounded polling of redis until it is in a good state.
        setTimeout(function() {
          callback(err);
        }, 3000);
      });
    }
  });
};

/**
 * Runs a command in a container, in interactive mode
 * @arg {string} image - Name of image to run command in
 * @arg {string} cmd - Command to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/git:stable';
 * var cmd = ['git', 'status'];
 * kbox.engine.run(image, cmd, {}, {}, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   done();
 * });
 */
exports.run = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.run(image, cmd, process.stdin, process.stdout,
        createOpts, startOpts, callback);
    }
  });
};

// @todo: document
var query = function(image, cmd, createOpts, startOpts, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.query(image, cmd, createOpts, startOpts, function(err, stream) {
        callback(err, stream);
      }, function() {

      });
    }
  });
};
exports.query = query;

/**
 * Queries a container and returns a string
 * @arg {string} image - Name of image to run query in
 * @arg {string} cmd - Command (query) to run
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {object} createOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @example
 * var image = 'kalabox/syncthing:stable';
 * var cmd = '/bin/ls';
 * kbox.engine.queryString(image, cmd, {}, {}, function(err, data) {
 *   if (err) {
 *     throw err;
 *   } else {
 *     console.log(data);
 *   }
 * });
 */
exports.queryString = function(image, cmd, createOpts, startOpts, callback) {
  query(image, cmd, createOpts, startOpts, function(err, stream) {
    if (err) {
      callback(err);
    } else {
      var buff = null;
      stream.on('data', function(data) {
        if (!buff) {
          buff = data;
        } else {
          buff = Buffer.concat([buff, data]);
        }
      });
      stream.on('end', function() {
        if (buff) {
          callback(null, buff.toString());
        } else {
          callback();
        }
      });
    }
  });
};

/**
 * Stops a container.
 * @arg {string} containerId - Id of the container to stop.
 * @arg {function} callback - Callback called when the container has been stopped.
 * @arg {error} callback.error
 * @example
 * kbox.engine.stop(containerId, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   console.log('Container stopped!');
 * });
 */
exports.stop = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.stop(cid, callback);
    }
  });
};

/**
 * Removes a container from the engine.
 * @arg {string} containerId - Id of the container to remove.
 * @arg {function} callback - Callback called when the container has been removed.
 * @arg {error} callback.error
 */
exports.remove = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.remove(cid, callback);
    }
  });
};

/**
 * Pulls or builds the image for a container.
 * @arg {object} image - Image object to pull or build.
 * @arg {function} callback - Callback called when the image has been built.
 * @arg {error} callback.error
 */
exports.build = function(image, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      var fn = (image.build) ? 'build' : 'pull';
      engine[fn](image, callback);
    }
  });
};
<|endoftext|>


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

// ---

var logger = require(path.join(__dirname, 'logger.js'));
var packages = require(path.join(__dirname, 'packages.js'));
var services = require(path.join(__dirname, 'services.js'));
var commands = require(path.join(__dirname, 'commands.js'));
var bootstrap = require(path.join(__dirname, 'bootstrap.js'));

// ---

function launch(opt, manifest, plugins, target, callback) {
	logger.silly('executing roost plugins');

	(plugins || []).forEach(function (plugin) {
		plugin.roost(opt, manifest, target);
	});

	logger.silly('executing roost workflow');

	bootstrap.roost(opt, manifest, target);
	packages.roost(opt, manifest, target);
	services.roost(opt, manifest, target);
	commands.roost(opt, manifest, target);

	target.on('error', function (error) {
		callback(error);
	});

	target.on('complete', function () {
		callback();
	});

	logger.silly('igniting target');

	target.ignite(opt.options.dry);
}

// ---

exports.launch = launch;
<commit_msg>Sync comes before everything.<commit_after>var path = require('path');

// ---

var sync = require(path.join(__dirname, 'sync.js'));
var logger = require(path.join(__dirname, 'logger.js'));
var packages = require(path.join(__dirname, 'packages.js'));
var services = require(path.join(__dirname, 'services.js'));
var commands = require(path.join(__dirname, 'commands.js'));
var bootstrap = require(path.join(__dirname, 'bootstrap.js'));

// ---

function launch(opt, manifest, plugins, target, callback) {
	logger.silly('executing roost plugins');

	(plugins || []).forEach(function (plugin) {
		plugin.roost(opt, manifest, target);
	});

	logger.silly('executing roost workflow');

	sync.roost(opt, manifest, target);
	bootstrap.roost(opt, manifest, target);
	packages.roost(opt, manifest, target);
	services.roost(opt, manifest, target);
	commands.roost(opt, manifest, target);

	target.on('error', function (error) {
		callback(error);
	});

	target.on('complete', function () {
		callback();
	});

	logger.silly('igniting target');

	target.ignite(opt.options.dry);
}

// ---

exports.launch = launch;
<|endoftext|>


<commit_before>"use strict";

var htmlparser = require("htmlparser2");
var domutils = require('domutils');
var visitor = require('./visitor.js');
var evaluator = require('./evaluator.js');
var nextTag = require('./utilities.js').nextTag;
var replaceNode = require('./utilities.js').replaceNode;

function pearl() {
}

function getModel(state) {
    var obj = {};
    for (var i = 0; i < state.modelStack.length; i++) {
        obj = Object.assign(obj, state.modelStack[i]);
    }
    return obj;
}

function popBlock(id, state) {
    for (var j = state.blockStack.length - 1; j >= 0; j--) {
        if (id in state.blockStack[j]) {
            var block = state.blockStack[j][id];
            delete state.blockStack[j][id];
            return htmlparser.parseDOM(block)[0];
        }
    }
    return null;
}

pearl.process = function (dom, model, config) {
    dom = { type: "tag", name: "pearl", children: dom };
    for (var c = 0; c < dom.children.length; c++) {
        dom.children[c].parent = dom;
    }

    var defaults = {};
    defaults.resource = {};
    if (process.env.NODE_ENV === "development") {
        defaults.resource.format = "{path}.{type}";
    } else {
        defaults.resource.format = "{path}.min.{type}";
    }

    //TODO: Extend defaults
    config = Object.assign({}, defaults, config);

    var state = {
        regions: {},
        templates: {},
        exports: {},
        blockStack: [],
        modelStack: [model],
        dom: dom,
        config: config
    };

    var els = domutils.getElementsByTagName("region", dom);
    for (var j = 0; j < els.length; j++) {
        state.regions[els[j].attribs.id] = els[j];
    }

    els = domutils.getElementsByTagName("component", dom);
    for (var i = 0; i < els.length; i++) {
        domutils.removeElement(els[i]);
        els[i].parent = null;
        els[i].next = null;
        els[i].prev = null;
        state.templates[els[i].attribs.id] = domutils.getOuterHTML(els[i]);
    }

    pearl.visitor.walk(dom.children, state);

    for (var k in state.regions) {
        domutils.removeElement(state.regions[k]);
    }

    return dom.children;
};

pearl.tags = {
    text: function (node, state) {
        //Simply rewrite the text node
        node.data = evaluator.rewrite(node.data, getModel(state));
    },
    include: function (node, state) {
        var $ = {};
        //Generate arguments object
        for (var attr in node.attribs) {
            if (attr[0] === '$') {
                $[attr.substr(1)] = evaluator.rewrite(node.attribs[attr], getModel(state));
            }
        }

        //Find and store all blocks that are being overridden and then remove them
        var overrideBlocks = domutils.getElementsByTagName("block", node);
        var blocks = {};
        for (var i = 0; i < overrideBlocks.length; i++) {
            blocks[overrideBlocks[i].attribs.id] = domutils.getOuterHTML(overrideBlocks[i]);
            domutils.removeElement(overrideBlocks[i]);
        }

        //Push new scope
        state.blockStack.push(blocks);
        state.modelStack.push({ $: $ });

        //Create a new DOM object from the template object and visit it
        var template = htmlparser.parseDOM(state.templates[node.attribs.name])[0];
        pearl.visitor.walk(template.children, state);

        //Pop scope
        state.modelStack.pop();
        state.blockStack.pop();

        //Replace this include with the children of the template
        replaceNode(node, template.children);

        //Dont update the children, we already have
        return false;
    },
    export: function (node, state) {
        //Check to see if this export is marked as unique indicating that it should only be exported once
        if ("unique" in node.attribs) {
            var uid = evaluator.rewrite(node.attribs.unique, getModel(state));
            //If we've already exported this just remove it
            if (uid in state.exports) {
                domutils.removeElement(node);
                return;
            } else {
                state.exports[uid] = true;
            }
        }

        //Ensure its children are processed and then copy it into the target region
        pearl.visitor.walk(node.children, state);

        var into = evaluator.rewrite(node.attribs.into, getModel(state));
        if (into in state.regions) {
            var region = state.regions[into];

            for (var i = 0; i < node.children.length; i++) {
                domutils.prepend(region, node.children[i]);
            }

            domutils.removeElement(node);

            //Dont update the children, we already have
            return false;
        } else {
            this.error(node, "region not found: " + into);
        }
    },
    resource: function (node, state) {
        var type = evaluator.rewrite(node.attribs.type, getModel(state));
        var path = evaluator.rewrite(node.attribs.path, getModel(state));

        path = state.config.resource.format.replace("{path}", path).replace("{type}", type);

        var newNode;

        //Create a new link or script tag depending on the type
        switch (type) {
            case "css":
                newNode = {
                    type: "tag",
                    name: "link",
                    attribs: {
                        href: path,
                        rel: "stylesheet"
                    }
                };
                break;
            case "js":
                newNode = {
                    type: "tag",
                    name: "script",
                    attribs: {
                        src: path,
                        type: "text/javascript"
                    }
                };
                break;
        }

        //Replace the resource node
        domutils.prepend(node, newNode);
        domutils.removeElement(node);
    },
    if: function (node, state) {
        var nodes = [];
        nodes.push(node);

        //Process all elseif/else nodes following
        while (true) {
            node = nextTag(node);
            if (node === null) {
                break;
            } else if (node.name === "elseif") {
                nodes.push(node);
            } else if (node.name === "else") {
                nodes.push(node);
                break;
            } else {
                break;
            }
        }

        //Iterate over each condition and check it for success
        for (var i = 0; i < nodes.length; i++) {
            var cond = false;
            var n = nodes[i];
            if (n.name === "else") {
                cond = true;
            } else {
                var condition = evaluator.evaluate(n.attribs.condition, getModel(state));
                if (condition && condition !== "undefined") {
                    cond = true;
                }
            }
            //If the condition evaluated to true then append its children
            if (cond) {
                pearl.visitor.walk(n.children, state);

                for (var j = 0; j < n.children.length; j++) {
                    domutils.prepend(n, n.children[j]);
                }
                break;
            }
        }

        //Remove all if/elseif/else nodes
        for (var k = 0; k < nodes.length; k++) {
            domutils.removeElement(nodes[k]);
        }
    },
    for: function (node, state) {
        var variable = node.attribs.var;
        var target = evaluator.rewrite(node.attribs.in, getModel(state));

        //Get the HTML of the node se we can duplicate it
        var html = domutils.getOuterHTML(node);

        //Iterate over each target
        for (var i = 0; i < target.length; i++) {
            var block = htmlparser.parseDOM(html)[0];

            //Create a new scope with the key and process children
            var k = {};
            k[variable] = i;
            state.modelStack.push(k);
            pearl.visitor.walk(block.children, state);
            //Pop the model off the stack
            state.modelStack.pop();

            //Append the children after the node
            for (var x = 0; x < block.children.length; x++) {
                domutils.prepend(node, block.children[x]);
            }
        }

        //Remove the node
        domutils.removeElement(node);
        return false;
    },
    foreach: function (node, state) {
        var variable = node.attribs.var;
        var target = evaluator.rewrite(node.attribs.in, getModel(state));

        //Get the HTML of the node se we can duplicate it
        var html = domutils.getOuterHTML(node);

        //Iterate over each target
        for (var key in target) {
            var block = htmlparser.parseDOM(html)[0];

            //Create a new scope with the key and process children
            var k = {};
            k[variable] = key;
            state.modelStack.push(k);
            pearl.visitor.walk(block.children, state);

            //Pop the model off the stack
            state.modelStack.pop();

            //Append the children after the node
            for (var i = 0; i < block.children.length; i++) {
                domutils.prepend(node, block.children[i]);
            }
        }

        //Remove the node
        domutils.removeElement(node);
        return false;
    },
    block: function (node, state) {
        //Try and find the block that we are overriding
        var block = popBlock(node.attribs.id, state);
        if (block === null) {
            replaceNode(node, node.children);
            return;
        }

        //Visit the children of the node and add then to the dom
        pearl.visitor.walk(block.children, state);

        replaceNode(node, block.children);
        return false;
    }
    /*,breakpoint: function (node, state) {
        //Debugging only, simply remove the node and break
        domutils.removeElement(node);
        debugger;
    },*/
};

pearl.visitor = new visitor(function (node, state) {
    if (node.type in pearl.tags) {
        if (pearl.tags[node.type](node, state) === false) return visitor.Skip;
    }

    if (node.type == "tag") {
        if (node.name in pearl.tags) {
            if (pearl.tags[node.name](node, state) === false) return visitor.Skip;
        }

        if (node.attribs) {
            for (var attr in node.attribs) {
                node.attribs[attr] = evaluator.rewrite(node.attribs[attr], getModel(state));
            }
        }
    }

}, function (node) {
    return node.children;
});

module.exports = pearl;<commit_msg>Now loads default values from the template<commit_after>"use strict";

var htmlparser = require("htmlparser2");
var domutils = require('domutils');
var visitor = require('./visitor.js');
var evaluator = require('./evaluator.js');
var nextTag = require('./utilities.js').nextTag;
var replaceNode = require('./utilities.js').replaceNode;

function pearl() {
}

function getModel(state) {
    var obj = {};
    for (var i = 0; i < state.modelStack.length; i++) {
        obj = Object.assign(obj, state.modelStack[i]);
    }
    return obj;
}

function popBlock(id, state) {
    for (var j = state.blockStack.length - 1; j >= 0; j--) {
        if (id in state.blockStack[j]) {
            var block = state.blockStack[j][id];
            delete state.blockStack[j][id];
            return htmlparser.parseDOM(block)[0];
        }
    }
    return null;
}

pearl.process = function (dom, model, config) {
    dom = { type: "tag", name: "pearl", children: dom };
    for (var c = 0; c < dom.children.length; c++) {
        dom.children[c].parent = dom;
    }

    var defaults = {};
    defaults.resource = {};
    if (process.env.NODE_ENV === "development") {
        defaults.resource.format = "{path}.{type}";
    } else {
        defaults.resource.format = "{path}.min.{type}";
    }

    //TODO: Extend defaults
    config = Object.assign({}, defaults, config);

    var state = {
        regions: {},
        templates: {},
        exports: {},
        blockStack: [],
        modelStack: [model],
        dom: dom,
        config: config
    };

    var els = domutils.getElementsByTagName("region", dom);
    for (var j = 0; j < els.length; j++) {
        state.regions[els[j].attribs.id] = els[j];
    }

    els = domutils.getElementsByTagName("component", dom);
    for (var i = 0; i < els.length; i++) {
        domutils.removeElement(els[i]);
        els[i].parent = null;
        els[i].next = null;
        els[i].prev = null;
        state.templates[els[i].attribs.id] = domutils.getOuterHTML(els[i]);
    }

    pearl.visitor.walk(dom.children, state);

    for (var k in state.regions) {
        domutils.removeElement(state.regions[k]);
    }

    return dom.children;
};

pearl.tags = {
    text: function (node, state) {
        //Simply rewrite the text node
        node.data = evaluator.rewrite(node.data, getModel(state));
    },
    include: function (node, state) {
        var $ = {};

        //Create a new DOM object from the template object and visit it
        var template = htmlparser.parseDOM(state.templates[node.attribs.name])[0];
        for (var def in template.attribs) {
            if (def[0] === '$') {
                $[def.substr(1)] = evaluator.rewrite(template.attribs[def], getModel(state));
            }
        }

        //Generate arguments object
        for (var attr in node.attribs) {
            if (attr[0] === '$') {
                $[attr.substr(1)] = evaluator.rewrite(node.attribs[attr], getModel(state));
            }
        }

        //Find and store all blocks that are being overridden and then remove them
        var overrideBlocks = domutils.getElementsByTagName("block", node);
        var blocks = {};
        for (var i = 0; i < overrideBlocks.length; i++) {
            blocks[overrideBlocks[i].attribs.id] = domutils.getOuterHTML(overrideBlocks[i]);
            domutils.removeElement(overrideBlocks[i]);
        }

        //Push new scope
        state.blockStack.push(blocks);
        state.modelStack.push({ $: $ });

        pearl.visitor.walk(template.children, state);

        //Pop scope
        state.modelStack.pop();
        state.blockStack.pop();

        //Replace this include with the children of the template
        replaceNode(node, template.children);

        //Dont update the children, we already have
        return false;
    },
    export: function (node, state) {
        //Check to see if this export is marked as unique indicating that it should only be exported once
        if ("unique" in node.attribs) {
            var uid = evaluator.rewrite(node.attribs.unique, getModel(state));
            //If we've already exported this just remove it
            if (uid in state.exports) {
                domutils.removeElement(node);
                return;
            } else {
                state.exports[uid] = true;
            }
        }

        //Ensure its children are processed and then copy it into the target region
        pearl.visitor.walk(node.children, state);

        var into = evaluator.rewrite(node.attribs.into, getModel(state));
        if (into in state.regions) {
            var region = state.regions[into];

            for (var i = 0; i < node.children.length; i++) {
                domutils.prepend(region, node.children[i]);
            }

            domutils.removeElement(node);

            //Dont update the children, we already have
            return false;
        } else {
            this.error(node, "region not found: " + into);
        }
    },
    resource: function (node, state) {
        var type = evaluator.rewrite(node.attribs.type, getModel(state));
        var path = evaluator.rewrite(node.attribs.path, getModel(state));

        path = state.config.resource.format.replace("{path}", path).replace("{type}", type);

        var newNode;

        //Create a new link or script tag depending on the type
        switch (type) {
            case "css":
                newNode = {
                    type: "tag",
                    name: "link",
                    attribs: {
                        href: path,
                        rel: "stylesheet"
                    }
                };
                break;
            case "js":
                newNode = {
                    type: "tag",
                    name: "script",
                    attribs: {
                        src: path,
                        type: "text/javascript"
                    }
                };
                break;
        }

        //Replace the resource node
        domutils.prepend(node, newNode);
        domutils.removeElement(node);
    },
    if: function (node, state) {
        var nodes = [];
        nodes.push(node);

        //Process all elseif/else nodes following
        while (true) {
            node = nextTag(node);
            if (node === null) {
                break;
            } else if (node.name === "elseif") {
                nodes.push(node);
            } else if (node.name === "else") {
                nodes.push(node);
                break;
            } else {
                break;
            }
        }

        //Iterate over each condition and check it for success
        for (var i = 0; i < nodes.length; i++) {
            var cond = false;
            var n = nodes[i];
            if (n.name === "else") {
                cond = true;
            } else {
                var condition = evaluator.evaluate(n.attribs.condition, getModel(state));
                if (condition && condition !== "undefined") {
                    cond = true;
                }
            }
            //If the condition evaluated to true then append its children
            if (cond) {
                pearl.visitor.walk(n.children, state);

                for (var j = 0; j < n.children.length; j++) {
                    domutils.prepend(n, n.children[j]);
                }
                break;
            }
        }

        //Remove all if/elseif/else nodes
        for (var k = 0; k < nodes.length; k++) {
            domutils.removeElement(nodes[k]);
        }
    },
    for: function (node, state) {
        var variable = node.attribs.var;
        var target = evaluator.rewrite(node.attribs.in, getModel(state));

        //Get the HTML of the node se we can duplicate it
        var html = domutils.getOuterHTML(node);

        //Iterate over each target
        for (var i = 0; i < target.length; i++) {
            var block = htmlparser.parseDOM(html)[0];

            //Create a new scope with the key and process children
            var k = {};
            k[variable] = i;
            state.modelStack.push(k);
            pearl.visitor.walk(block.children, state);
            //Pop the model off the stack
            state.modelStack.pop();

            //Append the children after the node
            for (var x = 0; x < block.children.length; x++) {
                domutils.prepend(node, block.children[x]);
            }
        }

        //Remove the node
        domutils.removeElement(node);
        return false;
    },
    foreach: function (node, state) {
        var variable = node.attribs.var;
        var target = evaluator.rewrite(node.attribs.in, getModel(state));

        //Get the HTML of the node se we can duplicate it
        var html = domutils.getOuterHTML(node);

        //Iterate over each target
        for (var key in target) {
            var block = htmlparser.parseDOM(html)[0];

            //Create a new scope with the key and process children
            var k = {};
            k[variable] = key;
            state.modelStack.push(k);
            pearl.visitor.walk(block.children, state);

            //Pop the model off the stack
            state.modelStack.pop();

            //Append the children after the node
            for (var i = 0; i < block.children.length; i++) {
                domutils.prepend(node, block.children[i]);
            }
        }

        //Remove the node
        domutils.removeElement(node);
        return false;
    },
    block: function (node, state) {
        //Try and find the block that we are overriding
        var block = popBlock(node.attribs.id, state);
        if (block === null) {
            replaceNode(node, node.children);
            return;
        }

        //Visit the children of the node and add then to the dom
        pearl.visitor.walk(block.children, state);

        replaceNode(node, block.children);
        return false;
    }
    /*,breakpoint: function (node, state) {
        //Debugging only, simply remove the node and break
        domutils.removeElement(node);
        debugger;
    },*/
};

pearl.visitor = new visitor(function (node, state) {
    if (node.type in pearl.tags) {
        if (pearl.tags[node.type](node, state) === false) return visitor.Skip;
    }

    if (node.type == "tag") {
        if (node.name in pearl.tags) {
            if (pearl.tags[node.name](node, state) === false) return visitor.Skip;
        }

        if (node.attribs) {
            for (var attr in node.attribs) {
                node.attribs[attr] = evaluator.rewrite(node.attribs[attr], getModel(state));
            }
        }
    }

}, function (node) {
    return node.children;
});

module.exports = pearl;<|endoftext|>


<commit_before>/*
 * PubSub.js by Brian Beckett
 * Version 1.0.0
 * https://github.com/cosmicflame/pubsub.js
 * Released under the MIT license
 */
; (function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else {
		// Browser globals
		root.pubsub = factory();
	}
}(this, function () {
	var PubSub = function() {

		var subscribers = {}

		/**
		 * Publish an event.
		 * @param eventName  The string name of the event.
		 * @param data  Data object to pass to subscribers.  Can be undefined.
		 */
		this.pub = function(eventName, data) {
			if (eventName && typeof eventName === 'string') {
				data = data || {}
				if (subscribers.hasOwnProperty(eventName)) {
					subscribers[eventName].forEach(function(callback) {
						callback(data)
					})
				}
			} else {
				throw new Error('pubsub.pub requires a string and an optional function')
			}
		}

		/**
		 * Subscribe to an event.
		 * @param event  The string name of the event to listen for.
		 * @param callback  Function to call when event happens.
		 * Will be passed data object.
		 */
		this.sub = function(event, callback) {
			if (event
			    && callback
			    && typeof event === 'string'
			    && typeof callback === 'function')
			{
				if (!subscribers.hasOwnProperty(event)) {
					subscribers[event] = []
				}
				if (subscribers[event].indexOf(callback) === -1) {
					subscribers[event].push(callback)
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}

		/**
		 * Unsubscribe from an event
		 * @param event  The string name of the event to unsubscribe from.
		 * @param callback  Function that's currently subscribed to event and should be unsubscribed
		 */
		this.unsub = function(event, callback) {
			if (event
			    && callback
			    && typeof event === 'string'
			    && typeof callback === 'function')
			{
				if (subscribers.hasOwnProperty(event)) {
					for (var i = 0; i < subscribers[event].length; i++) {
						if (subscribers[event][i] === callback) {
							subscribers[event][i] = function() {}
						}
					}
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}
	}

	return new PubSub()
}));
<commit_msg>Fix: useless error output<commit_after>/*
 * PubSub.js by Brian Beckett
 * Version 1.0.1
 * https://github.com/cosmicflame/pubsub.js
 * Released under the MIT license
 */
; (function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else {
		// Browser globals
		root.pubsub = factory();
	}
}(this, function () {
	var PubSub = function() {

		var subscribers = {}

		/**
		 * Publish an event.
		 * @param eventName  The string name of the event.
		 * @param data  Data object to pass to subscribers.  Can be undefined.
		 */
		this.pub = function(eventName, data) {
			if (eventName && typeof eventName === 'string') {
				data = data || {}
				if (subscribers.hasOwnProperty(eventName)) {
					subscribers[eventName].forEach(function(callback) {
						callback(data)
					})
				}
			} else {
				throw new Error('pubsub.pub requires a string and an optional data param')
			}
		}

		/**
		 * Subscribe to an event.
		 * @param event  The string name of the event to listen for.
		 * @param callback  Function to call when event happens.
		 * Will be passed data object.
		 */
		this.sub = function(event, callback) {
			if (event
			    && callback
			    && typeof event === 'string'
			    && typeof callback === 'function')
			{
				if (!subscribers.hasOwnProperty(event)) {
					subscribers[event] = []
				}
				if (subscribers[event].indexOf(callback) === -1) {
					subscribers[event].push(callback)
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}

		/**
		 * Unsubscribe from an event
		 * @param event  The string name of the event to unsubscribe from.
		 * @param callback  Function that's currently subscribed to event and should be unsubscribed
		 */
		this.unsub = function(event, callback) {
			if (event
			    && callback
			    && typeof event === 'string'
			    && typeof callback === 'function')
			{
				if (subscribers.hasOwnProperty(event)) {
					for (var i = 0; i < subscribers[event].length; i++) {
						if (subscribers[event][i] === callback) {
							subscribers[event][i] = function() {}
						}
					}
				}
			} else {
				throw new Error('pubsub.sub requires a string and a function')
			}
		}
	}

	return new PubSub()
}));
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-lwm2m
 *
 * iotagent-lwm2m is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-lwm2m is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-lwm2m.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

module.exports = {
    UnknownInternalError(msg) {
        this.name = 'UNKNOWN_INTERNAL_ERROR';
        this.message = 'Unknown, unespecified internal error: ' + msg;
    },
    OmaRegistryConnectionError(msg) {
        this.name = 'OMA_REGISTRY_CONNECTION_ERROR';
        this.message = "Couldn't retrieve OMA Registry information due to a connection error: " + msg;
    },
    OmaRegistryServerError(status) {
        this.name = 'OMA_REGISTRY_SERVER_ERROR';
        this.message = 'Server error retrieving OMA Registry. Status code: ' + status;
    },
    TypeNotFound() {
        this.name = 'TYPE_NOT_FOUND';
        this.message = 'It was not possible to determine the type for the registering client';
    },
    OmaMappingNotFound() {
        this.name = 'OMA_MAPPING_NOT_FOUND';
        this.message = 'No OMA to NGSI Mapping found for this device or type';
    }
};
<commit_msg>Add constructors<commit_after>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-lwm2m
 *
 * iotagent-lwm2m is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-lwm2m is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-lwm2m.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

class UnknownInternalError {
    constructor(msg) {
        this.name = 'UNKNOWN_INTERNAL_ERROR';
        this.message = 'Unknown, unespecified internal error: ' + msg;
    }
}
class OmaRegistryConnectionError {
    constructor(msg) {
        this.name = 'OMA_REGISTRY_CONNECTION_ERROR';
        this.message = "Couldn't retrieve OMA Registry information due to a connection error: " + msg;
    }
}
class OmaRegistryServerError {
    constructor(status) {
        this.name = 'OMA_REGISTRY_SERVER_ERROR';
        this.message = 'Server error retrieving OMA Registry. Status code: ' + status;
    }
}
class TypeNotFound {
    constructor() {
        this.name = 'TYPE_NOT_FOUND';
        this.message = 'It was not possible to determine the type for the registering client';
    }
}
class OmaMappingNotFound {
    constructor() {
        this.name = 'OMA_MAPPING_NOT_FOUND';
        this.message = 'No OMA to NGSI Mapping found for this device or type';
    }
}

module.exports = {
    UnknownInternalError,
    OmaRegistryConnectionError,
    OmaRegistryServerError,
    TypeNotFound,
    OmaMappingNotFound
};
<|endoftext|>


<commit_before>(function($){
  'use strict';

  var defaults = {
    attributeName: 'bindr',
    selector: function() {
      return ['[data-', this.attributeName, ']'].join('');
    }
  };

  $.fn.bindr = function(options) {

    options = $.extend({}, defaults, options);

    return this.each(function() {
      var $el     = $(this),
          targets = $el.find(options.selector()).addBack(options.selector());

      targets.each(function() {
        var $el            = $(this),
            methods        = $el.data(options.attributeName).split(' ').reverse(),
            args           = $el.data(options.attributeName+'Arguments') && $el.data(options.attributeName+'Arguments').split(', ').reverse(),
            includeLastArg = $el.data(options.attributeName+'LastArg'),
            method,
            arg,
            applyArgs = [];

        while(method = methods.pop()) {
          while(args && (arg = args.pop())) {
            applyArgs.push(arg)
          }

          if(!applyArgs.length || includeLastArg) {
            applyArgs.push($el.data());
          }

          $el[method].apply($el, applyArgs);
        }
      });
    });
  };

})(jQuery);<commit_msg>refactored code to be more OO<commit_after>(function($){
  'use strict';

  var Bindr = function(el, options) {
    this.$el = $(el);
    this.options = options;

    this.run();
  };

  Bindr.DEFAULTS = {
    attributeName: 'bindr',
    selector: function() {
      return ['[data-', this.attributeName, ']'].join('');
    },
    dataAttr: function(attribute) {
      return this.attributeName + attribute.charAt(0).toUpperCase() + attribute.slice(1);
    }
  };

  Bindr.prototype.methods = function() {
    return this.$el.data(this.options.attributeName).split(' ');
  };

  Bindr.prototype.args = function() {
    var args = this.$el.data(this.options.dataAttr('arguments')) ? this.$el.data(this.options.dataAttr('arguments')).split(', ') : [];
    var dataArgs   = this.$el.data();

    if(!args.length || this.$el.data(this.options.dataAttr('lastArg'))) {
      args.push(dataArgs);
    }

    return args;
  };

  Bindr.prototype.run = function() {
    var methods = this.methods().reverse();
    var i = methods.length;
    var args = this.args();

    while(i--) {
      this.$el[methods[i]].apply(this.$el, args);
    }
  };

  $.fn.bindr = function(options) {

    options = $.extend({}, Bindr.DEFAULTS, options);

    return this.each(function() {
      var targets = $(this).find(options.selector()).addBack(options.selector());

      targets.each(function() {
        var bindr = new Bindr(this, options);
      });
    });
  };

})(jQuery);
<|endoftext|>


<commit_before>// @ts-nocheck
'use strict';
const PrettyError = require('pretty-error');
const prettyError = new PrettyError();
prettyError.withoutColors();
prettyError.skipPackage('html-plugin-evaluation');
prettyError.skipNodeFiles();
prettyError.skip(function (traceLine) {
  return traceLine.path === 'html-plugin-evaluation';
});

module.exports = function (err, context) {
  return {
    toHtml: function () {
      return 'Html Webpack Plugin:\n
\n' + this.toString() + '
';
    },
    toJsonHtml: function () {
      return JSON.stringify(this.toHtml());
    },
    toString: function () {
      return prettyError.render(err).replace(/webpack:\/\/\/\./g, context);
    }
  };
};
<commit_msg>fix: Catch and ignore pretty-error errors<commit_after>// @ts-nocheck
'use strict';
const PrettyError = require('pretty-error');
const prettyError = new PrettyError();
prettyError.withoutColors();
prettyError.skipPackage('html-plugin-evaluation');
prettyError.skipNodeFiles();
prettyError.skip(function (traceLine) {
  return traceLine.path === 'html-plugin-evaluation';
});

module.exports = function (err, context) {
  return {
    toHtml: function () {
      return 'Html Webpack Plugin:\n
\n' + this.toString() + '
';
    },
    toJsonHtml: function () {
      return JSON.stringify(this.toHtml());
    },
    toString: function () {
      try {
        return prettyError.render(err).replace(/webpack:\/\/\/\./g, context);
      } catch (e) {
        // This can sometimes fail. We don't know why, but returning the
        // original error is better than returning the error thrown by
        // pretty-error.
        return err;
      }
    }
  };
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';
import { withRouter } from 'react-router';

const tapLogObject = function tapLogObject(obj) {
  console.log(obj);
  return obj;
};

const hostname = () => window.location.hostname;
const SHORT_CODE_LENGTH = 9;
const SHORTENED_LENGTH = hostname().length + SHORT_CODE_LENGTH + 1;
const urlRegex = /^(https?:\/\/)[^.]+(\.[^.]+)+$/i;

class ShortenForm extends Component {
  constructor() {
    super();
    this.state = {
      validURL: false,
      url: '',
    };
  }

  validType(url) {
    return typeof url === 'string';
  }

  validLength(url) {
    return url.length > SHORTENED_LENGTH;
  }

  validPattern(url) {
    const matches = urlRegex.exec(url);
    urlRegex.lastIndex = 0;

    return matches ? true : false;
  }

  isValidURL(url) {
    if (!this.validType(url)) {
      return {
        validURL: false,
        msg: 'Please, write a long URL for us to shorten',
      };
    }
    if (!this.validPattern(url)) {
      return {
        validURL: false,
        msg: `That is not a URL, please make sure it contains http:// https:// or whatever other protocol at the beginning.`,
      };
    }
    if (!this.validLength(url)) {
      return {
        validURL: false,
        msg: `That URL is already shorter than what we can give you (${SHORTENED_LENGTH} letters/symbols long).`,
      };
    }
    return { validURL: true, msg: "Hit 'Enter' or click 'shorten' button to get a shorter URL." };
  }

  updateText(event) {
    const val = event.target.value;
    this.setState({
      url: val,
      ...this.isValidURL(val),
    });
  }

  create(e) {
    e.preventDefault();
    this.props.shorten({
      variables: {
        short: {
          url: this.state.url,
        }
      }
    })
    .then(tapLogObject)
    .then(({
      data: {createShortURL: {shortCode}}
    }) => tapLogObject(shortCode))
    .then(code => this.props.history.push(`/data/public/${code}`));
  }

  render() {
    const { validURL } = this.state;
    let buttonClasses = 'button is-fullwidth is-large is-outlined is-danger is-disabled';
    let msgClasses = 'help has-text-centered is-danger';
    let urlIcon = 'fa fa-thumbs-down';
    if (validURL) {
      buttonClasses = 'button is-fullwidth is-large is-outlined is-danger';
      urlIcon = 'fa fa-check';
      msgClasses = 'help has-text-centered is-success';
    }
    return (

        <form onSubmit={this.create.bind(this)}>

              Pili-fy your URL

                <input
                  className="input is-large is-danger"
                  type="url"
                  placeholder="http://your-long-url.com/goes/here"
                  pattern="https?://.+\..+"
                  required={true}
                  onChange={this.updateText.bind(this)}
                  />

{this.state.msg || ''}

                <button
                  type="submit"
                  className={buttonClasses}
                  >Shorten</button>

        </form>

    );
  }
}

const createShortURL = gql`
mutation shorten($short: NewShortURLInput!){
	createShortURL(newShort: $short){
    id
    shortCode
    url
    owner
    visits
    lastVisited
  }
}
`;
const withMutation = graphql(createShortURL, {name: 'shorten'})(ShortenForm);
const withMutationAndRouter = withRouter(withMutation)
export default withMutationAndRouter;
<commit_msg>Changes<commit_after>import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';
import { withRouter } from 'react-router';

const tapLogObject = function tapLogObject(obj) {
  console.log(obj);
  return obj;
};

const hostname = () => window.location.hostname;
const SHORT_CODE_LENGTH = 9;
const SHORTENED_LENGTH = hostname().length + SHORT_CODE_LENGTH + 1;
const urlRegex = /^(https?:\/\/)[^.]+(\.[^.]+)+$/i;

class ShortenForm extends Component {
  constructor() {
    super();
    this.state = {
      validURL: false,
      url: '',
      customUrl: '',
      customShortCode: '',
    };
  }

  validType(url) {
    return typeof url === 'string';
  }

  validLength(url) {
    return url.length > SHORTENED_LENGTH;
  }

  validPattern(url) {
    const matches = urlRegex.exec(url);
    urlRegex.lastIndex = 0;

    return matches ? true : false;
  }

  isValidURL(url) {
    if (!this.validType(url)) {
      return {
        validURL: false,
        msg: 'Please, write a long URL for us to shorten',
      };
    }
    if (!this.validPattern(url)) {
      return {
        validURL: false,
        msg: `That is not a URL, please make sure it contains http:// https:// or whatever other protocol at the beginning.`,
      };
    }
    if (this.state.customShortCode.length <= 0) {

      if (!this.validLength(url)) {
        return {
          validURL: false,
          msg: `That URL is already shorter than what we can give you (${SHORTENED_LENGTH} letters/symbols long).`,
        };
      }

    }
    return { validURL: true, msg: "Hit 'Enter' or click 'shorten' button to get a shorter URL." };
  }

  updateText(event) {
    const val = event.target.value;
    this.setState({
      url: val,
      ...this.isValidURL(val),
    });
  }

  updateCustomText(event) {
    const customShortCode = event.target.value;
    const customUrl = `${hostname()}/${customShortCode}`;
    this.setState({
      ...this.isValidURL(this.state.url),
    })
    this.setState({
      customUrl,
      customShortCode,
    });
  }

  create(e) {
    e.preventDefault();
    this.props.shorten({
      variables: {
        short: {
          url: this.state.url,
          shortCode: this.state.customShortCode,
        }
      }
    })
    .then(tapLogObject)
    .then(({
      data: {createShortURL: {shortCode}}
    }) => tapLogObject(shortCode))
    .then(code => this.props.history.push(`/data/public/${code}`));
  }

  render() {
    const { validURL } = this.state;
    let buttonClasses = 'button is-fullwidth is-large is-outlined is-danger is-disabled';
    let msgClasses = 'help has-text-centered is-danger';
    let urlIcon = 'fa fa-thumbs-down';
    if (validURL) {
      buttonClasses = 'button is-fullwidth is-large is-outlined is-danger';
      urlIcon = 'fa fa-check';
      msgClasses = 'help has-text-centered is-success';
    }
    return (

        <form onSubmit={this.create.bind(this)}>

              Pili-fy your URL

                <input
                  className="input is-large is-danger"
                  type="url"
                  placeholder="http://your-long-url.com/goes/here"
                  pattern="https?://.+\..+"
                  required={true}
                  onChange={this.updateText.bind(this)}
                  />

{this.state.msg || ''}

              Customize it if you want.

                <input
                  className="input is-large is-danger"
                  placeholder="PickYourCustomUrl"
                  pattern="[\w]*"
                  onChange={this.updateCustomText.bind(this)}
                  />

{this.state.customUrl || "We'll generate a short url at random"}

                <button
                  type="submit"
                  className={buttonClasses}
                  >Shorten</button>

        </form>

    );
  }
}

const createShortURL = gql`
mutation shorten($short: NewShortURLInput!){
	createShortURL(newShort: $short){
    id
    shortCode
    url
    owner
    visits
    lastVisited
  }
}
`;
const withMutation = graphql(createShortURL, {name: 'shorten'})(ShortenForm);
const withMutationAndRouter = withRouter(withMutation)
export default withMutationAndRouter;
<|endoftext|>


<commit_before>
/**
 * socket.io
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

(function (exports, io) {

  /**
   * Expose constructor.
   */

  exports.EventEmitter = EventEmitter;

  /**
   * Event emitter constructor.
   *
   * @api public.
   */

  function EventEmitter () {};

  /**
   * Adds a listener
   *
   * @api public
   */

  EventEmitter.prototype.on = function (name, fn) {
    if (!this.$events) {
      this.$events = {};
    }

    if (!this.$events[name]) {
      this.$events[name] = fn;
    } else if (io.util.isArray(this.$events[name])) {
      this.$events[name].push(fn);
    } else {
      this.$events[name] = [this.$events[name], fn];
    }

    return this;
  };

  /**
   * Adds a volatile listener.
   *
   * @api public
   */

  EventEmitter.prototype.once = function (name, fn) {
    var self = this;

    function on () {
      self.removeListener(name, on);
      fn.apply(this, arguments);
    };

    on.listener = fn;
    this.on(name, on);

    return this;
  };

  /**
   * Removes a listener.
   *
   * @api public
   */

  EventEmitter.prototype.removeListener = function (name, fn) {
    if (this.$events && this.$events[name]) {
      var list = this.$events[name];

      if (io.util.isArray(list)) {
        var pos = -1;

        for (var i = 0, l = list.length; i < l; i++) {
          if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
            pos = i;
            break;
          }
        }

        if (pos < 0) {
          return this;
        }

        list.splice(pos, 1);

        if (!list.length) {
          delete this.$events[name];
        }
      } else if (list === fn || (list.listener && list.listener === fn)) {
        delete this.$events[name];
      }
    }

    return this;
  };

  /**
   * Removes all listeners for an event.
   *
   * @api public
   */

  EventEmitter.prototype.removeAllListeners = function (name) {
    if (name === undefined) {
      this.$events = {};
      return this;
    }

    if (this.$events && this.$events[name]) {
      this.$events[name] = null;
    }

    return this;
  };

  /**
   * Gets all listeners for a certain event.
   *
   * @api publci
   */

  EventEmitter.prototype.listeners = function (name) {
    if (!this.$events) {
      this.$events = {};
    }

    if (!this.$events[name]) {
      this.$events[name] = [];
    }

    if (!io.util.isArray(this.$events[name])) {
      this.$events[name] = [this.$events[name]];
    }

    return this.$events[name];
  };

  /**
   * Emits an event.
   *
   * @api public
   */

  EventEmitter.prototype.emit = function (name) {
    if (!this.$events) {
      return false;
    }

    var handler = this.$events[name];

    if (!handler) {
      return false;
    }

    var args = Array.prototype.slice.call(arguments, 1);

    if ('function' == typeof handler) {
      handler.apply(this, args);
    } else if (io.util.isArray(handler)) {
      var listeners = handler.slice();

      for (var i = 0, l = listeners.length; i < l; i++) {
        listeners[i].apply(this, args);
      }
    } else {
      return false;
    }

    return true;
  };

})(
    'undefined' != typeof io ? io : module.exports
  , 'undefined' != typeof io ? io : module.parent.exports
);
<commit_msg>added alias for addListener as the EventEmitter also supports this<commit_after>
/**
 * socket.io
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

(function (exports, io) {

  /**
   * Expose constructor.
   */

  exports.EventEmitter = EventEmitter;

  /**
   * Event emitter constructor.
   *
   * @api public.
   */

  function EventEmitter () {};

  /**
   * Adds a listener
   *
   * @api public
   */

  EventEmitter.prototype.on = function (name, fn) {
    if (!this.$events) {
      this.$events = {};
    }

    if (!this.$events[name]) {
      this.$events[name] = fn;
    } else if (io.util.isArray(this.$events[name])) {
      this.$events[name].push(fn);
    } else {
      this.$events[name] = [this.$events[name], fn];
    }

    return this;
  };

  EventEmitter.prototype.addListener = EventEmitter.prototype.on;

  /**
   * Adds a volatile listener.
   *
   * @api public
   */

  EventEmitter.prototype.once = function (name, fn) {
    var self = this;

    function on () {
      self.removeListener(name, on);
      fn.apply(this, arguments);
    };

    on.listener = fn;
    this.on(name, on);

    return this;
  };

  /**
   * Removes a listener.
   *
   * @api public
   */

  EventEmitter.prototype.removeListener = function (name, fn) {
    if (this.$events && this.$events[name]) {
      var list = this.$events[name];

      if (io.util.isArray(list)) {
        var pos = -1;

        for (var i = 0, l = list.length; i < l; i++) {
          if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
            pos = i;
            break;
          }
        }

        if (pos < 0) {
          return this;
        }

        list.splice(pos, 1);

        if (!list.length) {
          delete this.$events[name];
        }
      } else if (list === fn || (list.listener && list.listener === fn)) {
        delete this.$events[name];
      }
    }

    return this;
  };

  /**
   * Removes all listeners for an event.
   *
   * @api public
   */

  EventEmitter.prototype.removeAllListeners = function (name) {
    if (name === undefined) {
      this.$events = {};
      return this;
    }

    if (this.$events && this.$events[name]) {
      this.$events[name] = null;
    }

    return this;
  };

  /**
   * Gets all listeners for a certain event.
   *
   * @api publci
   */

  EventEmitter.prototype.listeners = function (name) {
    if (!this.$events) {
      this.$events = {};
    }

    if (!this.$events[name]) {
      this.$events[name] = [];
    }

    if (!io.util.isArray(this.$events[name])) {
      this.$events[name] = [this.$events[name]];
    }

    return this.$events[name];
  };

  /**
   * Emits an event.
   *
   * @api public
   */

  EventEmitter.prototype.emit = function (name) {
    if (!this.$events) {
      return false;
    }

    var handler = this.$events[name];

    if (!handler) {
      return false;
    }

    var args = Array.prototype.slice.call(arguments, 1);

    if ('function' == typeof handler) {
      handler.apply(this, args);
    } else if (io.util.isArray(handler)) {
      var listeners = handler.slice();

      for (var i = 0, l = listeners.length; i < l; i++) {
        listeners[i].apply(this, args);
      }
    } else {
      return false;
    }

    return true;
  };

})(
    'undefined' != typeof io ? io : module.exports
  , 'undefined' != typeof io ? io : module.parent.exports
);
<|endoftext|>


<commit_before>import {getFiles, isArray, isRegExp, isObject, isString} from 'stc-helper';
import stcFile from 'stc-file';
import path from 'path';
import {isMaster} from 'cluster';

/**
 * look file cache
 */
let lookFileCache = {};

/**
 * resource manage
 */
export default class Resource {
  /**
   * constructor
   */
  constructor(config = {}, astHandle){
    this.config = config;
    this.astHandle = astHandle;
    this.files = isMaster ? this._getInitFiles() : [];
  }
  /**
   * get init contain files
   */
  _getInitFiles(){
    let files = [];
    let {include, exclude, defaultExclude} = this.config;
    if(!isArray(include)){
      include = include ? [include] : [];
    }
    include.forEach(itemPath => {
      if(!itemPath){
        return;
      }
      let tFiles = getFiles(itemPath, itemPath);
      files = files.concat(tFiles);
    });
    return files.filter(item => {
      return !this.match(item, defaultExclude) && !this.match(item, exclude);
    }).map(item => {
      let instance = new stcFile({
        path: item,
        astHandle: this.astHandle
      });
      if(this.isTpl(item)){
        instance.prop('tpl', true);
      }
      return instance;
    });
  }
  /**
   * test file match pattern
   */
  match(file, pattern = []){
    if(!pattern){
      return false;
    }
    if(!isArray(pattern)){
      pattern = [pattern];
    }
    let filePath = file.path || file;
    return pattern.some(item => {
      // /\w/
      if(isRegExp(item)){
        return item.test(filePath);
      }
      if(isObject(item)){
        // {type: 'tpl'}
        if(item.type === 'tpl'){
          if(file.path){
            return file.prop('tpl') === true;
          }
          return this.isTpl(file);
        }
      }
      //@TODO support glob pattern?
      return item === filePath;
    });
  }
  /**
   * get files
   */
  getFiles(include = [], exclude = []){
    let files = this.files.filter(item => {
      if(item.prop('virtual')){
        return false;
      }
      if(this.match(item, include) && !this.match(item, exclude)){
        return true;
      }
    }).sort((a, b) => {
      //sort with file size
      return a.stat.size > b.stat.size ? 1 : -1;
    });
    return files;
  }
  /**
   * check file is template file
   */
  isTpl(extname){
    if(extname.indexOf('.') > -1){
      extname = path.extname(extname).slice(1);
    }
    if(extname === 'html'){
      return true;
    }
    let exts = this.config.tpl.extname;
    if(!isArray(exts)){
      exts = [exts];
    }
    return exts.indexOf(extname.toLowerCase()) > -1;
  }
  /**
   * create file
   */
  createFile(filepath, content, virtual){
    let instance = new stcFile({
      path: filepath,
      astHandle: this.astHandle
    });
    if(content === true){
      virtual = true;
      content = undefined;
    }
    if(content !== undefined){
      instance.setContent(content);
    }
    if(this.isTpl(filepath)){
      instance.prop('tpl', true);
    }
    if(virtual){
      instance.prop('virtual', true);
    }
    return instance;
  }
  /**
   * add file
   */
  addFile(filepath, content, virtual){
    let file;
    this.files.some(item => {
      if(item.isPath(filepath)){
        file = item;
        return true;
      }
    });
    if(file){
      if(content !== undefined){
        file.setContent(content);
      }
      return file;
    }
    let instance = this.createFile(filepath, content, virtual);
    this.files.push(instance);
    return instance;
  }
  /**
   * get file by path
   */
  getFileByPath(filepath, parentFile){
    //is already stc-file instance
    if(!isString(filepath) && filepath.path){
      return filepath;
    }
    if(isArray(filepath)){
      return this._getFileByPathHistory(filepath);
    }
    let file;
    this.files.some(item => {
      if(item.isPath(filepath)){
        file = item;
        return true;
      }
    });
    if(file){
      return file;
    }
    if(parentFile){
      return this._lookFile(filepath, parentFile);
    }
    if(!file){
      throw new Error('can not find file ' + filepath);
    }
  }
  /**
   * get file by path history
   */
  _getFileByPathHistory(pathHistory){
    let file;
    this.files.some(item => {
      if(pathHistory.indexOf(item.path) > -1){
        file = item;
        return true;
      }
    });
    return file;
  }
  /**
   * look file with linkpath
   */
  _lookFile(linkpath, parentFile){
    if(lookFileCache[linkpath]){
      return lookFileCache[linkpath];
    }

    let filepath;
    if(this.config.pathHandle){
      filepath = this.config.pathHandle(linkpath);
      if(filepath){
        let file;
        this.files.some(item => {
          if(item.pathHistory.indexOf(filepath) > -1){
            file = item;
            return true;
          }
        });
        if(file){
          lookFileCache[linkpath] = file;
          return file;
        }
      }
    }else{
      let loop = 0;
      let linkpaths = linkpath.split('/');
      let file;
      while(loop++ < 5 && linkpaths.length){
        let currentpath = linkpaths.join('/');
        this.files.some(item => {
          if(item.pathHistory.indexOf(currentpath) > -1){
            file = item;
            return true;
          }
        });
        if(file){
          break;
        }
        linkpaths.shift();
      }
      if(file){
        lookFileCache[linkpath] = file;
        return file;
      }
    }
    throw new Error('can not find resource `' + linkpath + '` in file `' + parentFile + '`');
  }
}<commit_msg>Support set AST when create file<commit_after>import {getFiles, isArray, isRegExp, isObject, isString, isBuffer} from 'stc-helper';
import stcFile from 'stc-file';
import path from 'path';
import {isMaster} from 'cluster';

/**
 * look file cache
 */
let lookFileCache = {};

/**
 * resource manage
 */
export default class Resource {
  /**
   * constructor
   */
  constructor(config = {}, astHandle){
    this.config = config;
    this.astHandle = astHandle;
    this.files = isMaster ? this._getInitFiles() : [];
  }
  /**
   * get init contain files
   */
  _getInitFiles(){
    let files = [];
    let {include, exclude, defaultExclude} = this.config;
    if(!isArray(include)){
      include = include ? [include] : [];
    }
    include.forEach(itemPath => {
      if(!itemPath){
        return;
      }
      let tFiles = getFiles(itemPath, itemPath);
      files = files.concat(tFiles);
    });
    return files.filter(item => {
      return !this.match(item, defaultExclude) && !this.match(item, exclude);
    }).map(item => {
      let instance = new stcFile({
        path: item,
        astHandle: this.astHandle
      });
      if(this.isTpl(item)){
        instance.prop('tpl', true);
      }
      return instance;
    });
  }
  /**
   * test file match pattern
   */
  match(file, pattern = []){
    if(!pattern){
      return false;
    }
    if(!isArray(pattern)){
      pattern = [pattern];
    }
    let filePath = file.path || file;
    return pattern.some(item => {
      // /\w/
      if(isRegExp(item)){
        return item.test(filePath);
      }
      if(isObject(item)){
        // {type: 'tpl'}
        if(item.type === 'tpl'){
          if(file.path){
            return file.prop('tpl') === true;
          }
          return this.isTpl(file);
        }
      }
      //@TODO support glob pattern?
      return item === filePath;
    });
  }
  /**
   * get files
   */
  getFiles(include = [], exclude = []){
    let files = this.files.filter(item => {
      if(item.prop('virtual')){
        return false;
      }
      if(this.match(item, include) && !this.match(item, exclude)){
        return true;
      }
    }).sort((a, b) => {
      //sort with file size
      return a.stat.size > b.stat.size ? 1 : -1;
    });
    return files;
  }
  /**
   * check file is template file
   */
  isTpl(extname){
    if(extname.indexOf('.') > -1){
      extname = path.extname(extname).slice(1);
    }
    if(extname === 'html'){
      return true;
    }
    let exts = this.config.tpl.extname;
    if(!isArray(exts)){
      exts = [exts];
    }
    return exts.indexOf(extname.toLowerCase()) > -1;
  }
  /**
   * create file
   */
  createFile(filepath, content, virtual){
    let instance = new stcFile({
      path: filepath,
      astHandle: this.astHandle
    });
    if(content === true){
      virtual = true;
      content = undefined;
    }
    if(content !== undefined){
      if(isString(content) || isBuffer(content)){
        instance.setContent(content);
      }else{
        instance.setAst(content);
      }
    }
    if(this.isTpl(filepath)){
      instance.prop('tpl', true);
    }
    if(virtual){
      instance.prop('virtual', true);
    }
    return instance;
  }
  /**
   * add file
   */
  addFile(filepath, content, virtual){
    let file;
    this.files.some(item => {
      if(item.isPath(filepath)){
        file = item;
        return true;
      }
    });
    if(file){
      if(content !== undefined){
        if(isString(content) || isBuffer(content)){
          file.setContent(content);
        }else{
          file.setAst(content);
        }
      }
      return file;
    }
    let instance = this.createFile(filepath, content, virtual);
    this.files.push(instance);
    return instance;
  }
  /**
   * get file by path
   */
  getFileByPath(filepath, parentFile){
    //is already stc-file instance
    if(!isString(filepath) && filepath.path){
      return filepath;
    }
    if(isArray(filepath)){
      return this._getFileByPathHistory(filepath);
    }
    let file;
    this.files.some(item => {
      if(item.isPath(filepath)){
        file = item;
        return true;
      }
    });
    if(file){
      return file;
    }
    if(parentFile){
      return this._lookFile(filepath, parentFile);
    }
    if(!file){
      throw new Error('can not find file ' + filepath);
    }
  }
  /**
   * get file by path history
   */
  _getFileByPathHistory(pathHistory){
    let file;
    this.files.some(item => {
      if(pathHistory.indexOf(item.path) > -1){
        file = item;
        return true;
      }
    });
    return file;
  }
  /**
   * look file with linkpath
   */
  _lookFile(linkpath, parentFile){
    if(lookFileCache[linkpath]){
      return lookFileCache[linkpath];
    }

    let filepath;
    if(this.config.pathHandle){
      filepath = this.config.pathHandle(linkpath);
      if(filepath){
        let file;
        this.files.some(item => {
          if(item.pathHistory.indexOf(filepath) > -1){
            file = item;
            return true;
          }
        });
        if(file){
          lookFileCache[linkpath] = file;
          return file;
        }
      }
    }else{
      let loop = 0;
      let linkpaths = linkpath.split('/');
      let file;
      while(loop++ < 5 && linkpaths.length){
        let currentpath = linkpaths.join('/');
        this.files.some(item => {
          if(item.pathHistory.indexOf(currentpath) > -1){
            file = item;
            return true;
          }
        });
        if(file){
          break;
        }
        linkpaths.shift();
      }
      if(file){
        lookFileCache[linkpath] = file;
        return file;
      }
    }
    throw new Error('can not find resource `' + linkpath + '` in file `' + parentFile + '`');
  }
}<|endoftext|>


<commit_before>function defineCachedGet(proto, prop, name) {
	const hname = '_' + name;
	Object.defineProperty(proto, name, {
		get: function() {
			if (this[hname] == undefined) this[hname] = this[prop][name];
			return this[hname];
		}
	});
}

module.exports = class Response {
	constructor(view, binding) {
		this.binding = binding;
		this.view = view;
		for (const name of ["uri", "status", "mime", "headers", "length", "filename", "stall"]) {
			defineCachedGet(Response.prototype, "binding", name);
		}
	}
	data(cb) {
		if (!cb) throw new Error("Missing callback");
		this.binding.data(cb);
		return this;
	}
};
<commit_msg>Set getters outside constructor<commit_after>class Response {
	constructor(view, binding) {
		this.binding = binding;
		this.view = view;
	}
	data(cb) {
		if (!cb) throw new Error("Missing callback");
		this.binding.data(cb);
		return this;
	}
}

module.exports = Response;

function defineCachedGet(proto, prop, name) {
	const hname = '_' + name;
	Object.defineProperty(proto, name, {
		get: function() {
			if (this[hname] == undefined) this[hname] = this[prop][name];
			return this[hname];
		}
	});
}

for (const name of ["uri", "status", "mime", "headers", "length", "filename", "stall"]) {
	defineCachedGet(Response.prototype, "binding", name);
}

<|endoftext|>


<commit_before>const requestFilterMiddleware = (requestFilter, middleware) => (req, res, next) =>
  (typeof requestFilter !== 'function') ? next() :
    requestFilter(req) ? middleware(req, res, next) : next();

module.exports = requestFilterMiddleware;
<commit_msg>Some renaming in filter middleware<commit_after>const filterMiddleware = (filter, middleware) => (req, res, next) =>
  (typeof filter !== 'function') ? next() :
    filter(req) ? middleware(req, res, next) : next();

module.exports = filterMiddleware;
<|endoftext|>


<commit_before>"use strict";

var semver = require("semver");

function isGitDependency(info) {
    return info.latest === "git";
}

function isAlreadyInstalled(info) {
    return info.updateTo === info.current;
}

function isUnstable(info) {
    // Check for hyphen in version string as this is a prerelease version according to SemVer
    return info.updateTo && info.updateTo.indexOf("-") !== -1;
}

function isExcluded(info, exclude) {
    return exclude.map(function (name) {
        return name.trim();
    }).indexOf(info.name) !== -1;
}

function isCurrentGreaterThanUpdateTo(info) {
    return info.current && info.updateTo !== "git" && semver.gt(info.current, info.updateTo);
}

function filter(config) {
    return function (info) {
        return isGitDependency(info) === false &&
            isAlreadyInstalled(info) === false &&
            isUnstable(info) === false &&
            isExcluded(info, config.exclude) === false &&
            isCurrentGreaterThanUpdateTo(info) === false;
    };
}

module.exports = filter;
<commit_msg>Fix wrong boolean casts in filter.js<commit_after>"use strict";

var semver = require("semver");

function isGitDependency(info) {
    return info.latest === "git";
}

function isAlreadyInstalled(info) {
    return info.updateTo === info.current;
}

function isUnstable(info) {
    // Check for hyphen in version string as this is a prerelease version according to SemVer
    return Boolean(info.updateTo && info.updateTo.indexOf("-") !== -1);
}

function isExcluded(info, exclude) {
    return exclude.map(function (name) {
        return name.trim();
    }).indexOf(info.name) !== -1;
}

function isCurrentGreaterThanUpdateTo(info) {
    return Boolean(info.current && info.updateTo !== "git" && semver.gt(info.current, info.updateTo));
}

function filter(config) {
    return function (info) {
        return isGitDependency(info) === false &&
            isAlreadyInstalled(info) === false &&
            isUnstable(info) === false &&
            isExcluded(info, config.exclude) === false &&
            isCurrentGreaterThanUpdateTo(info) === false;
    };
}

module.exports = filter;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PTT from './PTT';
import FontAwesome from 'react-fontawesome';

class UserButtons extends Component {
  constructor(props) {
    super(props);

    this._showOptions = this._showOptions.bind(this);
    this._toggleOptions = this._toggleOptions.bind(this);
    this._logout = this._logout.bind(this);

    this.state = {
      view: null,
      options: '',
      link: (this.props.user && this.props.user.id)
      ? PTT.get('site').url
        + '/wp-admin/user-edit.php?user_id='
        + this.props.user.id
      : '',
      optionsOpened: false,
    };
  }

  componentWillMount() {
    if (!this.props.user) {
      return;
    }
  }

  render() {
    return(

        {(this.state.optionsOpened) ? this._showOptions() : ''}

    );
  }

  _showOptions() {
    return (

            {this.props.user.name}

            <FontAwesome
            name="user"
            title="Visit My Profile" />
             Visit My Profile

            <FontAwesome
            name="chain-broken"
            title="Logout" />
             Logout

    );
  }

  _toggleOptions() {
    this.setState({
      optionsOpened: (this.state.optionsOpened) ? false : true,
    });
  }

  _logout(e) {
    e.preventDefault();
    PTT._reset();
    location.reload();
  }
}

export default UserButtons;<commit_msg>auto generate auto-login link url<commit_after>import React, { Component } from 'react';
import PTT from './PTT';
import FontAwesome from 'react-fontawesome';

class UserButtons extends Component {
  constructor(props) {
    super(props);

    this._showOptions   = this._showOptions.bind(this);
    this._toggleOptions = this._toggleOptions.bind(this);
    this._logout        = this._logout.bind(this);
    this._autoLoginLink = this._autoLoginLink.bind(this);

    this.state = {
      view: null,
      options: '',
      link: (this.props.user && this.props.user.id)
      ? PTT.get('site').url
        + '/wp-admin/user-edit.php?user_id='
        + this.props.user.id
      : '',
      optionsOpened: false,
    };
  }

  componentWillMount() {
    if (!this.props.user) {
      return;
    }
  }

  render() {
    return(

        {(this.state.optionsOpened) ? this._showOptions() : ''}

    );
  }

  _showOptions() {
    return (

            {this.props.user.name}

            <FontAwesome
            name="user"
            title="Visit My Profile" />
             Visit My Profile

            Auto-Login:

          {this._autoLoginLink()}

            <FontAwesome
            name="chain-broken"
            title="Logout" />
             Logout

    );
  }

  // return auto login link url
  _autoLoginLink() {
    let _url = location.origin + '?';
    if (PTT.get('creds')) {
      for (var i in PTT.get('creds')) {
        _url += i + '=' + PTT.get('creds')[i] + '&';
      }
    }
    return _url.substr(0,(_url.length - 1));
  }

  _toggleOptions() {
    this.setState({
      optionsOpened: (this.state.optionsOpened) ? false : true,
    });
  }

  _logout(e) {
    e.preventDefault();
    PTT._reset();
    location.reload();
  }
}

export default UserButtons;<|endoftext|>


<commit_before>// @flow

import equal from 'deep-equal';

type CptWithoutParents = {
  [key: string]: number
};

type CptWithParentsItem = {
  when: { [key: string]: string },
  then: { [key: string]: number }
};

type CptWithParents = CptWithParentsItem[];

type Node = {
  id: string,
  states: string[],
  parents: string[],
  cpt: CptWithoutParents | CptWithParents
};

type Network = {
  [key: string]: Node
};

type Combinations = {
  [key: string]: string
};

export function infer(network: Network, nodes: Combinations, giving: ?Combinations): number {
  const combinations: Combinations[] = buildCombinations(network);

  let filteredCombinations: Combinations[] = filterCombinations(combinations, nodes);
  let probGiving: number = 1;

  if (giving) {
    filteredCombinations = filterCombinations(filteredCombinations, giving);
    probGiving = infer(network, giving);
  }

  return calculateProbabilities(network, filteredCombinations) / probGiving;
}

function buildCombinations(network: Network): Combinations[] {
  const combinations: Combinations[] = [];

  makeCombinations(Object.keys(network));

  return combinations;

  function makeCombinations(nodes: string[], acc: Combinations = {}): void {
    if (nodes.length === 0) {
      combinations.push(acc);
      return;
    }

    const [ node: string, ...rest: string[] ] = nodes;
    const states: string[] = network[node].states;

    for (let i = 0; i < states.length; i++) {
      const state: string = states[i];

      makeCombinations(rest, {
        ...acc,
        [node]: state
      });
    }
  }
}

function filterCombinations(combinations: Combinations[], nodesToFilter: Combinations): Combinations[] {
  const idsToFilter = Object.keys(nodesToFilter);

  return combinations.filter(row => {
    for (let i = 0; i < idsToFilter.length; i++) {
      const idToFilter = idsToFilter[i];

      if (row[idToFilter] !== nodesToFilter[idToFilter]) {
        return false;
      }
    }

    return true;
  });
}

function calculateProbabilities(network: Network, combinations: Combinations[]): number {
  const rowsProducts: number[] = [];

  for (let i = 0; i < combinations.length; i++) {
    let rowProduct = 1;

    const row = combinations[i];
    const ids = Object.keys(row);

    for (let j = 0; j < ids.length; j++) {
      const nodeId = ids[j];
      const node = network[nodeId];
      const cpt = (node.cpt : any);

      if (node.parents.length === 0) {
        rowProduct *= cpt[row[nodeId]];
      } else {
        const when = {};

        for (let k = 0; k < node.parents.length; k++) {
          const parent = node.parents[k];
          when[parent] = row[parent];
        }

        for (let k = 0; k < cpt.length; k++) {
          const cptRow = cpt[k];
          if (equal(cptRow.when, when)) {
            rowProduct *= cptRow.then[row[nodeId]];
            break;
          }
        }
      }
    }

    rowsProducts.push(rowProduct);
  }

  let probability = 0;

  for (let i = 0; i < rowsProducts.length; i++) {
    probability += rowsProducts[i];
  }

  return probability;
}
<commit_msg>More perf improvements<commit_after>// @flow

import equal from 'deep-equal';

type CptWithoutParents = {
  [key: string]: number
};

type CptWithParentsItem = {
  when: { [key: string]: string },
  then: { [key: string]: number }
};

type CptWithParents = CptWithParentsItem[];

type Node = {
  id: string,
  states: string[],
  parents: string[],
  cpt: CptWithoutParents | CptWithParents
};

type Network = {
  [key: string]: Node
};

type Combinations = {
  [key: string]: string
};

const combinationsCache = new WeakMap();

export function infer(network: Network, nodes: Combinations, giving: ?Combinations): number {
  let combinations: Combinations[] = combinationsCache.get(network);

  if (combinations === undefined) {
    combinations = buildCombinations(network);
    combinationsCache.set(network, combinations);
  }

  let filteredCombinations: Combinations[] = filterCombinations(combinations, nodes);
  let probGiving: number = 1;

  if (giving) {
    filteredCombinations = filterCombinations(filteredCombinations, giving);
    probGiving = infer(network, giving);
  }

  return calculateProbabilities(network, filteredCombinations) / probGiving;
}

function buildCombinations(network: Network): Combinations[] {
  const combinations: Combinations[] = [];

  makeCombinations(Object.keys(network));

  return combinations;

  function makeCombinations(nodes: string[], acc: Combinations = {}): void {
    if (nodes.length === 0) {
      combinations.push(acc);
      return;
    }

    const [ node: string, ...rest: string[] ] = nodes;
    const states: string[] = network[node].states;

    for (let i = 0; i < states.length; i++) {
      const state: string = states[i];

      makeCombinations(rest, {
        ...acc,
        [node]: state
      });
    }
  }
}

function filterCombinations(combinations: Combinations[], nodesToFilter: Combinations): Combinations[] {
  const idsToFilter = Object.keys(nodesToFilter);

  return combinations.filter(row => {
    for (let i = 0; i < idsToFilter.length; i++) {
      const idToFilter = idsToFilter[i];

      if (row[idToFilter] !== nodesToFilter[idToFilter]) {
        return false;
      }
    }

    return true;
  });
}

function calculateProbabilities(network: Network, combinations: Combinations[]): number {
  const rowsProducts: number[] = [];

  for (let i = 0; i < combinations.length; i++) {
    let rowProduct = 1;

    const row = combinations[i];
    const ids = Object.keys(row);

    for (let j = 0; j < ids.length; j++) {
      const nodeId = ids[j];
      const node = network[nodeId];
      const cpt = (node.cpt : any);

      if (node.parents.length === 0) {
        rowProduct *= cpt[row[nodeId]];
      } else {
        const when = {};

        for (let k = 0; k < node.parents.length; k++) {
          const parent = node.parents[k];
          when[parent] = row[parent];
        }

        for (let k = 0; k < cpt.length; k++) {
          const cptRow = cpt[k];
          if (equal(cptRow.when, when)) {
            rowProduct *= cptRow.then[row[nodeId]];
            break;
          }
        }
      }
    }

    rowsProducts.push(rowProduct);
  }

  let probability = 0;

  for (let i = 0; i < rowsProducts.length; i++) {
    probability += rowsProducts[i];
  }

  return probability;
}
<|endoftext|>


<commit_before>'use strict'

const {EventEmitter} = require('events')
const {BrowserView} = process.atomBinding('browser_view')

Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype)

BrowserView.fromWebContents = (webContents) => {
  for (const view of BrowserView.getAllViews()) {
    if (view.webContents.equal(webContents)) return window
  }

  return null
}

module.exports = BrowserView
<commit_msg>:bug: Ooops, fix that<commit_after>'use strict'

const {EventEmitter} = require('events')
const {BrowserView} = process.atomBinding('browser_view')

Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype)

BrowserView.fromWebContents = (webContents) => {
  for (const view of BrowserView.getAllViews()) {
    if (view.webContents.equal(webContents)) return view
  }

  return null
}

module.exports = BrowserView
<|endoftext|>