async function getConfig(context, fileName, defaultConfig, deepMergeOptions) {
  const filePath = path.posix.join(CONFIG_PATH, fileName);
  const params = context.repo({
    path: filePath,
  });

  const config = await loadYaml(context, params);
  let baseRepo;
  if (config == null) {
    baseRepo = DEFAULT_BASE;
  } else if (config != null && BASE_KEY in config) {
    baseRepo = config[BASE_KEY];
    delete config[BASE_KEY];
  }

  let baseConfig;
  if (baseRepo) {
    const baseParams = getBaseParams(params, baseRepo);
    baseConfig = await loadYaml(context, baseParams);
  }

  if (config == null && baseConfig == null && !defaultConfig) {
    return null;
  }

  return deepMergeConfigs(
    [defaultConfig, baseConfig, config],
    deepMergeOptions
  );
}

async function getConfig ( context , fileName , defaultConfig , deepMergeOptions ) { const filePath = path . posix . join ( CONFIG_PATH , fileName ) ; const params = context . repo ( { path : filePath , } ) ; const config = await loadYaml ( context , params ) ; let baseRepo ; if ( config == null ) { baseRepo = DEFAULT_BASE ; } else if ( config != null && BASE_KEY in config ) { baseRepo = config [ BASE_KEY ] ; delete config [ BASE_KEY ] ; } let baseConfig ; if ( baseRepo ) { const baseParams = getBaseParams ( params , baseRepo ) ; baseConfig = await loadYaml ( context , baseParams ) ; } if ( config == null && baseConfig == null && ! defaultConfig ) { return null ; } return deepMergeConfigs ( [ defaultConfig , baseConfig , config ] , deepMergeOptions ) ; }

Loads the specified config file from the context's repository

If the config file contains a top-level key "_extends", it is merged
with a config of the same name in the repository specified by the
_extends key.  The repository of the base configuration can either be
given as "repository" or as "organization/repository".

If the config file does not exist in the context's repository, `null`
is returned. If the base repository does not exist or does not contain
the config file, it is ignored.

If a default config is given, it is merged with the config from the
repository, if it exists.

@param {Context} context A Probot context
@param {string} fileName Name of the config file
@param {object} defaultConfig A default config that is merged in
@param {object} deepMergeOptions from deepmerge
@returns {object} The merged configuration
@async

Loads the specified config file from the context s repository


function defineProperty (obj, name, value) {
  var enumerable = !!obj[name] && obj.propertyIsEnumerable(name)
  Object.defineProperty(obj, name, {
    configurable: true,
    enumerable: enumerable,
    writable: true,
    value: value
  })
}

function defineProperty ( obj , name , value ) { var enumerable = ! ! obj [ name ] && obj . propertyIsEnumerable ( name ) Object . defineProperty ( obj , name , { configurable : true , enumerable : enumerable , writable : true , value : value } ) }

Sets a property on an object, preserving its enumerability. This function assumes that the property is already writable.

Sets a property on an object preserving its enumerability . This function assumes that the property is already writable .


function shimmer (options) {
  if (options && options.logger) {
    if (!isFunction(options.logger)) logger("new logger isn't a function, not replacing")
    else logger = options.logger
  }
}


function injectManifest(data) {
  let manifestHtml = `<head><link rel=manifest href=${hexo.config.pwa.manifest.path}>`;

  if (data.indexOf(manifestHtml) === -1) {
    data = data.replace('<head>', manifestHtml);
  }

  return data;
}

function injectManifest ( data ) { let manifestHtml = ` ${ hexo . config . pwa . manifest . path } ` ; if ( data . indexOf ( manifestHtml ) === - 1 ) { data = data . replace ( '<head>' , manifestHtml ) ; } return data ; }

inject manifest html fragment into page code

@param {string} data html
@return {string}


function injectSWRegister(data) {
  let swHtml = `<script>${compiledSWRegTpl}</script></body>`;

  if (data.indexOf(compiledSWRegTpl) === -1) {
    data = data.replace('</body>', swHtml);
  }

  return data;
}

function injectSWRegister ( data ) { let swHtml = ` ${ compiledSWRegTpl } ` ; if ( data . indexOf ( compiledSWRegTpl ) === - 1 ) { data = data . replace ( '</body>' , swHtml ) ; } return data ; }

inject service worker registion fragment into page code

@param {string} data html
@return {string}


function injectAsyncLoadPageJS(data) {
  let injectHtml = `<script>${asyncLoadPageJSTpl}</script>`;

  if (data.indexOf(injectHtml) === -1) {
    data = data.replace('</head>', injectHtml);
  }

  return data;
}

function injectAsyncLoadPageJS ( data ) { let injectHtml = ` ${ asyncLoadPageJSTpl } ` ; if ( data . indexOf ( injectHtml ) === - 1 ) { data = data . replace ( '</head>' , injectHtml ) ; } return data ; }

inject async load page js fragment

@param {string} data html
@return {string}


function rehype2react(options) {
  var settings = options || {};
  var createElement = settings.createElement;
  var components = settings.components || {};

  this.Compiler = compiler;

  /* Compile HAST to React. */
  function compiler(node) {
    if (node.type === 'root') {
      if (node.children.length === 1 && node.children[0].type === 'element') {
        node = node.children[0];
      } else {
        node = {
          type: 'element',
          tagName: 'div',
          properties: node.properties || {},
          children: node.children
        };
      }
    }

    return toH(h, tableCellStyle(node), settings.prefix);
  }

  /* Wrap `createElement` to pass components in. */
  function h(name, props, children) {
    var component = has(components, name) ? components[name] : name;
    return createElement(component, props, children);
  }
}

Attach a react compiler.

@param {Unified} processor - Instance.
@param {Object?} [options]
@param {Object?} [options.components]
- Components.
@param {string?} [options.prefix]
- Key prefix.
@param {Function?} [options.createElement]
- `h()`.


function doExec(method, args) {
    var cp;
    var cpPromise = new ChildProcessPromise();
    var reject = cpPromise._cpReject;
    var resolve = cpPromise._cpResolve;

    var finalArgs = slice.call(args, 0);
    finalArgs.push(callback);

    cp = child_process[method].apply(child_process, finalArgs);

    function callback(err, stdout, stderr) {
        if (err) {
            var commandStr = args[0] + (Array.isArray(args[1]) ? (' ' + args[1].join(' ')) : '');
            err.message += ' `' + commandStr + '` (exited with error code ' + err.code + ')';
            err.stdout = stdout;
            err.stderr = stderr;
            var cpError = new ChildProcessError(err.message, err.code, child_process, stdout, stderr);
            reject(cpError);
        } else {
            resolve({
                childProcess: cp,
                stdout: stdout,
                stderr: stderr
            });
        }
    }

    cpPromise.childProcess = cp;

    return cpPromise;
}

function
doExec
(
method
,
args
)
{
var
cp
;
var
cpPromise
=
new
ChildProcessPromise
(
)
;
var
reject
=
cpPromise
.
_cpReject
;
var
resolve
=
cpPromise
.
_cpResolve
;
var
finalArgs
=
slice
.
call
(
args
,
0
)
;
finalArgs
.
push
(
callback
)
;
cp
=
child_process
[
method
]
.
apply
(
child_process
,
finalArgs
)
;
function
callback
(
err
,
stdout
,
stderr
)
{
if
(
err
)
{
var
commandStr
=
args
[
0
]
+
(
Array
.
isArray
(
args
[
1
]
)
(
' '
+
args
[
1
]
.
join
(
' '
)
)
:
''
)
;
err
.
message
+=
' `'
+
commandStr
+
'` (exited with error code '
+
err
.
code
+
')'
;
err
.
stdout
=
stdout
;
err
.
stderr
=
stderr
;
var
cpError
=
new
ChildProcessError
(
err
.
message
,
err
.
code
,
child_process
,
stdout
,
stderr
)
;
reject
(
cpError
)
;
}
else
{
resolve
(
{
childProcess
:
cp
,
stdout
:
stdout
,
stderr
:
stderr
}
)
;
}
}
cpPromise
.
childProcess
=
cp
;
return
cpPromise
;
}

Promise wrapper for exec, execFile

@param {String} method
@param {...*} args
@return {Promise}


function doSpawn(method, command, args, options) {
    var result = {};

    var cp;
    var cpPromise = new ChildProcessPromise();
    var reject = cpPromise._cpReject;
    var resolve = cpPromise._cpResolve;

    var successfulExitCodes = (options && options.successfulExitCodes) || [0];

    cp = method(command, args, options);

    // Don't return the whole Buffered result by default.
    var captureStdout = false;
    var captureStderr = false;

    var capture = options && options.capture;
    if (capture) {
        for (var i = 0, len = capture.length; i < len; i++) {
            var cur = capture[i];
            if (cur === 'stdout') {
                captureStdout = true;
            } else if (cur === 'stderr') {
                captureStderr = true;
            }
        }
    }

    result.childProcess = cp;

    if (captureStdout) {
        result.stdout = '';

        cp.stdout.on('data', function(data) {
            result.stdout += data;
        });
    }

    if (captureStderr) {
        result.stderr = '';

        cp.stderr.on('data', function(data) {
            result.stderr += data;
        });
    }

    cp.on('error', reject);

    cp.on('close', function(code) {
        if (successfulExitCodes.indexOf(code) === -1) {
            var commandStr = command + (args.length ? (' ' + args.join(' ')) : '');
            var message = '`' + commandStr + '` failed with code ' + code;
            var err = new ChildProcessError(message, code, cp);

            if (captureStderr) {
                err.stderr = result.stderr.toString();
            }

            if (captureStdout) {
                err.stdout = result.stdout.toString();
            }

            reject(err);
        } else {
            result.code = code;
            resolve(result);
        }
    });

    cpPromise.childProcess = cp;

    return cpPromise;
}

`spawn` as Promised

@param {String} command
@param {Array} args
@param {Object} options
@return {Promise}


function slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}

function slope2 ( that , t ) { var h = that . _x1 - that . _x0 ; return h ? ( 3 * ( that . _y1 - that . _y0 ) / h - t ) / 2 : t ; }


function shouldSetAttribute(name, value) {
  if (isReservedProp(name)) {
    return false;
  }
  if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
    return false;
  }
  if (value === null) {
    return true;
  }
  switch (typeof value) {
    case 'boolean':
      return shouldAttributeAcceptBooleanValue(name);
    case 'undefined':
    case 'number':
    case 'string':
    case 'object':
      return true;
    default:
      // function, symbol
      return false;
  }
}

function
shouldSetAttribute
(
name
,
value
)
{
if
(
isReservedProp
(
name
)
)
{
return
false
;
}
if
(
name
.
length
>
2
&&
(
name
[
0
]
===
'o'
||
name
[
0
]
===
'O'
)
&&
(
name
[
1
]
===
'n'
||
name
[
1
]
===
'N'
)
)
{
return
false
;
}
if
(
value
===
)
{
return
true
;
}
switch
(
typeof
value
)
{
case
'boolean'
:
return
shouldAttributeAcceptBooleanValue
(
name
)
;
case
'undefined'
:
case
'number'
:
case
'string'
:
case
'object'
:
return
true
;
default
:
// function, symbol
return
false
;
}
}

Checks whether a property name is a writeable attribute.
@method

Checks whether a property name is a writeable attribute .


