function getDataContext(ctxOrCanvas) {
  if (ctxOrCanvas instanceof HTMLCanvasElement) {
    return getDataContext(ctxOrCanvas.getContext('2d'));
  }

  var ctx = ctxOrCanvas;
  if (stubGetDataContext) {
    return stubGetDataContext(ctx);
  } else {
    for (var i = 0; i < getDataContext.cache.length; i++) {
      var pair = getDataContext.cache[i];
      if (pair[0] == ctx) return pair[1];
    }
    var dtx = new DataContext(ctx);
    getDataContext.cache.push([ctx, dtx]);
    return dtx;
  }
}

function getDataContext ( ctxOrCanvas ) { if ( ctxOrCanvas instanceof HTMLCanvasElement ) { return getDataContext ( ctxOrCanvas . getContext ( '2d' ) ) ; } var ctx = ctxOrCanvas ; if ( stubGetDataContext ) { return stubGetDataContext ( ctx ) ; } else { for ( var i = 0 ; i < getDataContext . cache . length ; i ++ ) { var pair = getDataContext . cache [ i ] ; if ( pair [ 0 ] == ctx ) return pair [ 1 ] ; } var dtx = new DataContext ( ctx ) ; getDataContext . cache . push ( [ ctx , dtx ] ) ; return dtx ; } }

Get a DataContext for the built-in CanvasRenderingContext2D.

This caches DataContexts and facilitates stubbing in tests.

As a convenience, you may pass in a Canvas element instead of a
CanvasRenderingContext2D. data-canvas will call getContext('2d') for you.

Get a DataContext for the built - in CanvasRenderingContext2D .


function findRecorder(div, selector) {
  if (!div) {
    if (!RecordingContext.recorders) {
      throw 'You must call RecordingContext.recordAll() before using other RecordingContext static methods';
    } else if (RecordingContext.recorders.length == 0) {
      throw 'Called a RecordingContext method, but no canvases are being recorded.';
    } else if (RecordingContext.recorders.length > 1) {
      throw 'Called a RecordingContext method while multiple canvases were being recorded. Specify one using a div and selector.';
    } else {
      return RecordingContext.recorders[0][1];
    }
  } else {
    return RecordingContext.recorderForSelector(div, selector);
  }
}

Resolves arguments for RecordingContext helpers. You can either specify a div & selector to find the canvas, or omit this if there's only one canvas being recorded.

Resolves arguments for RecordingContext helpers . You can either specify a div & selector to find the canvas or omit this if there s only one canvas being recorded .


function ClickTrackingContext(ctx, px, py) {
  forward(this, ctx);

  var stack = [];
  this.hits = [];
  this.hit = null;

  var that = this;
  function recordHit() {
    that.hits.unshift(Array.prototype.slice.call(stack));
    that.hit = that.hits[0];
  }

  this.pushObject = function(o) {
    stack.unshift(o);
  };

  this.popObject = function() {
    stack.shift();
  };

  this.reset = function() {
    this.hits = [];
    this.hit = null;
  };

  // These are (most of) the canvas methods which draw something.
  // TODO: would it make sense to purge existing hits covered by this?
  this.clearRect = function(x, y, w, h) { };

  this.fillRect = function(x, y, w, h) {
    if (px >= x && px <= x + w && py >= y && py <= y + h) recordHit();
  };

  this.strokeRect = function(x, y, w, h) {
    // ...
  };

  this.fill = function(fillRule) {
    // TODO: implement fillRule
    if (ctx.isPointInPath(px, py)) recordHit();
  };

  this.stroke = function() {
    if (ctx.isPointInStroke(px, py)) recordHit();
  };

  this.fillText = function(text, x, y, maxWidth) {
    // ...
  };

  this.strokeText = function(text, x, y, maxWidth) {
    // ...
  };
}

A context which determines the data at a particular location.

When drawing methods are called on this class, nothing is rendered. Instead,
each shape is checked to see if it includes the point of interest. If it
does, the current data stack is saved as a "hit".

The `hits` property records all such hits.
The `hit` property records only the last (top) hit.

A context which determines the data at a particular location .


function stringEscape (str) {

  let stringArray = str.toString().split('');

  for (let j = 0; j < stringArray.length; j++) {
    for (let i = 0; i < escapeArray.length; i++) {

      if (stringArray[j] === escapeArray[i]) {
        stringArray[j] = '\\' + escapeArray[i];
      }

    }
  }

  return stringArray.join('');
}

function stringEscape ( str ) { let stringArray = str . toString ( ) . split ( '' ) ; for ( let j = 0 ; j < stringArray . length ; j ++ ) { for ( let i = 0 ; i < escapeArray . length ; i ++ ) { if ( stringArray [ j ] === escapeArray [ i ] ) { stringArray [ j ] = '\\' + escapeArray [ i ] ; } } } return stringArray . join ( '' ) ; }

The string that needs to be matched is escaped


function get(czConfig) {
    const scopes = [];

    if (typeof czConfig.scopes === 'undefined') {
        return defaults;
    }

    for (const scope of czConfig.scopes) {
        scopes.push(scope.name);
    }

    if (typeof czConfig.scopeOverrides === 'undefined') {
        return scopes;
    }

    for (const type of Object.keys(czConfig.scopeOverrides)) {
        for (const scope of czConfig.scopeOverrides[type]) {
            scopes.push(scope.name);
        }
    }

    return scopes.filter(function (value, index, scope) {
        return scope.indexOf(value) === index;
    });
}

function get ( czConfig ) { const scopes = [ ] ; if ( typeof czConfig . scopes === 'undefined' ) { return defaults ; } for ( const scope of czConfig . scopes ) { scopes . push ( scope . name ) ; } if ( typeof czConfig . scopeOverrides === 'undefined' ) { return scopes ; } for ( const type of Object . keys ( czConfig . scopeOverrides ) ) { for ( const scope of czConfig . scopeOverrides [ type ] ) { scopes . push ( scope . name ) ; } } return scopes . filter ( function ( value , index , scope ) { return scope . indexOf ( value ) === index ; } ) ; }

Gets the `value` for `scope-enum` rule of commitlint config.

@param {Object} czConfig A cz-customizable config.

@returns {Object} The `value`.

Gets the value for scope - enum rule of commitlint config .


function get(pathOrCzConfig, defaultConfig) {
    const config = Object.assign(cloneDeep(defaults), cloneDeep(defaultConfig) || {});

    let czConfig = pathOrCzConfig || {};

    if (typeof pathOrCzConfig === 'string') {
        czConfig = CzConfig.get(pathOrCzConfig);
    }

    // Converts the `scopes` and `scopeOverrides` into `scope-enum` rule.
    const hasScopeEnum = Object.prototype.hasOwnProperty.call(config.rules, 'scope-enum');

    if (
        hasScopeEnum &&
        (typeof czConfig.scopes !== 'undefined' || typeof czConfig.scopeOverrides !== 'undefined')
    ) {
        config.rules['scope-enum'][2] = Scopes.get(czConfig);
    }

    // Removes empty `scope-enum` rule.
    if (hasScopeEnum && !config.rules['scope-enum'][2].length) {
        delete config.rules['scope-enum'];
    }

    // Converts the `types` into `type-enum` rule.
    const hasTypeEnum = Object.prototype.hasOwnProperty.call(config.rules, 'type-enum');

    if (hasTypeEnum && typeof czConfig.types !== 'undefined') {
        config.rules['type-enum'][2] = Types.get(czConfig);
    }

    // Removes empty `type-enum` rule.
    if (hasTypeEnum && !config.rules['type-enum'][2].length) {
        delete config.rules['type-enum'];
    }

    return config;
}

Gets the commitlint config converted from a cz-customizable config.

@param {string|Object} pathOrCzConfig The path to a cz-customizable config file, or a cz-customizable config object.
@param {Object} defaultConfig The default commitlint config.

@returns {Object} The converted commitlint config.

Gets the commitlint config converted from a cz - customizable config .


function get(path) {
    let czConfig;

    try {
        fs.accessSync(path, fs.R_OK);

        czConfig = require(path);
    } catch (err) {
        czConfig = {};
    }

    return czConfig;
}

function get ( path ) { let czConfig ; try { fs . accessSync ( path , fs . R_OK ) ; czConfig = require ( path ) ; } catch ( err ) { czConfig = { } ; } return czConfig ; }

Reads and gets the cz-customizable config from a path.

@param {string} path The path to a cz-customizable config file.

@returns {Object} The cz-customizable config.

Reads and gets the cz - customizable config from a path .


function get(czConfig) {
    const types = [];

    if (typeof czConfig.types === 'undefined') {
        return defaults;
    }

    for (const type of czConfig.types) {
        types.push(type.value);
    }

    return types;
}

function get ( czConfig ) { const types = [ ] ; if ( typeof czConfig . types === 'undefined' ) { return defaults ; } for ( const type of czConfig . types ) { types . push ( type . value ) ; } return types ; }

Gets the `value` for `type-enum` rule of commitlint config.

@param {Object} czConfig A cz-customizable config.

@returns {Object} The `value`.

Gets the value for type - enum rule of commitlint config .


function use(code, lightColor) {
        return util.format(base, (lightColor === true) ? code + colorLightValueChange : code);
    }

function use ( code , lightColor ) { return util . format ( base , ( lightColor === true ) ? code + colorLightValueChange : code ) ; }

Create effect from code. For colors set lightColor true to bright them up
@param code
@param lightColor
@returns {*}

Create effect from code . For colors set lightColor true to bright them up


function text(message, effect, lightColor) {
        return [
            use(effect[0], lightColor),
            String(message),
            use(effect[1], lightColor)
        ].join('');
    }

function text ( message , effect , lightColor ) { return [ use ( effect [ 0 ] , lightColor ) , String ( message ) , use ( effect [ 1 ] , lightColor ) ] . join ( '' ) ; }

Apply effect on both side of the string
@param message
@param effect
@param lightColor
@returns {string}


function clearLine() {
        if (process.stdout.clearLine) {
            process.stdout.clearLine();
            process.stdout.cursorTo(0);
        } else {
            var str = '\r',
                i = 0;
            for (i = 0; i < lastLineLength; i++) {
                str += ' ';
            }
            process.stdout.write(str);
        }
        lastLineLength = 0;

        return self;
    }

function
clearLine
(
)
{
if
(
process
.
stdout
.
clearLine
)
{
process
.
stdout
.
clearLine
(
)
;
process
.
stdout
.
cursorTo
(
0
)
;
}
else
{
var
str
=
'\r'
,
i
=
0
;
for
(
i
=
0
;
i
<
lastLineLength
;
i
++
)
{
str
+=
' '
;
}
process
.
stdout
.
write
(
str
)
;
}
lastLineLength
=
0
;
return
self
;
}

Clear line until last new line white character


function () {
        L.DomUtil.empty(this._container);
        var legends = this.options.legends;

        if (!legends) return;

        legends.forEach(function(legend) {
            if (!legend.elements) return;
            var elements = legend.elements;

            var className = 'legend-block';

            if (this.options.detectStretched) {
                if (elements.length === 3  && elements[0].label !== '' && elements[1].label === '' && elements[2].label !== ''){
                    legend.type = 'stretched';
                }
            }

            if (legend.type === 'stretched') {
                className += ' legend-stretched';
            }

            var block = L.DomUtil.create('div', className, this._container);

            if (this.options.collapseSimple && elements.length == 1 && !elements[0].label){
                this._addElement(elements[0].imageData, legend.name, block);
                return;
            }

            if (legend.name) {
                var header = L.DomUtil.create('h4', null, block);
                L.DomUtil.create('div', 'caret', header);
                L.DomUtil.create('span', null, header).innerHTML = legend.name;

                L.DomEvent.on(header, 'click', function() {
                    if (L.DomUtil.hasClass(header, 'closed')) {
                        L.DomUtil.removeClass(header, 'closed');
                    }
                    else {
                        L.DomUtil.addClass(header, 'closed');
                    }
                }, this);
            }
            var elementContainer = L.DomUtil.create('div', 'legend-elements', block);

            elements.forEach(function (element) {
                this._addElement(element.imageData, element.label, elementContainer);
            }, this);
        }, this);
    }

