Constructor for a cache object
@param {Object} options Settings to use when loading the cache
@param {function} cb Callback when the module has loaded
@returns {Cache} A cache object constructor
438677
function Cache(options, cb) {
	var cache = this;
	cache.modules = ['memory']; // Shorthand method that drivers should load - these should exist in modules/

	cache.modulePath = `${__dirname}/modules`

	cache.flushing = 0; // Number of set operations still writing (used by destroy to determine when to actually die)

	/**
	* The currently active module we are using to actually cache things
	* This is computed via init()
	* Its spec should resemble a standard driver export (e.g. use `id` key to determine unique ID)
	* @var {Object}
	*/
	cache.activeModule;

	cache.settings = {
		init: true, // automatically run cache.init() when constructing
		keyMangle: key => key,
		keyQuery: q => /./,
		modules: ['memory'],
		serialize: v => marshal.serialize(v, {circular: false}),
		deserialize: v => marshal.deserialize(v, {circular: false}),
	};


	/**
	* Merge the specified setting or object of settings into cache.settings
	* @param {string|array|Object} key Either the single (dotted notation allowed) path to set, an array of path segments or the entire object to be merged
	* @param {*} [val] If key is a single string this is the value to set
	* @returns {Cache} This chainable object
	*/
	cache.options = argy('string|array|Object [*]', function(key, val) {
		if (argy.isType(key, 'object')) {
			_.merge(cache.settings, key);
		} else {
			_.set(cache.settings, key, val);
		}
		return cache;
	});


	/**
	* Alias for options()
	* @alias options()
	*/
	cache.option = cache.options;


	/**
	* Boot the cache object (automaticaly called if cache.settings.init
	* @param {Object} [options] Options to load when booting - this is merged with cache.settings before boot
	* @param {function} [cb] Optional callback function to call when finsihed. Called as (err)
	* @returns {Promise} A promise which will resolve when the startup process completes
	* @emits loadedMod Emitted when a module has been successfully loaded
	* @emits noMods Emitted when no modules are available to load and we cannot continue - an error is also raised via the callback
	* @emits cantLoad Emitted as (mod) when a named module cannot be loaded
	*/
	cache.init = argy('[function]', cb =>
		async()
			.limit(1)
			// Try all selected modules in sequence until one says it can load {{{
			.forEach(_.castArray(cache.settings.modules), function(next, driverName) {
				if (cache.activeModule) return next(); // Already loaded something
				try {
					var mod = require(`${cache.modulePath}/${driverName}`).call(this, cache.settings, cache);

					mod.canLoad((err, res) => {
						if (err) {
							cache.emit('cantLoad', driverName);
							next(); // Disguard error and try next
						} else if (res) { // Response is truthy - accept module load
							cache.emit('loadedMod', driverName);
							cache.activeModule = mod;
							cache.activeModule.id = driverName;
							next();
						} else { // No response - try next
							cache.emit('cantLoad', driverName);
							next();
						}
					});
				} catch (e) {
					next(e);
				}
			})
			// }}}
			// Set the active mod or deal with errors {{{
			.then(function(next) {
				if (!cache.activeModule) {
					cache.emit('noMods');
					debug('No module to load!');
					return next('No module available to load from list: ' + cache.modules.join(', '));
				} else {
					debug('Using module', cache.activeModule.id);
					next();
				}
			})
			// }}}
			// End {{{
			.promise(cb)
			// }}}
	);


	/**
	* Calls the active modules set() function
	* @param {*} key The key to set, this can be any valid object storage key. If this is an object all keys will be set in parallel
	* @param {*} [val] The value to set, this can be any marshallable valid JS object, can be omitted if key is an object
	* @param {date|number|string} [expiry] The expiry of the value, after this date the storage will reset to undefined. Any value passed is run via cache.convertDateRelative() first
	* @param {function} [cb] The callback to fire when the value was stored. Called as (err, valueSet)
	* @returns {Promise} A promise representing the set action. Resolved as `(valueSet)`
	*/
	cache.set = argy('object|scalar [object|array|scalar] [date|number|string] [function]', function(key, val, expiry, cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		if (argy.isType(key, 'object')) {
			return async()
				.forEach(key, function(next, val, key) {
					debug('> Set', key);
					cache.flushing++;
					var expiryDate = cache.convertDateRelative(expiry);
					debug('Set Object' + (expiry ? ` (Expiry ${expiryDate})` : '') + ':');
					cache.activeModule.set(cache.settings.keyMangle(key), val, expiryDate, err => {
						cache.flushing--;
						next(err);
					});
				})
				.promise('key', cb)
		} else {
			cache.flushing++;
			var expiryDate = cache.convertDateRelative(expiry);
			debug('Set ' + key  + (expiry ? ` (Expiry ${expiryDate})` : ''));
			return async()
				.then(next => cache.activeModule.set(cache.settings.keyMangle(key), val, expiryDate, next))
				.then(()=> cache.flushing--)
				.promise(cb);
		}
	});


	/**
	* Calls the active modules get() function
	* @param {*|array} key The key to retrieve, this can be any valid object storage key, If this is an array an object is returned with a key/value combination
	* @param {*} [fallback=undefined] The falllback value to return if the storage has expired or is not set
	* @param {function} [cb] The callback to fire with the retrieved value
	* @returns {Promise} Promise representing the retrieved value
	*/
	cache.get = argy('scalar|array [object|array|scalar] [function]', function(key, fallback, cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		if (_.isArray(key)) {
			return async()
				.set('result', {})
				.forEach(key, function(next, key) {
					cache.activeModule.get(cache.settings.keyMangle(key), fallback, (err, res) => {
						if (err) return next(err);
						if (res) this.result[key] = res;
						next();
					});
				})
				.promise('result', cb);
		} else {
			debug('Get', key);
			return async()
				.then('value', next => cache.activeModule.get(cache.settings.keyMangle(key), fallback, next))
				.promise('value', cb);
		}
	});


	/**
	* Calls the active modules has() function
	* @param {*} key The key to check, this can be any valid object storage key
	* @param {function} [cb] The callback to fire with a boolean indicating that the value exists
	* @returns {Promise} A promise representing whether the key exists
	*/
	cache.has = argy('scalar [function]', function(key, cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		debug('Has', key);
		if (_.isFunction(cache.activeModule.has)) {
			return async()
				.then('hasValue', next => cache.activeModule.has(cache.settings.keyMangle(key), next))
				.promise('hasValue', cb);
		} else { // Doesn't implement 'has' use get as a quick fix
			return async()
				.then('value', next => cache.get(key, '!!!NONEXISTANT!!!', next))
				.then('hasValue', function(next) { next(null, this.value !== '!!!NONEXISTANT!!!') })
				.promise('hasValue', cb);
		}
	});


	/**
	* Calls the active modules size() function
	* @param {*} key The key to check, this can be any valid object storage key
	* @param {function} [cb] The callback to fire with a boolean indicating that the value exists
	* @returns {Promise} A promise representing whether the size in bytes or undefined
	*/
	cache.size = argy('scalar [function]', function(key, cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		debug('Size', key);
		if (!_.isFunction(cache.activeModule.size)) return Promise.reject('Size is not supported by the selected cache module');

		return async()
			.then('sizeValue', next => cache.activeModule.size(cache.settings.keyMangle(key), next))
			.promise('sizeValue', cb);
	});


	/**
	* Release a set key, any subsequent get() call for this key will fail
	* @param {*|array} key The key or array of keys to release, this can be any valid object storage key
	* @param {function} [cb] The callback to fire when completed
	* @returns {Promise}
	*/
	cache.unset = argy('scalar|array [function]', function(keys, cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		return async()
			.forEach(_.castArray(keys), function(next, key) {
				debug('Unset', key);
				cache.activeModule.unset(cache.settings.keyMangle(key), next);
			})
			.promise(cb);
	});


	/**
	* Return a list of current cache values
	* Only some drivers may implement this function
	* Each return item is expected to have at least 'id' with optional keys 'expiry', 'created'
	* @param {function} [cb] The callback to fire when completed. Called as (err, items)
	* @returns {Promise} A promise representing the cached items
	*/
	cache.list = argy('[function]', function(cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		debug('List');
		return async()
			.then('items', next => cache.activeModule.list(next))
			.promise('items', cb);
	});


	/**
	* Attempt to clean up any remaining items
	* Only some drivers may implement this function
	* NOTE: If the driver does not implement BUT the driver has a list function that returns expiry data a simple loop + expiry check + unset worker will be implemented instead
	* @param {function} [cb] The callback to fire when completed
	* @returns {Promise}
	*/
	cache.vacuume = argy('[function]', function(cb) {
		if (!cache.activeModule) throw new Error('No cache module loaded. Use cache.init() first');

		debug('Vacuume');

		if (cache.activeModule.vacuume) { // Driver implments its own function
			return async()
				.then(next => cache.activeModule.vacuume(next))
				.promise(cb);
		} else if (cache.activeModule.list && cache.activeModule.unset) { // Driver implements a list which we can use instead
			var now = new Date();
			return async()
				.then('items', next => cache.activeModule.list(next))
				.forEach('items', (next, item) => {
					if (item.id && item.expiry && item.expiry < now) {
						cache.activeModule.unset(item.id, next);
					} else {
						next();
					}
				})
				.promise(cb);
		} else {
			return Promise.reject('Vacuume is not supported by the selected cache module');
		}
	});


	/**
	* Attempt to erase ALL cache contents
	* Only some drivers may implement this function
	* NOTE: If the driver does not implement BUT the driver has a list function that returns expiry data a simple loop + expiry check + unset worker will be implemented instead
	* @param {function} [cb] The callback to fire when completed
	* @returns {Promise} This chainable cache module
	*/
	cache.clear = argy('[function]', function(cb) {
		if (!cache.activeModule) Promise.reject('No cache module loaded. Use cache.init() first');
		debug('Clear');

		if (cache.activeModule.clear) { // Driver implments its own function
			return async()
				.then(next => cache.activeModule.clear(next))
				.promise(cb);
		} else if (cache.activeModule.list && cache.activeModule.unset) { // Drive implements a list which we can use instead
			return async()
				.then('items', next => cache.activeModule.list(next))
				.forEach('items', (next, item) => cache.activeModule.unset(item.id, next))
				.promise(cb);
		} else {
			return Promise.reject('Clear is not supported by the selected cache module');
		}
	});


	/**
	* Returns whether the loaded module supports a given function
	* @param {string} func The function to query
	* @returns {boolean} Whether the active module supports the action
	*
	* @example Can a module clear?
	* cache.can('clear') //= Value depends on module
	*/
	cache.can = argy('string', function(func) {
		switch (func) {
			case 'clear':
			case 'vacuume':
				return _.isFunction(cache.activeModule[func])
				|| (_.isFunction(cache.activeModule.list) && _.isFunction(cache.activeModule.unset))
			default: // Also includes 'list'
				return !! _.isFunction(cache.activeModule[func]);
		}
	});


	/**
	* Politely close all driver resource handles
	* NOTE: The destroy function will wait until all set() operations complete before calling the callback
	* @param {function} [cb] The callback to fire when completed
	* @returns {Promise}
	*/
	cache.destroy = argy('[function]', function(cb) {
		debug('Destroy');

		return async()
			.then(function(next) {
				(cache.activeModule && cache.activeModule.destroy ? cache.activeModule.destroy : _.noop)(()=> {
					debug('Destroy - modules terminated');

					var dieAttempt = 0;
					var dieWait = 100;
					var tryDying = ()=> {
						if (cache.flushing > 0) {
							debug(`Destory - still flushing. Attempt ${dieAttempt++}, will try again in ${dieWait}ms`);
							dieWait *= 2; // Increase wait backoff
							setTimeout(tryDying, dieWait);
						} else {
							if (cb) cb();
							next();
						}
					};

					tryDying();
				});
			})
			.promise(cb);
	});


	/**
	* Utility function to hash complex objects
	* @param {*} val Value to hash. If this is a complex object it will be run via JSON.stringify
	* @returns {string} The SHA256 hash of the input
	*/
	cache.hash = function(val) {
		return crypto.createHash('sha256')
			.update(argy.isType(val, 'scalar') ? val : JSON.stringify(val))
			.digest('hex')
	};


	/**
	* Convert an input value into a Date object
	* This function can take dates, millisecond offsets, timestring() strings or moment objects
	* @param {number|string|Date|Moment} val The input value to convert
	* @returns {Date} A Date object
	*/
	cache.convertDateRelative = val =>
		!val ? undefined // Invalid object?
			: _.isDate(val) ? val // Already a date?
			: val.constructor.name == 'Moment' ? val.toDate() // Is a Moment object?
			: isFinite(val) ? new Date(Date.now() + Number(val)) // Looks like a number?
			: typeof val == 'string' ? new Date(Date.now() + timestring(val)) // Relative time string
			: undefined;


	cache.options(options);

	// Init automatically if cache.settings.init
	if (cache.settings.init) {
		cache.init(cb);
	} else if (argy.isType(cb, 'function')) {
		cb();
	}

	return cache;
}
611213
function get(sessionId, cb) {
        has(sessionId, (hasId) => {
            if (hasId) {
                cb(sessionIdCache[sessionId]);
            }
            else {
                cb();
            }
        });
    }