function createMarkupForProperty(name, value) {
  var propertyInfo = getPropertyInfo(name);
  if (propertyInfo) {
    if (shouldIgnoreValue(propertyInfo, value)) {
      return '';
    }
    var attributeName = propertyInfo.attributeName;
    if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
      return attributeName + '=""';
    } else if (typeof value !== 'boolean' || shouldAttributeAcceptBooleanValue(name)) {
      return attributeName + '=' + quoteAttributeValueForBrowser(value);
    }
  } else if (shouldSetAttribute(name, value)) {
    if (value == null) {
      return '';
    }
    return name + '=' + quoteAttributeValueForBrowser(value);
  }
  return null;
}

function createMarkupForProperty ( name , value ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo ) { if ( shouldIgnoreValue ( propertyInfo , value ) ) { return '' ; } var attributeName = propertyInfo . attributeName ; if ( propertyInfo . hasBooleanValue || propertyInfo . hasOverloadedBooleanValue && value === true ) { return attributeName + '=""' ; } else if ( typeof value !== 'boolean' || shouldAttributeAcceptBooleanValue ( name ) ) { return attributeName + '=' + quoteAttributeValueForBrowser ( value ) ; } } else if ( shouldSetAttribute ( name , value ) ) { if ( value == null ) { return '' ; } return name + '=' + quoteAttributeValueForBrowser ( value ) ; } return null ; }

Creates markup for a property.

@param {string} name
@param {*} value
@return {?string} Markup string, or null if the property was invalid.


function trapBubbledEvent(topLevelType, handlerBaseName, element) {
  if (!element) {
    return null;
  }
  return EventListener.listen(element, handlerBaseName, dispatchEvent.bind(null, topLevelType));
}

function trapBubbledEvent ( topLevelType , handlerBaseName , element ) { if ( ! element ) { return null ; } return EventListener . listen ( element , handlerBaseName , dispatchEvent . bind ( null , topLevelType ) ) ; }

Traps top-level events by using event bubbling.

@param {string} topLevelType Record from `BrowserEventConstants`.
@param {string} handlerBaseName Event name (e.g. "click").
@param {object} element Element on which to attach listener.
@return {?object} An object with a remove function which will forcefully
remove the listener.
@internal

Traps top - level events by using event bubbling .


function createUpdateQueue(baseState) {
  var queue = {
    baseState: baseState,
    expirationTime: NoWork,
    first: null,
    last: null,
    callbackList: null,
    hasForceUpdate: false,
    isInitialized: false
  };
  {
    queue.isProcessing = false;
  }
  return queue;
}

function createUpdateQueue ( baseState ) { var queue = { baseState : baseState , expirationTime : NoWork , first : null , last : null , callbackList : null , hasForceUpdate : false , isInitialized : false } ; { queue . isProcessing = false ; } return queue ; }

Singly linked-list of updates. When an update is scheduled, it is added to the queue of the current fiber and the work-in-progress fiber. The two queues are separate but they share a persistent structure.  During reconciliation, updates are removed from the work-in-progress fiber, but they remain on the current fiber. That ensures that if a work-in-progress is aborted, the aborted updates are recovered by cloning from current.  The work-in-progress queue is always a subset of the current queue.  When the tree is committed, the work-in-progress becomes the current.

Singly linked - list of updates . When an update is scheduled it is added to the queue of the current fiber and the work - in - progress fiber . The two queues are separate but they share a persistent structure . During reconciliation updates are removed from the work - in - progress fiber but they remain on the current fiber . That ensures that if a work - in - progress is aborted the aborted updates are recovered by cloning from current . The work - in - progress queue is always a subset of the current queue . When the tree is committed the work - in - progress becomes the current .


function mountClassInstance(workInProgress, renderExpirationTime) {
    var current = workInProgress.alternate;

    {
      checkClassInstance(workInProgress);
    }

    var instance = workInProgress.stateNode;
    var state = instance.state || null;

    var props = workInProgress.pendingProps;
    !props ? invariant(false, 'There must be pending props for an initial mount. This error is likely caused by a bug in React. Please file an issue.') : void 0;

    var unmaskedContext = getUnmaskedContext(workInProgress);

    instance.props = props;
    instance.state = workInProgress.memoizedState = state;
    instance.refs = emptyObject;
    instance.context = getMaskedContext(workInProgress, unmaskedContext);

    if (enableAsyncSubtreeAPI && workInProgress.type != null && workInProgress.type.prototype != null && workInProgress.type.prototype.unstable_isAsyncReactComponent === true) {
      workInProgress.internalContextTag |= AsyncUpdates;
    }

    if (typeof instance.componentWillMount === 'function') {
      callComponentWillMount(workInProgress, instance);
      // If we had additional state updates during this life-cycle, let's
      // process them now.
      var updateQueue = workInProgress.updateQueue;
      if (updateQueue !== null) {
        instance.state = processUpdateQueue(current, workInProgress, updateQueue, instance, props, renderExpirationTime);
      }
    }
    if (typeof instance.componentDidMount === 'function') {
      workInProgress.effectTag |= Update;
    }
  }

Invokes the mount life-cycles on a previously never rendered instance.

Invokes the mount life - cycles on a previously never rendered instance .


function requestWork(root, expirationTime) {
    if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
      invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
    }

    // Add the root to the schedule.
    // Check if this root is already part of the schedule.
    if (root.nextScheduledRoot === null) {
      // This root is not already scheduled. Add it.
      root.remainingExpirationTime = expirationTime;
      if (lastScheduledRoot === null) {
        firstScheduledRoot = lastScheduledRoot = root;
        root.nextScheduledRoot = root;
      } else {
        lastScheduledRoot.nextScheduledRoot = root;
        lastScheduledRoot = root;
        lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
      }
    } else {
      // This root is already scheduled, but its priority may have increased.
      var remainingExpirationTime = root.remainingExpirationTime;
      if (remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime) {
        // Update the priority.
        root.remainingExpirationTime = expirationTime;
      }
    }

    if (isRendering) {
      // Prevent reentrancy. Remaining work will be scheduled at the end of
      // the currently rendering batch.
      return;
    }

    if (isBatchingUpdates) {
      // Flush work at the end of the batch.
      if (isUnbatchingUpdates) {
        // ...unless we're inside unbatchedUpdates, in which case we should
        // flush it now.
        performWorkOnRoot(root, Sync);
      }
      return;
    }

    // TODO: Get rid of Sync and use current time?
    if (expirationTime === Sync) {
      performWork(Sync, null);
    } else if (!isCallbackScheduled) {
      isCallbackScheduled = true;
      startRequestCallbackTimer();
      scheduleDeferredCallback(performAsyncWork);
    }
  }

requestWork is called by the scheduler whenever a root receives an update. It's up to the renderer to call renderRoot at some point in the future.

requestWork is called by the scheduler whenever a root receives an update . It s up to the renderer to call renderRoot at some point in the future .


function shouldYield() {
    if (deadline === null) {
      return false;
    }
    if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
      return false;
    }
    deadlineDidExpire = true;
    return true;
  }

function shouldYield ( ) { if ( deadline === null ) { return false ; } if ( deadline . timeRemaining ( ) > timeHeuristicForUnitOfWork ) { return false ; } deadlineDidExpire = true ; return true ; }

When working on async work, the reconciler asks the renderer if it should yield execution. For DOM, we implement this with requestIdleCallback.

When working on async work the reconciler asks the renderer if it should yield execution . For DOM we implement this with requestIdleCallback .


function deleteValueForProperty(node, name) {
  var propertyInfo = getPropertyInfo(name);
  if (propertyInfo) {
    var mutationMethod = propertyInfo.mutationMethod;
    if (mutationMethod) {
      mutationMethod(node, undefined);
    } else if (propertyInfo.mustUseProperty) {
      var propName = propertyInfo.propertyName;
      if (propertyInfo.hasBooleanValue) {
        node[propName] = false;
      } else {
        node[propName] = '';
      }
    } else {
      node.removeAttribute(propertyInfo.attributeName);
    }
  } else {
    node.removeAttribute(name);
  }
}

function deleteValueForProperty ( node , name ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo ) { var mutationMethod = propertyInfo . mutationMethod ; if ( mutationMethod ) { mutationMethod ( node , undefined ) ; } else if ( propertyInfo . mustUseProperty ) { var propName = propertyInfo . propertyName ; if ( propertyInfo . hasBooleanValue ) { node [ propName ] = false ; } else { node [ propName ] = '' ; } } else { node . removeAttribute ( propertyInfo . attributeName ) ; } } else { node . removeAttribute ( name ) ; } }

Deletes the value for a property on a node.

@param {DOMElement} node
@param {string} name

Deletes the value for a property on a node .


function updateProperties$1(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
  var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
  var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
  // Apply the diff.
  updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);

  // TODO: Ensure that an update gets scheduled if any of the special props
  // changed.
  switch (tag) {
    case 'input':
      // Update the wrapper around inputs *after* updating props. This has to
      // happen after `updateDOMProperties`. Otherwise HTML5 input validations
      // raise warnings and prevent the new value from being assigned.
      updateWrapper(domElement, nextRawProps);

      // We also check that we haven't missed a value update, such as a
      // Radio group shifting the checked value to another named radio input.
      updateValueIfChanged(domElement);
      break;
    case 'textarea':
      updateWrapper$1(domElement, nextRawProps);
      break;
    case 'select':
      // <select> value update needs to occur after <option> children
      // reconciliation
      postUpdateWrapper(domElement, nextRawProps);
      break;
  }
}


async function sympact(code, options) {
  if (typeof code !== 'string') {
    throw new TypeError("The 'code' paramater must a string'");
  }
  if (typeof options === 'undefined') {
    options = {};
  }
  if (typeof options !== 'object') {
    throw new TypeError("The 'options' paramater must an object'");
  }
  const interval = options.interval || 125;
  const cwd = options.cwd || path.dirname(caller());

  if (interval < 1) {
    throw new TypeError("The 'interval' paramater must be greater than 0'");
  }

  return new Promise((resolve, reject) => {
    const slave = new Worker(code, cwd);
    const probe = new Profiler(slave.pid(), interval);

    slave.on('ready', async () => {
      await probe.watch();
      slave.run();
    });

    slave.on('after', async (start, end) => {
      await probe.unwatch();
      slave.kill();

      resolve(probe.report(start, end));
    });

    slave.on('error', async err => {
      await probe.unwatch();
      slave.kill();

      reject(err);
    });
  });
}

Measures the impact of running a certain script on your system.
Monitors the cpu and memory usage of the whole tree of processes generated by
the script provided.
@public
@param  {string} code The source code to test.
@param  {Object} [options] Optional configurations.
@param  {number} [options.interval=125] Sampling interval in milliseconds.
@param  {string} [options.cwd=caller] CWD for the script.
@return {Promise.<Object>} An object containing the results.

Measures the impact of running a certain script on your system . Monitors the cpu and memory usage of the whole tree of processes generated by the script provided .


function ExponentialBackoffStrategy(options) {
    BackoffStrategy.call(this, options);
    this.backoffDelay_ = 0;
    this.nextBackoffDelay_ = this.getInitialDelay();
    this.factor_ = ExponentialBackoffStrategy.DEFAULT_FACTOR;

    if (options && options.factor !== undefined) {
        precond.checkArgument(options.factor > 1,
            'Exponential factor should be greater than 1 but got %s.',
            options.factor);
        this.factor_ = options.factor;
    }
}


function Backoff(backoffStrategy) {
    events.EventEmitter.call(this);

    this.backoffStrategy_ = backoffStrategy;
    this.maxNumberOfRetry_ = -1;
    this.backoffNumber_ = 0;
    this.backoffDelay_ = 0;
    this.timeoutID_ = -1;

    this.handlers = {
        backoff: this.onBackoff_.bind(this)
    };
}