function
(
)
{
L
.
DomUtil
.
empty
(
this
.
_container
)
;
var
legends
=
this
.
options
.
legends
;
if
(
!
legends
)
return
;
legends
.
forEach
(
function
(
legend
)
{
if
(
!
legend
.
elements
)
return
;
var
elements
=
legend
.
elements
;
var
className
=
'legend-block'
;
if
(
this
.
options
.
detectStretched
)
{
if
(
elements
.
length
===
3
&&
elements
[
0
]
.
label
!==
''
&&
elements
[
1
]
.
label
===
''
&&
elements
[
2
]
.
label
!==
''
)
{
legend
.
type
=
'stretched'
;
}
}
if
(
legend
.
type
===
'stretched'
)
{
className
+=
' legend-stretched'
;
}
var
block
=
L
.
DomUtil
.
create
(
'div'
,
className
,
this
.
_container
)
;
if
(
this
.
options
.
collapseSimple
&&
elements
.
length
==
1
&&
!
elements
[
0
]
.
label
)
{
this
.
_addElement
(
elements
[
0
]
.
imageData
,
legend
.
name
,
block
)
;
return
;
}
if
(
legend
.
name
)
{
var
header
=
L
.
DomUtil
.
create
(
'h4'
,
,
block
)
;
L
.
DomUtil
.
create
(
'div'
,
'caret'
,
header
)
;
L
.
DomUtil
.
create
(
'span'
,
,
header
)
.
innerHTML
=
legend
.
name
;
L
.
DomEvent
.
on
(
header
,
'click'
,
function
(
)
{
if
(
L
.
DomUtil
.
hasClass
(
header
,
'closed'
)
)
{
L
.
DomUtil
.
removeClass
(
header
,
'closed'
)
;
}
else
{
L
.
DomUtil
.
addClass
(
header
,
'closed'
)
;
}
}
,
this
)
;
}
var
elementContainer
=
L
.
DomUtil
.
create
(
'div'
,
'legend-elements'
,
block
)
;
elements
.
forEach
(
function
(
element
)
{
this
.
_addElement
(
element
.
imageData
,
element
.
label
,
elementContainer
)
;
}
,
this
)
;
}
,
this
)
;
}


function updateLocation(method) {
  return function () {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return {
      type: _constants.CALL_HISTORY_METHOD,
      payload: { method: method, args: args }
    };
  };
}

function updateLocation ( method ) { return function ( ) { for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } return { type : _constants . CALL_HISTORY_METHOD , payload : { method : method , args : args } } ; } ; }

This action type will be dispatched by the history actions below.
If you're writing a middleware to watch for navigation events, be sure to
look for actions of this type.

This action type will be dispatched by the history actions below . If you re writing a middleware to watch for navigation events be sure to look for actions of this type .


function getHeader (data) {
  var header = {}
  header.umid = data.slice(0, 3)
  header.mt_version = data.slice(3, 5)
  header.rics = data.slice(5, 9)
  header.key_id = data.slice(9, 14)
  return header
}

function getHeader ( data ) { var header = { } header . umid = data . slice ( 0 , 3 ) header . mt_version = data . slice ( 3 , 5 ) header . rics = data . slice ( 5 , 9 ) header . key_id = data . slice ( 9 , 14 ) return header }

Get raw data and uncompress the TicketData


function timeOutput(difference, timeValue, pluralTimeName) {
    let result = '';
    if (Math.round(difference / timeValue) === 1) {
        result = `1 ${pluralTimeName.substring(0, pluralTimeName.length - 1)} ago`;
    } else {
        result = `${Math.round(difference / timeValue)} ${pluralTimeName} ago`;
    }
    return result;
}

function timeOutput ( difference , timeValue , pluralTimeName ) { let result = '' ; if ( Math . round ( difference / timeValue ) === 1 ) { result = ` ${ pluralTimeName . substring ( 0 , pluralTimeName . length - 1 ) } ` ; } else { result = ` ${ Math . round ( difference / timeValue ) } ${ pluralTimeName } ` ; } return result ; }

Returns string value of the output
@param {Number} difference - difference from current in milliseconds
@param {Number} timeValue - unit being calculated ex. seconds: 1000
@param {string} pluralTimeName - plural name of time value ex. 'seconds'
@return {string} string of how long ago ex. '1 second ago' or '5 minutes ago'


function RestClient(baseUrl) {

    if (typeof baseUrl !== 'string') {
        if (typeof document !== 'undefined') {
            baseUrl = document.getElementById('baseUrlHolder').getAttribute('data') + '/api/';
        } else {
            baseUrl = '/api/';
        }
    }
    this.organizations = new OrganizationsClient(baseUrl);
    this.projects = new ProjectsClient(baseUrl);
    this.user = new UserClient(baseUrl);
    this.users = new UsersClient(baseUrl);

    /**
     * Gets the current user
     * @return {Promise} //TODO: How to document the resolved value.
     */
    this.getStatus = () => {
        return this.user.get(['status']);
    };
}

Single rest clients that contains user, users, projects, and orgs clients
@param {string} baseUrl - the base url

Single rest clients that contains user users projects and orgs clients


function register(ports, log) {
  // Mapped to Storage API: https://developer.mozilla.org/en-US/docs/Web/API/Storage
  ports.storageGetItem.subscribe(storageGetItem);
  ports.storageSetItem.subscribe(storageSetItem);
  ports.storageRemoveItem.subscribe(storageRemoveItem);
  ports.storageClear.subscribe(storageClear);

  // Not in Storage API
  ports.storagePushToSet.subscribe(storagePushToSet);
  ports.storageRemoveFromSet.subscribe(storageRemoveFromSet);

  // StorageEvent API
  storageEventListenerPorts.push(ports);

  log = log || function() {};

  function storageGetItem(key) {
    log('storageGetItem', key);
    const response = getLocalStorageItem(key);

    log('storageGetItemResponse', key, response);
    ports.storageGetItemResponse.send([key, response]);
  }

  function storageSetItem([key, value]) {
    log('storageSetItem', key, value);
    setLocalStorageItem(key, value);
  }

  function storageRemoveItem(key) {
    log('storageRemoveItem', key);
    window.localStorage.removeItem(key);
  }

  function storageClear() {
    log('storageClear');
    window.localStorage.clear();
  }

  // A Set is a list with only unique values. (No duplication.)
  function storagePushToSet([key, value]) {
    log('storagePushToSet', key, value);

    const item = getLocalStorageItem(key);
    const list = Array.isArray(item) ? item : [];

    if (list.indexOf(value) === -1) {
      list.push(value);
    }

    setLocalStorageItem(key, list);
  }

  function storageRemoveFromSet([key, value]) {
    log('storageRemoveFromSet', key, value);

    const list = getLocalStorageItem(key);

    if (!Array.isArray(list)) {
      log('storageRemoveFromSet [aborting; not a list]', key, value, list);
      return;
    }

    // Filter based on JSON strings in to ensure equality-by-value instead of equality-by-reference
    const jsonValue = JSON.stringify(value);
    const updatedSet = list.filter(item => jsonValue !== JSON.stringify(item));

    setLocalStorageItem(key, updatedSet);
  }
}

Subscribe the given Elm app ports to ports from the Elm LocalStorage ports module.

@param  {Object}   ports  Ports object from an Elm app
@param  {Function} log    Function to log ports for the given Elm app

Subscribe the given Elm app ports to ports from the Elm LocalStorage ports module .


function run (options) {
    if (options.results) {
        return map(options);
    }

    return fetch(options).then(map.bind(null, options));
}

function run ( options ) { if ( options . results ) { return map ( options ) ; } return fetch ( options ) . then ( map . bind ( null , options ) ) ; }

Public function `run`.

Invokes WebPageTest then maps the result data, returns an ES6 promise.

@option uri        {string}  Base URI for the WebPageTest instance, defaults to
`www.webpagetest.org`.
@option key        {string}  WebPageTest API key.
@option location   {string}  WebPageTest location, defaults to `Dulles:Chrome`.
@option connection {string}  WebPageTest connection speed, defaults to `Native
Connection`.
@option tests      {string}  Path to the test definitions JSON file, defaults
to `tests.json`.
@option count      {number}  Number of times to run each test, defaults to `9`.
@option email      {string}  Email address to send notifications to.
@option dump       {string}  Dump intermediate results to file.
@option results    {string}  Read intermediate results from file, skips tests.
@option mapper     {string}  Mapper to use, defaults to `html-comparison`.
@option silent     {boolean} Disable logging, overrides `syslog` and `log`.
@option syslog     {string}  Send logs to syslog, overrides `log`.
@option log        {object}  Logging implementation, needs `log.info()`,
`log.warn()` and `log.error()`.
@option config     {string}  Load options from JSON config file.


function fetch (options) {
    var time, promise, resolve, reject;

    time = new Date();
    promise = new Promise(function (r1, r2) { resolve = r1; reject = r2; } );

    try {
        options = normalise(options);

        if (options.resultIds) {
            wpt.getResults(options, options.resultIds).then(after);
        } else {
            wpt.runTests(options).then(wpt.getResults.bind(null, options)).then(after);
        }
    } catch (error) {
        reject(error);
    }

    return promise;

    function after (results) {
        results = {
            data: results,
            options: options,
            times: {
                begin: time,
                end: new Date()
            }
        };

        if (options.dump) {
            dump(options, results);
        }

        resolve(results);
    }
}

function fetch ( options ) { var time , promise , resolve , reject ; time = new Date ( ) ; promise = new Promise ( function ( r1 , r2 ) { resolve = r1 ; reject = r2 ; } ) ; try { options = normalise ( options ) ; if ( options . resultIds ) { wpt . getResults ( options , options . resultIds ) . then ( after ) ; } else { wpt . runTests ( options ) . then ( wpt . getResults . bind ( null , options ) ) . then ( after ) ; } } catch ( error ) { reject ( error ) ; } return promise ; function after ( results ) { results = { data : results , options : options , times : { begin : time , end : new Date ( ) } } ; if ( options . dump ) { dump ( options , results ) ; } resolve ( results ) ; } }

Public function `fetch`.

Invokes WebPageTest, returns an ES6 promise.

@option uri        {string}  Base URI for the WebPageTest instance, defaults to
`www.webpagetest.org`.
@option key        {string}  WebPageTest API key.
@option location   {string}  WebPageTest location, defaults to `Dulles:Chrome`.
@option connection {string}  WebPageTest connection speed, defaults to `Native
Connection`.
@option tests      {string}  Path to the test definitions JSON file, defaults
to `tests.json`.
@option count      {number}  Number of times to run each test, defaults to `9`.
@option email      {string}  Email address to send notifications to.
@option dump       {string}  Dump intermediate results to file.
@option resultIds  {array}   Bypass running the tests and fetch the specified
results instead.
@option silent     {boolean} Disable logging, overrides `syslog` and `log`.
@option syslog     {string}  Send logs to syslog, overrides `log`.
@option log        {object}  Logging implementation, needs `log.info()`,
`log.warn()` and `log.error()`.
@option config     {string}  Load options from JSON config file.


function map (options, results) {
    var promise, resolve, reject;

    promise = new Promise(function (r1, r2) { resolve = r1; reject = r2; } );

    try {
        // Song and dance to ensure that map options match fetch options.
        results = results || get.results(options);
        results.options.log = get.log(options);
        results.options.mapper = get.mapper(options);
        options = results.options;

        resolve(options.mapper.map(options, results));
    } catch (error) {
        reject(error);
    }

    return promise;
}

Public function `map`.

Maps WebPageTest result data to other formats, returns an ES6 promise.