181765
function MempoolCache(options) {
  if (!(this instanceof MempoolCache))
    return new MempoolCache(options);

  this.logger = options.logger;
  this.chain = options.chain;
  this.network = options.network;
  this.db = null;
  this.batch = null;

  if (options.persistent)
    this.db = LDB(options);
}
663393
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {};
	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = options[i];
	            }
	        }

	        dbInfo.keyPrefix = dbInfo.name + '/';

	        if (dbInfo.storeName !== self._defaultConfig.storeName) {
	            dbInfo.keyPrefix += dbInfo.storeName + '/';
	        }

	        self._dbInfo = dbInfo;

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return Promise.resolve();
	        });
	    }
98119
function thinkCache(name, value, config) {
  assert(name && helper.isString(name), 'cache.name must be a string');
  if (config) {
    config = helper.parseAdapterConfig(this.config('cache'), config);
  } else {
    config = helper.parseAdapterConfig(this.config('cache'));
  }
  const Handle = config.handle;
  assert(helper.isFunction(Handle), 'cache.handle must be a function');
  delete config.handle;
  const instance = new Handle(config);
  // delete cache
  if (value === null) {
    return Promise.resolve(instance.delete(name));
  }
  // get cache
  if (value === undefined) {
    return debounceInstance.debounce(name, () => {
      return instance.get(name);
    });
  }

  // get cache when value is function
  if (helper.isFunction(value)) {
    return debounceInstance.debounce(name, () => {
      let cacheData;
      return instance.get(name).then(data => {
        if (data === undefined) {
          return value(name);
        }
        cacheData = data;
      }).then(data => {
        if (data !== undefined) {
          cacheData = data;
          return instance.set(name, data);
        }
      }).then(() => {
        return cacheData;
      });
    });
  }
  // set cache
  return Promise.resolve(instance.set(name, value));
}
547641
function createLoader(options, fn) {
  var loader = new utils.Loader(options);
  return function() {
    if (!this.isApp) loader.cache = this.views;
    loader.options.loaderFn = fn.bind(this);
    loader.load.apply(loader, arguments);
    return loader.cache;
  };
}
872000
function MemcachedStore(options) {
    options = options || {};
    Store.call(this, options);

    this.prefix = options.prefix || "";
    this.ttl = options.ttl;
    if (!options.client) {
      if (!options.hosts) {
        options.hosts = "127.0.0.1:11211";
      }
      if (options.secret) {
        (this.crypto = require("crypto")), (this.secret = options.secret);
      }
      if (options.algorithm) {
        this.algorithm = options.algorithm;
      }

      options.client = new Memcached(options.hosts, options);
    }

    this.client = options.client;
  }