function Backoff ( backoffStrategy ) { events . EventEmitter . call ( this ) ; this . backoffStrategy_ = backoffStrategy ; this . maxNumberOfRetry_ = - 1 ; this . backoffNumber_ = 0 ; this . backoffDelay_ = 0 ; this . timeoutID_ = - 1 ; this . handlers = { backoff : this . onBackoff_ . bind ( this ) } ; }

A class to hold the state of a backoff operation. Accepts a backoff strategy to generate the backoff delays.

A class to hold the state of a backoff operation . Accepts a backoff strategy to generate the backoff delays .


function FunctionCall(fn, args, callback) {
    events.EventEmitter.call(this);

    precond.checkIsFunction(fn, 'Expected fn to be a function.');
    precond.checkIsArray(args, 'Expected args to be an array.');
    precond.checkIsFunction(callback, 'Expected callback to be a function.');

    this.function_ = fn;
    this.arguments_ = args;
    this.callback_ = callback;
    this.lastResult_ = [];
    this.numRetries_ = 0;

    this.backoff_ = null;
    this.strategy_ = null;
    this.failAfter_ = -1;
    this.retryPredicate_ = FunctionCall.DEFAULT_RETRY_PREDICATE_;

    this.state_ = FunctionCall.State_.PENDING;
}

function
FunctionCall
(
fn
,
args
,
callback
)
{
events
.
EventEmitter
.
call
(
this
)
;
precond
.
checkIsFunction
(
fn
,
'Expected fn to be a function.'
)
;
precond
.
checkIsArray
(
args
,
'Expected args to be an array.'
)
;
precond
.
checkIsFunction
(
callback
,
'Expected callback to be a function.'
)
;
this
.
function_
=
fn
;
this
.
arguments_
=
args
;
this
.
callback_
=
callback
;
this
.
lastResult_
=
[
]
;
this
.
numRetries_
=
0
;
this
.
backoff_
=
;
this
.
strategy_
=
;
this
.
failAfter_
=
1
;
this
.
retryPredicate_
=
FunctionCall
.
DEFAULT_RETRY_PREDICATE_
;
this
.
state_
=
FunctionCall
.
State_
.
PENDING
;
}

Wraps a function to be called in a backoff loop.

Wraps a function to be called in a backoff loop .


function Channel(connection, name, options) {
    options || (options = {});
    options.capped = true;
    // In mongo v <= 2.2 index for _id is not done by default
    options.autoIndexId = true;
    options.size || (options.size = 1024 * 1024 * 5);
    options.strict = false;

    this.options = options;
    this.connection = connection;
    this.closed = false;
    this.listening = null;
    this.name = name || 'mubsub';

    this.create().listen();
    this.setMaxListeners(0);
}

Channel constructor.

@param {Connection} connection
@param {String} [name] optional channel/collection name, default is 'mubsub'
@param {Object} [options] optional options
- `size` max size of the collection in bytes, default is 5mb
- `max` max amount of documents in the collection
- `retryInterval` time in ms to wait if no docs found, default is 200ms
- `recreate` recreate the tailable cursor on error, default is true
@api public


function Connection(uri, options) {
    var self = this;

    options || (options = {});
    options.autoReconnect != null || (options.autoReconnect = true);

    // It's a Db instance.
    if (uri.collection) {
        this.db = uri;
    } else {
        MongoClient.connect(uri, options, function (err, db) {
            if (err) return self.emit('error', err);
            self.db = db;
            self.emit('connect', db);
            db.on('error', function (err) {
                self.emit('error', err);
            });
        });
    }

    this.destroyed = false;
    this.channels = {};
}

function
Connection
(
uri
,
options
)
{
var
self
=
this
;
options
||
(
options
=
{
}
)
;
options
.
autoReconnect
!=
||
(
options
.
autoReconnect
=
true
)
;
// It's a Db instance.
if
(
uri
.
collection
)
{
this
.
db
=
uri
;
}
else
{
MongoClient
.
connect
(
uri
,
options
,
function
(
err
,
db
)
{
if
(
err
)
return
self
.
emit
(
'error'
,
err
)
;
self
.
db
=
db
;
self
.
emit
(
'connect'
,
db
)
;
db
.
on
(
'error'
,
function
(
err
)
{
self
.
emit
(
'error'
,
err
)
;
}
)
;
}
)
;
}
this
.
destroyed
=
false
;
this
.
channels
=
{
}
;
}

Connection constructor.

@param {String|Db} uri string or Db instance
@param {Object} mongo driver options
@api public


function Draggable(target, options) {
	if (!(this instanceof Draggable)) {
		return new Draggable(target, options);
	}

	var that = this;

	//ignore existing instance
	var instance = draggableCache.get(target);
	if (instance) {
		instance.state = 'reset';

		//take over options
		extend(instance, options);

		instance.update();

		return instance;
	}

	else {
		//get unique id for instance
		//needed to track event binders
		that.id = getUid();
		that._ns = '.draggy_' + that.id;

		//save element passed
		that.element = target;

		draggableCache.set(target, that);
	}

	//define state behaviour
	defineState(that, 'state', that.state);

	//preset handles
	that.currentHandles = [];

	//take over options
	extend(that, options);

	//define handle
	if (that.handle === undefined) {
		that.handle = that.element;
	}

	//setup droppable
	if (that.droppable) {
		that.initDroppable();
	}

	//try to calc out basic limits
	that.update();

	//go to initial state
	that.state = 'idle';
}

function
Draggable
(
target
,
options
)
{
if
(
!
(
this
instanceof
Draggable
)
)
{
return
new
Draggable
(
target
,
options
)
;
}
var
that
=
this
;
//ignore existing instance
var
instance
=
draggableCache
.
get
(
target
)
;
if
(
instance
)
{
instance
.
state
=
'reset'
;
//take over options
extend
(
instance
,
options
)
;
instance
.
update
(
)
;
return
instance
;
}
else
{
//get unique id for instance
//needed to track event binders
that
.
id
=
getUid
(
)
;
that
.
_ns
=
'.draggy_'
+
that
.
id
;
//save element passed
that
.
element
=
target
;
draggableCache
.
set
(
target
,
that
)
;
}
//define state behaviour
defineState
(
that
,
'state'
,
that
.
state
)
;
//preset handles
that
.
currentHandles
=
[
]
;
//take over options
extend
(
that
,
options
)
;
//define handle
if
(
that
.
handle
===
undefined
)
{
that
.
handle
=
that
.
element
;
}
//setup droppable
if
(
that
.
droppable
)
{
that
.
initDroppable
(
)
;
}
//try to calc out basic limits
that
.
update
(
)
;
//go to initial state
that
.
state
=
'idle'
;
}

Make an element draggable.

@constructor

@param {HTMLElement} target An element whether in/out of DOM
@param {Object} options An draggable options

@return {HTMLElement} Target element


function ConjunctionMap() {
  let _conjunctions = [];

  /**
   * Add a mapping of a conjunction to a value to this map.
   * @param {Array} conjunction The conjunction to map the value
   * @param {any} value       The value to be mapped
   */
  this.add = function add(conjunction, value) {
    if (value === undefined) {
      return;
    }
    let map = new LiteralTreeMap();
    conjunction.forEach((conjunct) => {
      map.add(conjunct);
    });
    _conjunctions.push([map.size(), map, value]);
  };

  /**
   * Get the value of a conjunction.
   * @return {any} Return the value of the conjunction mapped if it exists. Otherwise if the
   *    conjunction is not mapped then undefined would be returned instead.
   */
  this.get = function get(conjunction) {
    let result;
    for (let i = 0; i < _conjunctions.length; i += 1) {
      let pair = _conjunctions[i];
      let containMismatch = false;
      if (conjunction.length !== pair[0]) {
        continue;
      }
      for (let j = 0; j < conjunction.length; j += 1) {
        let conjunct = conjunction[j];
        if (!pair[1].contains(conjunct)) {
          containMismatch = true;
          break;
        }
      }
      if (!containMismatch) {
        result = pair[2];
        break;
      }
    }
    return result;
  };
}

Maps conjunctions to a value.
@constructor


function sortTimables(conjunction, forTime) {
  let earlyConjuncts = [];
  let laterConjuncts = [];

  let dependentTimeVariables = {};

  // determine the time dependent variables
  for (let k = 0; k < conjunction.length; k += 1) {
    let conjunct = conjunction[k];

    if (!(conjunct instanceof Timable)) {
      // skip over non-Timables
      if (conjunct instanceof Functor
          && comparisonTerms.indexOf(conjunct.getId()) !== -1) {
        conjunct.getVariables()
          .forEach((v) => {
            dependentTimeVariables[v] = true;
          });
      }
      continue;
    }

    let conjunctStartTime = conjunct.getStartTime();
    let conjunctEndTime = conjunct.getEndTime();

    if (conjunctEndTime instanceof Variable) {
      let endTimeName = conjunctEndTime.evaluate();
      if (conjunctStartTime instanceof Value
          || (conjunctStartTime instanceof Variable
            && conjunctStartTime.evaluate() !== endTimeName)) {
        // different start/end times
        dependentTimeVariables[endTimeName] = true;
      }
    }
  }

  // sort between early and later
  for (let k = 0; k < conjunction.length; k += 1) {
    let conjunct = conjunction[k];

    if (!(conjunct instanceof Timable)) {
      if (laterConjuncts.length > 0) {
        laterConjuncts.push(conjunct);
        continue;
      }
      earlyConjuncts.push(conjunct);
      continue;
    }

    if (!conjunct.isInRange(forTime)) {
      laterConjuncts.push(conjunct);
      continue;
    }

    let conjunctStartTime = conjunct.getStartTime();

    if (conjunctStartTime instanceof Variable) {
      if (dependentTimeVariables[conjunctStartTime.evaluate()] !== undefined) {
        laterConjuncts.push(conjunct);
        continue;
      }
    }

    earlyConjuncts.push(conjunct);
  }

  return [
    earlyConjuncts,
    laterConjuncts
  ];
}

Sort timables into set of earlyConjuncts and laterConjuncts
@param  {Array} conjunction The conjunction. Must be an array of functors or timables
@param  {number} forTime     A positive integer of the time to determine earlyConjuncts
@return {Array}             Return a pair of early conjuncts and later conjuncts


function (programArgs) {
  let _programArgs = programArgs;
  if (programArgs === undefined) {
    _programArgs = [];
  }
  // map to values
  _programArgs = _programArgs.map(arg => new Value(arg));
  let argsList = new List(_programArgs);
  let theta = {
    List: argsList
  };
  return programArgsPredicate.substitute(theta);
}

function
(
programArgs
)
{
let
_programArgs
=
programArgs
;
if
(
programArgs
===
undefined
)
{
_programArgs
=
[
]
;
}
// map to values
_programArgs
=
_programArgs
.
map
(
arg
=>
new
Value
(
arg
)
)
;
let
argsList
=
new
List
(
_programArgs
)
;
let
theta
=
{
List
:
argsList
}
;
return
programArgsPredicate
.
substitute
(
theta
)
;
}

Construct the program arguments predicate
@private
@param  {array} programArgs The array of program arguments
@return {Functor}             The constructed predicate that contains the program arguments


function createProgramArgsUpdaterFunc(programArgs) {
  return (program) => {
    let programArgsFact = buildProgramArgsPredicate(programArgs);
    program.getFacts().add(programArgsFact);
    return Promise.resolve(program);
  };
}