@option results    {string}  Read WebPageTest results from file.
@option mapper     {string}  Mapper to use, defaults to `html-comparison`.
@option silent     {boolean} Disable logging, overrides `syslog` and `log`.
@option syslog     {string}  Send logs to syslog, overrides `log`.
@option log        {object}  Logging implementation, needs `log.info()`,
`log.warn()` and `log.error()`.
@option config     {string}  Load options from JSON config file.


function onMessage(msg, rinfo) {
            // if the message starts with the bytes "0x23, 0x02" (i.e. a Z/IP packet) then accept this as our gateway
            // TODO: consider checking the sequence number in this packet, to make sure it matches the packet we sent
            if (msg.length >= 15 && msg[0] === 0x23 && msg[1] === 0x02 && msg[14] === thisObject.findGatewaySequenceNumber && rinfo.family === "IPv4") {
                gatewayFound = true;
                resolve(rinfo.address);
            }
        }

do not let this socket's reference block node.js from exiting

do not let this socket s reference block node . js from exiting


function(o) {
        function CreatedObject(){}
        CreatedObject.prototype = o;
        var tmp = new CreatedObject();
        tmp.__proto__ = o;
        return tmp;
    }

function ( o ) { function CreatedObject ( ) { } CreatedObject . prototype = o ; var tmp = new CreatedObject ( ) ; tmp . __proto__ = o ; return tmp ; }

utility function to have Object.create on all browsers

utility function to have Object . create on all browsers


function toRingClass(claz) {
        if (claz.__classId__)
            return;
        var proto = ! Object.getOwnPropertyNames ? claz.prototype : (function() {
            var keys = {};
            (function crawl(p) {
                if (p === Object.prototype)
                    return;
                _.extend(keys, _.chain(Object.getOwnPropertyNames(p))
                    .map(function(el) {return [el, true];})
                    .fromPairs().value());
                crawl(Object.getPrototypeOf(p));
            })(claz.prototype);
            return _.fromPairs(_.map(_.keys(keys), function(k) {return [k, claz.prototype[k]];}));
        })();
        proto = _.chain(proto).map(function(v, k) { return [k, v]; })
            .filter(function(el) {return el[0] !== "constructor" && el[0] !== "__proto__";})
            .fromPairs().value();
        var id = classCounter++;
        _.extend(claz, {
            __mro__: [claz, ring.Object],
            __properties__: _.extend({}, proto, {
                __ringConstructor__: function() {
                    this.$super.apply(this, arguments);
                    var tmp = this.$super;
                    this.$super = null;
                    try {
                        claz.apply(this, arguments);
                    } finally {
                        this.$super = tmp;
                    }
                }
            }),
            __classId__: id,
            __parents__: [ring.Object],
            __classIndex__: {"1": ring.Object},
            __ringConvertedObject__: true
        });
        claz.__classIndex__[id] = claz;
    }

function toRingClass ( claz ) { if ( claz . __classId__ ) return ; var proto = ! Object . getOwnPropertyNames ? claz . prototype : ( function ( ) { var keys = { } ; ( function crawl ( p ) { if ( p === Object . prototype ) return ; _ . extend ( keys , _ . chain ( Object . getOwnPropertyNames ( p ) ) . map ( function ( el ) { return [ el , true ] ; } ) . fromPairs ( ) . value ( ) ) ; crawl ( Object . getPrototypeOf ( p ) ) ; } ) ( claz . prototype ) ; return _ . fromPairs ( _ . map ( _ . keys ( keys ) , function ( k ) { return [ k , claz . prototype [ k ] ] ; } ) ) ; } ) ( ) ; proto = _ . chain ( proto ) . map ( function ( v , k ) { return [ k , v ] ; } ) . filter ( function ( el ) { return el [ 0 ] !== "constructor" && el [ 0 ] !== "__proto__" ; } ) . fromPairs ( ) . value ( ) ; var id = classCounter ++ ; _ . extend ( claz , { __mro__ : [ claz , ring . Object ] , __properties__ : _ . extend ( { } , proto , { __ringConstructor__ : function ( ) { this . $super . apply ( this , arguments ) ; var tmp = this . $super ; this . $super = null ; try { claz . apply ( this , arguments ) ; } finally { this . $super = tmp ; } } } ) , __classId__ : id , __parents__ : [ ring . Object ] , __classIndex__ : { "1" : ring . Object } , __ringConvertedObject__ : true } ) ; claz . __classIndex__ [ id ] = claz ; }

Convert an existing class to be used with the ring.js class system.

Convert an existing class to be used with the ring . js class system .


function ensureNameForm(name, i) {
  var pos = i || 0; // just to be clear
  if (!utils.isArray(name.data.nameForms)) {
    name.data.nameForms = [];
  }
  while (pos >= name.data.nameForms.length) {
    name.data.nameForms.push({});
  }
  return name.data.nameForms[pos];
}

function
ensureNameForm
(
name
,
i
)
{
var
pos
=
i
||
0
;
// just to be clear
if
(
!
utils
.
isArray
(
name
.
data
.
nameForms
)
)
{
name
.
data
.
nameForms
=
[
]
;
}
while
(
pos
>=
name
.
data
.
nameForms
.
length
)
{
name
.
data
.
nameForms
.
push
(
{
}
)
;
}
return
name
.
data
.
nameForms
[
pos
]
;
}

return the i'th name form; add it if it doesn't exist

return the i th name form ; add it if it doesn t exist


function(client){
  this.settings = client.settings;
  this.client = client;
  this.accessTokenInactiveTimer = null;
  this.accessTokenCreationTimer = null;
}

function ( client ) { this . settings = client . settings ; this . client = client ; this . accessTokenInactiveTimer = null ; this . accessTokenCreationTimer = null ; }

Internal utility functions. This differs from utils.js in that it contains
functions which are specific to FamilySearch or need access to a client instance.

Internal utility functions . This differs from utils . js in that it contains functions which are specific to FamilySearch or need access to a client instance .


function (object) {
		var parts = [];
		for (var param in object) {
			if (object.hasOwnProperty(param)) {
				parts.push(encodeURIComponent(param) + '=' + encodeURIComponent(object[param]));
			}
		}

		return parts.join('&');
	}

function ( object ) { var parts = [ ] ; for ( var param in object ) { if ( object . hasOwnProperty ( param ) ) { parts . push ( encodeURIComponent ( param ) + '=' + encodeURIComponent ( object [ param ] ) ) ; } } return parts . join ( '&' ) ; }

Serialize an object into a string of query parameters. This does not return the beginning ?.

@param {object} object The object to serialize
@returns {string}

Serialize an object into a string of query parameters . This does not return the beginning ? .


function (queryString) {
		var pairs = queryString.split('&');

		var params = {};
		pairs.forEach(function(pair) {
			pair = pair.split('=');
			params[pair[0]] = decodeURIComponent(pair[1] || '');
		});

		return params;
	}

function ( queryString ) { var pairs = queryString . split ( '&' ) ; var params = { } ; pairs . forEach ( function ( pair ) { pair = pair . split ( '=' ) ; params [ pair [ 0 ] ] = decodeURIComponent ( pair [ 1 ] || '' ) ; } ) ; return params ; }

Break apart a query string into an object

@param {string} queryString The query string to seserialize into an object
@returns {object}


function templateMatches(template, obj) {
  for (var key in template) {
    if (template.hasOwnProperty(key) && obj[key] !== template[key]) {
      return false;
    }
  }
  return true;
}

function templateMatches ( template , obj ) { for ( var key in template ) { if ( template . hasOwnProperty ( key ) && obj [ key ] !== template [ key ] ) { return false ; } } return true ; }

return true if all corresponding object properties match


function liftFeedbackLoop(loops, mappings) {
    return function (outerState, scheduler) {
        var embededLoops = loops.map(function (loop) {
            return loop(outerState.pipe(map_1.map(mappings.mapState)), scheduler)
                .pipe(map_1.map(mappings.mapEvent));
        });
        return rx.merge.apply(rx, embededLoops);
    };
}

function liftFeedbackLoop ( loops , mappings ) { return function ( outerState , scheduler ) { var embededLoops = loops . map ( function ( loop ) { return loop ( outerState . pipe ( map_1 . map ( mappings . mapState ) ) , scheduler ) . pipe ( map_1 . map ( mappings . mapEvent ) ) ; } ) ; return rx . merge . apply ( rx , embededLoops ) ; } ; }

Lifts feedback loop that operates on a subset of state and emits embeddable events to the parent feedback loop.

@param loops Lifted feedback loops.
@param mappings State and event transformers.

Lifts feedback loop that operates on a subset of state and emits embeddable events to the parent feedback loop .


function system(initialState, reduce, feedback) {
    return rx.defer(function () {
        var state = new rx.ReplaySubject(1);
        var scheduler = rx.queueScheduler;
        var events = feedback.map(function (x) { return x(state, scheduler); });
        var mergedEvent = rx.merge.apply(rx, events).pipe(observeOn_1.observeOn(scheduler));
        var eventsWithEffects = mergedEvent
            .pipe(scan_1.scan(reduce, initialState), tap_1.tap(function (x) {
            state.next(x);
        }), subscribeOn_1.subscribeOn(scheduler), startWith_1.startWith(initialState), observeOn_1.observeOn(scheduler));
        var hackOnSubscribed = rx.defer(function () {
            state.next(initialState);
            return rx.empty();
        });
        return rx.merge.apply(rx, [eventsWithEffects, hackOnSubscribed]).pipe(catchError_1.catchError(function (e) {
            dispatchError(e);
            return rx.throwError(e);
        }));
    });
}

function system ( initialState , reduce , feedback ) { return rx . defer ( function ( ) { var state = new rx . ReplaySubject ( 1 ) ; var scheduler = rx . queueScheduler ; var events = feedback . map ( function ( x ) { return x ( state , scheduler ) ; } ) ; var mergedEvent = rx . merge . apply ( rx , events ) . pipe ( observeOn_1 . observeOn ( scheduler ) ) ; var eventsWithEffects = mergedEvent . pipe ( scan_1 . scan ( reduce , initialState ) , tap_1 . tap ( function ( x ) { state . next ( x ) ; } ) , subscribeOn_1 . subscribeOn ( scheduler ) , startWith_1 . startWith ( initialState ) , observeOn_1 . observeOn ( scheduler ) ) ; var hackOnSubscribed = rx . defer ( function ( ) { state . next ( initialState ) ; return rx . empty ( ) ; } ) ; return rx . merge . apply ( rx , [ eventsWithEffects , hackOnSubscribed ] ) . pipe ( catchError_1 . catchError ( function ( e ) { dispatchError ( e ) ; return rx . throwError ( e ) ; } ) ) ; } ) ; }

The system simulation will be started upon subscription and stopped after subscription is disposed.

System state is represented as a `State` parameter.
Events are represented by the `Event` parameter.

@param initialState The initial state of the system.
@param reduce Calculates the new system state from the existing state and a transition event (system integrator, reducer).
@param feedback The feedback loops that produce events depending on the current system state.
@returns The current state of the system.

The system simulation will be started upon subscription and stopped after subscription is disposed .


function materializedRetryStrategy(strategy) {
    return function (source) {
        switch (strategy.kind) {
            case "ignoreErrorJustComplete":
                return source.pipe(catchError_1.catchError(function (e) {
                    dispatchError(e);
                    return rx.empty();
                }));
            case "ignoreErrorAndReturn":
                return source.pipe(catchError_1.catchError(function (e) {
                    dispatchError(e);
                    return rx.of(strategy.value);
                }));
            case "exponentialBackoff":
                return rx.defer(function () {
                    var counter = 1;
                    return source.pipe(tap_1.tap(function () {
                        counter = 1;
                    }, function () {
                        if (counter * 2 <= strategy.maxBackoffFactor) {
                            counter *= 2;
                        }
                    }), retryWhen_1.retryWhen(function (e) {
                        return e.pipe(switchMap_1.switchMap(function (x) {
                            dispatchError(x);
                            return rx.of(0).pipe(delay_1.delay(strategy.initialTimeout * counter * 1000));
                        }));
                    }));
                });
            case "catchError":
                return source.pipe(catchError_1.catchError(function (e) {
                    dispatchError(e);
                    return rx.of(strategy.handle(e));
                }));
            default:
                return js_extensions_1.unhandledCase(strategy);
        }
    };
}