748351
function load(cb) {
    var timer = u.timer();
    generator.getSources(opts.sources, opts, function(err, fragments) {

      if (err) return cb && cb(err);

      generator.fragments = fragments;
      generator.fragment$ = u.indexBy(generator.fragments, '_href');

      var pageFragments = u.filter(fragments, function(fragment) {
        return !fragment._compile;
      });
      compilePages(pageFragments);

      var templateFragments = u.where(fragments, { _compile: 'handlebars' } );
      compileTemplates(templateFragments);

      generator.emit('load');    // hook custom loaders
      generator.emit('loaded');  // then announce loaded

      debug('loaded %sms', timer());
      cb && cb();
    });
  }
325056
function init(){
    try {
      self.db = new nodeCache();
      log(false, 'Node-cache client created with the following defaults:', {expiration: this.expiration, verbose: this.verbose, readOnly: this.readOnly});
    } catch (err) {
      log(true, 'Node-cache client not created:', err);
      self.db = false;
    }
    self.type = config.type || 'node-cache';
  }
1275860
function createSession(config, cb) {
  checkOpts(config, cb)

  cb = utils.callOnce(cb)

  var url = config.url
  var key = config.key

  config = {
    url: url,
    key: key
  }

  session.createSession(config, cb)
}
698641
function cache(item, options) {
    var dir_path = pathutils.join([
        item.conf.cache.base_path,
        pathutils.getHashPath(item.source),
    ]);

    var meta_path = pathutils.join([dir_path, "meta"]);
    var source_path = pathutils.join([dir_path, "source"]);

    if (item.source_type === "file" && !item.conf.cache.copy_source_file) {
        source_path = item.source;
    }

    var target_path = pathutils.join([dir_path, 'targets', pathutils.getOptionsPath(options)]);

    /*
     * lock the files in sequence, not in parallel
     * otherwise a deadlock with other request may occur
     */
    var promise = lock(source_path).then(function(l) {
        logging.debug(item.id, "Locked: source file");
        item.locks.source = l;
        return lock(meta_path);
    }).then(function(l) {
        logging.debug(item.id, "Locked: metadata");
        item.locks.meta = l;
        return lock(target_path);
    }).then(function(l) {
        logging.debug(item.id, "Locked: target file");
        item.locks.target = l;
        return item;
    }).
    then(function(item) {
        return meta_data_still_fresh(item);
    }).
    then(function(item) {
        //meta data is still fresh
        logging.debug(item.id, "Metadata is still fresh");

        return item;
    }, function(item) {
        //meta_data is stale or doesn't exist
        logging.debug(item.id, "Metadata is stale");
        //clear the item directory and download a new version of the source
        var source_promise = fsutils.cleardir(dir_path).
        then(function() {
            logging.debug(item.id, "Item directory cleared");
            logging.debug(item.id, "Requesting source", item.source);
            return source(item);
        }, function(err) {
            // clearing the directory failed.
            // maybe it didn't exists, which would be ok
            if (err.code === "ENOENT") {
                logging.debug(item.id, "Requesting source", item.source);
                return source(item);
            } else {
                //no, it failed for some other reason
                item.error = err;
                throw item;
            }
        }).
        then(function(success) {
            //download succeeded
            logging.debug(item.id, "Source file ready");
            stats.download_success();
            //now only read metadata, don't evaluate headers or else
            //things with max-age=0 will always fail
            return read_meta_data(item);
        }, function(error) {
            logging.debug(item.id, "Acquiring source failed", error);
            stats.download_failure();
            throw item;
        });

        return source_promise;
    }).
    then(function(item) {
        //at this point the item is definitely fresh
        return get_target_file(item);
    }).
    then(function(item) {
        //the target has also been found. all done! \o/
        item.locks.meta();
        logging.debug(item.id, "Released lock: metadata");
        if (typeof item.locks.source === "function") {
            item.locks.source();
            logging.debug(item.id, "Released lock: source file");
        } else {
            //
        }

        register_for_gc(item);
        return item;
    },function(item) {
        item.locks.meta();
        logging.debug(item.id, "Released lock: metadata");
        item.locks.source();
        logging.debug(item.id, "Released lock: source file");
        item.locks.target();
        logging.debug(item.id, "Released lock: target file");

        register_for_gc(item);
        throw item;
    });

    return promise;
}
1265679
function load(opts, cb) {
  if(typeof opts === 'function') {
    cb = opts;
    opts = null;
  }

  var args = opts && opts.args ? opts.args : null
    , defaults = path.normalize(path.join(__dirname, 'command'));
  opts = opts || argv(args);

  if(opts.commands === undefined) {
    opts.commands = [defaults];
  }else if(Array.isArray(opts.commands) && opts.defaults) {
    opts.commands.unshift(defaults);
  }

  function onConfigError(err) {
    //console.dir(err);
    console.error(err.message);
    if(process.env.NODE_ENV !== Constants.TEST) {
      process.exit(1);
    }
  }

  this.conf.once('error', onConfigError.bind(this));

  function onConfigLoad() {
    // if we loaded ok we are done with fatal config errors
    // config set/rewrite need to catch errors now
    this.conf.removeAllListeners('error');

    this.emit('config', this.conf);

    opts.conf = this.conf;

    // spawning the daemon process
    if(this.conf.get(ConfigKey.DAEMONIZE) && !this._daemonized) {
      var pid = daemon(
        path.join(__dirname, 'daemonize.js'), this.conf, opts.args);
      if(cb) cb(pid);
      return;
    }

    this.log.notice('cwd: %s', process.cwd());

    // pass configured timeout to script manager
    ScriptManager.timeout = this.conf.get(ConfigKey.LUA_TIME_LIMIT);

    // spawn now, makes first script executions faster
    // later this should be configurable - allow disabling all
    // scripting
    ScriptManager.spawn();

    // load commands
    return loader(opts, onCommandLoad);
  }

  function onCommandLoad(err, commands) {
    if(err) return cb(err);
    this.execs = commands;
    this.emit('ready', this.execs);

    // inject command list so the script manager
    // can detect write commands
    ScriptManager.commands = commands;

    // loading from rdb files breaks the tests
    if(process.env.NODE_ENV === Constants.TEST) {
      return cb();
    }
    Persistence.load(this.state.store, this.state.conf, onDatabaseLoad);
  }

  function onDatabaseLoad(err, time, diff, version) {
    // load errors are thrown, will cause
    // the process to exit
    if(err) throw err;
    if(err !== false) {
      this.log.notice('db loaded from disk: %s seconds (v%s)', time, version);
      this.emit('database', time, diff, version);
    }
    cb();
  }

  onConfigLoad = onConfigLoad.bind(this);
  onCommandLoad = onCommandLoad.bind(this);
  onDatabaseLoad = onDatabaseLoad.bind(this);

  // load config
  this.conf.load(opts, onConfigLoad);
}
676473
function load(opts, cb) {
  if(typeof opts === 'function') {
    cb = opts;
    opts = null;
  }
  opts = opts || {};
  var files = opts.commands || []
    , i = 0
    , list = []
    , conf = opts.conf
    , rename = conf.get(ConfigKey.RENAME_COMMAND) || []
    , commands = {};

  if(!Array.isArray(files)) {
    files = [files];
  }

  function complete(err) {
    if(err) return cb(err);
    if(Object.keys(commands).length === 0) {
      return cb(new Error('no command definitions found'));
    }
    cb(null, commands);
  }

  /**
   *  Requires the array of files.
   */
  function include(list) {
    var cmd, clazz, i, file, j, name, newname;
    for(i = 0;i < list.length;i++) {
      file = list[i];
      try {
        clazz = require(file);
        // assume it is already instantiated
        if(typeof clazz === 'object') {
          cmd = clazz;
        }else{
          cmd = new clazz(clazz.definition);
        }

        // rename and delete commands
        if(cmd && cmd.definition && cmd.definition.name) {
          for(j = 0;j < rename.length;j++) {
            name = rename[j][0];
            newname = rename[j][1];
            if(name
              && name.toLowerCase() === cmd.definition.name.toLowerCase()) {
              newname = (newname || '').toLowerCase();
              // actually renaming
              if(newname) {
                log.warning(
                  'rename command %s -> %s', cmd.definition.name, newname);
                cmd.definition.name = newname;
              // deleting the command, mark as deleted with false
              }else{
                log.warning(
                  'deleted command %s (%s)', cmd.definition.name, file);
                commands[cmd.definition.name] = false;
                // clear the module cache
                delete require.cache[file];
              }
              break;
            }
          }
        }

        // deleted the command
        if(!require.cache[file]) continue;

        // sanity checks
        if(!(cmd instanceof CommandExec)) {
          throw new Error(
            util.format(
              'module does not export a command exec instance (%s)', file));
        }else if(
          !cmd.definition
          || !cmd.definition.constructor
          || cmd.definition.constructor.name !== Command.name) {
          throw new Error(
            util.format(
              'command does not have a valid definition (%s)', file));
        }else if(!cmd.definition.name) {
          throw new Error(
            util.format(
              'command definition does not have a name (%s)', file));
        }

        if(opts.override !== true && commands[cmd.definition.name]) {
          throw new Error(util.format(
              'duplicate command %s (%s)', cmd.definition.name, file));
        }

        log.debug('loaded %s (%s)', cmd.definition.name, file);

        // map of command names to command exec handlers
        commands[cmd.definition.name] = cmd;
      }catch(e) {
        return complete(e);
      }
    }
    complete();
  }

  /**
   *  Walk the file list array.
   */
  function walk(files, cb, list) {
    var i = 0;
    list = list || [];

    function check(file, cb) {
      fs.stat(file, function onStat(err, stats) {
        if(err) return cb(err);
        if(stats.isFile() && !/\.js$/.test(file)) {
          log.warning('ignoring %s', file);
          return cb();
        }
        if(stats.isFile()) {
          list.push(file);
          return cb(null, list);
        }else{
          return fs.readdir(file, function onRead(err, files) {
            if(err) return cb(err);
            if(!files.length) return cb();
            files = files.map(function(nm) {
              return path.join(file, nm);
            })
            //files.forEach()
            return walk(files, cb, list);
          })
        }
      });
    }

    check(files[i], function onCheck(err, list) {
      if(err) return cb(err);
      if(i === files.length - 1) {
        return cb(null, list);
      }
      i++;
      check(files[i], onCheck);
    });
  }

  walk(files, function onList(err, list) {
    if(err) return complete(err);
    if(list.length === 0) {
      return complete(new Error('no command files found'));
    }
    include(list);
  });
}
1278370
function (source, options) {
        this.index = this._geIndex(source);
        this.data = '';
        this.options = options;
        this._cache = {};
        this._usedHeaders = [];
    }