function createProgramArgsUpdaterFunc ( programArgs ) { return ( program ) => { let programArgsFact = buildProgramArgsPredicate ( programArgs ) ; program . getFacts ( ) . add ( programArgsFact ) ; return Promise . resolve ( program ) ; } ; }

Create a function to update a given program with the given program arguments
@param  {array} programArgs Array of program arguments
@return {[type]}             [description]


function processCycleObservations() {
    let activeObservations = new LiteralTreeMap();

    if (_observations[_currentTime] === undefined) {
      // no observations for current time
      return activeObservations;
    }
    let cloneProgram = _program.clone();
    cloneProgram.setExecutedActions(activeObservations);

    const nextTime = _currentTime + 1;

    // process observations for the current time
    _observations[_currentTime].forEach((ob) => {
      let action = ob.action;

      let tempTreeMap = new LiteralTreeMap();
      tempTreeMap.add(action);

      activeObservations.add(action);

      let postCloneProgram = cloneProgram.clone();
      let postState = postCloneProgram.getState();
      postCloneProgram.setExecutedActions(new LiteralTreeMap());
      updateStateWithFluentActors(
        this,
        tempTreeMap,
        postState
      );
      postCloneProgram.setState(postState);

      // perform pre-check and post-check
      if (!checkConstraintSatisfaction.call(this, cloneProgram)
          || !checkConstraintSatisfaction.call(this, postCloneProgram)) {
        // reject the observed event
        // to keep model true
        activeObservations.remove(action);

        // warning
        _engineEventManager.notify('warning', {
          type: 'observation.reject',
          message: stringLiterals(
            'engine.rejectObservationWarning',
            action,
            _currentTime,
            nextTime
          )
        });
      }

      // if the given observation endTime has not ended
      // propagate to the next cycle's
      if (ob.endTime > nextTime) {
        if (_observations[nextTime] === undefined) {
          _observations[nextTime] = [];
        }
        _observations[nextTime].push(ob);
      }
    });

    return activeObservations;
  }

Process observations for the current cycle
@return {LiteralTreeMap} Returns the set of observed event for the current time.


function actionsSelector(goalTrees) {
    const recursiveActionsSelector = (actionsSoFar, programSoFar, l) => {
      if (l >= goalTrees.length) {
        let actions = new LiteralTreeMap();
        actionsSoFar.forEach((map) => {
          map.forEach((literal) => {
            actions.add(literal);
          });
        });
        return actions;
      }
      let goalTree = goalTrees[l];
      let resultSet = null;
      goalTree.forEachCandidateActions(_currentTime, (candidateActions) => {
        let cloneProgram = programSoFar.clone();

        let cloneExecutedActions = cloneProgram.getExecutedActions();
        candidateActions.forEach((a) => {
          cloneExecutedActions.add(a);
        });

        // pre-condition check
        if (!checkConstraintSatisfaction.call(this, cloneProgram)) {
          return false;
        }

        // post condition checks
        let clonePostProgram = programSoFar.clone();
        clonePostProgram.setExecutedActions(new LiteralTreeMap());
        let postState = clonePostProgram.getState();
        updateStateWithFluentActors(
          this,
          candidateActions,
          postState
        );
        clonePostProgram.setState(postState);

        if (!checkConstraintSatisfaction.call(this, clonePostProgram)) {
          return false;
        }

        resultSet = recursiveActionsSelector(
          actionsSoFar.concat([candidateActions]),
          cloneProgram,
          l + 1
        );
        return true;
      });

      if (resultSet !== null) {
        return resultSet;
      }

      return recursiveActionsSelector(
        actionsSoFar,
        programSoFar,
        l + 1
      );
    };

    return recursiveActionsSelector([], _program, 0);
  }

function
actionsSelector
(
goalTrees
)
{
const
recursiveActionsSelector
=
(
actionsSoFar
,
programSoFar
,
l
)
=>
{
if
(
l
>=
goalTrees
.
length
)
{
let
actions
=
new
LiteralTreeMap
(
)
;
actionsSoFar
.
forEach
(
(
map
)
=>
{
map
.
forEach
(
(
literal
)
=>
{
actions
.
add
(
literal
)
;
}
)
;
}
)
;
return
actions
;
}
let
goalTree
=
goalTrees
[
l
]
;
let
resultSet
=
;
goalTree
.
forEachCandidateActions
(
_currentTime
,
(
candidateActions
)
=>
{
let
cloneProgram
=
programSoFar
.
clone
(
)
;
let
cloneExecutedActions
=
cloneProgram
.
getExecutedActions
(
)
;
candidateActions
.
forEach
(
(
a
)
=>
{
cloneExecutedActions
.
add
(
a
)
;
}
)
;
// pre-condition check
if
(
!
checkConstraintSatisfaction
.
call
(
this
,
cloneProgram
)
)
{
return
false
;
}
// post condition checks
let
clonePostProgram
=
programSoFar
.
clone
(
)
;
clonePostProgram
.
setExecutedActions
(
new
LiteralTreeMap
(
)
)
;
let
postState
=
clonePostProgram
.
getState
(
)
;
updateStateWithFluentActors
(
this
,
candidateActions
,
postState
)
;
clonePostProgram
.
setState
(
postState
)
;
if
(
!
checkConstraintSatisfaction
.
call
(
this
,
clonePostProgram
)
)
{
return
false
;
}
resultSet
=
recursiveActionsSelector
(
actionsSoFar
.
concat
(
[
candidateActions
]
)
,
cloneProgram
,
l
+
1
)
;
return
true
;
}
)
;
if
(
resultSet
!==
)
{
return
resultSet
;
}
return
recursiveActionsSelector
(
actionsSoFar
,
programSoFar
,
l
+
1
)
;
}
;
return
recursiveActionsSelector
(
[
]
,
_program
,
0
)
;
}

Select the appropriate set of actions from the given goal trees such that
constraints are not violated for the current cycle.
@param  {Array<GoalTree>} goalTrees The goal trees to choose actions from
@return {LiteralTreeMap}            The set of actions chosen to execute

Select the appropriate set of actions from the given goal trees such that constraints are not violated for the current cycle .


function performCycle() {
    _currentTime += 1;

    let selectedAndExecutedActions = new LiteralTreeMap();
    let executedObservations = new LiteralTreeMap();

    // Step 0 - Updating database
    let updatedState = _program.getState().clone();
    updateStateWithFluentActors(
      this,
      _program.getExecutedActions(),
      updatedState
    );
    _program.setState(updatedState);

    _nextCycleObservations.forEach((obs) => {
      executedObservations.add(obs);
    });
    _nextCycleActions.forEach((act) => {
      selectedAndExecutedActions.add(act);
    });

    // Step 1 - Processing rules
    let newFiredGoals = processRules(this, _program, _currentTime, _profiler);
    _goals = _goals.concat(newFiredGoals);

    // Step 3 - Processing
    return evaluateGoalTrees(_currentTime, _goals, _profiler)
      .then((newGoals) => {
        _goals = newGoals;

        // Start preparation for next cycle

        // reset the set of executed actions
        _program.setExecutedActions(new LiteralTreeMap());
        _goals.sort(goalTreeSorter(_currentTime));

        // select actions from candidate actions
        return actionsSelector.call(this, _goals);
      })
      .then((nextCycleActions) => {
        _nextCycleActions = new LiteralTreeMap();
        nextCycleActions.forEach((l) => {
          _nextCycleActions.add(l);
        });
        _nextCycleObservations = new LiteralTreeMap();
        let cycleObservations = processCycleObservations.call(this);
        cycleObservations.forEach((observation) => {
          nextCycleActions.add(observation);
          _nextCycleObservations.add(observation);
        });

        _program.setExecutedActions(nextCycleActions);

        _lastCycleActions = selectedAndExecutedActions;
        _lastCycleObservations = executedObservations;

        // done with cycle
        return Promise.resolve();
      });
  }

Performs the state transition for a single cycle.
@return {Promise} Returns a promise that when fulfilled, indicates the completion of the
cycle processing.

Performs the state transition for a single cycle .


function applyArgs(func, thisObj, args) {
		return func.apply(thisObj, Array.prototype.slice.call(args));
	}

function applyArgs ( func , thisObj , args ) { return func . apply ( thisObj , Array . prototype . slice . call ( args ) ) ; }

converts native arguments object to an array and applies function


function define() {
		var thisFlow = function() {
			applyArgs(thisFlow.exec, thisFlow, arguments);
		}

		thisFlow.blocks = arguments;

		thisFlow.exec = function() {
			// The flowState is the actual object each step in the flow is applied to. It acts as a
			// callback to the next function. It also maintains the internal state of each execution
			// and acts as a place for users to save values between steps of the flow.
			var flowState = function() {
				if (flowState.__frozen) return;

				if (flowState.__timeoutId) {
					clearTimeout(flowState.__timeoutId);
					delete flowState.__timeoutId;
				}

				var blockIdx = flowState.__nextBlockIdx ++;
				var block = thisFlow.blocks[blockIdx];

				if (block === undefined) {
					return;
				}
				else {
					applyArgs(block, flowState, arguments);
				}
			}

			// __nextBlockIdx specifies which function is the next step in the flow.
			flowState.__nextBlockIdx = 0;

			// __multiCount is incremented every time MULTI is used to createa a multiplexed callback
			flowState.__multiCount = 0;

			// __multiOutputs accumulates the arguments of each call to callbacks generated by MULTI
			flowState.__multiOutputs = [];

			// REWIND signals that the next call to thisFlow should repeat this step. It allows you
			// to create serial loops.
			flowState.REWIND = function() {
				flowState.__nextBlockIdx -= 1;
			}

			// MULTI can be used to generate callbacks that must ALL be called before the next step
			// in the flow is executed. Arguments to those callbacks are accumulated, and an array of
			// of those arguments objects is sent as the one argument to the next step in the flow.
			// @param {String} resultId An identifier to get the result of a multi call.
			flowState.MULTI = function(resultId) {
				flowState.__multiCount += 1;
				return function() {
					flowState.__multiCount -= 1;
					flowState.__multiOutputs.push(arguments);

          if (resultId) {
            var result = arguments.length <= 1 ? arguments[0] : arguments
            flowState.__multiOutputs[resultId] = result;
          }

					if (flowState.__multiCount === 0) {
						var multiOutputs = flowState.__multiOutputs;
						flowState.__multiOutputs = [];
						flowState(multiOutputs);
					}
				}
			}

			// TIMEOUT sets a timeout that freezes a flow and calls the provided callback. This
			// timeout is cleared if the next flow step happens first.
			flowState.TIMEOUT = function(milliseconds, timeoutCallback) {
				if (flowState.__timeoutId !== undefined) {
					throw new Error("timeout already set for this flow step");
				}

				flowState.__timeoutId = setTimeout(function() {
					flowState.__frozen = true;
					timeoutCallback();
				}, milliseconds);
			}

			applyArgs(flowState, this, arguments);
		}

		return thisFlow;
	}

defines a flow given any number of functions as arguments


function() {
				if (flowState.__frozen) return;

				if (flowState.__timeoutId) {
					clearTimeout(flowState.__timeoutId);
					delete flowState.__timeoutId;
				}

				var blockIdx = flowState.__nextBlockIdx ++;
				var block = thisFlow.blocks[blockIdx];

				if (block === undefined) {
					return;
				}
				else {
					applyArgs(block, flowState, arguments);
				}
			}