function materializedRetryStrategy ( strategy ) { return function ( source ) { switch ( strategy . kind ) { case "ignoreErrorJustComplete" : return source . pipe ( catchError_1 . catchError ( function ( e ) { dispatchError ( e ) ; return rx . empty ( ) ; } ) ) ; case "ignoreErrorAndReturn" : return source . pipe ( catchError_1 . catchError ( function ( e ) { dispatchError ( e ) ; return rx . of ( strategy . value ) ; } ) ) ; case "exponentialBackoff" : return rx . defer ( function ( ) { var counter = 1 ; return source . pipe ( tap_1 . tap ( function ( ) { counter = 1 ; } , function ( ) { if ( counter * 2 <= strategy . maxBackoffFactor ) { counter *= 2 ; } } ) , retryWhen_1 . retryWhen ( function ( e ) { return e . pipe ( switchMap_1 . switchMap ( function ( x ) { dispatchError ( x ) ; return rx . of ( 0 ) . pipe ( delay_1 . delay ( strategy . initialTimeout * counter * 1000 ) ) ; } ) ) ; } ) ) ; } ) ; case "catchError" : return source . pipe ( catchError_1 . catchError ( function ( e ) { dispatchError ( e ) ; return rx . of ( strategy . handle ( e ) ) ; } ) ) ; default : return js_extensions_1 . unhandledCase ( strategy ) ; } } ; }

Creates `Observable` transformation from configuration.

@param strategy The strategy configuration.

Creates Observable transformation from configuration .


function getElementServices (app, name) {
  let forecasts = app.get('forecasts')
  if (name) {
    forecasts = forecasts.filter(forecast => forecast.name === name)
  }

  // Iterate over configured forecast models
  let services = []
  for (let forecast of forecasts) {
    for (let element of forecast.elements) {
      let service = app.getService(forecast.name + '/' + element.name)
      if (service) {
        services.push(service)
      }
    }
  }
  return services
}


function fatalError(stderr) {
  return {
    errors: [{
      message: [{
        path: '',
        code: 0,
        line: 0,
        start: 0,
        descr: stderr
      }]
    }]
  };
}

function fatalError ( stderr ) { return { errors : [ { message : [ { path : '' , code : 0 , line : 0 , start : 0 , descr : stderr } ] } ] } ; }

Wrap critical Flow exception into default Error json format


function (next) {
        var options = {
          type: ctx.type,
          count: ctx.count,
          now: ctx.now,
          nowISOString: ctx.nowISOString,
          params: {
            pk: Model.getIdName(),
            id: ctx.params.id,
            relation: ctx.params.relation,
            custom: ctx.params.custom
          }
        };
        if (ctx.type === 'model') {
          options.params.where = ctx.params.where;
          options.params.range = ctx.params.range;
        }
        new _queryBuilder2.default(options).onComplete(next).build();
      }

function ( next ) { var options = { type : ctx . type , count : ctx . count , now : ctx . now , nowISOString : ctx . nowISOString , params : { pk : Model . getIdName ( ) , id : ctx . params . id , relation : ctx . params . relation , custom : ctx . params . custom } } ; if ( ctx . type === 'model' ) { options . params . where = ctx . params . where ; options . params . range = ctx . params . range ; } new _queryBuilder2 . default ( options ) . onComplete ( next ) . build ( ) ; }

Create Scope Query We dont pass complete context because we expect specific behaviour


function (query, next) {
        switch (ctx.type) {
          case 'model':
            Model.find(query, next);
            break;
          case 'relation':
            Model.findOne(query, function (err, instance) {
              if (err) return next(err);
              var builder = new _queryBuilder2.default({
                type: ctx.type,
                count: ctx.count,
                now: ctx.now,
                nowISOString: ctx.nowISOString,
                params: {
                  range: ctx.params.range,
                  where: ctx.params.where,
                  custom: ctx.params.custom
                }
              });
              builder.onComplete(function (_err, _query) {
                if (_err) return next(_err);
                instance[ctx.relation || ctx.params.relation](_query, next);
              });
              builder.build();
            });
            break;
          case 'nested':
            Model.findOne(query, function (err, instance) {
              return next(err, instance[ctx.nested]);
            });
            break;
          default:
            next(null, []);
        }
      }

function ( query , next ) { switch ( ctx . type ) { case 'model' : Model . find ( query , next ) ; break ; case 'relation' : Model . findOne ( query , function ( err , instance ) { if ( err ) return next ( err ) ; var builder = new _queryBuilder2 . default ( { type : ctx . type , count : ctx . count , now : ctx . now , nowISOString : ctx . nowISOString , params : { range : ctx . params . range , where : ctx . params . where , custom : ctx . params . custom } } ) ; builder . onComplete ( function ( _err , _query ) { if ( _err ) return next ( _err ) ; instance [ ctx . relation || ctx . params . relation ] ( _query , next ) ; } ) ; builder . build ( ) ; } ) ; break ; case 'nested' : Model . findOne ( query , function ( err , instance ) { return next ( err , instance [ ctx . nested ] ) ; } ) ; break ; default : next ( null , [ ] ) ; } }


