Validate a book configuration for plugins and
returns an update configuration with default values.

@param {Book}
@param {OrderedMap<String:Plugin>}
@return {Promise<Book>}
775987
function validateConfig(book, plugins) {
    return Promise.reduce(plugins, function(newBook, plugin) {
        return validatePluginConfig(newBook, plugin);
    }, book);
}
296873
function orderResults (results) {
    // get id column names
    var idColumn = this.model.defaultColumnsInverse.id
    // require id column for model
    if (!defined(idColumn)) {
        return results
    }
    // get id column name that was used for query
    var queryIdColumn = defined(this.args.where.id)
        ? 'id'
        : defined(this.args.where[idColumn])
            ? idColumn
            : undefined
    // if query was not on id column then do not reorder
    if (!defined(queryIdColumn)) {
        return results
    }
    // list of ids as querired
    var queryIds
    // if id property is array then get ids
    if (Array.isArray(this.args.where[queryIdColumn])) {
        queryIds = this.args.where[queryIdColumn]
    }
    // if id has an in query with array then get ids
    else if (typeof this.args.where[queryIdColumn] === 'object' && Array.isArray(this.args.where[queryIdColumn].in)) {
        queryIds = this.args.where[queryIdColumn].in
    }
    // if query is not by list of ids then do not reorder
    if (!defined(queryIds)) {
        return results
    }
    // group results by id - if current record was queried then must use
    // the id that column was selected by instead of record id
    var resultsById = _.keyBy(results, this.args.current ? idColumn+'Select' : idColumn)
    // ordered result set
    var orderedRes = []
    // iterate over queried ids and add to ordered result set
    _.each(queryIds, queryId => {
        if (defined(resultsById[queryId])) {
            orderedRes.push(resultsById[queryId])
        }
    })

    return orderedRes
}
56431
function loadForBook(book) {
    var logger = book.getLogger();

    // List the dependencies
    var requirements = listDepsForBook(book);

    // List all plugins installed in the book
    return findForBook(book)
    .then(function(installedMap) {
        var missing = [];
        var plugins = requirements.reduce(function(result, dep) {
            var name = dep.getName();
            var installed = installedMap.get(name);

            if (installed) {
                var deps = installedMap
                    .filter(function(plugin) {
                        return plugin.getParent() === name;
                    })
                    .toArray();

                result = result.concat(deps);
                result.push(installed);
            } else {
                missing.push(name);
            }

            return result;
        }, []);

        // Convert plugins list to a map
        plugins = Immutable.List(plugins)
            .map(function(plugin) {
                return [
                    plugin.getName(),
                    plugin
                ];
            });
        plugins = Immutable.OrderedMap(plugins);

        // Log state
        logger.info.ln(installedMap.size + ' plugins are installed');
        if (requirements.size != installedMap.size) {
            logger.info.ln(requirements.size + ' explicitly listed');
        }

        // Verify that all plugins are present
        if (missing.length > 0) {
            throw new Error('Couldn\'t locate plugins "' + missing.join(', ') + '", Run \'gitbook install\' to install plugins from registry.');
        }

        return Promise.map(plugins, function(plugin) {
            return loadPlugin(book, plugin);
        });
    });
}
903022
function overrideCracoConfig({ plugin, options }, cracoConfig, context) {
    if (isFunction(plugin.overrideCracoConfig)) {
        const resultingConfig = plugin.overrideCracoConfig({
            cracoConfig: cracoConfig,
            pluginOptions: options,
            context: context
        });

        if (!resultingConfig) {
            throw new Error("craco: Plugin returned an undefined craco config.");
        }
    }

    log("Overrided craco config with plugin.");

    return cracoConfig;
}
652985
function OrderBook(currencyPair) {
    this._currencyPair = currencyPair;

    this._updateBufferMaxSize = OrderBook.DEFAULT_UPDATE_BUFFER_MAX_SIZE;

    this._wrapperPush = new PushWrapper();
    this._wrapperPublic = new PublicWrapper();

    this._statusRunning = false;
    this._statusSync = OrderBook.SYNC_STATUS_DESYNCHRONIZED;

    this._asks = new Table();
    this._bids = new Table();

    this._lastHandledSeq = -1;

    this._updateBuffer = new Array();

    this._eventEmitter = new events.EventEmitter();

    this._metrics = {
        "spread": 0,
        "askSumAmount": 0,
        "askSumTotal": 0,
        "bidSumAmount": 0,
        "bidSumTotal": 0
    };
}
1075849
function _validateConfig(configObject, mittoObject) {
  var packageObject = _findFile('package.json');
  if (!mittoObject) {
    return configObject;
  }

  if (!configObject && mittoObject.required && Object.keys(mittoObject.required).length) {
    throw new Error(mittoObject.name + " configuration file not found, and is required by " + packageObject.name);
  } else if (!configObject && mittoObject.hasDefault) {
    return _addOnDefaults({}, mittoObject);
  } else if (!configObject) {
    return configObject;
  }

  for (var key in mittoObject.required) {
    if (!configObject.hasOwnProperty(key)) {
      throw new Error("Required property " + key + " not found in " + mittoObject.name);
    } else if (_typeof(configObject[key]) !== mittoObject.required[key].type) {
      throw new Error("Required property " + key + " expected to be of type " + mittoObject.required[key].type);
    }
  }

  for (var key in mittoObject.optional) {
    if (configObject[key] && _typeof(configObject[key]) !== mittoObject.optional[key].type) {
      throw new Error("Optional property " + key + " is type " + _typeof(configObject[key]) + " and expected to be of type " + mittoObject.optional[key].type);
    }
  }

  if (mittoObject.hasDefault) {
    return _addOnDefaults(configObject, mittoObject);
  }

  return configObject;
}
1006975
function validateOptions(options) {
  const notSupported = _.reject(_.keys(options), (key) => (
    OPTIONS.has(key)
  ));

  if (notSupported.length > 0) {
    console.warn(`[${PLUGIN_NAME}] Options ${notSupported} are not supported, use following options: ${Array.from(OPTIONS)}`);
  }
}
1278154
function _withPlugins(fn) {
  return function() {
    const args = Array.from(arguments);
    const opts = args[1] || {};
    args[1] = Object.assign({}, opts, {
      plugins: loadPlugins(opts.plugins, opts.pluginSearchDirs)
    });
    return fn.apply(null, args);
  };
}
1039189
function( MyPlugin, defaults ) {

        // make sure a function has been passed in to
        // create a plugin from.
        if (typeof MyPlugin === 'function') {

            /**
             * the plugin object, inherits all attributes and methods
             * from the base plugin and the user's plugin
             *
             * @param {object} element
             * @param {object} options
             * @return {object} instance
             */
            var Plugin = function( element, options ) {
                Boilerplate.call( this, element, options || {}, defaults || {} );
                MyPlugin.call( this, element, options );
                return this;
            }
            // inherit prototype methods from MyPlugin
            Plugin.prototype = MyPlugin.prototype;
            // set constructor method to Plugin
            Plugin.prototype.constructor = Plugin;
            // set a couple static variables
            Plugin.init = Boilerplate.init;
            Plugin.instances = {};
            Plugin.defaults = defaults || {};

            /**
             * An externalized object used to initialize the plugin and
             * provides external access to plugin.
             *
             * @param {object} options
             * @return {object} instance
             */
            var Boost = function( options ) {
                return Plugin.init.call( Plugin, this, options );
            }
            // externalize a couple vars by attaching them to obj
            Boost.init = function( elems, options ) {
                return Plugin.init.call( Plugin, elems, options );
            }
            Boost.instances = Plugin.instances;
            Boost.defaults = Plugin.defaults;

            // return the Boost object
            return Boost;

        } else {

            throw '\'Boost JS\' requires a function as first paramater.';

        }

    }