function ( ) { if ( flowState . __frozen ) return ; if ( flowState . __timeoutId ) { clearTimeout ( flowState . __timeoutId ) ; delete flowState . __timeoutId ; } var blockIdx = flowState . __nextBlockIdx ++ ; var block = thisFlow . blocks [ blockIdx ] ; if ( block === undefined ) { return ; } else { applyArgs ( block , flowState , arguments ) ; } }

The flowState is the actual object each step in the flow is applied to. It acts as a callback to the next function. It also maintains the internal state of each execution and acts as a place for users to save values between steps of the flow.

The flowState is the actual object each step in the flow is applied to . It acts as a callback to the next function . It also maintains the internal state of each execution and acts as a place for users to save values between steps of the flow .


function exec() {
		var flow = typeof exports != 'undefined' ? exports : window.flow;
		applyArgs(flow.define, flow, arguments)();
	}

function exec ( ) { var flow = typeof exports != 'undefined' ? exports : window . flow ; applyArgs ( flow . define , flow , arguments ) ( ) ; }

defines a flow and evaluates it immediately. The first flow function won't receive any arguments.

defines a flow and evaluates it immediately . The first flow function won t receive any arguments .


function padStart(str, length, padChar) {
  if (str.length >= length) {
      return str;
  } else {
      return padChar.repeat(length - str.length) + str;
  }
}

function padStart ( str , length , padChar ) { if ( str . length >= length ) { return str ; } else { return padChar . repeat ( length - str . length ) + str ; } }

Pads supplied string with character to fill the desired length.

@param {*} str String to pad
@param {*} length Desired length of result string
@param {*} padChar Character to use as padding

Pads supplied string with character to fill the desired length .


function SM2Curve(params) {
  if (!(this instanceof SM2Curve)) {
    return new SM2Curve(params);
  }

  elliptic.curve.short.call(this, params);
}

function SM2Curve ( params ) { if ( ! ( this instanceof SM2Curve ) ) { return new SM2Curve ( params ) ; } elliptic . curve . short . call ( this , params ) ; }


function SM2KeyPair(pub, pri) {
  if (!(this instanceof SM2KeyPair)) {
    return new SM2KeyPair(pub, pri);
  }
  this.curve = SM2; // curve parameter
  this.pub = null; // public key, should be a point on the curve
  this.pri = null; // private key, should be a integer

  var validPub = false;
  var validPri = false;

  if (pub != null) {
    if (typeof pub === 'string') {
      this._pubFromString(pub);
    } else if (Array.isArray(pub)) {
      this._pubFromBytes(pub);
    } else if ('x' in pub && pub.x instanceof BN &&
               'y' in pub && pub.y instanceof BN) {
      // pub is already the Point object
      this.pub = pub;
      validPub = true;
    } else {
      throw 'invalid public key';
    }
  }
  if (pri != null) {
    if (typeof pri === 'string') {
      this.pri = new BN(pri, 16);
    } else if (pri instanceof BN) {
      this.pri = pri;
      validPri = true;
    } else {
      throw 'invalid private key';
    }

    // calculate public key
    if (this.pub == null) {
      this.pub = SM2.g.mul(this.pri);
    }
  }

  if (!(validPub && validPri) && !this.validate()) {
    throw 'invalid key';
  }
}

SM2 public and private key pair

Either `pub` and `pri` can be a hex string or byte array or null.
If `pub` is a string, it should be the same format as output of pubToString().


function gulpStaticI18n(options) {
  return through.obj(function(target, encoding, cb) {
    var stream = this;
    var build = new StaticI18n(target, options, stream);
    build.translate(cb);
  });
}

function gulpStaticI18n ( options ) { return through . obj ( function ( target , encoding , cb ) { var stream = this ; var build = new StaticI18n ( target , options , stream ) ; build . translate ( cb ) ; } ) ; }

plugin wrapper so streams can pipe to it.

plugin wrapper so streams can pipe to it .


function (obj, type, fn, scope) {
                scope = scope || obj;

                var wrappedFn = function (e) { fn.call(scope, e); };

                obj.addEventListener(type, wrappedFn, false);
                cache.push([obj, type, fn, wrappedFn]);
            }

function ( obj , type , fn , scope ) { scope = scope || obj ; var wrappedFn = function ( e ) { fn . call ( scope , e ) ; } ; obj . addEventListener ( type , wrappedFn , false ) ; cache . push ( [ obj , type , fn , wrappedFn ] ) ; }

Add an event to an object and optionally adjust it's scope

@param obj {HTMLElement} The object to attach the event to
@param type {string} The type of event excluding "on"
@param fn {function} The function
@param scope {object} Object to adjust the scope to (optional)

Add an event to an object and optionally adjust it s scope


function (obj, type, fn) {
                var wrappedFn, item, len = cache.length, i;

                for (i = 0; i < len; i++) {
                    item = cache[i];

                    if (item[0] === obj && item[1] === type && item[2] === fn) {
                        wrappedFn = item[3];

                        if (wrappedFn) {
                            obj.removeEventListener(type, wrappedFn, false);
                            cache = cache.slice(i);
                            return true;
                        }
                    }
                }
            }

function ( obj , type , fn ) { var wrappedFn , item , len = cache . length , i ; for ( i = 0 ; i < len ; i ++ ) { item = cache [ i ] ; if ( item [ 0 ] === obj && item [ 1 ] === type && item [ 2 ] === fn ) { wrappedFn = item [ 3 ] ; if ( wrappedFn ) { obj . removeEventListener ( type , wrappedFn , false ) ; cache = cache . slice ( i ) ; return true ; } } } }

Remove an event from an object

@param obj {HTMLElement} The object to remove the event from
@param type {string} The type of event excluding "on"
@param fn {function} The function


function View(model) {
    var wrapper;

    this.el = wrapper = document.createElement('div');
    this.model = model;
    this.isShowing = false;

    // HTML
    wrapper.id = config.name;
    config.parent.appendChild(wrapper);

    // CSS
    css.inject(document.getElementsByTagName('head')[0], config.styles);

    // JavaScript
    events.add(document, ('ontouchstart' in window) ? 'touchstart' : 'click', viewevents.click, this);
    events.add(document, 'keyup', viewevents.keyup, this);
    events.add(document, 'readystatechange', viewevents.readystatechange, this);
    events.add(window, 'pageshow', viewevents.pageshow, this);
}

function
View
(
model
)
{
var
wrapper
;
this
.
el
=
wrapper
=
document
.
createElement
(
'div'
)
;
this
.
model
=
model
;
this
.
isShowing
=
false
;
// HTML
wrapper
.
id
=
config
.
name
;
config
.
parent
.
appendChild
(
wrapper
)
;
// CSS
css
.
inject
(
document
.
getElementsByTagName
(
'head'
)
[
0
]
,
config
.
styles
)
;
// JavaScript
events
.
add
(
document
,
(
'ontouchstart'
in
window
)
'touchstart'
:
'click'
,
viewevents
.
click
,
this
)
;
events
.
add
(
document
,
'keyup'
,
viewevents
.
keyup
,
this
)
;
events
.
add
(
document
,
'readystatechange'
,
viewevents
.
readystatechange
,
this
)
;
events
.
add
(
window
,
'pageshow'
,
viewevents
.
pageshow
,
this
)
;
}

Creates a view model.

@constructor
@param {object} model


function Product(data) {
    data.quantity = parser.quantity(data.quantity);
    data.amount = parser.amount(data.amount);
    data.href = parser.href(data.href);

    this._data = data;
    this._options = null;
    this._discount = null;
    this._amount = null;
    this._total = null;

    Pubsub.call(this);
}

function Product ( data ) { data . quantity = parser . quantity ( data . quantity ) ; data . amount = parser . amount ( data . amount ) ; data . href = parser . href ( data . href ) ; this . _data = data ; this . _options = null ; this . _discount = null ; this . _amount = null ; this . _total = null ; Pubsub . call ( this ) ; }

Creates a new product.

@constructor
@param {object} data Item data


function Cart(name, duration) {
    var data, items, settings, len, i;

    this._items = [];
    this._settings = { bn: constants.BN };

    Pubsub.call(this);
    Storage.call(this, name, duration);

    if ((data = this.load())) {
        items = data.items;
        settings = data.settings;

        if (settings) {
            this._settings = settings;
        }

        if (items) {
            for (i = 0, len = items.length; i < len; i++) {
                this.add(items[i]);
            }
        }
    }
}

function Cart ( name , duration ) { var data , items , settings , len , i ; this . _items = [ ] ; this . _settings = { bn : constants . BN } ; Pubsub . call ( this ) ; Storage . call ( this , name , duration ) ; if ( ( data = this . load ( ) ) ) { items = data . items ; settings = data . settings ; if ( settings ) { this . _settings = settings ; } if ( items ) { for ( i = 0 , len = items . length ; i < len ; i ++ ) { this . add ( items [ i ] ) ; } } } }

Renders the Mini Cart to the page's DOM.

@constructor
@param {string} name Name of the cart (used as a key for storage)
@param {duration} number Time in milliseconds that the cart data should persist

Renders the Mini Cart to the page s DOM .


function onRejected(error) {

            attemts_left -= 1;

            if (attemts_left < 1) {
                throw error;
            }

            console.log("A retried call failed. Retrying " + attemts_left + " more time(s).");

            // retry call self again with the same arguments, except attemts_left is now lower
            var fullArguments = [attemts_left, promiseFunction].concat(promiseFunctionArguments);
            return module.exports.retryPromise.apply(undefined, fullArguments);
        }

on rejection either retry, or throw the error

on rejection either retry or throw the error


function fixDate(type, value, hash) {
  if (type !== "commit" && type !== "tag") return;
  // Add up to 3 extra newlines and try all 30-minutes timezone offsets.
  var clone = JSON.parse(JSON.stringify(value));
  for (var x = 0; x < 3; x++) {
    for (var i = -720; i < 720; i += 30) {
      if (type === "commit") {
        clone.author.date.offset = i;
        clone.committer.date.offset = i;
      }
      else if (type === "tag") {
        clone.tagger.date.offset = i;
      }
      if (hash !== hashAs(type, clone)) continue;
      // Apply the changes and return.
      value.message = clone.message;
      if (type === "commit") {
        value.author.date.offset = clone.author.date.offset;
        value.committer.date.offset = clone.committer.date.offset;
      }
      else if (type === "tag") {
        value.tagger.date.offset = clone.tagger.date.offset;
      }
      return true;
    }
    clone.message += "\n";
  }
  return false;
}

GitHub has a nasty habit of stripping whitespace from messages and losing the timezone.  This information is required to make our hashes match up, so we guess it by mutating the value till the hash matches. If we're unable to match, we will just force the hash when saving to the cache.

GitHub has a nasty habit of stripping whitespace from messages and losing the timezone . This information is required to make our hashes match up so we guess it by mutating the value till the hash matches . If we re unable to match we will just force the hash when saving to the cache .


function () {
            var $this = this;

            // remove all data set with .data()
            $this.removeData();

            // unbind the document as well
            $(document)
                .unbind('mousemove.nstSlider')
                .unbind('mouseup.nstSlider');

            // unbind events bound to the container element
            $this.parent()
                .unbind('mousedown.nstSlider')
                .unbind('touchstart.nstSlider')
                .unbind('touchmove.nstSlider')
                .unbind('touchend.nstSlider');

            // unbind events bound to the current element
            $this.unbind('keydown.nstSlider')
                .unbind('keyup.nstSlider');

            return $this;
        }