function(sourceFileName, code) {

    // If we're processing a block of code,
    // let's try to find a class name in the block to specify the sourceFileName

    var re = /class\s?([^\s]+)(\s?{|\s.*)|\s([^\s]+)\s?=\s?class/;
    var m = re.exec(code);

    return (sourceFileName || "") + (m && m[1] || nonce());
}

When concatenating multiple source map, each one need to have a specific source name,
otherwize it will the last source will erase the previous ones.
@param   {String} sourceFileName source file name original from options
@param   {String} code           code associated
@returns {String} a generated source file name unique form each codes

When concatenating multiple source map each one need to have a specific source name otherwize it will the last source will erase the previous ones .


function(options, code) {
    var rst = JSON.parse(JSON.stringify(options)); // Let's clone options

    // In the case were source maps are activated, we need to make some verifications

    if (rst.sourceMaps) {

        // 1. If we're processing a block of code, we need to ensure that the block will have a specific source name
        if (code) {
            rst.sourceFileName = processSourceFileName(rst.sourceFileName, code);
        }

        // 2. If the sourceMap options equals to "inline" or "both", we need to set it to true before processing babel transform
        // otherwize, the sourceMapUrl will be added by babel to the generated code of each file / block of code.
        // We will take care to handle the "inline" or "both" specification when the concatenated code has been fully generated
        if (rst.sourceMaps === "inline" || rst.sourceMaps === "both") {
            rst.sourceMaps = true;
        }
    }

    return rst;
}

Process the babel options to adapt the options to avoid some issue after transformation.
@param   {Object} options current options for babel
@param   {String} code    code associated
@returns {Object} options really used during transformation

Process the babel options to adapt the options to avoid some issue after transformation .


function get(self, steamObj, key) {
    steamObj = steamObj || {};
    if (steamObj[key] !== undefined) {
        return steamObj[key];
    }
    else if (self[key] !== undefined) {
        return self[key];
    }
    else if (Steam[key] !== undefined) {
        return Steam[key];
    }
    else {
        throw new Error("Missing required field: "+key);
    }
}

function
get
(
self
,
steamObj
,
key
)
{
steamObj
=
steamObj
||
{
}
;
if
(
steamObj
[
key
]
!==
undefined
)
{
return
steamObj
[
key
]
;
}
else
if
(
self
[
key
]
!==
undefined
)
{
return
self
[
key
]
;
}
else
if
(
Steam
[
key
]
!==
undefined
)
{
return
Steam
[
key
]
;
}
else
{
throw
new
Error
(
"Missing required field: "
+
key
)
;
}
}

Helper method to get a value by searching for it by priority

First checking the options object passed in to the method call
then the instance object properties
or finally the global Steam object


function request(self, options, callback) {
    var _http = get(self, options, 'secure')? https : http;

    if (Steam.devMode) console.log(options);

    var req = _http.request(options, function(res) {
        var data, dataStr = '';

        res.on('data', function (chunk) {
            dataStr += chunk;
        });
        res.on('end', function(){

            var statusCode = res.statusCode;
            if (statusCode !== 200) {

                if (statusCode === 401) {
                    return callback(new Error('Invalid API Key'));
                }
                else {
                    return callback(new Error("HTTP "+statusCode+" "+http.STATUS_CODES[statusCode]));
                }

            }

            // Ensure it is complete and valid JSON
            try {
                data = JSON.parse(dataStr);
            }
            catch (e) {
                return callback(new Error('Unable to parse JSON data'));
            }

            // Trim or simplify data object if it's entirely wrapped in data.response or data.result
            if ((data.response instanceof Object) && (Object.keys(data).length === 1)) {
                data = data.response;
            }
            if ((data.result instanceof Object) && Object.keys(data).length === 1) {
                data = data.result;
            }
            callback(null, data);
        })

    });

    req.end(options.data);

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

}


function getParams(self, steamObj, requiredParams, optionalParams) {
    // Required params will throw exception if they don't exist
    var paramObj = {};
    for (var i = 0, len = requiredParams.length; i < len; i++) {
        var paramName = requiredParams[i];

        // Support array arguments
        paramName = paramName.replace("[0]","");

        paramObj[paramName] = get(self, steamObj, paramName);
    }

    // Ignore the thrown exception on optionalParams if field isn't given
    for (var i = 0, len = optionalParams.length; i < len; i++) {
        var paramName = optionalParams[i];

        // Support array arguments
        paramName = paramName.replace("[0]","");

        try {
            paramObj[paramName] = get(self, steamObj, paramName);
        } catch(e) {

        }

    }
    return paramObj;
}

Get the parameters from the steamObj passed in or Steam instance


function addInterfaceMethod(interfaceName, funcName, fN) {

    // Store a reference to every interface/method
    if (Steam.INTERFACES[interfaceName] === undefined) {
        Steam.INTERFACES[interfaceName] = {};
    }
    Steam.INTERFACES[interfaceName][funcName] = fN;

    // Camel case the method name
    var name = funcName.substr(0,1).toLowerCase() + funcName.substr(1);

    // Add method to Steam's prototype
    if (!isMultiGameInterface(interfaceName)) {
        steam[name] = fN;
    }
    // If multiple interfaces use the same method name
    // Create a new method that requires a gameid property to find the correct method
    //  and call the steam method automatically
    else {
        // We only need to do this once
        if (steam[name] !== undefined) return;

        // e.g. Turns 'IEconItems_440' into 'IEconItems'
        var multi_interface_name = interfaceName.split('_')[0];

        // Add method to Steam's prototype
        steam[name] = function(steamObj, callback) {
            var gameid = get(this, steamObj, 'gameid');

            var interface_name = multi_interface_name + '_' + gameid;

            Steam.INTERFACES[interface_name][funcName].call(this, steamObj, callback);
        };
    }

}

Add some easy references to the new method


function buildSteamWrapperMethod(interfaceName, funcName, defaultVersion, httpMethod, requiredParams, optionalParams) {

    // Always include the key and language fields, if available
    // GetSupportedAPIList doesn't always list them.
    optionalParams.push('key');
    optionalParams.push('language');

    // Require gameid for methods with the same name in the different interfaces
    if (isMultiGameInterface(interfaceName)) {
        requiredParams.push('gameid');
    }

    var wrapperMethod = function(steamObj, callback) {
        var params = getParams(this, steamObj, requiredParams, optionalParams);
        var version = steamObj.version || defaultVersion;
        this.request(interfaceName, funcName, version, httpMethod, params, callback);
    };

    addInterfaceMethod(interfaceName, funcName, wrapperMethod);
}


function retrieveSteamAPIMethods(key, callback) {

    var _steam = new Steam();
    _steam.getSupportedAPIList({key:key}, function(err, data) {

        if (err) return callback(err);

        var apiList = data.apilist;
        if (apiList === undefined) return callback(new Error('No data returned'));

        apiList = apiList.interfaces;

        // List of interfaces
        for (var i= 0; i<apiList.length; i++) {
            var _interface = apiList[i];
            var methods = _interface.methods;

            // List of methods
            for (var j= 0; j<methods.length; j++) {
                var method = methods[j];
                var optionalParams = [], requiredParams = [];
                var params = method.parameters;

                //List of parameters
                for (var k=0; k<params.length; k++) {
                    var param = params[k];

                    if (param.optional) {
                        optionalParams.push(param.name);
                    } else {
                        requiredParams.push(param.name);
                    }
                }

                buildSteamWrapperMethod(_interface.name, method.name, method.version, method.httpmethod, requiredParams, optionalParams);
            }
        }
        callback();

    });
}

function
retrieveSteamAPIMethods
(
key
,
callback
)
{
var
_steam
=
new
Steam
(
)
;
_steam
.
getSupportedAPIList
(
{
key
:
key
}
,
function
(
err
,
data
)
{
if
(
err
)
return
callback
(
err
)
;
var
apiList
=
data
.
apilist
;
if
(
apiList
===
undefined
)
return
callback
(
new
Error
(
'No data returned'
)
)
;
apiList
=
apiList
.
interfaces
;
// List of interfaces
for
(
var
i
=
0
;
i
<
apiList
.
length
;
i
++
)
{
var
_interface
=
apiList
[
i
]
;
var
methods
=
_interface
.
methods
;
// List of methods
for
(
var
j
=
0
;
j
<
methods
.
length
;
j
++
)
{
var
method
=
methods
[
j
]
;
var
optionalParams
=
[
]
,
requiredParams
=
[
]
;
var
params
=
method
.
parameters
;
//List of parameters
for
(
var
k
=
0
;
k
<
params
.
length
;
k
++
)
{
var
param
=
params
[
k
]
;
if
(
param
.
optional
)
{
optionalParams
.
push
(
param
.
name
)
;
}
else
{
requiredParams
.
push
(
param
.
name
)
;
}
}
buildSteamWrapperMethod
(
_interface
.
name
,
method
.
name
,
method
.
version
,
method
.
httpmethod
,
requiredParams
,
optionalParams
)
;
}
}
callback
(
)
;
}
)
;
}

Retrieve all Steam WebAPI http methods and add to our class prototype


function filterElement(flJson){
  var returnJson = {"photo":{}};

  returnJson.photo.title       = flJson.photo.title;
  returnJson.photo.description = flJson.photo.description;
  returnJson.photo.farm        = flJson.photo.farm;
  returnJson.photo.id          = flJson.photo.id;
  returnJson.photo.media       = flJson.photo.media;
  returnJson.photo.secret      = flJson.photo.secret;
  returnJson.photo.server      = flJson.photo.server;
  returnJson.photo.urls        = flJson.photo.urls;

  return returnJson;
}

function filterElement ( flJson ) { var returnJson = { "photo" : { } } ; returnJson . photo . title = flJson . photo . title ; returnJson . photo . description = flJson . photo . description ; returnJson . photo . farm = flJson . photo . farm ; returnJson . photo . id = flJson . photo . id ; returnJson . photo . media = flJson . photo . media ; returnJson . photo . secret = flJson . photo . secret ; returnJson . photo . server = flJson . photo . server ; returnJson . photo . urls = flJson . photo . urls ; return returnJson ; }


function getFlickrCacheJson(photoId){
  if(!enabledCache)return null;
  var d = new Date();
  for(var i = 0; i < cacheJson.length; i++){
    if(cacheJson[i].fl.photo.id == photoId){
      if( cacheJson[i].expires > d.getTime() ){
        return cacheJson[i].fl;
      }
      break;
    }
  }
  return null;
}

function getFlickrCacheJson ( photoId ) { if ( ! enabledCache ) return null ; var d = new Date ( ) ; for ( var i = 0 ; i < cacheJson . length ; i ++ ) { if ( cacheJson [ i ] . fl . photo . id == photoId ) { if ( cacheJson [ i ] . expires > d . getTime ( ) ) { return cacheJson [ i ] . fl ; } break ; } } return null ; }


function getImageSize( flickrJson, photo_id, photo_size ){
  var sizeInfo = {"width":0, "height":0};

  var sizeTable = {
      "s": "Square",
      "q": "Large Square",
      "t": "Thumbnail",
      "m": "Small",
      "n": "Small 320",
      "-" : "Medium",
      "z": "Medium 640",
      "c": "Medium 800",
      "b": "Large",
      "o": "Original"
  }

  if(flickrJson && flickrJson.sizes.size){
    for(var i=0; i<flickrJson.sizes.size.length; i++){
      if(flickrJson.sizes.size[i].label == sizeTable[photo_size]){
        sizeInfo.width  = flickrJson.sizes.size[i].width;
        sizeInfo.height = flickrJson.sizes.size[i].height;
      }
    }
  }

  return sizeInfo;
}

function
getImageSize
(
flickrJson
,
photo_id
,
photo_size
)
{
var
sizeInfo
=
{
"width"
:
0
,
"height"
:
0
}
;
var
sizeTable
=
{
"s"
:
"Square"
,
"q"
:
"Large Square"
,
"t"
:
"Thumbnail"
,
"m"
:
"Small"
,
"n"
:
"Small 320"
,
"-"
:
"Medium"
,
"z"
:
"Medium 640"
,
"c"
:
"Medium 800"
,
"b"
:
"Large"
,
"o"
:
"Original"
}
if
(
flickrJson
&&
flickrJson
.
sizes
.
size
)
{
for
(
var
i
=
0
;
i
<
flickrJson
.
sizes
.
size
.
length
;
i
++
)
{
if
(
flickrJson
.
sizes
.
size
[
i
]
.
label
==
sizeTable
[
photo_size
]
)
{
sizeInfo
.
width
=
flickrJson
.
sizes
.
size
[
i
]
.
width
;
sizeInfo
.
height
=
flickrJson
.
sizes
.
size
[
i
]
.
height
;
}
}
}
return
sizeInfo
;
}


function hasClass(el, className) {
    var test;

    if (el.classList) {
      test = el.classList.contains(className);
    } else {
      var className = new RegExp('(^| )' + className + '( |$)', 'gi');
      test = new RegExp(className).test(el.className);
    }

    return test;
  }

function
hasClass
(
el
,
className
)
{
var
test
;
if
(
el
.
classList
)
{
test
=
el
.
classList
.
contains
(
className
)
;
}
else
{
var
className
=
new
RegExp
(
'(^| )'
+
className
+
'( |$)'
,
'gi'
)
;
test
=
new
RegExp
(
className
)
.
test
(
el
.
className
)
;
}
return
test
;
}

Checks if an element has a given class
@private
@param {Element} el - element to search for the class
@param {String} className - class name to search for


function LeipzigEvent(name, data) {
    var leipzigEvent = undefined;

    if (window.CustomEvent) {
      leipzigEvent = new CustomEvent(name, {
        detail: data,
        bubbles: true,
        cancelable: true
      });
    } else {
      // For Internet Explorer & PhantomJS
      leipzigEvent = document.createEvent('CustomEvent');
      leipzigEvent.initCustomEvent(name, true, true, data);
    }

    return leipzigEvent;
  }

function
LeipzigEvent
(
name
,
data
)
{
var
leipzigEvent
=
undefined
;
if
(
window
.
CustomEvent
)
{
leipzigEvent
=
new
CustomEvent
(
name
,
{
detail
:
data
,
bubbles
:
true
,
cancelable
:
true
}
)
;
}
else
{
// For Internet Explorer & PhantomJS
leipzigEvent
=
document
.
createEvent
(
'CustomEvent'
)
;
leipzigEvent
.
initCustomEvent
(
name
,
true
,
true
,
data
)
;
}
return
leipzigEvent
;
}

Helper function for creating custom events
@private


function triggerEvent(el, name, data) {
    var e = new LeipzigEvent(name, data);
    el.dispatchEvent(e);
  }

function triggerEvent ( el , name , data ) { var e = new LeipzigEvent ( name , data ) ; el . dispatchEvent ( e ) ; }

Helper function for triggering custom events
@private


function processGloss(gloss, callback) {
      if (!(gloss instanceof Element)) {
        var err = new Error('Invalid gloss element');

        if (typeof callback === 'function') {
          callback(err);
        } else {
          throw err;
        }
      }

      var lines = Array.prototype.slice.call(gloss.children);
      var linesToAlign = [];
      var firstRawLine = null;
      var firstRawLineNum = 0;

      triggerEvent(gloss, events.beforeGloss);

      if (firstLineOrig) {
        var firstLine = lines[0];
        addClass(firstLine, classes.original);
      }

      if (lastLineFree) {
        var lastLine = lines[lines.length - 1];
        addClass(lastLine, classes.freeTranslation);
      }

      // process each line in the gloss
      lines.forEach(function (line, lineNum) {
        // don't align lines that are free translations or original,
        // unformatted lines
        var isOrig = hasClass(line, classes.original);
        var isFree = hasClass(line, classes.freeTranslation);
        var shouldSkip = hasClass(line, classes.noAlign);

        var shouldAlign = !isOrig && !isFree && !shouldSkip;

        if (shouldAlign) {
          triggerEvent(line, events.beforeLex, { lineNum: lineNum });
          var tokens = _this2.lex(line.innerHTML);
          triggerEvent(line, events.afterLex, {
            tokens: tokens,
            lineNum: lineNum
          });

          linesToAlign.push(tokens);
          addClass(line, classes.hidden);

          // if this is the first aligned line, mark the location
          // so that the final aligned glosses can be inserted here
          if (!firstRawLine) {
            firstRawLine = line;
            firstRawLineNum = lineNum;
          }
        } else {
          addClass(line, classes.line);
          addClass(line, classes.lineNum + lineNum);
        }
      });

      var lastRawLineNum = firstRawLineNum + (linesToAlign.length - 1);

      triggerEvent(gloss, events.beforeAlign, {
        lines: linesToAlign,
        firstLineNum: firstRawLineNum,
        lastLineNum: lastRawLineNum
      });

      var alignedLines = _this2.align(linesToAlign);

      triggerEvent(gloss, events.afterAlign, {
        lines: alignedLines,
        firstLineNum: firstRawLineNum,
        lastLineNum: lastRawLineNum
      });

      // determine which type of element the aligned glosses should be wrapped in
      var alignedWrapper = undefined;
      if (gloss.tagName === 'UL' || gloss.tagName === 'OL') {
        alignedWrapper = 'li';
      } else {
        alignedWrapper = 'div';
      }

      triggerEvent(gloss, events.beforeFormat, {
        lines: alignedLines,
        firstLineNum: firstRawLineNum,
        lastLineNum: lastRawLineNum
      });

      var formattedLines = _this2.format(alignedLines, alignedWrapper, firstRawLineNum);
      gloss.insertBefore(formattedLines, firstRawLine);

      triggerEvent(formattedLines, events.afterFormat, {
        firstLineNum: firstRawLineNum,
        lastLineNum: lastRawLineNum
      });

      // finish up by adding relevant classes to the main container
      if (!spacing) {
        addClass(gloss, classes.noSpace);
      }

      addClass(gloss, classes.glossed);

      triggerEvent(gloss, events.afterGloss);
    }


function UrlHelper(params){
	this.url = "http://store.steampowered.com/search/?";

	if(!!params.tags){
		for(i = 0; i < params.tags.length; i++)
			params.tags[i] = parameters.tags.get(params.tags[i]).value
		this.url += "tags=" + params.tags.join(",") + "&";
	}

	if(!!params.os){
		for(i = 0; i < params.os.length; i++)
			params.os[i] = parameters.os.get(params.os[i]).value
		this.url += "os=" + params.os.join(",") + "&";
	}

	if(!!params.playerAmount)
		for(i = 0; i < params.playerAmount.length; i++)
			params.playerAmount[i] = parameters.playerAmount.get(params.playerAmount[i]).value
		this.url += "category3=" + params.playerAmount.join(",") + "&";

	if(params.gamesOnly)
		this.url += "category1=998&";
}

Make url to Steam Store from Params object
@param {Object} params


function serializeState(){
      var data = model.data,
          scale = model.scale,
          translate = model.translate;
      model.state = {
        nodes: data.nodes.map(function(node){
          return {
            type: node.type,
            property: node.property,
            fixed: node.fixed,

            // Keep size of JSON small, so it fits in a URL.
            x: Math.round(node.x),
            y: Math.round(node.y)
          };
        }),
        links: data.links.map(function(link){
          // Replaced link object references with indices for serialization.
          return {
            source: link.source.index,
            target: link.target.index
          };
        }),
        scale: scale,
        translate: translate
      };
    }

Sets model.state to expose the serialized state.

Sets model . state to expose the serialized state .


function track(property){
      if(!(property in trackedProperties)){
        trackedProperties[property] = true;
        values[property] = model[property];
        Object.defineProperty(model, property, {
          get: function () { return values[property]; },
          set: function(value) {
            values[property] = value;
            getListeners(property).forEach(function(callback){
              callback(value);
            });
          }
        });
      }
    }

function track ( property ) { if ( ! ( property in trackedProperties ) ) { trackedProperties [ property ] = true ; values [ property ] = model [ property ] ; Object . defineProperty ( model , property , { get : function ( ) { return values [ property ] ; } , set : function ( value ) { values [ property ] = value ; getListeners ( property ) . forEach ( function ( callback ) { callback ( value ) ; } ) ; } } ) ; } }

Tracks a property if it is not already tracked.

Tracks a property if it is not already tracked .


function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

function randomDate ( start , end ) { return new Date ( start . getTime ( ) + Math . random ( ) * ( end . getTime ( ) - start . getTime ( ) ) ) ; }

Returns a random date
@param {Date} start - the start Date
@param {Date} end - the end Date
@return {Date} date - a random date between start and end date


function randomPrice(oldPrice, volatility) {
  const rnd = randomNumber();
  let changePercent = 2 * volatility * rnd;
  if (changePercent > volatility) {
    changePercent -= (2 * volatility);
  }
  const changeAmount = oldPrice * changePercent;
  const newPrice = oldPrice + changeAmount;
  return newPrice;
}

function randomPrice ( oldPrice , volatility ) { const rnd = randomNumber ( ) ; let changePercent = 2 * volatility * rnd ; if ( changePercent > volatility ) { changePercent -= ( 2 * volatility ) ; } const changeAmount = oldPrice * changePercent ; const newPrice = oldPrice + changeAmount ; return newPrice ; }

Return a random price based on the previous price and volatility
@param {Number} oldPrice - the previous price
@param {Number} volatility - the current volatility
@return {Number} newPrice


function randomIncident(types, start, end) {
  const x1 = randomDate(start, end);
  const x2 = new Date(x1);
  x2.setDate(x1.getDate() + (Math.floor(Math.random() * 45)));
  Incidents.insert({
    x1: x1.getTime(),
    x2: x2.getTime(),
    y1: (Math.floor(Math.random() * 99)),
    type: types[(Math.floor(Math.random() * 2))],
  });
}

function randomIncident ( types , start , end ) { const x1 = randomDate ( start , end ) ; const x2 = new Date ( x1 ) ; x2 . setDate ( x1 . getDate ( ) + ( Math . floor ( Math . random ( ) * 45 ) ) ) ; Incidents . insert ( { x1 : x1 . getTime ( ) , x2 : x2 . getTime ( ) , y1 : ( Math . floor ( Math . random ( ) * 99 ) ) , type : types [ ( Math . floor ( Math . random ( ) * 2 ) ) ] , } ) ; }

Insert a random incident into a collection
@param {Array} types - the types of incidents ['info', 'success']
@param {Date} start - the start Date
@param {Date} end - the end Date
@return None


function getDatetimeUnit(min, max) {
  const diff = max.diff(min, 'days');
  let unit = 'month';
  if (diff <= 14) {
    unit = 'day';
  } else if (diff > 14 && diff <= 183) {
    unit = 'week';
  }
  return unit;
}

function getDatetimeUnit ( min , max ) { const diff = max . diff ( min , 'days' ) ; let unit = 'month' ; if ( diff <= 14 ) { unit = 'day' ; } else if ( diff > 14 && diff <= 183 ) { unit = 'week' ; } return unit ; }

getDatetimeUnit - determine the unit of time for padding the axis

@param {object} min, the min moment datetime object
@param {object} max, the max moment datetime object
@return {string} the datetime unit {day, week, month}


function getRenderedTemplate(template, data, variableRegex) {
  return template.replace(variableRegex, (match, captured) => {
    const replacement = valueForProperty(data, captured.trim());
    // If a template variable is found but nothing is supplied to fill it, remove it
    if (replacement == null) {
      return '';
    }

    // If the replacement is a function, replace the variable with the result of the function
    if (typeof replacement === 'function') {
      return replacement();
    }

    // otherwise replace the template variable with the associated data
    return replacement;
  });
}

Gets the rendered output of a template
@param {String} template - A template to use as a base for the render
@param {Object} data - The data to use when populating the templates
@param {RegExp} variableRegex - The regex to use for indentifying template variables


function getProcessedPath(file, data) {
  return file.replace(/__([A-Za-z0-9-]+_?[A-Za-z0-9-]+)+__/g, (match) => {
    const dataKey = match.substring(2, match.length - 2);
    const dataVal = data[dataKey];

    if (dataVal) {
      return dataVal;
    }
    return match;
  });
}

function getProcessedPath ( file , data ) { return file . replace ( / __([A-Za-z0-9-]+_?[A-Za-z0-9-]+)+__ / g , ( match ) => { const dataKey = match . substring ( 2 , match . length - 2 ) ; const dataVal = data [ dataKey ] ; if ( dataVal ) { return dataVal ; } return match ; } ) ; }

Gets the processed filepath of a dynamic filepath
@param {String} file - A filepath to search for variables
@param {Object} data - The data to use if a variable is found


function scaffold(
  {
    source = '',
    destination = 'destination',
    onlyFiles = false,
    exclude = [],
    variableRegex = /\{\{\s?([A-Za-z0-9-]+_?[A-Za-z0-9-]+)+\s?\}\}/g,
  } = {},
  data = {},
) {
  const cwd = process.cwd();

  const thisSource = pathIsAbsolute(source) ? source : path.join(cwd, source);
  const thisDestination = pathIsAbsolute(destination) ? destination : path.join(cwd, destination);
  const thisOnlyFiles = onlyFiles;
  const thisExclude = exclude;
  const thisVariableRegex = variableRegex;

  try {
    const listOfFiles = fs.readdirSync(thisSource);
    const destinationExists = fs.existsSync(thisDestination);

    if (!destinationExists) {
      fs.mkdirSync(thisDestination);
    }

    listOfFiles.forEach((file) => {
      const thisFile = path.join(thisSource, file);
      const stat = fs.statSync(thisFile);
      const destinationFilename = getProcessedPath(file, data);
      const destinationPath = path.join(thisDestination, destinationFilename);

      if (stat && stat.isDirectory() && !thisOnlyFiles && !thisExclude.includes(file)) {
        scaffold({
          source: thisFile,
          destination: destinationPath,
          onlyFiles: thisOnlyFiles,
          exclude: thisExclude,
          variableRegex: thisVariableRegex,
        }, data);
      } else if (!stat.isDirectory()) {
        const template = fs.readFileSync(thisFile, 'utf-8');
        const filledTemplate = getRenderedTemplate(template, data, thisVariableRegex);

        fs.writeFileSync(destinationPath, filledTemplate);
      }
    });
  } catch (e) {
    throw new Error(e);
  }
}

Creates file resources based on another file resource

@param {String} arg0.source - The path to the source files
@param {String} arg0.destination - The base path of the generated files
@param {Boolean} arg0.onlyFiles - Whether to only generate files
@param {Array} arg0.exclude - The paths to exclude from generated files
@param {RegExp} arg0.variableRegex - The pattern for indentifying template variables
@param {Object} data - The data to pass to the templates when generating


function (lookup) {
  var matches = tmplRegExp.exec(lookup);
  if (matches) {
    return {
      src: matches && matches[0],
      prop: matches && matches[1] || matches[2],
    };
  } else {
    return false;
  }
}

function ( lookup ) { var matches = tmplRegExp . exec ( lookup ) ; if ( matches ) { return { src : matches && matches [ 0 ] , prop : matches && matches [ 1 ] || matches [ 2 ] , } ; } else { return false ; } }

inspect string for lookups that satisfy the above regexp


function (data, lookup, options) {
  var property;
  // as long as this contains a template string, keep traversing
  while(property = findProperty(lookup)) {
    // if this doesn't solely contain a template lookup (e.g. '<%= key %>'), then
    // recursively process it as a template to handle interpolated strings (e.g. 'hi <%= key %>).
    if (property.src !== lookup) {
      lookup = _.template(lookup, data, options);
    } else {
      // expand to the literal value of this key
      lookup = expander.process(data, getobject.get(data, property.prop), options);
    }
  }
  // do one final check for templates.
  if (hasTemplate(lookup)) {
    lookup = _.template(lookup, data, options);
  }
  return lookup;
}

recursively expand a string until it doesn't contain any template strings

recursively expand a string until it doesn t contain any template strings


function (data, arr, options) {
  return arr.map(function(lookup) {
    return expander.process(data, lookup, options);
  });
}

function ( data , arr , options ) { return arr . map ( function ( lookup ) { return expander . process ( data , lookup , options ) ; } ) ; }

recursively expand an array until it doesn't contain any template strings

recursively expand an array until it doesn t contain any template strings


function (data, obj, options) {
  var result = {};
  Object.keys(obj).forEach(function(key) {
    result[key] = expander.process(data, obj[key], options);
  });
  return result;
}

function ( data , obj , options ) { var result = { } ; Object . keys ( obj ) . forEach ( function ( key ) { result [ key ] = expander . process ( data , obj [ key ] , options ) ; } ) ; return result ; }

recursively expand an object, resolving its template strings

recursively expand an object resolving its template strings


function _set(obj, keypath, value) {
    var parts = _keyPathNormalize(keypath).split('.')
    var last = parts.pop()
    var dest = obj
    var hasError
    var errorInfo
    util.some(parts, function(key) {
        var t = util.type(dest)
        if (t != 'object' && t != 'array') {
            hasError = true
            errorInfo = [key, dest]
            return true
        }
        dest = dest[key]
    })
    // set value
    if (!hasError) {
        if (util.type(dest) != 'object' && util.type(dest) != 'array') {
            hasError = true
            errorInfo = [last, dest]
        } else {
            dest[last] = value
            return obj
        }
    }
    throw new Error('Can\' not access "' + errorInfo[0] + '" of "'+ errorInfo[1] + '" when set value of "' + keypath + '"')
}

function
_set
(
obj
,
keypath
,
value
)
{
var
parts
=
_keyPathNormalize
(
keypath
)
.
split
(
'.'
)
var
last
=
parts
.
pop
(
)
var
dest
=
obj
var
hasError
var
errorInfo
util
.
some
(
parts
,
function
(
key
)
{
var
t
=
util
.
type
(
dest
)
if
(
t
!=
'object'
&&
t
!=
'array'
)
{
hasError
=
true
errorInfo
=
[
key
,
dest
]
return
true
}
dest
=
dest
[
key
]
}
)
// set value
if
(
!
hasError
)
{
if
(
util
.
type
(
dest
)
!=
'object'
&&
util
.
type
(
dest
)
!=
'array'
)
{
hasError
=
true
errorInfo
=
[
last
,
dest
]
}
else
{
dest
[
last
]
=
value
return
obj
}
}
throw
new
Error
(
'Can\' not access "'
+
errorInfo
[
0
]
+
'" of "'
+
errorInfo
[
1
]
+
'" when set value of "'
+
keypath
+
'"'
)
}


function(text) {
        if (!text || !text.replace) return text
        return text.replace(/(&[#a-zA-Z0-9]+;)/g, function (m, s) {
            return _convertEntity(s)
        })
    }

function ( text ) { if ( ! text || ! text . replace ) return text return text . replace ( / (&[#a-zA-Z0-9]+;) / g , function ( m , s ) { return _convertEntity ( s ) } ) }

Covert HTML entities
@doc http://www.w3school.com.cn/tags/html_ref_entities.html


function compute () {
                // set value
                util.forEach(expressions, function(exp, index) {
                    var v = that.$exec(exp)
                    if (!v[0]) caches[index] = v[1]
                })
                // get content
                var str = ''
                util.forEach(parts, function(item, index) {
                    str += emptyStr(item)
                    if (index < expressions.length) {
                        str += emptyStr(caches[index])
                    }
                })
                return Expression.unveil(str)
            }

function
compute
(
)
{
// set value
util
.
forEach
(
expressions
,
function
(
exp
,
index
)
{
var
v
=
that
.
$exec
(
exp
)
if
(
!
v
[
0
]
)
caches
[
index
]
=
v
[
1
]
}
)
// get content
var
str
=
''
util
.
forEach
(
parts
,
function
(
item
,
index
)
{
str
+=
emptyStr
(
item
)
if
(
index
<
expressions
.
length
)
{
str
+=
emptyStr
(
caches
[
index
]
)
}
}
)
return
Expression
.
unveil
(
str
)
}

Computed all expression and get concated result


function patchFileObjects( formData ) {
	// There are several landmines to avoid when making file uploads work on all browsers:
	// - the `new File()` constructor trick breaks file uploads on Safari 10 in a way that's
	//   impossible to detect: it will send empty files in the multipart/form-data body.
	//   Therefore we need to detect Chrome.
	// - IE11 and Edge don't support the `new File()` constructor at all. It will throw exception,
	//   so it's detectable by the `supportsFileConstructor` code.
	// - `window.chrome` exists also on Edge (!), `window.chrome.webstore` is only in Chrome and
	//   not in other Chromium based browsers (which have the site isolation bug, too).
	if ( ! window.chrome || ! supportsFileConstructor ) {
		return;
	}

	for ( let i = 0; i < formData.length; i++ ) {
		const val = getFileValue( formData[ i ][ 1 ] );
		if ( val ) {
			formData[ i ][ 1 ] = new File( [ val ], val.name, { type: val.type } );
		}
	}
}

//   Therefore we need to detect Chrome.

Finds all `File` instances in `formData` and creates a new `File` instance whose storage is
forced to be a `Blob` instead of being backed by a file on disk. That works around a bug in
Chrome where `File` instances with `has_backing_file` flag cannot be sent over a process
boundary when site isolation is on.

@see https://bugs.chromium.org/p/chromium/issues/detail?id=866805
@see https://bugs.chromium.org/p/chromium/issues/detail?id=631877

@param {Array} formData Form data to patch

Finds all File instances in formData and creates a new File instance whose storage is forced to be a Blob instead of being backed by a file on disk . That works around a bug in Chrome where File instances with has_backing_file flag cannot be sent over a process boundary when site isolation is on .


function onmessage( e ) {
	debug( 'onmessage' );

	// safeguard...
	if ( e.origin !== proxyOrigin ) {
		debug( 'ignoring message... %o !== %o', e.origin, proxyOrigin );
		return;
	}

	let { data } = e;
	if ( ! data ) {
		return debug( 'no `data`, bailing' );
	}

	// Once the iframe is loaded, we can start using it.
	if ( data === 'ready' ) {
		onload();
		return;
	}

	if ( postStrings && 'string' === typeof data ) {
		data = JSON.parse( data );
	}

	// check if we're receiving a "progress" event
	if ( data.upload || data.download ) {
		return onprogress( data );
	}

	if ( ! data.length ) {
		return debug( '`e.data` doesn\'t appear to be an Array, bailing...' );
	}

	// first get the `xhr` instance that we're interested in
	const id = data[ data.length - 1 ];
	if ( ! ( id in requests ) ) {
		return debug( 'bailing, no matching request with callback: %o', id );
	}

	const xhr = requests[ id ];

	// Build `error` and `body` object from the `data` object
	const { params } = xhr;
	let body, statusCode, headers;

	// apiNamespace (WP-API)
	const { apiNamespace } = params;

	body = data[ 0 ];
	statusCode = data[ 1 ];
	headers = data[ 2 ];

	if ( statusCode === 207 ) {
		// 207 is a signal from rest-proxy. It means, "this isn't the final
		// response to the query." The proxy supports WebSocket connections
		// by invoking the original success callback for each message received.
	} else {
		// this is the final response to this query
		delete requests[ id ];
	}

	if ( ! params.metaAPI ) {
		debug( 'got %o status code for URL: %o', statusCode, params.path );
	} else {
		statusCode = body === 'metaAPIupdated' ? 200 : 500;
	}

	// add statusCode into headers object
	if ( typeof headers === 'object' ) {
		headers.status = statusCode;
	}

	if ( statusCode && 2 === Math.floor( statusCode / 100 ) ) {
		// 2xx status code, success
		resolve( xhr, body, headers );
	} else {
		// any other status code is a failure
		const wpe = WPError( params, statusCode, body );
		reject( xhr, wpe, headers );
	}
}

The main `window` object's "message" event callback function.

@param {Event} e
@api private

The main window object s message event callback function .


function onprogress( data ) {
	debug( 'got "progress" event: %o', data );
	const xhr = requests[ data.callbackId ];
	if ( xhr ) {
		const prog = new ProgressEvent( 'progress', data );
		const target = data.upload ? xhr.upload : xhr;
		target.dispatchEvent( prog );
	}
}

function
onprogress
(
data
)
{
debug
(
'got "progress" event: %o'
,
data
)
;
const
xhr
=
requests
[
data
.
callbackId
]
;
if
(
xhr
)
{
const
prog
=
new
ProgressEvent
(
'progress'
,
data
)
;
const
target
=
data
.
upload
xhr
.
upload
:
xhr
;
target
.
dispatchEvent
(
prog
)
;
}
}

Handles a "progress" event being proxied back from the iframe page.

@param {Object} data
@private

Handles a progress event being proxied back from the iframe page .


function resolve( xhr, body, headers ) {
	const e = new ProgressEvent( 'load' );
	e.data = e.body = e.response = body;
	e.headers = headers;
	xhr.dispatchEvent( e );
}

function resolve ( xhr , body , headers ) { const e = new ProgressEvent ( 'load' ) ; e . data = e . body = e . response = body ; e . headers = headers ; xhr . dispatchEvent ( e ) ; }

Emits the "load" event on the `xhr`.

@param {XMLHttpRequest} xhr
@param {Object} body
@private


function reject( xhr, err, headers ) {
	const e = new ProgressEvent( 'error' );
	e.error = e.err = err;
	e.headers = headers;
	xhr.dispatchEvent( e );
}

function reject ( xhr , err , headers ) { const e = new ProgressEvent ( 'error' ) ; e . error = e . err = err ; e . headers = headers ; xhr . dispatchEvent ( e ) ; }

Emits the "error" event on the `xhr`.

@param {XMLHttpRequest} xhr
@param {Error} err
@private


function instanceScopedDirective(tar, dec, dname) {
        // don't compile child scope
        if (scopedChilds && scopedChilds.length && util.some(scopedChilds, function (item) {
            return tar == item
        })) return

        var drefs = tar._diretives || []
        // prevent repetitive binding
        if (drefs && ~util.indexOf(drefs, dname)) return

        var def = _diretives[dname]
        var expr = _getAttribute(tar, dec) || ''
        drefs.push(dec)
        tar._diretives = drefs
        _removeAttribute(tar, dec)

        var d = new Directive(vm, tar, def, dec, expr, scope)
        $directives.push(d)
    }

function
instanceScopedDirective
(
tar
,
dec
,
dname
)
{
// don't compile child scope
if
(
scopedChilds
&&
scopedChilds
.
length
&&
util
.
some
(
scopedChilds
,
function
(
item
)
{
return
tar
==
item
}
)
)
return
var
drefs
=
tar
.
_diretives
||
[
]
// prevent repetitive binding
if
(
drefs
&&
~
util
.
indexOf
(
drefs
,
dname
)
)
return
var
def
=
_diretives
[
dname
]
var
expr
=
_getAttribute
(
tar
,
dec
)
||
''
drefs
.
push
(
dec
)
tar
.
_diretives
=
drefs
_removeAttribute
(
tar
,
dec
)
var
d
=
new
Directive
(
vm
,
tar
,
def
,
dec
,
expr
,
scope
)
$directives
.
push
(
d
)
}


function _safelyCall(isCatch, fn, ctx) {
    if (!fn) return

    if (isCatch) {
        try {
            fn.call(ctx)
        } catch(e) {
            consoler.errorTrace(e)
        }
    } else {
        fn.call(ctx)
    }
}

function _safelyCall ( isCatch , fn , ctx ) { if ( ! fn ) return if ( isCatch ) { try { fn . call ( ctx ) } catch ( e ) { consoler . errorTrace ( e ) } } else { fn . call ( ctx ) } }

Call method and catch error then log by console.log

Call method and catch error then log by console . log


function loadMiddlewareFilters(filters) {

  var result = [],
      index,
      num = filters.length,
      filter,
      modulePath,
      middleware;

  function startsWith(string, searchString, position) {
    position = position || 0;
    return string.indexOf(searchString, position) === position;
  }

  for (index = 0; index < num; index++ ) {
    filter = filters[index];

    // Check filter has required properties
    if (!filter.id) {
      throw new InvalidConfiguration(InvalidConfiguration.INVALID_FILTER_MESSAGE + " Filter at index " + index + " has no 'id' property.");
    }
    if (!filter.path) {
      throw new InvalidConfiguration(InvalidConfiguration.INVALID_FILTER_MESSAGE + " Filter at index " + index + " has no 'path' property.");
    }

    // Determine module path depending on if it must be loaded from 'filters' folder
    // or node modules.
    modulePath = filter.path;
    if (startsWith(filter.path, ".")) {
      modulePath = path.join(basePath, filter.path);
    }

    // Load filter module and initialize middleware filter
    middleware = require(modulePath).init(filter.id, filter.config);

    result.push({
      id: filter.id,
      path: modulePath,
      config: filter.config,
      middleware: middleware
    });
  }

  return result;
}

Loads the modules associated to each filter and returns an array of middlewares.

@private
@param  {Array} filters Array with filters configuration
@returns {Array<object>} Array with filter's configuration plus a middleware
object referencing the loaded filter's module.

Loads the modules associated to each filter and returns an array of middlewares .


function loadResources(resources, providerIndex) {

  var result = [],
      index,
      num = resources.length,
      resource,
      prefilters, postfilters;

  for (index = 0; index < num; index++ ) {
    resource = resources[index];
    prefilters = [];
    postfilters = [];

    // Check resource has required properties
    if (!resource.id) {
      throw new InvalidConfiguration(
        InvalidConfiguration.INVALID_RESOURCE_MESSAGE
        + " Resource at index " + index + " on"
        + " provider at index " + providerIndex + " has no 'id' property."
      );
    }
    if (!resource.context) {
      throw new InvalidConfiguration(
        InvalidConfiguration.INVALID_RESOURCE_MESSAGE
        + " Resource at index " + index + " on"
        + " provider at index " + providerIndex + " has no 'context' property."
      );
    }

    // Load resource's filters
    if (resource.prefilters) {
      prefilters = loadMiddlewareFilters(resource.prefilters);
    }
    if (resource.postfilters) {
      postfilters = loadMiddlewareFilters(resource.postfilters);
    }

    // Store resource information
    result.push({
      id: resource.id,
      context: resource.context,
      prefilters: prefilters,
      postfilters: postfilters
    });
  }

  return result;
}

Load resources configuration loading its pre and postfilters modules.

@private
@param  {Array<object>} resources Array with resources configuration.
@param  {boolean} providerIndex Index of the provider within array of providers.
@returns {Array<object>} Array with resources configuration plus a middleware
object referencing the filter's module.

Load resources configuration loading its pre and postfilters modules .


function loadProviders(providers) {

  var result = [],
      index,
      num = providers.length,
      provider,
      prefilters, postfilters, resources;

  for (index = 0; index < num; index++ ) {
    provider = providers[index];
    prefilters = [];
    postfilters = [];
    resources = [];

    // Check provider has required properties
    if (!provider.id) {
      throw new InvalidConfiguration(InvalidConfiguration.INVALID_PROVIDER_MESSAGE + " Provider at index " + index + " has no 'id' property.");
    }
    if (!provider.target) {
      throw new InvalidConfiguration(InvalidConfiguration.INVALID_PROVIDER_MESSAGE + " Provider at index " + index + " has no 'target' property.");
    }
    if (!provider.context) {
      throw new InvalidConfiguration(InvalidConfiguration.INVALID_PROVIDER_MESSAGE + " Provider at index " + index + " has no context' property.");
    }

    // Load provider's filters
    if (provider.prefilters) {
      prefilters = loadMiddlewareFilters(provider.prefilters);
    }
    if (provider.postfilters) {
      postfilters = loadMiddlewareFilters(provider.postfilters);
    }

    // Load provider's resources
    if (provider.resources) {
      resources = loadResources(provider.resources, index);
    }

    // Store provider information
    result.push({
      id: provider.id,
      context: provider.context,
      target: provider.target,
      prefilters: prefilters,
      postfilters: postfilters,
      resources: resources
    });
  }

  return result;
}

Load providers configuration loading its pre and postfilters modules.

@private
@param  {Array<object>} providers Array with providers configuration.
@returns {Array<object>} Array with provider's configuration plus a middleware
object referencing the filter's module.

Load providers configuration loading its pre and postfilters modules .


function load(config) {

  var configuration = {
    prefilters: [],
    providers: [],
    postfilters: []
  };

  // Check a valid object
  if (typeof config !== "object") {
    throw new InvalidConfiguration(InvalidConfiguration.EMPTY_MESSAGE);
  }

  // Check at least one provider
  if (!config.providers || !config.providers.length) {
    throw new InvalidConfiguration(InvalidConfiguration.NO_PROVIDER_MESSAGE);
  }

  // Load prefilters
  if (config.prefilters) {
    configuration.prefilters = loadMiddlewareFilters(config.prefilters);
  }

  // Load postfilters
  if (config.postfilters) {
    configuration.postfilters = loadMiddlewareFilters(config.postfilters);
  }

  // Load providers
  configuration.providers = loadProviders(config.providers);

  return configuration;
}

function
load
(
config
)
{
var
configuration
=
{
prefilters
:
[
]
,
providers
:
[
]
,
postfilters
:
[
]
}
;
// Check a valid object
if
(
typeof
config
!==
"object"
)
{
throw
new
InvalidConfiguration
(
InvalidConfiguration
.
EMPTY_MESSAGE
)
;
}
// Check at least one provider
if
(
!
config
.
providers
||
!
config
.
providers
.
length
)
{
throw
new
InvalidConfiguration
(
InvalidConfiguration
.
NO_PROVIDER_MESSAGE
)
;
}
// Load prefilters
if
(
config
.
prefilters
)
{
configuration
.
prefilters
=
loadMiddlewareFilters
(
config
.
prefilters
)
;
}
// Load postfilters
if
(
config
.
postfilters
)
{
configuration
.
postfilters
=
loadMiddlewareFilters
(
config
.
postfilters
)
;
}
// Load providers
configuration
.
providers
=
loadProviders
(
config
.
providers
)
;
return
configuration
;
}

Load a configuration returning and object with prefilters, postfilters and
providers middlewares ready to be used.

@public
@param  {object} config JavaScript object with configuration
@returns {object} configuration with middlewares loaded.

Load a configuration returning and object with prefilters postfilters and providers middlewares ready to be used .


function Currencies (currencies) {
    if (!currencies) {
        throw new Error('Missing currencies object');
    }

    this.keys = parseInt(currencies.keys || 0);
    this.metal = parseFloat(currencies.metal || 0);

    if (isNaN(this.keys) || isNaN(this.metal)) {
        throw new Error('Not a valid currencies object');
    }

    this.metal = toRefined(toScrap(this.metal));
}

function
Currencies
(
currencies
)
{
if
(
!
currencies
)
{
throw
new
Error
(
'Missing currencies object'
)
;
}
this
.
keys
=
parseInt
(
currencies
.
keys
||
0
)
;
this
.
metal
=
parseFloat
(
currencies
.
metal
||
0
)
;
if
(
isNaN
(
this
.
keys
)
||
isNaN
(
this
.
metal
)
)
{
throw
new
Error
(
'Not a valid currencies object'
)
;
}
this
.
metal
=
toRefined
(
toScrap
(
this
.
metal
)
)
;
}

Creates a new Currencies instance
@class
@param {object} currencies The currencies object
@throws Will throw an error if missing currencies object, or if it is not valid


function getOptions() {

  //
  // Defines and parses the command line interface to start Clyde server.
  //
  var argv = yargs
    .usage("Usage: $0 [options] config_file")
    .example("$0 config.json", "Start clyde reading configuration from 'config.json' file.")
    .example("$0 --log debug config.json", "Start clyde with log messages on 'debug' level and reading configuration from 'config.json' file.")
    .describe("logfile", "Path to the log file. Default 'clyde.log'.")
    .nargs("logfile", 1)
    .describe("loglevel", "Level used for clyde log messages. Default 'info'.")
    .nargs("loglevel", 1)
    .describe("port", "Port where clyde will listen. Default 8080.")
    .nargs("port", 1)
    .help("help")
    .demand(1, "A configuration file must be specified")
    .showHelpOnFail(false, "Specify --help for available options")
    .argv;

  //
  // Load configuration file
  //
  var options = require(path.join(process.cwd(), argv._[0]));

  //
  // Override options with command line specified. Command line takes precedence.
  //
  options.logfile = argv.logfile || options.logfile || "clyde.log";
  options.loglevel = argv.loglevel || options.loglevel || "info";
  options.port = argv.port || options.port || 8000;

  return options;
}

Merge command line options with configuration file

@returns {Object} Configuration object


function getWindowForElement(element) {
        var doc = element.ownerDocument || element;
        return doc.defaultView || doc.parentWindow || window;
    }

function getWindowForElement ( element ) { var doc = element . ownerDocument || element ; return doc . defaultView || doc . parentWindow || window ; }

get the window object of an element
@param {HTMLElement} element
@returns {DocumentView|Window}


function createInputInstance(manager) {
        var Type;
        var inputClass = manager.options.inputClass;

        if (inputClass) {
            Type = inputClass;
        } else if (SUPPORT_POINTER_EVENTS) {
            Type = PointerEventInput;
        } else if (SUPPORT_ONLY_TOUCH) {
            Type = TouchInput;
        } else if (!SUPPORT_TOUCH) {
            Type = MouseInput;
        } else {
            Type = TouchMouseInput;
        }
        return new Type(manager, inputHandler);
    }

function createInputInstance ( manager ) { var Type ; var inputClass = manager . options . inputClass ; if ( inputClass ) { Type = inputClass ; } else if ( SUPPORT_POINTER_EVENTS ) { Type = PointerEventInput ; } else if ( SUPPORT_ONLY_TOUCH ) { Type = TouchInput ; } else if ( ! SUPPORT_TOUCH ) { Type = MouseInput ; } else { Type = TouchMouseInput ; } return new Type ( manager , inputHandler ) ; }

create new input type manager
called by the Manager constructor
@param {Hammer} manager
@returns {Input}


function inputHandler(manager, eventType, input) {
        var pointersLen = input.pointers.length;
        var changedPointersLen = input.changedPointers.length;
        var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
        var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;

        input.isFirst = !!isFirst;
        input.isFinal = !!isFinal;

        if (isFirst) {
            manager.session = {};
        }

        // source event is the normalized value of the domEvents
        // like 'touchstart, mouseup, pointerdown'
        input.eventType = eventType;

        // compute scale, rotation etc
        computeInputData(manager, input);

        // emit secret event
        manager.emit('hammer.input', input);

        manager.recognize(input);
        manager.session.prevInput = input;
    }

handle input events
@param {Manager} manager
@param {String} eventType
@param {Object} input


function computeInputData(manager, input) {
        var session = manager.session;
        var pointers = input.pointers;
        var pointersLength = pointers.length;

        // store the first input to calculate the distance and direction
        if (!session.firstInput) {
            session.firstInput = simpleCloneInputData(input);
        }

        // to compute scale and rotation we need to store the multiple touches
        if (pointersLength > 1 && !session.firstMultiple) {
            session.firstMultiple = simpleCloneInputData(input);
        } else if (pointersLength === 1) {
            session.firstMultiple = false;
        }

        var firstInput = session.firstInput;
        var firstMultiple = session.firstMultiple;
        var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;

        var center = input.center = getCenter(pointers);
        input.timeStamp = now();
        input.deltaTime = input.timeStamp - firstInput.timeStamp;

        input.angle = getAngle(offsetCenter, center);
        input.distance = getDistance(offsetCenter, center);

        computeDeltaXY(session, input);
        input.offsetDirection = getDirection(input.deltaX, input.deltaY);

        var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
        input.overallVelocityX = overallVelocity.x;
        input.overallVelocityY = overallVelocity.y;
        input.overallVelocity = abs(overallVelocity.x) > abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y;

        input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
        input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;

        input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers;

        computeIntervalInputData(session, input);

        // find the correct target
        var target = manager.element;
        if (hasParent(input.srcEvent.target, target)) {
            target = input.srcEvent.target;
        }
        input.target = target;
    }

extend the data with some usable properties like scale, rotate, velocity etc
@param {Object} manager
@param {Object} input

extend the data with some usable properties like scale rotate velocity etc


function TMEhandler(manager, inputEvent, inputData) {
            var isTouch = inputData.pointerType == INPUT_TYPE_TOUCH,
                isMouse = inputData.pointerType == INPUT_TYPE_MOUSE;

            if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
                return;
            }

            // when we're in a touch event, record touches to  de-dupe synthetic mouse event
            if (isTouch) {
                recordTouches.call(this, inputEvent, inputData);
            } else if (isMouse && isSyntheticEvent.call(this, inputData)) {
                return;
            }

            this.callback(manager, inputEvent, inputData);
        }

handle mouse and touch events
@param {Hammer} manager
@param {String} inputEvent
@param {Object} inputData


function (input) {
            var srcEvent = input.srcEvent;
            var direction = input.offsetDirection;

            // if the touch action did prevented once this session
            if (this.manager.session.prevented) {
                srcEvent.preventDefault();
                return;
            }

            var actions = this.actions;
            var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
            var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
            var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];

            if (hasNone) {
                //do not prevent defaults if this is a tap gesture

                var isTapPointer = input.pointers.length === 1;
                var isTapMovement = input.distance < 2;
                var isTapTouchTime = input.deltaTime < 250;

                if (isTapPointer && isTapMovement && isTapTouchTime) {
                    return;
                }
            }

            if (hasPanX && hasPanY) {
                // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
                return;
            }

            if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
                return this.preventSrc(srcEvent);
            }
        }

this method is called on each input cycle and provides the preventing of the browser behavior
@param {Object} input