457908
function tryPlugin(mId, space) {
  const parsed = parse(mId);
  const pluginId = parsed.prefix.slice(0, -1);
  // text,json,raw plugins are built-in
  if (pluginId) {
    if (pluginId !== 'text' && pluginId !== 'raw') {
      return new Promise((resolve, reject) => {
        const req = (deps, callback, errback) => {
          const errback2 = e => {
            if (errback) {
              try {
                errback(e);
              } catch (err) {
                // ignore
              }
            }
            reject(e);
          };
          return requirejs(deps, callback, errback2);
        };
        try {
          const onload = loaded => {
            space.define(mId, [], () => loaded);
            resolve(space.req(mId));
          };
          onload.error = err => reject(err);

          requirejs([pluginId], plugin => {
            // Call requirejs plugin api load(name, require, load, options)
            // Options set to {} just to make existing requirejs plugins happy.
            plugin.load(parsed.bareId, req, onload, {});
          });
        } catch (err) {
          reject(err);
        }
      });
    }
  } else if (parsed.ext && parsed.ext !== '.js') {
    // Try extension plugin like "ext:css".
    const extPluginName = 'ext:' + parsed.ext.slice(1);
    if (userSpace.has(extPluginName) || packageSpace.has(extPluginName)) {
      return new Promise((resolve, reject) => {
        const req = (deps, callback, errback) => {
          const errback2 = e => {
            if (errback) {
              try {
                errback(e);
              } catch (err) {
                // ignore
              }
            }
            reject(e);
          };
          return requirejs(deps, callback, errback2);
        };
        try {
          const onload = loaded => {
            space.define(mId, [], () => loaded);
            resolve(space.req(mId));
          };
          onload.error = err => reject(err);

          requirejs([extPluginName], plugin => {
            // Call requirejs plugin api load(name, require, load, options)
            // Options set to {} just to make existing requirejs plugins happy.
            plugin.load(parsed.cleanId, req, onload, {});
          });
        } catch (err) {
          reject(err);
        }
      });
    }
    // else by default use text! for any unknown extname
    return new Promise(resolve => {
      space.define(parsed.cleanId,['text!' + parsed.cleanId], m => m);
      resolve(space.req(mId));
    });
  }
}
761245
function validateGlobals(globalsConfig, source = null) {
    if (!globalsConfig) {
        return;
    }

    Object.entries(globalsConfig)
        .forEach(([configuredGlobal, configuredValue]) => {
            try {
                ConfigOps.normalizeConfigGlobal(configuredValue);
            } catch (err) {
                throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
            }
        });
}
628892
function () {
	    	var deferred = $q.defer();
	    	var promise = deferred.promise;
            
            function ok(value){
                deferred.resolve(value);
            }
            
            function errorCallback(error){
                deferred.reject(new Error(error));
            }
            
            if($window.plugins){
                $window.plugins.appPreferences.show()
                    .then(ok, errorCallback);
            } else {
                deferred.reject(new Error(this.pluginNotEnabledMessage));
            }
	    	
	    	this.decoratePromise(promise);
	    	return promise;
	    }