713349
function fetchFromCache(options, opts, cb) {
  // look for existing cached resource
  if (indirFiles.length > 0) {
    var etag;
    var regexp = '^' + opts.prefix +
                 '([A-Za-z0-9]+={0,2})' + // base64 encoded
                 opts.suffix + '$';
    var regex = new RegExp(regexp);
    var i;
    for (i = 0; i < indirFiles.length; i++) {
      var file = regex.exec(indirFiles[i]);
      if (file) {
        etag = new Buffer(file[1], 'base64').toString();
        break;
      }
    }

    if (etag) {
      try {
        var headOpts = JSON.parse(JSON.stringify(options)); // clone options
        headOpts.headers = { 'If-None-Match': etag };
        request.head(headOpts, function(err, res, body) {
          if (err) {
            logger.error(err);
            cb();
            // not fatal; continue
          } else if (res.statusCode === 304) {
            var filename = path.join(opts.outdir, indirFiles[i]);
            fs.copy(path.join(opts.indir, indirFiles[i]),
                    filename,
                    { preserveTimestamps: true },
                    function(err) {
                      if (err) {
                        throw (err);
                      }
                      var body = decryptData(fs.readFileSync(filename));
                      logger.info('Using cached copy of %s', indirFiles[i]);
                      var result = {
                        file: filename,
                        contents: body };
                      cb(null, result);
                    });
          } else {
            cb();
          }
        });
      } catch (e) {
        logger.error(e);
        cb();
        // not fatal; continue
      }
    } else {
      cb();
    }
  } else {
    cb();
  }
}
12391
function getCacheCtor(cache){
  if (!cache){
    return;
  }

  if (typeof cache === 'function'){
    return cache;
  }

  function runtimeLoad(moduleRef){
    return require(moduleRef);
  }

  var cacheCtors = {
    disabled: runtimeLoad('./DisabledCache'),
    memory: runtimeLoad('./MemoryStore'),
    memcached: runtimeLoad('./MemcachedStore'),
    redis: runtimeLoad('./RedisStore')
  };

  if (!(cache in cacheCtors)){
    throw new Error('Unsupported cache provider: ' + cache);
  }

  return cacheCtors[cache];
}
730599
function(options) {
	if (!options) { options = {}; }

	Object.keys(options).forEach(function(k) {
		console.assert(supportedOptions.has(k), 'Invalid cacheKey option: ' + k);
	});

	// default: not an include context
	if (options.isInclude === undefined) {
		options.isInclude = false;
	}

	// default: wrap templates
	if (options.expandTemplates === undefined) {
		options.expandTemplates = true;
	}

	return options;
}