function () {
            var $this = this;

            // re-set the slider step if specified
            var lastStepHistogram = $this.data('last_step_histogram');
            if (typeof lastStepHistogram !== 'undefined') {
                methods.set_step_histogram.call($this, lastStepHistogram);
            }

            // re-center given values
            _methods.set_position_from_val.call($this,
                methods.get_current_min_value.call($this),
                methods.get_current_max_value.call($this)
            );

            // re-highlight the range
            var highlightRangeMin = $this.data('highlightedRangeMin');
            if (typeof highlightRangeMin === 'number') {
                // a highlight range is present, we must update it
                var highlightRangeMax = $this.data('highlightedRangeMax');
                methods.highlight_range.call($this, highlightRangeMin, highlightRangeMax);
            }

            _methods.notify_changed_implicit.call($this, 'refresh');
            return $this;
        }

just call set_position on the current values


function GoogleLogin() {
    if (!(this instanceof GoogleLogin)) {
        return new GoogleLogin();
    }
    const self = this;

    /**
     * Based of https://github.com/tejado/pgoapi/blob/master/pgoapi/auth_google.py#L33
     */
    const GOOGLE_LOGIN_ANDROID_ID = '9774d56d682e549c';
    const GOOGLE_LOGIN_SERVICE =
        'audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com';
    const GOOGLE_LOGIN_APP = 'com.nianticlabs.pokemongo';
    const GOOGLE_LOGIN_CLIENT_SIG = '321187995bc7cdc2b5fc91b11a96e2baa8602c62';

    /**
     * Sets a proxy address to use for logins.
     * @param {string} proxy
     */
    this.setProxy = function(proxy) {
        google.setProxy(proxy);
    };

    /**
     * Performs the Google Login using Android Device and returns a Promise that will be resolved
     * with the auth token.
     * @param {string} username
     * @param {string} password
     * @return {Promise}
     */
    this.login = function(username, password) {
        return self.getMasterToken(username, password)
            .then(loginData => self.getToken(username, loginData))
            .then(authData => authData.Auth);
    };

    /**
     * Performs the Google login by skipping the password step and starting with the Master Token
     * instead. Returns a Promise that will be resolved with the auth token.
     * @param {string} username
     * @param {string} token
     * @return {Promise}
     */
    this.loginWithToken = function(username, token) {
        var loginData = {
            androidId: GOOGLE_LOGIN_ANDROID_ID,
            masterToken: token
        };
        return self.getToken(username, loginData).then(authData => authData.Auth);
    };

    /**
     * Initialize Google Login
     * @param {string} username
     * @param {string} password
     * @return {Promise}
     */
    this.getMasterToken = function(username, password) {
        return new Promise((resolve, reject) => {
            google.login(username, password, GOOGLE_LOGIN_ANDROID_ID, (err, data) => {
                if (err) {
                    if (err.response.statusCode === 403) {
                        reject(Error(
                            'Received code 403 from Google login. This could be because your account has ' +
                            '2-Step-Verification enabled. If that is the case, you need to generate an ' +
                            'App Password and use that instead of your regular password: ' +
                            'https://security.google.com/settings/security/apppasswords'
                        ));
                    } else {
                        reject(Error(err.response.statusCode + ': ' + err.response.statusMessage));
                    }
                    return;
                }

                resolve(data);
            });
        });
    };

    /**
     * Finalizes oAuth request using master token and resolved with the auth data
     * @private
     * @param {string} username
     * @param {string} loginData
     * @return {Promise}
     */
    this.getToken = function(username, loginData) {
        return new Promise((resolve, reject) => {
            google.oauth(username, loginData.masterToken, loginData.androidId,
                GOOGLE_LOGIN_SERVICE, GOOGLE_LOGIN_APP, GOOGLE_LOGIN_CLIENT_SIG, (err, data) => {
                    if (err) {
                        reject(Error(err.response.statusCode + ': ' + err.response.statusMessage));
                        return;
                    }

                    resolve(data);
                });
        });
    };
}

Google login client.
@class GoogleLogin
@memberof pogobuf


function(lat, lng, radius, level) {
        if (typeof radius === 'undefined') radius = 3;
        if (typeof level === 'undefined') level = 15;

        /* eslint-disable new-cap */
        var origin = s2.S2Cell.FromLatLng({
            lat: lat,
            lng: lng
        }, level);
        var cells = [];

        cells.push(origin.toHilbertQuadkey()); // middle block

        for (var i = 1; i < radius; i++) {
            // cross in middle
            cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0], origin.ij[1] - i], origin.level)
                .toHilbertQuadkey());
            cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0], origin.ij[1] + i], origin.level)
                .toHilbertQuadkey());
            cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] - i, origin.ij[1]], origin.level)
                .toHilbertQuadkey());
            cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] + i, origin.ij[1]], origin.level)
                .toHilbertQuadkey());

            for (var j = 1; j < radius; j++) {
                cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] - j, origin.ij[1] - i], origin.level)
                    .toHilbertQuadkey());
                cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] + j, origin.ij[1] - i], origin.level)
                    .toHilbertQuadkey());
                cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] - j, origin.ij[1] + i], origin.level)
                    .toHilbertQuadkey());
                cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] + j, origin.ij[1] + i], origin.level)
                    .toHilbertQuadkey());
            }
        }
        /* eslint-enable new-cap */

        return cells.map(s2.toId);
    }

function
(
lat
,
lng
,
radius
,
level
)
{
if
(
typeof
radius
===
'undefined'
)
radius
=
3
;
if
(
typeof
level
===
'undefined'
)
level
=
15
;
/* eslint-disable new-cap */
var
origin
=
s2
.
S2Cell
.
FromLatLng
(
{
lat
:
lat
,
lng
:
lng
}
,
level
)
;
var
cells
=
[
]
;
cells
.
push
(
origin
.
toHilbertQuadkey
(
)
)
;
// middle block
for
(
var
i
=
1
;
i
<
radius
;
i
++
)
{
// cross in middle
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
,
origin
.
ij
[
1
]
i
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
,
origin
.
ij
[
1
]
+
i
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
i
,
origin
.
ij
[
1
]
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
+
i
,
origin
.
ij
[
1
]
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
for
(
var
j
=
1
;
j
<
radius
;
j
++
)
{
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
j
,
origin
.
ij
[
1
]
i
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
+
j
,
origin
.
ij
[
1
]
i
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
j
,
origin
.
ij
[
1
]
+
i
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
cells
.
push
(
s2
.
S2Cell
.
FromFaceIJ
(
origin
.
face
,
[
origin
.
ij
[
0
]
+
j
,
origin
.
ij
[
1
]
+
i
]
,
origin
.
level
)
.
toHilbertQuadkey
(
)
)
;
}
}
/* eslint-enable new-cap */
return
cells
.
map
(
s2
.
toId
)
;
}

Provides cell IDs of nearby cells based on the given coords and radius
@param {number} lat
@param {number} lng
@param {number} [radius=3]
@param {number} [level=15]
@returns {array}
@static


function(enumObj, val) {
        for (var key of Object.keys(enumObj)) {
            if (enumObj[key] === val) {
                return key.split('_')
                    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
                    .join(' ');
            }
        }
        return null;
    }

function
(
enumObj
,
val
)
{
for
(
var
key
of
Object
.
keys
(
enumObj
)
)
{
if
(
enumObj
[
key
]
===
val
)
{
return
key
.
split
(
'_'
)
.
map
(
word
=>
word
.
charAt
(
0
)
.
toUpperCase
(
)
+
word
.
slice
(
1
)
.
toLowerCase
(
)
)
.
join
(
' '
)
;
}
}
return
;
}

Utility method that finds the name of the key for a given enum value and makes it
look a little nicer.
@param {object} enumObj
@param {number} val
@returns {string}
@static

Utility method that finds the name of the key for a given enum value and makes it look a little nicer .


function(object) {
        if (!object || typeof object !== 'object') return object;
        if (object instanceof ByteBuffer) return object;

        if (Long.isLong(object)) {
            return object.lessThanOrEqual(Number.MAX_SAFE_INTEGER)
                && object.greaterThanOrEqual(Number.MIN_SAFE_INTEGER)
                ? object.toNumber() : object.toString();
        }

        for (var i in object) {
            if (object.hasOwnProperty(i)) {
                if (Long.isLong(object[i])) {
                    object[i] = object[i].lessThanOrEqual(Number.MAX_SAFE_INTEGER) && object[i].greaterThanOrEqual(
                        Number.MIN_SAFE_INTEGER) ? object[i].toNumber() : object[i].toString();
                } else if (typeof object[i] === 'object') {
                    object[i] = this.convertLongs(object[i]);
                }
            }
        }

        return object;
    }

function ( object ) { if ( ! object || typeof object !== 'object' ) return object ; if ( object instanceof ByteBuffer ) return object ; if ( Long . isLong ( object ) ) { return object . lessThanOrEqual ( Number . MAX_SAFE_INTEGER ) && object . greaterThanOrEqual ( Number . MIN_SAFE_INTEGER ) ? object . toNumber ( ) : object . toString ( ) ; } for ( var i in object ) { if ( object . hasOwnProperty ( i ) ) { if ( Long . isLong ( object [ i ] ) ) { object [ i ] = object [ i ] . lessThanOrEqual ( Number . MAX_SAFE_INTEGER ) && object [ i ] . greaterThanOrEqual ( Number . MIN_SAFE_INTEGER ) ? object [ i ] . toNumber ( ) : object [ i ] . toString ( ) ; } else if ( typeof object [ i ] === 'object' ) { object [ i ] = this . convertLongs ( object [ i ] ) ; } } } return object ; }

Utility method to convert all Long.js objects to integers or strings
@param {object} object – An object
@returns {object}
@static

Utility method to convert all Long . js objects to integers or strings


function Random(seed) {
    this.multiplier = 16807;
    this.modulus = 0x7fffffff;
    this.seed = seed;
    this.mq = Math.floor(this.modulus / this.multiplier);
    this.mr = this.modulus % this.multiplier;
}

function Random ( seed ) { this . multiplier = 16807 ; this . modulus = 0x7fffffff ; this . seed = seed ; this . mq = Math . floor ( this . modulus / this . multiplier ) ; this . mr = this . modulus % this . multiplier ; }

Lehmer random module used by the app to generate request ids