866916
function resolvePlugins(definition: SchemaDefinition) {
  return promiseReduce(
    definition._plugins,
    (accum, p, name) => {
      const { plugin, installed } = p;
      if (!installed) {
        assert(
          plugin instanceof GraphQLFactoryPlugin,
          `plugin ${name} is not an instance of GraphQLFactoryPlugin`,
        );
        if (plugin.dependenciesMet(definition)) {
          definition.merge(plugin);
          return Promise.resolve(plugin.install(definition)).then(() => {
            p.installed = true;
          });
        }
      }
    },
    null,
    true,
  );
}
291639
function (plugin) {
                var plugins = [], self = this, isString = typeof plugin === 'string';
                util.each(self.get('plugins'), function (p) {
                    var keep = 0, pluginId;
                    if (plugin) {
                        if (isString) {
                            // user defined takes priority
                            pluginId = p.get && p.get('pluginId') || p.pluginId;
                            if (pluginId !== plugin) {
                                plugins.push(p);
                                keep = 1;
                            }
                        } else {
                            if (p !== plugin) {
                                plugins.push(p);
                                keep = 1;
                            }
                        }
                    }
                    if (!keep) {
                        p.pluginDestructor(self);
                    }
                });
                self.setInternal('plugins', plugins);
                return self;
            }
1312486
function promise(p) {
        var me = this;

        var canHandlePromise =
            this.children.indexOf("completed") >= 0 &&
            this.children.indexOf("failed") >= 0;

        if (!canHandlePromise){
            throw new Error("Publisher must have \"completed\" and \"failed\" child publishers");
        }

        p.then(function(response) {
            return me.completed(response);
        }, function(error) {
            return me.failed(error);
        });
    }
1220063
function(context, pkg){
		var deps = crawl.getDependencyMap(context.loader, pkg, true);

		var pluginsPromise = crawl.loadPlugins(context, pkg, true, deps, true);
		var stealPromise = crawl.loadSteal(context, pkg, true, deps);

		return Promise.all([pluginsPromise, stealPromise]);
	}
698187
function updateSampleConfig() {
  console.info('Updating plugin package.json...');

  const argVersion = process.argv[2]; // -v
  const argVersionNumber = process.argv[3]; // eg 1.5.6

  let pluginPackageFile = './package.json';
  let samplePackageFile = './sample/package.json';
  fs.readFile(pluginPackageFile, 'utf8', (err, data) => {
    let obj = JSON.parse(data);

    let versions = new Array();

    versions = obj.version.split('.');

    PLUGIN_NAME = obj.name || PLUGIN_NAME;
    PLUGIN_VERSION = obj.version || PLUGIN_VERSION;

    if (versions && (versions.length > 0)) {
      if (argVersion != undefined && argVersionNumber == undefined) {
        versions[versions.length - 1] = safeIncreaseVersion(versions[versions.length - 1]);
      }
      if (argVersionNumber != undefined) {
        versions = argVersionNumber.split('.');
      }
      console.info(`Version changing ${obj.version} => ${versions.join('.')}`);
      obj.version = versions.join('.');
      PLUGIN_VERSION = versions.join('.');
    }

    const dev = obj.dependencies;
    let sampleDep = {};
    let sample = {};

    fs.readFile(samplePackageFile, 'utf8', (err, res) => {

      sample = JSON.parse(res);
      sampleDep = sample.dependencies;

      sample.dependencies = dev;
      sample.version = PLUGIN_VERSION;
      sample.name = PLUGIN_SAMPLE_NAME;

      obj = JSON.stringify(obj, null, 4);
      let smplObj = JSON.stringify(sample, null, 4);

      fs.writeFile(pluginPackageFile, obj, function (e) { });
      fs.writeFile(samplePackageFile, smplObj, function (e) { });

      console.log('Plugin package.json updated.');

    });


  });
}