function prettyDate(time){
	/*var date = new Date((time || "")*/
	var diff = (((new Date()).getTime() - time) / 1000),
			day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;

	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

function
prettyDate
(
time
)
{
/*var date = new Date((time || "")*/
var
diff
=
(
(
(
new
Date
(
)
)
.
getTime
(
)
time
)
/
1000
)
,
day_diff
=
Math
.
floor
(
diff
/
86400
)
;
if
(
isNaN
(
day_diff
)
||
day_diff
<
0
||
day_diff
>=
31
)
return
;
return
day_diff
==
0
&&
(
diff
<
60
&&
"just now"
||
diff
<
120
&&
"1 minute ago"
||
diff
<
3600
&&
Math
.
floor
(
diff
/
60
)
+
" minutes ago"
||
diff
<
7200
&&
"1 hour ago"
||
diff
<
86400
&&
Math
.
floor
(
diff
/
3600
)
+
" hours ago"
)
||
day_diff
==
1
&&
"Yesterday"
||
day_diff
<
7
&&
day_diff
+
" days ago"
||
day_diff
<
31
&&
Math
.
ceil
(
day_diff
/
7
)
+
" weeks ago"
;
}

Takes an ISO time and returns a string representing how long ago the date represents.

Takes an ISO time and returns a string representing how long ago the date represents .


function LoggerFactory(options) {
      options = options || {
        prefix: true
      };

      // If `console.log` is not accessible, `log` is a noop.
      if (
        typeof console !== 'object' ||
        typeof console.log !== 'function' ||
        typeof console.log.bind !== 'function'
      ) {
        return function noop() {};
      }

      return function log() {
        var args = Array.prototype.slice.call(arguments);

        // All logs are disabled when `io.sails.environment = 'production'`.
        if (io.sails.environment === 'production') return;

        // Add prefix to log messages (unless disabled)
        var PREFIX = '';
        if (options.prefix) {
          args.unshift(PREFIX);
        }

        // Call wrapped logger
        console.log
          .bind(console)
          .apply(this, args);
      };
    }

A little logger for this library to use internally.
Basically just a wrapper around `console.log` with
support for feature-detection.

@api private
@factory

A little logger for this library to use internally . Basically just a wrapper around console . log with support for feature - detection .


function runRequestQueue (socket) {
      var queue = socket.requestQueue;

      if (!queue) return;
      for (var i in queue) {

        // Double-check that `queue[i]` will not
        // inadvertently discover extra properties attached to the Object
        // and/or Array prototype by other libraries/frameworks/tools.
        // (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5)
        var isSafeToDereference = ({}).hasOwnProperty.call(queue, i);
        if (isSafeToDereference) {
          // Get the arguments that were originally made to the "request" method
          var requestArgs = queue[i];
          // Call the request method again in the context of the socket, with the original args
          socket.request.apply(socket, requestArgs);
        }
      }

      // Now empty the queue to remove it as a source of additional complexity.
      socket.requestQueue = null;
    }

What is the `requestQueue`?

The request queue is used to simplify app-level connection logic--
i.e. so you don't have to wait for the socket to be connected
to start trying to  synchronize data.

@api private
@param  {SailsSocket}  socket


function jsonp(opts, cb) {
      opts = opts || {};

      if (typeof window === 'undefined') {
        // FUTURE: refactor node usage to live in here
        return cb();
      }

      var scriptEl = document.createElement('script');
      window._sailsIoJSConnect = function(response) {
        // In rare circumstances our script may have been vaporised.
        // Remove it, but only if it still exists
        // https://github.com/balderdashy/sails.io.js/issues/92
        if (scriptEl && scriptEl.parentNode) {
            scriptEl.parentNode.removeChild(scriptEl);
        }

        cb(response);
      };
      scriptEl.src = opts.url;
      document.getElementsByTagName('head')[0].appendChild(scriptEl);

    }

Send a JSONP request.

@param  {Object}   opts [optional]
@param  {Function} cb
@return {XMLHttpRequest}


function validateParameterValue (parameter, type, format, value) {
  if (type === 'integer') {
    const parsedValue = Number.parseInt(value)
    if (_.isNaN(parsedValue)) {
      throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as integer`)
    }
    return parsedValue
  } else if (type === 'number') {
    const parsedValue = Number.parseFloat(value)
    if (_.isNaN(parsedValue)) {
      throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as number`)
    }
    return Number.isInteger(parsedValue) ? Number.parseInt(value) : parsedValue
  } else if (type === 'string' && format) {
    if (format === 'date-time' && !moment(value, moment.ISO_8601).isValid()) {
      throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as date-time string`)
    } else if (format === 'date' && !moment(value, 'YYYY-MM-DD').isValid()) {
      throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as date string`)
    }
    return value
  }

  return value
}

function validateParameterValue ( parameter , type , format , value ) { if ( type === 'integer' ) { const parsedValue = Number . parseInt ( value ) if ( _ . isNaN ( parsedValue ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } return parsedValue } else if ( type === 'number' ) { const parsedValue = Number . parseFloat ( value ) if ( _ . isNaN ( parsedValue ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } return Number . isInteger ( parsedValue ) ? Number . parseInt ( value ) : parsedValue } else if ( type === 'string' && format ) { if ( format === 'date-time' && ! moment ( value , moment . ISO_8601 ) . isValid ( ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } else if ( format === 'date' && ! moment ( value , 'YYYY-MM-DD' ) . isValid ( ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } return value } return value }


function parameterDeclarationToYargs (yargs, parameter, declaration) {
  const optionName = _.kebabCase(parameter)

  let option = {}
  if (declaration.description) {
    option.describe = declaration.description
  }
  if (declaration.type) {
    if (declaration.type === 'integer') {
      option.type = 'number'
    } else {
      option.type = declaration.type
    }
  }
  if (declaration.enum) {
    option.choices = declaration.enum
  }
  if (declaration.default) {
    option.default = declaration.default
  }
  if (declaration.required) {
    option.demandOption = declaration.required
  }
  if (declaration.conflicts) {
    option.conflicts = declaration.conflicts
  }
  yargs.option(optionName, option)

  yargs.coerce(optionName, (value) => {
    if (declaration.type === 'array') {
      return _.map(value, (value) => {
        return validateParameterValue(`${optionName}[]`, declaration.item, declaration.format, value)
      })
    }

    return validateParameterValue(optionName, declaration.type, declaration.format, value)
  })
}

function parameterDeclarationToYargs ( yargs , parameter , declaration ) { const optionName = _ . kebabCase ( parameter ) let option = { } if ( declaration . description ) { option . describe = declaration . description } if ( declaration . type ) { if ( declaration . type === 'integer' ) { option . type = 'number' } else { option . type = declaration . type } } if ( declaration . enum ) { option . choices = declaration . enum } if ( declaration . default ) { option . default = declaration . default } if ( declaration . required ) { option . demandOption = declaration . required } if ( declaration . conflicts ) { option . conflicts = declaration . conflicts } yargs . option ( optionName , option ) yargs . coerce ( optionName , ( value ) => { if ( declaration . type === 'array' ) { return _ . map ( value , ( value ) => { return validateParameterValue ( ` ${ optionName } ` , declaration . item , declaration . format , value ) } ) } return validateParameterValue ( optionName , declaration . type , declaration . format , value ) } ) }


function configDeclarationToYargs (yargs, configDeclaration) {
  _.forOwn(configDeclaration, (parameter, parameterName) => {
    parameterDeclarationToYargs(yargs, parameterName, parameter)
  })
  return yargs
}

function configDeclarationToYargs ( yargs , configDeclaration ) { _ . forOwn ( configDeclaration , ( parameter , parameterName ) => { parameterDeclarationToYargs ( yargs , parameterName , parameter ) } ) return yargs }

Converts configuration declaration to yargs options

@param {ConfigDeclaration} configDeclaration


function NGramParser(theNgramList, theByteMap) {
  var N_GRAM_MASK = 0xFFFFFF;

  this.byteIndex = 0;
  this.ngram = 0;

  this.ngramList = theNgramList;
  this.byteMap = theByteMap;

  this.ngramCount = 0;
  this.hitCount = 0;

  this.spaceChar;

  /*
   * Binary search for value in table, which must have exactly 64 entries.
   */
  this.search = function(table, value) {
    var index = 0;

    if (table[index + 32] <= value) index += 32;
    if (table[index + 16] <= value) index += 16;
    if (table[index + 8]  <= value) index += 8;
    if (table[index + 4]  <= value) index += 4;
    if (table[index + 2]  <= value) index += 2;
    if (table[index + 1]  <= value) index += 1;
    if (table[index]      > value)  index -= 1;

    if (index < 0 || table[index] != value)
      return -1;

    return index;
  };

  this.lookup = function(thisNgram) {
    this.ngramCount += 1;
    if (this.search(this.ngramList, thisNgram) >= 0) {
      this.hitCount += 1;
    }
  };

  this.addByte = function(b) {
    this.ngram = ((this.ngram << 8) + (b & 0xFF)) & N_GRAM_MASK;
    this.lookup(this.ngram);
  }

  this.nextByte = function(det) {
    if (this.byteIndex >= det.fInputLen)
      return -1;

    return det.fInputBytes[this.byteIndex++] & 0xFF;
  }

  this.parse = function(det, spaceCh) {
    var b, ignoreSpace = false;
    this.spaceChar = spaceCh;

    while ((b = this.nextByte(det)) >= 0) {
      var mb = this.byteMap[b];

      // TODO: 0x20 might not be a space in all character sets...
      if (mb != 0) {
        if (!(mb == this.spaceChar && ignoreSpace)) {
          this.addByte(mb);
        }

        ignoreSpace = (mb == this.spaceChar);
      }
    }

    // TODO: Is this OK? The buffer could have ended in the middle of a word...
    this.addByte(this.spaceChar);

    var rawPercent = this.hitCount / this.ngramCount;

    // TODO - This is a bit of a hack to take care of a case
    // were we were getting a confidence of 135...
    if (rawPercent > 0.33)
      return 98;

    return Math.floor(rawPercent * 300.0);
  };
}

This class recognizes single-byte encodings. Because the encoding scheme is so
simple, language statistics are used to do the matching.

This class recognizes single - byte encodings . Because the encoding scheme is so simple language statistics are used to do the matching .


function collectScenariosFromElement(parentElement) {
      var scenarios = [];
      var templates = [];

      var elements = parentElement.children();
      var i        = 0;

      angular.forEach(elements, function(el) {
        var elem = angular.element(el);

        //if no source or no html, capture element itself
        if (!elem.attr('src') || !elem.attr('src').match(/.html$/)) {
          templates[i] = elem;
          scenarios[i] = { media: elem.attr('media'), templ: i };
        } else {
          scenarios[i] = { media: elem.attr('media'), src: elem.attr('src') };
        }

        i++;
      });

      return {
        scenarios: scenarios,
        templates: templates
      };
    }

Collects a scenario object and templates from element


function changed (done) {
  const files = [].slice.call(arguments);
  if (typeof files[files.length - 1] === 'function') done = files.pop();
  done = typeof done === 'function' ? done : () => {};
  debug('Notifying %d servers - Files: ', servers.length, files);
  servers.forEach(srv => {
    const params = { params: { files: files } };
    srv && srv.changed(params);
  });
  done();
}

function
changed
(
done
)
{
const
files
=
[
]
.
slice
.
call
(
arguments
)
;
if
(
typeof
files
[
files
.
length
1
]
===
'function'
)
done
=
files
.
pop
(
)
;
done
=
typeof
done
===
'function'
done
:
(
)
=>
{
}
;
debug
(
'Notifying %d servers - Files: '
,
servers
.
length
,
files
)
;
servers
.
forEach
(
srv
=>
{
const
params
=
{
params
:
{
files
:
files
}
}
;
srv
&&
srv
.
changed
(
params
)
;
}
)
;
done
(
)
;
}

Changed helper, helps with notifying the server of a file change

Changed helper helps with notifying the server of a file change


function(children, element) {
        this.portalNode = document.createElement('div');
        (element || document.body).appendChild(this.portalNode);
        ReactDOM.render(children, this.portalNode);
    }

function ( children , element ) { this . portalNode = document . createElement ( 'div' ) ; ( element || document . body ) . appendChild ( this . portalNode ) ; ReactDOM . render ( children , this . portalNode ) ; }

Creates a new detatched DOM node to render child components within.
@param {Object} children  The items to be displayed in the portal.
@param {Object} [element] Optional HTML Element to append PageMessage object to.

Creates a new detatched DOM node to render child components within .


function() {
        /* eslint-disable no-alert */
        var close = typeof this.portalConfirmOnCloseMessage === 'string' ? confirm(this.portalConfirmOnCloseMessage) : true;
        /* eslint-enable no-alert */

        if (this.portalNode && this.portalNode.parentNode && close) {
            ReactDOM.unmountComponentAtNode(this.portalNode);
            this.portalNode.parentNode.removeChild(this.portalNode);
            this.portalNode = null;
        }
    }

function
(
)
{
/* eslint-disable no-alert */
var
close
=
typeof
this
.
portalConfirmOnCloseMessage
===
'string'
confirm
(
this
.
portalConfirmOnCloseMessage
)
:
true
;
/* eslint-enable no-alert */
if
(
this
.
portalNode
&&
this
.
portalNode
.
parentNode
&&
close
)
{
ReactDOM
.
unmountComponentAtNode
(
this
.
portalNode
)
;
this
.
portalNode
.
parentNode
.
removeChild
(
this
.
portalNode
)
;
this
.
portalNode
=
;
}
}

Unmounts the components rendered in the portal and removes the associated DOM node.

Unmounts the components rendered in the portal and removes the associated DOM node .


function(data) {
        if (this.filterValue) {
            data = this.quickFilterData(data, this.filterValue);
        }

        if (this.advancedFilters) {
            data = this.advancedFilterData(data, this.advancedFilters);
        }

        this.dataCount = data.length;

        return data;
    }

function ( data ) { if ( this . filterValue ) { data = this . quickFilterData ( data , this . filterValue ) ; } if ( this . advancedFilters ) { data = this . advancedFilterData ( data , this . advancedFilters ) ; } this . dataCount = data . length ; return data ; }

Triggers quick filtering and advanced filtering of the data if either of those properties have been set.
@param {Array} data - Cloned Table.data.
@returns {Array} - The subset of fully filtered data.

Triggers quick filtering and advanced filtering of the data if either of those properties have been set .


function(id, definition, dataFormatter) {
        this.collection[id] = new Table(id, definition, dataFormatter);
        return this.collection[id];
    }

function ( id , definition , dataFormatter ) { this . collection [ id ] = new Table ( id , definition , dataFormatter ) ; return this . collection [ id ] ; }

Creates an instance of Table.
@param  {String} id - The unique identifier used to access the Table instance.
@param  {String} definition - A defined Table.
@param  {Function} dataFormatter - A function that will allow for post processing of data from the server.
@return {object}                   The newly created Table instance


function(payload) {
        var action = payload.action;

        if (!this.shouldHandleAction(action.component)) {
            return;
        }

        switch (action.actionType) {
            case ActionTypes.REQUEST_DATA:
                this.handleRequestDataAction(action);
                break;
            case ActionTypes.TABLE_SORT:
                this.collection[action.id].sortData(action.data.colIndex, action.data.direction);
                this.emitChange(action.id);
                break;
            case ActionTypes.FILTER:
                this.collection[action.id].setFilterValue(action.data.value);
                this.emitChange(action.id);
                break;
            case ActionTypes.ADVANCED_FILTER:
                this.collection[action.id].setAdvancedFilters(action.data.advancedFilters);
                this.emitChange(action.id);
                break;
            case ActionTypes.PAGINATE:
                this.collection[action.id].paginate(action.data.direction);
                this.emitChange(action.id);
                break;
            case ActionTypes.TOGGLE_BULK_SELECT:
                this.collection[action.id].updateBulkSelection(action.data.deselect);
                this.emitChange(action.id);
                break;
            case ActionTypes.TOGGLE_ROW_SELECT:
                this.collection[action.id].updateRowSelection(action.data.rowIndex);
                this.emitChange(action.id);
                break;
            case ActionTypes.DESTROY_INSTANCE:
                this.destroyInstance(action.id);
                break;
        }
    }

function ( payload ) { var action = payload . action ; if ( ! this . shouldHandleAction ( action . component ) ) { return ; } switch ( action . actionType ) { case ActionTypes . REQUEST_DATA : this . handleRequestDataAction ( action ) ; break ; case ActionTypes . TABLE_SORT : this . collection [ action . id ] . sortData ( action . data . colIndex , action . data . direction ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . FILTER : this . collection [ action . id ] . setFilterValue ( action . data . value ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . ADVANCED_FILTER : this . collection [ action . id ] . setAdvancedFilters ( action . data . advancedFilters ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . PAGINATE : this . collection [ action . id ] . paginate ( action . data . direction ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . TOGGLE_BULK_SELECT : this . collection [ action . id ] . updateBulkSelection ( action . data . deselect ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . TOGGLE_ROW_SELECT : this . collection [ action . id ] . updateRowSelection ( action . data . rowIndex ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . DESTROY_INSTANCE : this . destroyInstance ( action . id ) ; break ; } }

Handles all events sent from the dispatcher. Filters out to only those sent via the Table
@param {Object} payload - Contains action details.

Handles all events sent from the dispatcher . Filters out to only those sent via the Table


function(nextProps) {
            if (this.props.filters !== nextProps.filters && JSON.stringify(this.props.filters) !== JSON.stringify(nextProps.filters)) {
                setTimeout(function() {
                    this.requestData();
                }.bind(this), 0);
            }
        }

function ( nextProps ) { if ( this . props . filters !== nextProps . filters && JSON . stringify ( this . props . filters ) !== JSON . stringify ( nextProps . filters ) ) { setTimeout ( function ( ) { this . requestData ( ) ; } . bind ( this ) , 0 ) ; } }

Requests data for a component when the filter property changes. When comparing filters we do a direct
comparison in addition to a JSON stringify comparison. This fixes issues where the filters object is a new literal
object every time, but isn't actually changing. Using a JSON stringify has the downside of causing requestData to
be called if the objects are in a different order, but that is pretty unlikely to happen. The setTimeout insures that
the currently dispatched action has completed the dispatching process before the request data
action is kicked off.
@param {object} nextProps - The set of properties that will be on the component after it updates.

Requests data for a component when the filter property changes . When comparing filters we do a direct comparison in addition to a JSON stringify comparison . This fixes issues where the filters object is a new literal object every time but isn t actually changing . Using a JSON stringify has the downside of causing requestData to be called if the objects are in a different order but that is pretty unlikely to happen . The setTimeout insures that the currently dispatched action has completed the dispatching process before the request data action is kicked off .


function(store) {
        return {
            /**
             * Adds the listeners required when requesting data from the server.
             */
            componentDidMount: function() {
                store.on('change:' + this.props.componentId, this.onDataReceived);
                store.on('fail:' + this.props.componentId, this.onError);
            },

            /**
             * Removes the listeners required when requesting data from the server.
             */
            componentWillUnmount: function() {
                store.removeListener('change:' + this.props.componentId, this.onDataReceived);
                store.removeListener('fail:' + this.props.componentId, this.onError);
            }
        };
    }

Used to add and remove the listeners required when requesting data from the server.
@param {object} store - The object returned from the store file associated with the component.
@returns {{componentDidMount: componentDidMount, componentWillUnmount: componentWillUnmount}}  - React lifecycle functions.

Used to add and remove the listeners required when requesting data from the server .


function() {
                store.on('change:' + this.props.componentId, this.onDataReceived);
                store.on('fail:' + this.props.componentId, this.onError);
            }

function ( ) { store . on ( 'change:' + this . props . componentId , this . onDataReceived ) ; store . on ( 'fail:' + this . props . componentId , this . onError ) ; }

Adds the listeners required when requesting data from the server.

Adds the listeners required when requesting data from the server .


function() {
                store.removeListener('change:' + this.props.componentId, this.onDataReceived);
                store.removeListener('fail:' + this.props.componentId, this.onError);
            }

function ( ) { store . removeListener ( 'change:' + this . props . componentId , this . onDataReceived ) ; store . removeListener ( 'fail:' + this . props . componentId , this . onError ) ; }

Removes the listeners required when requesting data from the server.

Removes the listeners required when requesting data from the server .


function(id, definition, dataFormatter, filters) {
        AppDispatcher.dispatchAction({
            actionType: this.actionTypes.REQUEST_DATA,
            component: 'Table',
            id: id,
            data: {
                definition: definition,
                dataFormatter: dataFormatter,
                filters: filters
            }
        });
    }

function ( id , definition , dataFormatter , filters ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . REQUEST_DATA , component : 'Table' , id : id , data : { definition : definition , dataFormatter : dataFormatter , filters : filters } } ) ; }

Action for populating table data. Used both for initial and subsequent loads.
@param {String} id - Unique identifier for the Table component.
@param {Object} definition - A configuration object for the Table.
@param {Function} dataFormatter - A function that will allow for post processing of data from the server.
@param {Object} filters - The query string params to be sent with any data requests to the server.

Action for populating table data . Used both for initial and subsequent loads .


function(id, value) {
        AppDispatcher.dispatchAction({
            actionType: this.actionTypes.FILTER,
            component: 'Table',
            id: id,
            data: {
                value: value
            }
        });
    }

function ( id , value ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . FILTER , component : 'Table' , id : id , data : { value : value } } ) ; }

Filters out table data that does not match the filter value for table cols that have quickFilter set to true.
@param {String} id - The unique identifier of the Table instance to request filtering data for.
@param {String|Number} value - The string or number used to filter out table rows that are not a match.

Filters out table data that does not match the filter value for table cols that have quickFilter set to true .


function(id, direction) {
        AppDispatcher.dispatchAction({
            actionType: this.actionTypes.PAGINATE,
            component: 'Table',
            id: id,
            data: {
                direction: direction
            }
        });
    }

function ( id , direction ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . PAGINATE , component : 'Table' , id : id , data : { direction : direction } } ) ; }

Moves the cursor forwards or backwards through paginated data.
@param {String} id - The unique identifier of the Table instance to paginate.
@param {String} direction - the direction paginate (right or left).

Moves the cursor forwards or backwards through paginated data .


function(id, deselect) {
        AppDispatcher.dispatchAction({
            actionType: this.actionTypes.TOGGLE_BULK_SELECT,
            component: 'Table',
            id: id,
            data: {
                deselect: deselect
            }
        });
    }

function ( id , deselect ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . TOGGLE_BULK_SELECT , component : 'Table' , id : id , data : { deselect : deselect } } ) ; }

Bulk toggle selection for table rows.
@param {String} id - The unique identifier of the Table instance to toggle bulk selection for.
@param {Boolean} deselect - There are selected items in the filtered data set, so we need to deselect them.


function(id, rowIndex) {
        AppDispatcher.dispatchAction({
            actionType: this.actionTypes.TOGGLE_ROW_SELECT,
            component: 'Table',
            id: id,
            data: {
                rowIndex: rowIndex
            }
        });
    }

function ( id , rowIndex ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . TOGGLE_ROW_SELECT , component : 'Table' , id : id , data : { rowIndex : rowIndex } } ) ; }

Selects or deselects a table row.
@param {String} id - The unique identifier of the Table instance to select a row within.
@param {Number} rowIndex - The index of the table row containing the select box that was toggled.


function extractValue(attr, node) {
                    if (attr === 'translate') {
                        return node.html() || getAttr(attr) || '';
                    }
                    return getAttr(attr) || node.html() || '';
                }

function extractValue ( attr , node ) { if ( attr === 'translate' ) { return node . html ( ) || getAttr ( attr ) || '' ; } return getAttr ( attr ) || node . html ( ) || '' ; }

Extract the value, default translate filter behavior
else if it is an attribute we need to get its value first
@param  {String} attr Key name
@param  {Node} node
@return {String}

Extract the value default translate filter behavior else if it is an attribute we need to get its value first