function (res) {
        var bundle = this._bundles[res.bundleName],
            type = res.type,
            subtype,
            selector = res.selector,
            name = res.name;

        if (!bundle.resources[selector]) {
            bundle.resources[selector] = {};
        }
        if (!bundle.resources[selector][type]) {
            bundle.resources[selector][type] = {};
        }
        if (res.hasOwnProperty('subtype')) {
            subtype = res.subtype;
            if (!bundle.resources[selector][type][subtype]) {
                bundle.resources[selector][type][subtype] = {};
            }
            bundle.resources[selector][type][subtype][name] = res;
        } else {
            bundle.resources[selector][type][name] = res;
        }
    }

function ( res ) { var bundle = this . _bundles [ res . bundleName ] , type = res . type , subtype , selector = res . selector , name = res . name ; if ( ! bundle . resources [ selector ] ) { bundle . resources [ selector ] = { } ; } if ( ! bundle . resources [ selector ] [ type ] ) { bundle . resources [ selector ] [ type ] = { } ; } if ( res . hasOwnProperty ( 'subtype' ) ) { subtype = res . subtype ; if ( ! bundle . resources [ selector ] [ type ] [ subtype ] ) { bundle . resources [ selector ] [ type ] [ subtype ] = { } ; } bundle . resources [ selector ] [ type ] [ subtype ] [ name ] = res ; } else { bundle . resources [ selector ] [ type ] [ name ] = res ; } }

Handles the resource.
@private
@method _onResource
@param {object} res The resource.


function (res, filter) {
        if (!filter || Object.keys(filter).length === 0) {
            return true;
        }
        var prop;
        for (prop in filter) {
            if ('extensions' === prop) {
                // sugar for users
                if ('string' === typeof filter.extensions) {
                    filter.extensions = filter.extensions.split(',');
                }
                if (!filter.extensions || filter.extensions.indexOf(res.ext) === -1) {
                    return false;
                }
            } else if ('types' === prop) {
                // sugar for users
                if ('string' === typeof filter.types) {
                    filter.types = filter.types.split(',');
                }
                if (!filter.types || filter.types.indexOf(res.type) === -1) {
                    return false;
                }
            } else {
                return false; // unknown filters should fail to pass
            }
        }
        return true;
    }

function ( res , filter ) { if ( ! filter || Object . keys ( filter ) . length === 0 ) { return true ; } var prop ; for ( prop in filter ) { if ( 'extensions' === prop ) { if ( 'string' === typeof filter . extensions ) { filter . extensions = filter . extensions . split ( ',' ) ; } if ( ! filter . extensions || filter . extensions . indexOf ( res . ext ) === - 1 ) { return false ; } } else if ( 'types' === prop ) { if ( 'string' === typeof filter . types ) { filter . types = filter . types . split ( ',' ) ; } if ( ! filter . types || filter . types . indexOf ( res . type ) === - 1 ) { return false ; } } else { return false ; } } return true ; }

Determines whether a resource is filtered or not.
@private
@method _filterResource
@param {LocatorResource} res The resource to filter.
@param {object} filter The filter.
@return {boolean} Whether resource passes the filter.

Determines whether a resource is filtered or not .


function (pkgDepths) {
        // pkgDepths -> depth: [metas]
        var depths,
            minDepth,
            maxDepth,
            seeds;
        depths = Object.keys(pkgDepths);
        minDepth = Math.min.apply(Math, depths);
        maxDepth = Math.max.apply(Math, depths);
        seeds = pkgDepths[minDepth];
        if (1 === seeds.length) {
            if (minDepth !== maxDepth) {
                debug('multiple "' + seeds[0].name + '" packages found, using version ' +
                    seeds[0].version + ' from ' + seeds[0].baseDirectory);
            }
            return seeds[0];
        }
        seeds.sort(function (a, b) {
            return libsemver.rcompare(a.version, b.version);
        });
        debug('multiple "' + seeds[0].name + '" packages found, using version ' +
            seeds[0].version + ' from ' + seeds[0].baseDirectory);
        return seeds[0];
    }

function
(
pkgDepths
)
{
var
depths
,
minDepth
,
maxDepth
,
seeds
;
depths
=
Object
.
keys
(
pkgDepths
)
;
minDepth
=
Math
.
min
.
apply
(
Math
,
depths
)
;
maxDepth
=
Math
.
max
.
apply
(
Math
,
depths
)
;
seeds
=
pkgDepths
[
minDepth
]
;
if
(
1
===
seeds
.
length
)
{
if
(
minDepth
!==
maxDepth
)
{
debug
(
'multiple "'
+
seeds
[
0
]
.
name
+
'" packages found, using version '
+
seeds
[
0
]
.
version
+
' from '
+
seeds
[
0
]
.
baseDirectory
)
;
}
return
seeds
[
0
]
;
}
seeds
.
sort
(
function
(
a
,
b
)
{
return
libsemver
.
rcompare
(
a
.
version
,
b
.
version
)
;
}
)
;
debug
(
'multiple "'
+
seeds
[
0
]
.
name
+
'" packages found, using version '
+
seeds
[
0
]
.
version
+
' from '
+
seeds
[
0
]
.
baseDirectory
)
;
return
seeds
[
0
]
;
}

Figures out which seed to use from the list of available packages.
Select by depth, then by semver.
@private
@method _dedupeSeeds
@param {object} pkgDepths List of seed by deep.
@return {object} The metas of the selected package.

Figures out which seed to use from the list of available packages . Select by depth then by semver .


function (all) {
        var byDepth = {}; // name: depth: [metas]
        all.forEach(function (seed) {
            if (!byDepth[seed.name]) {
                byDepth[seed.name] = {};
            }
            if (!byDepth[seed.name][seed.npmDepth]) {
                byDepth[seed.name][seed.npmDepth] = [];
            }
            byDepth[seed.name][seed.npmDepth].push(seed);
        });
        return Object.keys(byDepth).map(function (name) {
            return this._dedupeSeeds(byDepth[name]);
        }, this);
    }

function ( all ) { var byDepth = { } ; all . forEach ( function ( seed ) { if ( ! byDepth [ seed . name ] ) { byDepth [ seed . name ] = { } ; } if ( ! byDepth [ seed . name ] [ seed . npmDepth ] ) { byDepth [ seed . name ] [ seed . npmDepth ] = [ ] ; } byDepth [ seed . name ] [ seed . npmDepth ] . push ( seed ) ; } ) ; return Object . keys ( byDepth ) . map ( function ( name ) { return this . _dedupeSeeds ( byDepth [ name ] ) ; } , this ) ; }

Figures out which bundles to use from the list.
The returned list is sorted first by NPM package depth then by name.
@private
@method _filterBundleSeeds
@param {array} all List of all bundle seeds from NPM packages.
@return {array} The metas of the packages to actually use.

Figures out which bundles to use from the list . The returned list is sorted first by NPM package depth then by name .


function (bundleSeed) {
        var self = this,
            parentName,
            parent,
            bundle,
            filters;
        // TODO -- merge options (second arg) over bundleSeed.options

        parentName = this._getBundleNameByPath(libpath.dirname(bundleSeed.baseDirectory));
        parent = this._bundles[parentName];

        bundle = this._makeBundle(bundleSeed, parent);
        this._bundles[bundle.name] = bundle;
        filters = this._options.exclude.concat(['node_modules', /^\./]);
        // adding the bundle dir itself for BC
        this._processFile(bundle.baseDirectory);
        walk.walkSync(bundle.baseDirectory, {
            filters: [],
            listeners: {
                directories: function (root, dirStatsArray, next) {
                    var i, dirStats, exclude;
                    function filterDir(filter) {
                        if (dirStats.name.match(filter)) {
                            return true;
                        }
                    }
                    for (i = dirStatsArray.length - 1; i >= 0; i -= 1) {
                        dirStats = dirStatsArray[i];
                        exclude = filters.some(filterDir);
                        if (exclude) {
                            // the sync walk api is pretty bad, it requires to
                            // mutate the actual dir array
                            dirStatsArray.splice(i, 1);
                        } else {
                            self._processFile(libpath.join(root, dirStats.name));
                        }
                    }
                    next();
                },
                file: function(root, fileStats, next) {
                    self._processFile(libpath.join(root, fileStats.name));
                    next();
                },
                errors: function(root, nodeStatsArray, next) {
                    next();
                }
            }
        });

        return bundle;
    }

function ( bundleSeed ) { var self = this , parentName , parent , bundle , filters ; parentName = this . _getBundleNameByPath ( libpath . dirname ( bundleSeed . baseDirectory ) ) ; parent = this . _bundles [ parentName ] ; bundle = this . _makeBundle ( bundleSeed , parent ) ; this . _bundles [ bundle . name ] = bundle ; filters = this . _options . exclude . concat ( [ 'node_modules' , / ^\. / ] ) ; this . _processFile ( bundle . baseDirectory ) ; walk . walkSync ( bundle . baseDirectory , { filters : [ ] , listeners : { directories : function ( root , dirStatsArray , next ) { var i , dirStats , exclude ; function filterDir ( filter ) { if ( dirStats . name . match ( filter ) ) { return true ; } } for ( i = dirStatsArray . length - 1 ; i >= 0 ; i -= 1 ) { dirStats = dirStatsArray [ i ] ; exclude = filters . some ( filterDir ) ; if ( exclude ) { dirStatsArray . splice ( i , 1 ) ; } else { self . _processFile ( libpath . join ( root , dirStats . name ) ) ; } } next ( ) ; } , file : function ( root , fileStats , next ) { self . _processFile ( libpath . join ( root , fileStats . name ) ) ; next ( ) ; } , errors : function ( root , nodeStatsArray , next ) { next ( ) ; } } } ) ; return bundle ; }

Creates a bundle from an NPM package, and queues up files in the package.
@private
@method _walkBundle
@param {object} bundleSeed Metadata about the package. See the docs for _makeBundleSeed()
for format of this metadata.
@return {Bundle} The bundle made from the NPM package.

Creates a bundle from an NPM package and queues up files in the package .


function (srcObject, excludeKeys) {
        var destObject = {},
            key;
        for (key in srcObject) {
            if (srcObject.hasOwnProperty(key)) {
                if (-1 === excludeKeys.indexOf(key)) {
                    destObject[key] = srcObject[key];
                }
            }
        }
        return destObject;
    }

function ( srcObject , excludeKeys ) { var destObject = { } , key ; for ( key in srcObject ) { if ( srcObject . hasOwnProperty ( key ) ) { if ( - 1 === excludeKeys . indexOf ( key ) ) { destObject [ key ] = srcObject [ key ] ; } } } return destObject ; }

Creates a new object with the certain keys excluded.
This is used instead of "delete" since that has performance implications in V8.
@private
@method _objectExclude
@param {object} srcObject The original object.
@param {array} excludeKeys The keys to exclude from the results.
@return {object} A version of the original object with the keys excluded.

Creates a new object with the certain keys excluded . This is used instead of delete since that has performance implications in V8 .


function Bundle(baseDirectory, options) {
    this.options = options || {};
    this.name = libpath.basename(baseDirectory);
    this.baseDirectory = baseDirectory;
    this.type = undefined;
    this.files = {};
    this.resources = {};
}

function Bundle ( baseDirectory , options ) { this . options = options || { } ; this . name = libpath . basename ( baseDirectory ) ; this . baseDirectory = baseDirectory ; this . type = undefined ; this . files = { } ; this . resources = { } ; }

The Locator walks the filesystem and gives semantic meaning to
files in the application.
@module ModownLocator

@class Bundle
@constructor
@param {string} baseDirectory Directory in which a bundle is rooted.
@param {object} options Options for how the configuration files are handled.

The Locator walks the filesystem and gives semantic meaning to files in the application .


function getBaseScales(type, domain, range, nice, tickCount) {
  const factory = (type === 'time' && scaleUtc) || (type === 'log' && scaleLog) || scaleLinear
  const scale = createScale(factory, domain, range)
  if (nice) scale.nice(tickCount)
  return scale
}

function getBaseScales ( type , domain , range , nice , tickCount ) { const factory = ( type === 'time' && scaleUtc ) || ( type === 'log' && scaleLog ) || scaleLinear const scale = createScale ( factory , domain , range ) if ( nice ) scale . nice ( tickCount ) return scale }

get a scale with logic for the x and y axis, if the domain starts and finishes on the same number returns the mid range value

get a scale with logic for the x and y axis if the domain starts and finishes on the same number returns the mid range value


function BufferingTracer(tracer, options) {
  options = options || {};

  var self = this;

  this._tracer = tracer;
  this._maxTraces = options.maxTraces || 50;
  this._sendInterval = options.sendInterval ? (options.sendInterval * 1000) : 10 * 1000;
  this._lastSentTs = Date.now();
  this._buffer = [];
  this._stopped = false;

  this._periodSendTimeoutId = setTimeout(this._periodicSendFunction.bind(this),
                                         this._sendInterval);
}

function BufferingTracer ( tracer , options ) { options = options || { } ; var self = this ; this . _tracer = tracer ; this . _maxTraces = options . maxTraces || 50 ; this . _sendInterval = options . sendInterval ? ( options . sendInterval * 1000 ) : 10 * 1000 ; this . _lastSentTs = Date . now ( ) ; this . _buffer = [ ] ; this . _stopped = false ; this . _periodSendTimeoutId = setTimeout ( this . _periodicSendFunction . bind ( this ) , this . _sendInterval ) ; }

Buffer traces and defer recording until maxTraces have been received or
sendInterval has elapsed since the last trace was recorded.

@param {Tracer} tracer Tracer provider to record buffered tracers to.
@param {Options} options Options object with the following keys:
- maxTraces - Number of traces to buffer before recording occurs (default:
50).
- sendInterval - An average number of seconds which can pass after the last
trace has been sent to the backend before sending all the buffered traces
to the backend again (default: 10).

Buffer traces and defer recording until maxTraces have been received or sendInterval has elapsed since the last trace was recorded .


function build(gulp) {
    // make sure we don't lose anything from required files
    // @see https://github.com/Mikhus/gulp-help-doc/issues/2
    // currently this is not supported for typescript

    var source = OPTIONS.isTypescript ?
        fs.readFileSync('gulpfile.ts').toString() :
        OPTIONS.gulpfile ?
            fs.readFileSync(OPTIONS.gulpfile).toString() :
        Object.keys(require.cache || {'gulpfile.js': ''}).map(function(file) {
            if (!/node_modules|\.json$/.test(file)) {
                return fs.readFileSync(file).toString() + '\n';
            }
        }).join('');

    var rxDoc = '\\/\\*\\*\\r?\n(((?!\\*\\/)[\\s\\S])*?)' +
        '@task\\s+\\{(.*)?\\}((?!\\*\\/)[\\s\\S])*?\\*\\/';

    var rxArgs = '@arg\\s+\\{(.*?)\\}(.*?)\\r?\\n';
    var rxOrder = '@order\\s+\\{(\\d+)\\}(.*?)\\r?\\n';
    var rxGroup = '@group\\s+\\{(.*?)\\}(.*?)\\r?\\n';

    var globalRxDoc = new RegExp(rxDoc, 'g');
    var localRxDoc = new RegExp(rxDoc);

    var globalRxArgs = new RegExp(rxArgs, 'g');
    var localRxArgs = new RegExp(rxArgs);

    var globalRxOrder = new RegExp(rxOrder, 'g');
    var localRxOrder = new RegExp(rxOrder);

    var globalRxGroup = new RegExp(rxGroup, 'g');
    var localRxGroup = new RegExp(rxGroup);

    var jsDoc  = (source.match(globalRxDoc) || []);
    var tasks = gulpTasks(gulp);

    Object.keys(tasks).forEach(function (task) {
        reflection[task] = {
            name: tasks[task].name,
            desc: '',
            dep: tasks[task].dep
        };
    });

    jsDoc.map(function (block) {
        var parts = block.match(localRxDoc);

        var name = parts[3].trim();
        var desc = parts[1].replace(/\s*\*/g, ' ')
            .replace(/\s{2,}/g, ' ')
            .trim();

        if (!reflection[name]) {
            return;
        }

        reflection[name].desc = desc;
        reflection[name].public = true;
        reflection[name].args = (block.match(globalRxArgs) || [])
            .map(function (def) {
                var argsParts = def.match(localRxArgs);

                return {
                    name: argsParts[1],
                    desc: argsParts[2].replace(/\s*\*/g, ' ')
                        .replace(/\s{2,}/g, ' ')
                        .trim()
                };
            });

        reflection[name].order = (function () {
            var orderParts = block.match(globalRxOrder);

            if (orderParts) {
                return +orderParts[0].match(localRxOrder)[1];
            }

            return Number.MAX_SAFE_INTEGER;
        })();

        reflection[name].group = (function () {
            var groupParts = block.match(globalRxGroup);

            if (groupParts) {
                return groupParts[0].match(localRxGroup)[1];
            }

            return OPTIONS.defaultGroupName;
        })();
    });

    // Re-group tasks using user-defined groups
    var tmp = {};

    Object.keys(reflection).forEach(function(task) {
        var group = reflection[task].group || OPTIONS.defaultGroupName;

        tmp[group] = tmp[group] || {};
        tmp[group][task] = reflection[task];
    });

    reflection = tmp;
}

Analyzes given gulp instance and build internal cache
for further printing

@param {Gulp} gulp
@access private


function chunk(str, maxLen) {
    var len  = maxLen || OPTIONS.lineWidth;
    var curr = len;
    var prev = 0;
    var out  = [];

    while (str[curr]) {
        if (str[curr++] == ' ') {
            out.push(str.substring(prev, curr));
            prev = curr;
            curr += len;
        }
    }

    out.push(str.substr(prev));

    return out;
}

function
chunk
(
str
,
maxLen
)
{
var
len
=
maxLen
||
OPTIONS
.
lineWidth
;
var
curr
=
len
;
var
prev
=
0
;
var
out
=
[
]
;
while
(
str
[
curr
]
)
{
if
(
str
[
curr
++
]
==
' '
)
{
out
.
push
(
str
.
substring
(
prev
,
curr
)
)
;
prev
=
curr
;
curr
+=
len
;
}
}
out
.
push
(
str
.
substr
(
prev
)
)
;
return
out
;
}

Chunks given string into pieces making each chunk less or equal to
OPTIONS.lineWidth, taking into account safe word-break

@param {string} str
@param {number} maxLen
@returns {Array}
@access private

Chunks given string into pieces making each chunk less or equal to OPTIONS . lineWidth taking into account safe word - break


function usage(gulp, options) {
    // re-define options if needed
    if (options) {
        Object.assign(OPTIONS, options);
    }

    return new Promise(function(resolve) {
        build(gulp);
        print();
        resolve();
    });
}

function usage ( gulp , options ) { if ( options ) { Object . assign ( OPTIONS , options ) ; } return new Promise ( function ( resolve ) { build ( gulp ) ; print ( ) ; resolve ( ) ; } ) ; }

Prints usage help information for the given gulp
instance.
Usually it is used as a task within gulpfile.js in your project
Please make sure all your comments are properly annotated

@examples
<caption>Typical usage:</caption>
var gulp = require('gulp');

gulp.task('help', => require('gulp-help-doc')(gulp));

@param {Gulp} gulp - gulp instance to analyze
@param {ConfigOptions} [options]
@returns {Promise}
@access public

Prints usage help information for the given gulp instance . Usually it is used as a task within gulpfile . js in your project Please make sure all your comments are properly annotated


function filterArray (arr, toKeep) {
  var i = 0
  while (i < arr.length) {
    if (toKeep(arr[i])) {
      i++
    } else {
      arr.splice(i, 1)
    }
  }
}

function filterArray ( arr , toKeep ) { var i = 0 while ( i < arr . length ) { if ( toKeep ( arr [ i ] ) ) { i ++ } else { arr . splice ( i , 1 ) } } }

a filter implementation that mutates the original array


function cssExtract (bundle, opts) {
  opts = opts || {}

  var outFile = opts.out || opts.o || 'bundle.css'
  var sourceMap = d(opts.sourceMap, bundle && bundle._options && bundle._options.debug, false)

  assert.equal(typeof bundle, 'object', 'bundle should be an object')
  assert.equal(typeof opts, 'object', 'opts should be an object')

  // every time .bundle is called, attach hook
  bundle.on('reset', addHooks)
  addHooks()

  function addHooks () {
    const extractStream = through.obj(write, flush)
    const writeStream = (typeof outFile === 'function')
      ? outFile()
      : bl(writeComplete)

    // run before the "label" step in browserify pipeline
    bundle.pipeline.get('label').unshift(extractStream)

    function write (chunk, enc, cb) {
      // Performance boost: don't do ast parsing unless we know it's needed
      if (!/(insert-css|sheetify\/insert)/.test(chunk.source)) {
        return cb(null, chunk)
      }

      var source = from2(chunk.source)
      var sm = staticModule({
        'insert-css': function (src) {
          writeStream.write(String(src) + '\n')
          return from2('null')
        },
        'sheetify/insert': function (src) {
          writeStream.write(String(src) + '\n')
          return from2('null')
        }
      }, { sourceMap: sourceMap })

      source.pipe(sm).pipe(bl(complete))

      function complete (err, source) {
        if (err) return extractStream.emit('error', err)
        chunk.source = String(source)
        cb(null, chunk)
      }
    }

    // close stream and signal end
    function flush (cb) {
      writeStream.end()
      cb()
    }

    function writeComplete (err, buffer) {
      if (err) return extractStream.emit('error', err)
      fs.writeFileSync(outFile, buffer)
    }
  }
}

function
cssExtract
(
bundle
,
opts
)
{
opts
=
opts
||
{
}
var
outFile
=
opts
.
out
||
opts
.
o
||
'bundle.css'
var
sourceMap
=
d
(
opts
.
sourceMap
,
bundle
&&
bundle
.
_options
&&
bundle
.
_options
.
debug
,
false
)
assert
.
equal
(
typeof
bundle
,
'object'
,
'bundle should be an object'
)
assert
.
equal
(
typeof
opts
,
'object'
,
'opts should be an object'
)
bundle
.
on
(
'reset'
,
addHooks
)
addHooks
(
)
function
addHooks
(
)
{
const
extractStream
=
through
.
obj
(
write
,
flush
)
const
writeStream
=
(
typeof
outFile
===
'function'
)
outFile
(
)
:
bl
(
writeComplete
)
bundle
.
pipeline
.
get
(
'label'
)
.
unshift
(
extractStream
)
function
write
(
chunk
,
enc
,
cb
)
{
if
(
!
/
(insert-css|sheetify\/insert)
/
.
test
(
chunk
.
source
)
)
{
return
cb
(
,
chunk
)
}
var
source
=
from2
(
chunk
.
source
)
var
sm
=
staticModule
(
{
'insert-css'
:
function
(
src
)
{
writeStream
.
write
(
String
(
src
)
+
'\n'
)
\n
}
,
return
from2
(
'null'
)
}
,
'sheetify/insert'
:
function
(
src
)
{
writeStream
.
write
(
String
(
src
)
+
'\n'
)
\n
}
)
return
from2
(
'null'
)
{
sourceMap
:
sourceMap
}
}
source
.
pipe
(
sm
)
.
pipe
(
bl
(
complete
)
)
function
complete
(
err
,
source
)
{
if
(
err
)
return
extractStream
.
emit
(
'error'
,
err
)
chunk
.
source
=
String
(
source
)
cb
(
,
chunk
)
}
}
}

Extract CSS from a browserify bundle obj -> null

Extract CSS from a browserify bundle obj - > null


function validatePlaceholders(
  { id, idPlural, translations },
  validationErrors
) {
  // search for {{placeholderName}}
  // Also search for e.g. Chinese symbols in the placeholderName
  let pattern = /{{\s*(\S+?)\s*?}}/g;
  let placeholders = id.match(pattern) || [];

  // We also want to add placeholders from the plural string
  if (idPlural) {
    let pluralPlaceholders = idPlural.match(pattern) || [];
    pluralPlaceholders.forEach((placeholder) => {
      if (!placeholders.includes(placeholder)) {
        placeholders.push(placeholder);
      }
    });
  }

  if (!placeholders.length) {
    return;
  }

  translations.forEach((translation) => {
    let translatedPlaceholders = translation.match(pattern) || [];

    // Search for placeholders in the translated string that are not in the original string
    let invalidPlaceholder = translatedPlaceholders.find(
      (placeholder) => !placeholders.includes(placeholder)
    );
    if (invalidPlaceholder) {
      validationErrors.push({
        id,
        translation,
        message: `The placeholder "${invalidPlaceholder}" seems to be wrongly translated. Allowed: ${placeholders.join(
          ', '
        )}`,
        level: 'ERROR'
      });
    }
  });
}

function
validatePlaceholders
(
{
id
,
idPlural
,
translations
}
,
validationErrors
)
{
let
pattern
=
/
{{\s*(\S+?)\s*?}}
/
g
;
let
placeholders
=
id
.
match
(
pattern
)
||
[
]
;
if
(
idPlural
)
{
let
pluralPlaceholders
=
idPlural
.
match
(
pattern
)
||
[
]
;
pluralPlaceholders
.
forEach
(
(
placeholder
)
=>
{
if
(
!
placeholders
.
includes
(
placeholder
)
)
{
placeholders
.
push
(
placeholder
)
;
}
}
)
;
}
if
(
!
placeholders
.
length
)
{
return
;
}
translations
.
forEach
(
(
translation
)
=>
{
let
translatedPlaceholders
=
translation
.
match
(
pattern
)
||
[
]
;
let
invalidPlaceholder
=
translatedPlaceholders
.
find
(
(
placeholder
)
=>
!
placeholders
.
includes
(
placeholder
)
)
;
if
(
invalidPlaceholder
)
{
validationErrors
.
push
(
{
id
,
translation
,
message
:
`
${
invalidPlaceholder
}
${
placeholders
.
join
(
', '
)
}
`
,
level
:
'ERROR'
}
)
;
}
}
)
;
}

Validate the regular placeholders of an item.
This possibly modifies the given validationErrors.

@method _validatePlaceholder
@param {String} id
@param {String} idPlural
@param {String[]} translations
@private

Validate the regular placeholders of an item . This possibly modifies the given validationErrors .


function groupGettextItems(gettextItems) {
  return gettextItems
    .filter((item) => item.messageId) // filter out items without message id
    .sort((item1, item2) => {
      return (
        item1.loc.fileName.localeCompare(item2.loc.fileName) ||
        item1.loc.line - item2.loc.line
      );
    })
    .reduce((allGroups, item) => {
      let group = allGroups.find((group) => {
        return (
          group.messageId === item.messageId &&
          group.messageContext === item.messageContext
        );
      });

      if (group) {
        group.locs.push(item.loc);

        // Although it is an edge case, it is possible for two translations to have the same messageID
        // while only one of them has a plural
        // For example: {{t 'Find item'}} {{n 'Find item' 'Find items' count}}
        // For such a case, we make sure to also add the plural, if it was previously missing
        if (!group.messageIdPlural && item.messageIdPlural) {
          group.messageIdPlural = item.messageIdPlural;
        }
      } else {
        group = Object.assign({}, item);
        group.locs = [item.loc];
        delete group.loc;
        allGroups.push(group);
      }

      return allGroups;
    }, []);
}

function groupGettextItems ( gettextItems ) { return gettextItems . filter ( ( item ) => item . messageId ) . sort ( ( item1 , item2 ) => { return ( item1 . loc . fileName . localeCompare ( item2 . loc . fileName ) || item1 . loc . line - item2 . loc . line ) ; } ) . reduce ( ( allGroups , item ) => { let group = allGroups . find ( ( group ) => { return ( group . messageId === item . messageId && group . messageContext === item . messageContext ) ; } ) ; if ( group ) { group . locs . push ( item . loc ) ; if ( ! group . messageIdPlural && item . messageIdPlural ) { group . messageIdPlural = item . messageIdPlural ; } } else { group = Object . assign ( { } , item ) ; group . locs = [ item . loc ] ; delete group . loc ; allGroups . push ( group ) ; } return allGroups ; } , [ ] ) ; }

Group equal entries together The generated groups look like the given gettextItems, only that they have `locs` instead of `loc` Where `locs` is an array of `loc` entries, having a `fileName`, `line` and `column`.

Group equal entries together The generated groups look like the given gettextItems only that they have locs instead of loc Where locs is an array of loc entries having a fileName line and column .


function traverseJson(json, callback) {
  let { translations } = json;

  Object.keys(translations).forEach((namespace) => {
    Object.keys(translations[namespace]).forEach((k) => {
      callback(translations[namespace][k], translations[namespace], k);
    });
  });
}

function traverseJson ( json , callback ) { let { translations } = json ; Object . keys ( translations ) . forEach ( ( namespace ) => { Object . keys ( translations [ namespace ] ) . forEach ( ( k ) => { callback ( translations [ namespace ] [ k ] , translations [ namespace ] , k ) ; } ) ; } ) ; }

This will traverse an l10n-JSON file, and call the callback function for each translation item.

For example:

```js
traverseJson(json, (item) => delete item.comment);
```

@method traverseJson
@param {Object} json
@param {Function} callback
@public

This will traverse an l10n - JSON file and call the callback function for each translation item .


function findAllDependencies(file, knownDependencies, sourceDirectories, knownFiles) {
  if (!knownDependencies) {
    knownDependencies = [];
  }

  if (typeof knownFiles === "undefined"){
    knownFiles = [];
  } else if (knownFiles.indexOf(file) > -1){
    return knownDependencies;
  }

  if (sourceDirectories) {
    return findAllDependenciesHelp(file, knownDependencies, sourceDirectories, knownFiles).then(function(thing){
      return thing.knownDependencies;
    });
  } else {
    return getBaseDir(file)
      .then(getElmPackageSourceDirectories)
      .then(function(newSourceDirs) {
        return findAllDependenciesHelp(file, knownDependencies, newSourceDirs, knownFiles).then(function(thing){
          return thing.knownDependencies;
        });
      });
  }
}

function findAllDependencies ( file , knownDependencies , sourceDirectories , knownFiles ) { if ( ! knownDependencies ) { knownDependencies = [ ] ; } if ( typeof knownFiles === "undefined" ) { knownFiles = [ ] ; } else if ( knownFiles . indexOf ( file ) > - 1 ) { return knownDependencies ; } if ( sourceDirectories ) { return findAllDependenciesHelp ( file , knownDependencies , sourceDirectories , knownFiles ) . then ( function ( thing ) { return thing . knownDependencies ; } ) ; } else { return getBaseDir ( file ) . then ( getElmPackageSourceDirectories ) . then ( function ( newSourceDirs ) { return findAllDependenciesHelp ( file , knownDependencies , newSourceDirs , knownFiles ) . then ( function ( thing ) { return thing . knownDependencies ; } ) ; } ) ; } }

Returns a Promise that returns a flat list of all the Elm files the given Elm file depends on, based on the modules it loads via `import`.

Returns a Promise that returns a flat list of all the Elm files the given Elm file depends on based on the modules it loads via import .


function parse(query) {
        if (query[0] == "?") query = query.slice(1);
        var pairs = query.split("&"),
            obj = {};

        for (var i in pairs) {
            var pair = pairs[i].split("="),
                key = decodeURIComponent(pair[0]),
                value = pair[1] ? decodeURIComponent(pair[1]) : "";

            obj[key] = value;
        }

        return obj;
    }

function parse ( query ) { if ( query [ 0 ] == "?" ) query = query . slice ( 1 ) ; var pairs = query . split ( "&" ) , obj = { } ; for ( var i in pairs ) { var pair = pairs [ i ] . split ( "=" ) , key = decodeURIComponent ( pair [ 0 ] ) , value = pair [ 1 ] ? decodeURIComponent ( pair [ 1 ] ) : "" ; obj [ key ] = value ; } return obj ; }

Parses URL query string.
@param {string} query
@returns {object}


function stringify(obj) {
        var arr = [];
        for (var x in obj) {
            arr.push(encodeURIComponent(x) + "=" + encodeURIComponent(obj[x]));
        }
        return arr.join("&");
    }

function stringify ( obj ) { var arr = [ ] ; for ( var x in obj ) { arr . push ( encodeURIComponent ( x ) + "=" + encodeURIComponent ( obj [ x ] ) ) ; } return arr . join ( "&" ) ; }

Stringifies an object to a URL query string.
@param {object} obj
@returns {string}

Stringifies an object to a URL query string .


function _compileAny(any, options){
    // Array
    if (oj.isArray(any))
      _compileTag(any, options)

    // String
    else if (oj.isString(any)){
      if (options.html != null)
        options.html.push(any)

      if (any.length > 0 && any[0] === '<'){
        var root = document.createElement('div')
        root.innerHTML = any
        if (options.dom != null)
          options.dom.appendChild(root)
      } else {
        if (options.dom != null)
          options.dom.appendChild(document.createTextNode(any))
      }

    // Boolean or Number
    } else if (oj.isBoolean(any) || oj.isNumber(any)){
      if (options.html != null)
        options.html.push("" + any)

      if (options.dom != null)
        options.dom.appendChild(document.createTextNode("" + any))

    // Function
    } else if (oj.isFunction(any)){

      // Wrap function call to allow full oj generation within any
      _compileAny(oj(any), options)

    // Date
    } else if (oj.isDate(any)){
      if (options.html != null)
        options.html.push("" + (any.toLocaleString()))

      if (options.dom != null)
        options.dom.appendChild(document.createTextNode("" + (any.toLocaleString())))

    // OJ Type or Instance
    } else if (oj.isOJ(any)){
      if (options.types != null)
        options.types.push(any)

      if (options.html != null)
        options.html.push(any.toHTML(options))

      if (options.dom != null)
        options.dom.appendChild(any.toDOM(options))

      if (options.css != null)
        _extend(options.css, any.toCSSMap(options))
    }
    // Do nothing for: null, undefined, object
  }

function _compileAny ( any , options ) { if ( oj . isArray ( any ) ) _compileTag ( any , options ) else if ( oj . isString ( any ) ) { if ( options . html != null ) options . html . push ( any ) if ( any . length > 0 && any [ 0 ] === '<' ) { var root = document . createElement ( 'div' ) root . innerHTML = any if ( options . dom != null ) options . dom . appendChild ( root ) } else { if ( options . dom != null ) options . dom . appendChild ( document . createTextNode ( any ) ) } } else if ( oj . isBoolean ( any ) || oj . isNumber ( any ) ) { if ( options . html != null ) options . html . push ( "" + any ) if ( options . dom != null ) options . dom . appendChild ( document . createTextNode ( "" + any ) ) } else if ( oj . isFunction ( any ) ) { _compileAny ( oj ( any ) , options ) } else if ( oj . isDate ( any ) ) { if ( options . html != null ) options . html . push ( "" + ( any . toLocaleString ( ) ) ) if ( options . dom != null ) options . dom . appendChild ( document . createTextNode ( "" + ( any . toLocaleString ( ) ) ) ) } else if ( oj . isOJ ( any ) ) { if ( options . types != null ) options . types . push ( any ) if ( options . html != null ) options . html . push ( any . toHTML ( options ) ) if ( options . dom != null ) options . dom . appendChild ( any . toDOM ( options ) ) if ( options . css != null ) _extend ( options . css , any . toCSSMap ( options ) ) } }

_compileAny Recursive helper for compiling ojml or any type


function _attributesBindEventsToDOM(events, el, inserts){
    var ek, ev, _results = []
    for (ek in events){
      ev = events[ek]
      _a(oj.$ != null, "jquery is missing when binding a '" + ek + "' event")
      // accumulate insert events manually since DOMNodeInserted is slow and depreciated
      if (ek == 'insert' && inserts)
        inserts.push(function(){ev.call(el,el)})
      else if (oj.isArray(ev))
        _results.push(oj.$(el)[ek].apply(this, ev))
      else
        _results.push(oj.$(el)[ek](ev))
    }
    return _results
  }

function
_attributesBindEventsToDOM
(
events
,
el
,
inserts
)
{
var
ek
,
ev
,
_results
=
[
]
for
(
ek
in
events
)
{
ev
=
events
[
ek
]
_a
(
oj
.
$
!=
,
"jquery is missing when binding a '"
+
ek
+
"' event"
)
if
(
ek
==
'insert'
&&
inserts
)
inserts
.
push
(
function
(
)
{
ev
.
call
(
el
,
el
)
}
)
else
if
(
oj
.
isArray
(
ev
)
)
_results
.
push
(
oj
.
$
(
el
)
[
ek
]
.
apply
(
this
,
ev
)
)
else
_results
.
push
(
oj
.
$
(
el
)
[
ek
]
(
ev
)
)
}
return
_results
}


function(){
      _a(oj.isDOM(this.el), this.typeName, 'constructor did not set this.el')

      // Set instance on @el
      _setInstanceOnElement(this.el, this)

      var u = oj.unionArguments(arguments),
        options = u.options,
        args = u.args

      // Emit as a tag if it isn't quiet or used new keyword
      if (this.__autonew__ && !options.__quiet__)
        this.emit()

      // Remove quiet flag as it has served its purpose
      if (options.__quiet__ != null)
        delete options.__quiet__

      // Add class oj-typeName
      this.$el.addClass("oj-" + this.typeName)

      // Views automatically set all options to their properties
      // arguments directly to properties
      this.set(options)

      // Remove options that were set
      options = _clone(options)
      this.properties.forEach(function(v){return delete options[v]})

      // Views pass through remaining options to be attributes on the root element
      // This can include jquery events and interpreted arguments
      this.addAttributes(options)

      // Record if view is fully constructed
      return this._isConstructed = true
    }

function
(
)
{
_a
(
oj
.
isDOM
(
this
.
el
)
,
this
.
typeName
,
'constructor did not set this.el'
)
_setInstanceOnElement
(
this
.
el
,
this
)
var
u
=
oj
.
unionArguments
(
arguments
)
,
options
=
u
.
options
,
args
=
u
.
args
if
(
this
.
__autonew__
&&
!
options
.
__quiet__
)
this
.
emit
(
)
if
(
options
.
__quiet__
!=
)
delete
options
.
__quiet__
this
.
$el
.
addClass
(
"oj-"
+
this
.
typeName
)
this
.
set
(
options
)
options
=
_clone
(
options
)
this
.
properties
.
forEach
(
function
(
v
)
{
return
delete
options
[
v
]
}
)
this
.
addAttributes
(
options
)
return
this
.
_isConstructed
=
true
}

Views are special objects map properties together. This is a union of arguments With the remaining arguments becoming a list

Views are special objects map properties together . This is a union of arguments With the remaining arguments becoming a list


function($el, args){

      // No arguments return the first instance
      if (args.length === 0)
        return $el[0].oj

      // Compile ojml
      var r = oj.compile.apply(oj, [{dom: 1, html: 0, cssMap: 1 }].concat(slice.call(args)))

      _insertStyles(r.cssMap, {global: 0})

      // Reset content and append to dom
      $el.html('')

      // Ensure r.dom is an array
      if (!oj.isArray(r.dom))
        r.dom = [r.dom]

      // Append resulting dom elements
      for (var ix = 0; ix < r.dom.length; ix++)
        $el.append(r.dom[ix])

      // Trigger inserted events
      _triggerInserted(r.types, r.inserts)
    }

function ( $el , args ) { if ( args . length === 0 ) return $el [ 0 ] . oj var r = oj . compile . apply ( oj , [ { dom : 1 , html : 0 , cssMap : 1 } ] . concat ( slice . call ( args ) ) ) _insertStyles ( r . cssMap , { global : 0 } ) $el . html ( '' ) if ( ! oj . isArray ( r . dom ) ) r . dom = [ r . dom ] for ( var ix = 0 ; ix < r . dom . length ; ix ++ ) $el . append ( r . dom [ ix ] ) _triggerInserted ( r . types , r . inserts ) }


function _jqGetValue($el, args){
    var el = $el[0],
      child = el.firstChild

    // Return the instance if the element has an oj instance
    if (oj.isOJInstance(_getInstanceOnElement(el)))
      return _getInstanceOnElement(el)

    // Parse the text to turn it into bool, number, or string
    else if (oj.isDOMText(child))
      return oj.parse(child.nodeValue)

    // Return the first child otherwise as an oj instance or child element
    else if (oj.isDOMElement(child))
      return _d(_getInstanceOnElement(child), child)
  }

function _jqGetValue ( $el , args ) { var el = $el [ 0 ] , child = el . firstChild if ( oj . isOJInstance ( _getInstanceOnElement ( el ) ) ) return _getInstanceOnElement ( el ) else if ( oj . isDOMText ( child ) ) return oj . parse ( child . nodeValue ) else if ( oj . isDOMElement ( child ) ) return _d ( _getInstanceOnElement ( child ) , child ) }

Helper method that abstracts getting oj values


function(describe) {
		if (!Array.isArray(describe.m)) {
			return when.reject('no modules in describe message');
		}

		var allDeps = [];
		var modules = describe.m;

		for(var i=0;i<modules.length;i++) {
			var checkModule = modules[i];

			// don't look for dependencies of things that don't have dependencies.
			// they'll never cause safe mode as a result of their requirements,
			// and they're probably referenced by other things

			for(var d = 0; d < checkModule.d.length; d++) {
				var moduleNeeds = checkModule.d[d];

				// what things do we need that we don't have?
				var deps = this._walkChain(modules, moduleNeeds);
				if (deps && (deps.length > 0)) {
					allDeps = allDeps.concat(deps);
				}
			}
		}

		var keyFn = function(dep) {
			// todo - location should also be taken into account
			return [dep.f, dep.n, dep.v].join('_');
		};
		return utilities.dedupArray(allDeps, keyFn);
	}

function
(
describe
)
{
if
(
!
Array
.
isArray
(
describe
.
m
)
)
{
return
when
.
reject
(
'no modules in describe message'
)
;
}
var
allDeps
=
[
]
;
var
modules
=
describe
.
m
;
for
(
var
i
=
0
;
i
<
modules
.
length
;
i
++
)
{
var
checkModule
=
modules
[
i
]
;
for
(
var
d
=
0
;
d
<
checkModule
.
d
.
length
;
d
++
)
{
var
moduleNeeds
=
checkModule
.
d
[
d
]
;
var
deps
=
this
.
_walkChain
(
modules
,
moduleNeeds
)
;
if
(
deps
&&
(
deps
.
length
>
0
)
)
{
allDeps
=
allDeps
.
concat
(
deps
)
;
}
}
}
var
keyFn
=
function
(
dep
)
{
return
[
dep
.
f
,
dep
.
n
,
dep
.
v
]
.
join
(
'_'
)
;
}
;
return
utilities
.
dedupArray
(
allDeps
,
keyFn
)
;
}

tell us if anything with dependencies is missing something

(this covers scenarios where user app needs something else, or user app has no deps, and part 1 is old, but
part2 is current, etc.)  Built this because I hit this during testing.

in what order should we apply updates?
is it possible for us to get conflicting / out of order update recommendations?!

@param describe


async function main() {
  // Initialize the application.
  process.title = 'Coveralls.js';

  // Parse the command line arguments.
  program.name('coveralls')
    .description('Send a coverage report to the Coveralls service.')
    .version(packageVersion, '-v, --version')
    .arguments('<file>').action(file => program.file = file)
    .parse(process.argv);

  if (!program.file) {
    program.outputHelp();
    process.exitCode = 64;
    return null;
  }

  // Run the program.
  const client = new Client('COVERALLS_ENDPOINT' in process.env ? new URL(process.env.COVERALLS_ENDPOINT) : Client.defaultEndPoint);
  const coverage = await promises.readFile(program.file, 'utf8');
  console.log(`[Coveralls] Submitting to ${client.endPoint}`);
  return client.upload(coverage);
}

Application entry point.
@return {Promise<void>} Completes when the program is terminated.


function Shortline(options) {
  const self = this;

  self._input = (options && options.input) || process.stdin;
  self._output = (options && options.output) || process.stderr;

  /** Most recent error emitted by the input stream.
   * @type {Error}
   */
  self.inputError = null;
  self._input.on('end', () => {
    self.inputError = new EOFError(EOF_MESSAGE);
  });
  // Note:  Can't listen for 'error' since it changes behavior if there are no
  // other listeners.  Listen for it only when reading from input (since that
  // is our error and will be returned to the caller).
}

function Shortline ( options ) { const self = this ; self . _input = ( options && options . input ) || process . stdin ; self . _output = ( options && options . output ) || process . stderr ; self . inputError = null ; self . _input . on ( 'end' , ( ) => { self . inputError = new EOFError ( EOF_MESSAGE ) ; } ) ; }

Creates a new instance of Shortline which can be used to prompt users
for input.

This class is intended to be similar to {@link http://highline.rubyforge.org
Highline}, although it is currently missing nearly all of its functionality.

@constructor
@param {{
input: stream.Readable|undefined,
output: stream.Writable|undefined
}=} options Options to control the input source and output destination.

Creates a new instance of Shortline which can be used to prompt users for input .


function findElements(node, name) {
  return name in node && Array.isArray(node[name]) ? node[name] : [];
}

function findElements ( node , name ) { return name in node && Array . isArray ( node [ name ] ) ? node [ name ] : [ ] ; }

Defines the shape of a node in an XML document.
@typedef {object} XmlNode

Returns direct child elements of the specified node.
@param {XmlNode} node The node to process.
@param {string} name The tag name of the child elements to find.
@return {XmlNode[]} The direct child elements with the given tag name.

Defines the shape of a node in an XML document .


async function main() { // eslint-disable-line no-unused-vars
  try {
    const coverage = await promises.readFile('/path/to/coverage.report', 'utf8');
    await new Client().upload(coverage);
    console.log('The report was sent successfully.');
  }

  catch (error) {
    console.log(`An error occurred: ${error.message}`);
    if (error instanceof ClientError) console.log(`From: ${error.uri}`);
  }
}

async
function
main
(
)
{
try
{
const
coverage
=
await
promises
.
readFile
(
'/path/to/coverage.report'
,
'utf8'
)
;
await
new
Client
(
)
.
upload
(
coverage
)
;
console
.
log
(
'The report was sent successfully.'
)
;
}
catch
(
error
)
{
console
.
log
(
`
${
error
.
message
}
`
)
;
if
(
error
instanceof
ClientError
)
console
.
log
(
`
${
error
.
uri
}
`
)
;
}
}


function TravisStatusHttp(endpoint, options) {
  if (endpoint && typeof endpoint !== 'string') {
    throw new TypeError('endpoint must be a string');
  }
  endpoint = endpoint && trimSlash(endpoint);

  if (options && typeof options !== 'object') {
    throw new TypeError('options must be an object');
  }

  options = Object.assign({gzip: true}, options);
  options.headers = Object.assign({}, options.headers);

  // Careful about providing default values for case-insensitive headers
  const caselessHeaders = caseless(options.headers);
  // The Travis CI API docs say
  // "Always set the Accept header to application/vnd.travis-ci.2+json"
  // but the API actually sends Content-Type application/json.
  // Declare that we accept either.
  if (!caselessHeaders.has('Accept')) {
    options.headers.Accept =
      'application/vnd.travis-ci.2+json, application/json';
  }
  if (!caselessHeaders.has('User-Agent')) {
    options.headers['User-Agent'] = DEFAULT_USER_AGENT;
  }

  TravisHttp.call(
    this,
    endpoint === constants.PRO_URI,
    options.headers
  );

  this._endpoint = endpoint || constants.ORG_URI;
  // Set this._headers as TravisHttp does
  this._headers = options.headers;
  delete options.headers;
  this._options = options;
}

Creates an instance of the travis-ci HTTP agent with a given endpoint
and request options.

This class has the following features above TravisHttp:
- Uses a newer version of request (for gzip and proxy support)
- Supports caller-specified API endpoints (e.g. for enterprise or local use)
- Supports caller-specified request options (e.g. pooling, strictSSL, proxy,
tunnel, timeouts, etc.)
- Improved error values which are real Error instances and include the
HTTP response information, regardless of content.

@param {string=} endpoint Travis CI API endpoint (base URL).
(default: {@link TravisStatusChecker.ORG_URI})
@param {Object=} options Options to pass to the request
constructor.

Creates an instance of the travis - ci HTTP agent with a given endpoint and request options .


function git(...args) {
  return new Promise((resolve, reject) => {
    const child = execFile('git', args, (err, stdout, stderr) => {
      if (err) {
        reject(err);
      } else {
        // Creating an object with named properties would probably be clearer
        // but this is compatible with thenify/promisify if we switch later.
        resolve([stdout, stderr]);
      }
    });
    child.stdin.end();
  });
}

function git ( ... args ) { return new Promise ( ( resolve , reject ) => { const child = execFile ( 'git' , args , ( err , stdout , stderr ) => { if ( err ) { reject ( err ) ; } else { resolve ( [ stdout , stderr ] ) ; } } ) ; child . stdin . end ( ) ; } ) ; }

Runs git with given arguments.
@param {...string} args Arguments to git command.
@return {Promise} Promise with the process output or Error for non-0 exit.
@private


function SlugDetectionError(message) {
  if (!(this instanceof SlugDetectionError)) {
    return new SlugDetectionError(message);
  }

  Error.captureStackTrace(this, SlugDetectionError);
  // Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
  if (message !== undefined) {
    Object.defineProperty(this, 'message', {
      value: String(message),
      configurable: true,
      writable: true
    });
  }
}

function SlugDetectionError ( message ) { if ( ! ( this instanceof SlugDetectionError ) ) { return new SlugDetectionError ( message ) ; } Error . captureStackTrace ( this , SlugDetectionError ) ; if ( message !== undefined ) { Object . defineProperty ( this , 'message' , { value : String ( message ) , configurable : true , writable : true } ) ; } }

Constructs a SlugDetectionError.

@class Represents an error during repository slug detection.
@constructor
@param {string=} message Human-readable description of the error.
 Note:  Only needed before https://github.com/eslint/eslint/pull/5398 eslint-disable-next-line consistent-return


function createScopedCss(html, scope, filepath, cssVariables) {
	scope = typeof scope === 'string' ? {ns: scope, vars: new Map()} : scope;

	const style = html.match(styleMatcher);
	if (!style) {
		return [{}, scope.vars, ''];
	}
	const cssom = css.parse(style[1], {source: filepath});
	const vars = new Map(scope.vars.entries());
	getVariables(cssom).forEach((value, key) => vars.set(key, value));

	if (cssVariables) {
		resolveScopeVariables(cssom, vars);
	}
	const [classes, transformMap] = rewriteSelectors(`${decamelize(scope.ns, '-')}`, cssom);

	return [classes, vars, css.stringify(cssom), transformMap];
}

function createScopedCss ( html , scope , filepath , cssVariables ) { scope = typeof scope === 'string' ? { ns : scope , vars : new Map ( ) } : scope ; const style = html . match ( styleMatcher ) ; if ( ! style ) { return [ { } , scope . vars , '' ] ; } const cssom = css . parse ( style [ 1 ] , { source : filepath } ) ; const vars = new Map ( scope . vars . entries ( ) ) ; getVariables ( cssom ) . forEach ( ( value , key ) => vars . set ( key , value ) ) ; if ( cssVariables ) { resolveScopeVariables ( cssom , vars ) ; } const [ classes , transformMap ] = rewriteSelectors ( ` ${ decamelize ( scope . ns , '-' ) } ` , cssom ) ; return [ classes , vars , css . stringify ( cssom ) , transformMap ] ; }

Strips scoped style from html and return html and metadata.

@param {string} html HTML input source
@param {Object|string} scope Namespace for generated classNames
@param {string?} filepath Input file path (mainly for debugging)
@param {boolean} cssVariables True if css-variables support should be enabled
@returns [classNames: any, vars: any, css: string, transformMap: Object]

Strips scoped style from html and return html and metadata .


function combineCss(templates, scopedCss) {
	if (!Array.isArray(scopedCss)) {
		scopedCss = [scopedCss];
	}
	return [
		...Object.keys(templates).map(name => templates[name].css),
		...scopedCss
	]
	.join('\n').trim();
}

function combineCss ( templates , scopedCss ) { if ( ! Array . isArray ( scopedCss ) ) { scopedCss = [ scopedCss ] ; } return [ ... Object . keys ( templates ) . map ( name => templates [ name ] . css ) , ... scopedCss ] . join ( '\n' ) . \n trim ; }

Returns a combined CSS from all component CSS and scopedCss.

@param {object} templates A map of schlump templates
@param {string[]} scopedCss A list of page CSS
@returns {string} CSS result

Returns a combined CSS from all component CSS and scopedCss .


function InvalidSlugError(message) {
  if (!(this instanceof InvalidSlugError)) {
    return new InvalidSlugError(message);
  }

  Error.captureStackTrace(this, InvalidSlugError);
  // Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
  if (message !== undefined) {
    Object.defineProperty(this, 'message', {
      value: String(message),
      configurable: true,
      writable: true
    });
  }
}

function InvalidSlugError ( message ) { if ( ! ( this instanceof InvalidSlugError ) ) { return new InvalidSlugError ( message ) ; } Error . captureStackTrace ( this , InvalidSlugError ) ; if ( message !== undefined ) { Object . defineProperty ( this , 'message' , { value : String ( message ) , configurable : true , writable : true } ) ; } }

Constructs an InvalidSlugError.

@class Represents an error caused by a repository slug which does not
fit the required format.
@constructor
@param {string=} message Human-readable description of the error.
 Note:  Only needed before https://github.com/eslint/eslint/pull/5398 eslint-disable-next-line consistent-return


function checkBuildCommit(build, localCommit) {
  const buildCommit = build.commit;
  let message = `Build commit ${buildCommit.sha
  } does not match ${localCommit.sha}`;
  if (localCommit.name) {
    message += ` (${localCommit.name})`;
  }
  // assert gives us useful exception properties for callers
  assert.strictEqual(
    buildCommit.sha,
    localCommit.sha,
    message
  );
  return build;
}

function checkBuildCommit ( build , localCommit ) { const buildCommit = build . commit ; let message = ` ${ buildCommit . sha } ${ localCommit . sha } ` ; if ( localCommit . name ) { message += ` ${ localCommit . name } ` ; } assert . strictEqual ( buildCommit . sha , localCommit . sha , message ) ; return build ; }

Checks that a build has an expected commit hash.
@param {!{commit:!{sha: string}}} build Build (or branch) object returned
by the Travis CI API.
@param {!{sha: string, name: ?string}} localCommit Expected commit
information.
@return {!Object} build
@throws AssertionError If build.commit.sha is not equal to
expected.

Checks that a build has an expected commit hash .


function trimSlash(string) {
  if (typeof string !== 'string') {
    return string;
  }
  if (string.length > 0 && string.charAt(string.length - 1) === '/') {
    return string.slice(0, string.length - 1);
  }
  return string;
}

function trimSlash ( string ) { if ( typeof string !== 'string' ) { return string ; } if ( string . length > 0 && string . charAt ( string . length - 1 ) === '/' ) { return string . slice ( 0 , string . length - 1 ) ; } return string ; }

Trims a single slash from the end of a string, if present.
@ template ArgType
@param {ArgType} string String to trim.
@return {ArgType} If string is a string which ends with
'/', string with the last character removed.
Otherwise, string unmodified.
@ nosideeffects

Trims a single slash from the end of a string if present .


function parseOptions (opts) {
  return removeEmpty({
    plugins: convertFn.call(this, opts.plugins),
    locals: convertFn.call(this, opts.locals),
    filename: convertFn.call(this, opts.filename),
    parserOptions: convertFn.call(this, opts.parserOptions),
    generatorOptions: convertFn.call(this, opts.generatorOptions),
    runtime: convertFn.call(this, opts.runtime),
    parser: convertFnSpecial.call(this, opts.parser),
    multi: convertFn.call(this, opts.multi)
  })
}

function parseOptions ( opts ) { return removeEmpty ( { plugins : convertFn . call ( this , opts . plugins ) , locals : convertFn . call ( this , opts . locals ) , filename : convertFn . call ( this , opts . filename ) , parserOptions : convertFn . call ( this , opts . parserOptions ) , generatorOptions : convertFn . call ( this , opts . generatorOptions ) , runtime : convertFn . call ( this , opts . runtime ) , parser : convertFnSpecial . call ( this , opts . parser ) , multi : convertFn . call ( this , opts . multi ) } ) }

Allows any option to be passed as a function which gets webpack's context as its first argument, in case some info from the loader context is necessary

Allows any option to be passed as a function which gets webpack s context as its first argument in case some info from the loader context is necessary


function serializeVerbatim (obj) {
  let i = 0
  const fns = []
  let res = JSON.stringify(obj, (k, v) => {
    if (typeof v === 'function') {
      fns.push(v.toString())
      return `__REPLACE${i++}`
    } else {
      return v
    }
  })
  res = res.replace(/"__REPLACE(\d{1})"/g, (m, v) => {
    return fns[v]
  })
  return res
}

function serializeVerbatim ( obj ) { let i = 0 const fns = [ ] let res = JSON . stringify ( obj , ( k , v ) => { if ( typeof v === 'function' ) { fns . push ( v . toString ( ) ) return ` ${ i ++ } ` } else { return v } } ) res = res . replace ( / "__REPLACE(\d{1})" / g , ( m , v ) => { return fns [ v ] } ) return res }

The runtime contains functions which must be converted into strings without any escaping at all. Yes, this method of doing so is insane. But it works!

The runtime contains functions which must be converted into strings without any escaping at all . Yes this method of doing so is insane . But it works!


function renderPages(filepaths, dest, {templates, vars, statics, disableValidation, cssVariables, host}) {
	console.log(`\nGenerating pages...`);
	return Promise.all(filepaths.map(filepath => {
		return sander.readFile(filepath)
			.then(content => renderPage(content, filepath, {templates, vars, dest, cssVariables}))
			.then(([html, destinationPath, cssParts]) => sander.writeFile(destinationPath, html)
				.then(() => [destinationPath, cssParts]))
			.then(([destinationPath, cssParts]) => {
				console.log(`  ${chalk.bold.green(figures.tick)} ${filepath} -> ${destinationPath}`);
				return [destinationPath, cssParts];
			});
	}))
	.then(pageResults => disableValidation ||
		validatePages(host, dest, pageResults.map(result => result[0]), statics)
			.then(() => pageResults.map(result => result[1])));
}

function renderPages ( filepaths , dest , { templates , vars , statics , disableValidation , cssVariables , host } ) { console . log ( ` \n ` ) ; return Promise . all ( filepaths . map ( filepath => { return sander . readFile ( filepath ) . then ( content => renderPage ( content , filepath , { templates , vars , dest , cssVariables } ) ) . then ( ( [ html , destinationPath , cssParts ] ) => sander . writeFile ( destinationPath , html ) . then ( ( ) => [ destinationPath , cssParts ] ) ) . then ( ( [ destinationPath , cssParts ] ) => { console . log ( ` ${ chalk . bold . green ( figures . tick ) } ${ filepath } ${ destinationPath } ` ) ; return [ destinationPath , cssParts ] ; } ) ; } ) ) . then ( pageResults => disableValidation || validatePages ( host , dest , pageResults . map ( result => result [ 0 ] ) , statics ) . then ( ( ) => pageResults . map ( result => result [ 1 ] ) ) ) ; }

Renders all given pages as static HTML into the destination folder.

@param {string[]} filepaths Input files to generate
@param {string} dest Path to write files to
@param {any} {components, vars, statics, disableValidation, scopedCss}
components
vars key-value pairs of globals
statics list of all available static files
disableValidation true to disable sanity checks
@returns

Renders all given pages as static HTML into the destination folder .


function gitUrlPath(gitUrl) {
  // Foreign URL for remote helper
  // See transport_get in transport.c
  // Note:  url.parse considers second : as part of path.  So check this first.
  const foreignParts = /^([A-Za-z0-9][A-Za-z0-9+.-]*)::(.*)$/.exec(gitUrl);
  if (foreignParts) {
    return foreignParts[2];
  }

  // Typical URL
  const gitUrlObj = url.parse(gitUrl);
  if (gitUrlObj.protocol) {
    return gitUrlObj.path;
  }

  // SCP-like syntax.  Host can be wrapped in [] to disambiguate path.
  // See parse_connect_url and host_end in connect.c
  const scpParts = /^([^@/]+)@(\[[^]\/]+\]|[^:/]+):(.*)$/.exec(gitUrl);
  if (scpParts) {
    return scpParts[3];
  }

  // Assume URL is a local path
  return gitUrl;
}

function gitUrlPath ( gitUrl ) { const foreignParts = / ^([A-Za-z0-9][A-Za-z0-9+.-]*)::(.*)$ / . exec ( gitUrl ) ; if ( foreignParts ) { return foreignParts [ 2 ] ; } const gitUrlObj = url . parse ( gitUrl ) ; if ( gitUrlObj . protocol ) { return gitUrlObj . path ; } const scpParts = / ^([^@/]+)@(\[[^]\/]+\]|[^:/]+):(.*)$ / . exec ( gitUrl ) ; if ( scpParts ) { return scpParts [ 3 ] ; } return gitUrl ; }

Gets the path portion of a git URL.
@param {string} gitUrl Git URL to parse.
@return {string} Path portion of the URL.
@private


function() {
    var appEnv = this.app.env;
    if (process.env.DEPLOY_TARGET) {
      appEnv = process.env.DEPLOY_TARGET;
    }
    var publicFiles = new Funnel(this.app.trees.public);

    this._requireBuildPackages();

    fs.stat(
      path.join(this.project.root, 'public', 'robots.txt'),
      function(err, stats) {
        if (stats && stats.isFile()) {
          console.log(chalk.yellow('There is a robots.txt in /public and ENV specific robots.txt are ignored!'));
        }
      }
    );

    publicFiles = stew.rename(
      publicFiles,
      'robots-' + appEnv + '.txt',
      'robots.txt'
    );

    return new Funnel(publicFiles, {
      srcDir: '/',
      destDir: '/'
    });
  }


function compileIndex() {
    fs.readFile(path.join(__dirname, 'templates', 'index.hogan'), function(err, data) {
        if (err) throw err;
        // write rendered result to index.html
        fs.writeFile(path.join(__dirname, 'index.html'),
                    hogan.compile(data.toString()).render({
                        'schemes': schemes,
                        'variations': variations,
                        'colors': colors,
                        'variants': variants,
                        }),
                    function(err) {if (err) throw err});

        // open index.html in browser
        open(path.join(__dirname, 'index.html'));
    });
}

function compileIndex ( ) { fs . readFile ( path . join ( __dirname , 'templates' , 'index.hogan' ) , function ( err , data ) { if ( err ) throw err ; fs . writeFile ( path . join ( __dirname , 'index.html' ) , hogan . compile ( data . toString ( ) ) . render ( { 'schemes' : schemes , 'variations' : variations , 'colors' : colors , 'variants' : variants , } ) , function ( err ) { if ( err ) throw err } ) ; open ( path . join ( __dirname , 'index.html' ) ) ; } ) ; }

compile hogan template and open index.html

compile hogan template and open index . html


function sortMentions(mentions) {
  return mentions.slice().sort((a, b) => b.length - a.length);
}

function sortMentions ( mentions ) { return mentions . slice ( ) . sort ( ( a , b ) => b . length - a . length ) ; }

Sort users by username length. Longest usernames first.

@param {Array.<Object>} users
@return {Array.<Object>}

Sort users by username length . Longest usernames first .


function findEmoji(names, match) {
  const compare = match.toLowerCase();
  for (let i = 0; i < names.length; i += 1) {
    const name = names[i].toLowerCase();
    if (name === compare) {
      return names[i];
    }
  }

  return null;
}

function findEmoji ( names , match ) { const compare = match . toLowerCase ( ) ; for ( let i = 0 ; i < names . length ; i += 1 ) { const name = names [ i ] . toLowerCase ( ) ; if ( name === compare ) { return names [ i ] ; } } return null ; }

Case-insensitively get the correct emoji name from the possible emoji for an
input string.

@param {Array.<string>} names All possible emoji names.
@param {string} match The input string.
@return {string|null} The correct emoji name (including casing), or `null` if
the requested emoji does not exist.

Case - insensitively get the correct emoji name from the possible emoji for an input string .


function fiberize(fn){
  return function(done){

    var self = this;
    Fiber(function(){

      try{
        if(fn.length == 1){
          fn.call(self, done);
        } else {
          fn.call(self);
          done();
        }
      } catch(e) {
        process.nextTick(function(){
          throw(e);
        });
      }

    }).run();

  };
}

function fiberize ( fn ) { return function ( done ) { var self = this ; Fiber ( function ( ) { try { if ( fn . length == 1 ) { fn . call ( self , done ) ; } else { fn . call ( self ) ; done ( ) ; } } catch ( e ) { process . nextTick ( function ( ) { throw ( e ) ; } ) ; } } ) . run ( ) ; } ; }

Wrap a function in a fiber.  Correctly handles expected presence of done callback

Wrap a function in a fiber . Correctly handles expected presence of done callback


function(regex, type, types, selector) {
  var matches = selector.match(regex);
  if (matches) {
    for (var i = 0; i < matches.length; i++) {
      types[type]++;
      // Replace this simple selector with whitespace so it won't be counted in further simple selectors
      selector = selector.replace(matches[i], ' ');
    }
  }

  return selector;
}

function
(
regex
,
type
,
types
,
selector
)
{
var
matches
=
selector
.
match
(
regex
)
;
if
(
matches
)
{
for
(
var
i
=
0
;
i
<
matches
.
length
;
i
++
)
{
types
[
type
]
++
;
selector
=
selector
.
replace
(
matches
[
i
]
,
' '
)
;
}
}
return
selector
;
}

Find matches for a regular expression in a string and push their details to parts Type is "a" for IDs, "b" for classes, attributes and pseudo-classes and "c" for elements and pseudo-elements

Find matches for a regular expression in a string and push their details to parts Type is a for IDs b for classes attributes and pseudo - classes and c for elements and pseudo - elements


function(selector) {
  var commaIndex = selector.indexOf(',');
  if (commaIndex !== -1) {
    selector = selector.substring(0, commaIndex);
  }

  var  types = {
    a: 0,
    b: 0,
    c: 0
  };

  // Remove the negation psuedo-class (:not) but leave its argument because specificity is calculated on its argument
  selector = selector.replace(notRegex, ' $1 ');

  // Remove anything after a left brace in case a user has pasted in a rule, not just a selector
  selector = selector.replace(ruleRegex, ' ');

  // Add attribute selectors to parts collection (type b)
  selector = findMatch(attributeRegex, 'b', types, selector);

  // Add ID selectors to parts collection (type a)
  selector = findMatch(idRegex, 'a', types, selector);

  // Add class selectors to parts collection (type b)
  selector = findMatch(classRegex, 'b', types, selector);

  // Add pseudo-element selectors to parts collection (type c)
  selector = findMatch(pseudoElementRegex, 'c', types, selector);

  // Add pseudo-class selectors to parts collection (type b)
  selector = findMatch(pseudoClassRegex, 'b', types, selector);

  // Remove universal selector and separator characters
  selector = selector.replace(separatorRegex, ' ');

  // Remove any stray dots or hashes which aren't attached to words
  // These may be present if the user is live-editing this selector
  selector = selector.replace(straysRegex, ' ');

  // The only things left should be element selectors (type c)
  findMatch(elementRegex, 'c', types, selector);

  return (types.a * 100) + (types.b * 10) + (types.c * 1);
}

function
(
selector
)
{
var
commaIndex
=
selector
.
indexOf
(
','
)
;
if
(
commaIndex
!==
1
)
{
selector
=
selector
.
substring
(
0
,
commaIndex
)
;
}
var
types
=
{
a
:
0
,
b
:
0
,
c
:
0
}
;
selector
=
selector
.
replace
(
notRegex
,
' $1 '
)
;
selector
=
selector
.
replace
(
ruleRegex
,
' '
)
;
selector
=
findMatch
(
attributeRegex
,
'b'
,
types
,
selector
)
;
selector
=
findMatch
(
idRegex
,
'a'
,
types
,
selector
)
;
selector
=
findMatch
(
classRegex
,
'b'
,
types
,
selector
)
;
selector
=
findMatch
(
pseudoElementRegex
,
'c'
,
types
,
selector
)
;
selector
=
findMatch
(
pseudoClassRegex
,
'b'
,
types
,
selector
)
;
selector
=
selector
.
replace
(
separatorRegex
,
' '
)
;
selector
=
selector
.
replace
(
straysRegex
,
' '
)
;
findMatch
(
elementRegex
,
'c'
,
types
,
selector
)
;
return
(
types
.
a
*
100
)
+
(
types
.
b
*
10
)
+
(
types
.
c
*
1
)
;
}

Calculate the specificity for a selector by dividing it into simple selectors and counting them


function(collectionName, indexName, columns, unique, callback) {

    var options = {
      indexName: indexName,
      columns: columns,
      unique: unique
    };

    return this._run('createIndex', collectionName, options)
      .nodeify(callback);
  }

function ( collectionName , indexName , columns , unique , callback ) { var options = { indexName : indexName , columns : columns , unique : unique } ; return this . _run ( 'createIndex' , collectionName , options ) . nodeify ( callback ) ; }

Adds an index to a collection

@param collectionName  - The collection to add the index to
@param indexName       - The name of the index to add
@param columns         - The columns to add an index on
@param	unique          - A boolean whether this creates a unique index


function (name, callback) {
    return this._run('insert', this.internals.migrationTable, {name: name, run_on: new Date()})
      .nodeify(callback);
  }

function ( name , callback ) { return this . _run ( 'insert' , this . internals . migrationTable , { name : name , run_on : new Date ( ) } ) . nodeify ( callback ) ; }

Inserts a migration record into the migration collection

@param name                - The name of the migration being run
@param callback


function (name, callback) {
    return this._run('insert', this.internals.seedTable, {name: name, run_on: new Date()})
      .nodeify(callback);
  }

function ( name , callback ) { return this . _run ( 'insert' , this . internals . seedTable , { name : name , run_on : new Date ( ) } ) . nodeify ( callback ) ; }

Inserts a seeder record into the seeder collection

@param name                - The name of the seed being run
@param callback


function(err, data) {

          if(err) {
            prCB(err);
          }

          prCB(null, data);
          db.close();
        }

function ( err , data ) { if ( err ) { prCB ( err ) ; } prCB ( null , data ) ; db . close ( ) ; }

Callback function to return mongo records


function parseParameters(options) {
  var opt = {
    maximumAge: 0,
    enableHighAccuracy: true,
    timeout: Infinity,
    interval: 6000,
    fastInterval: 1000,
    priority: PRIORITY_HIGH_ACCURACY
  };

  if (options) {
    if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) {
      opt.maximumAge = options.maximumAge;
    }
    if (options.enableHighAccuracy !== undefined) {
      opt.enableHighAccuracy = options.enableHighAccuracy;
    }
    if (options.timeout !== undefined && !isNaN(options.timeout)) {
      if (options.timeout < 0) {
        opt.timeout = 0;
      } else {
        opt.timeout = options.timeout;
      }
    }
    if (options.interval !== undefined && !isNaN(options.interval) && options.interval > 0) {
      opt.interval = options.interval;
    }
    if (options.fastInterval !== undefined && !isNaN(options.fastInterval) && options.fastInterval > 0) {
      opt.fastInterval = options.fastInterval;
    }
    if (options.priority !== undefined && !isNaN(options.priority) && options.priority >= PRIORITY_NO_POWER && options.priority <= PRIORITY_HIGH_ACCURACY) {
      if (options.priority === PRIORITY_NO_POWER) {
        opt.priority = PRIORITY_NO_POWER;
      }
      if (options.priority === PRIORITY_LOW_POWER) {
        opt.priority = PRIORITY_LOW_POWER;
      }
      if (options.priority === PRIORITY_BALANCED_POWER_ACCURACY) {
        opt.priority = PRIORITY_BALANCED_POWER_ACCURACY;
      }
      if (options.priority === PRIORITY_HIGH_ACCURACY) {
        opt.priority = PRIORITY_HIGH_ACCURACY;
      }
    }
  }

  return opt;
}

function parseParameters ( options ) { var opt = { maximumAge : 0 , enableHighAccuracy : true , timeout : Infinity , interval : 6000 , fastInterval : 1000 , priority : PRIORITY_HIGH_ACCURACY } ; if ( options ) { if ( options . maximumAge !== undefined && ! isNaN ( options . maximumAge ) && options . maximumAge > 0 ) { opt . maximumAge = options . maximumAge ; } if ( options . enableHighAccuracy !== undefined ) { opt . enableHighAccuracy = options . enableHighAccuracy ; } if ( options . timeout !== undefined && ! isNaN ( options . timeout ) ) { if ( options . timeout < 0 ) { opt . timeout = 0 ; } else { opt . timeout = options . timeout ; } } if ( options . interval !== undefined && ! isNaN ( options . interval ) && options . interval > 0 ) { opt . interval = options . interval ; } if ( options . fastInterval !== undefined && ! isNaN ( options . fastInterval ) && options . fastInterval > 0 ) { opt . fastInterval = options . fastInterval ; } if ( options . priority !== undefined && ! isNaN ( options . priority ) && options . priority >= PRIORITY_NO_POWER && options . priority <= PRIORITY_HIGH_ACCURACY ) { if ( options . priority === PRIORITY_NO_POWER ) { opt . priority = PRIORITY_NO_POWER ; } if ( options . priority === PRIORITY_LOW_POWER ) { opt . priority = PRIORITY_LOW_POWER ; } if ( options . priority === PRIORITY_BALANCED_POWER_ACCURACY ) { opt . priority = PRIORITY_BALANCED_POWER_ACCURACY ; } if ( options . priority === PRIORITY_HIGH_ACCURACY ) { opt . priority = PRIORITY_HIGH_ACCURACY ; } } } return opt ; }

Returns default params, overrides if provided with values

Returns default params overrides if provided with values


function noProp(props, propNameOrFunction) {
    if (!props) {
        throw new Error('Headful: You must pass all declared props when you use headful.props.x() calls.');
    }
    const propName = typeof propNameOrFunction === 'function' ? propNameOrFunction.name : propNameOrFunction;
    return !props.hasOwnProperty(propName);
}

Tests whether the given `props` object contains a property with the name of `propNameOrFunction`.

Tests whether the given props object contains a property with the name of propNameOrFunction .


function GifCli(path, callback) {
    var frames = [];

    OneByOne([
        Tmp.dir
      , function (next, tmpDir) {
            var str = Fs.createReadStream(path)
              , isFinished = false
              , complete = []
              , i = 0
              ;

            str.on("end", function () {
                isFinished = true;
            });

            str.pipe(
                GifExplode(function (frame) {
                    Tmp.file({ postfix: ".gif", }, function (err, cImg) {
                        (function (i, cImg) {
                            if (err) { return next(err); }
                            var wStr = Fs.createWriteStream(cImg);
                            frame.pipe(wStr);
                            complete[i] = false;
                            wStr.on("close", function () {
                                // TODO Allow passing options
                                ImageToAscii(cImg, function (err, asciified) {
                                    complete[i] = true;
                                    frames[i] = asciified || "";
                                    // TODO https://github.com/hughsk/gif-explode/issues/4
                                    //if (err) { return next(err); }
                                    if (!isFinished) { return; }
                                    if (!complete.filter(function (c) {
                                        return c !== true
                                    }).length) {
                                        next();
                                    }
                                });
                            });
                        })(i++, cImg);
                    });
                })
            );
        }
      , function (next) {
            frames = frames.filter(Boolean);
            next();
        }
    ], function (err) {
        if (err) { return callback(err); }
        callback(null, frames);
    });
}

function GifCli ( path , callback ) { var frames = [ ] ; OneByOne ( [ Tmp . dir , function ( next , tmpDir ) { var str = Fs . createReadStream ( path ) , isFinished = false , complete = [ ] , i = 0 ; str . on ( "end" , function ( ) { isFinished = true ; } ) ; str . pipe ( GifExplode ( function ( frame ) { Tmp . file ( { postfix : ".gif" , } , function ( err , cImg ) { ( function ( i , cImg ) { if ( err ) { return next ( err ) ; } var wStr = Fs . createWriteStream ( cImg ) ; frame . pipe ( wStr ) ; complete [ i ] = false ; wStr . on ( "close" , function ( ) { ImageToAscii ( cImg , function ( err , asciified ) { complete [ i ] = true ; frames [ i ] = asciified || "" ; if ( ! isFinished ) { return ; } if ( ! complete . filter ( function ( c ) { return c !== true } ) . length ) { next ( ) ; } } ) ; } ) ; } ) ( i ++ , cImg ) ; } ) ; } ) ) ; } , function ( next ) { frames = frames . filter ( Boolean ) ; next ( ) ; } ] , function ( err ) { if ( err ) { return callback ( err ) ; } callback ( null , frames ) ; } ) ; }

GifCli
Converts the gif file into ASCII frames.

@name GifCli
@function
@param {String} path The input gif file path.
@param {Function} callback The callback function.

GifCli Converts the gif file into ASCII frames .


function shouldLog(testlevel, thresholdLevel) {
  var allowed = logLevelAllowedGranular(testlevel);
  if (allowed) {
    return true;
  }

  return logLevelAllowed(testlevel, thresholdLevel);
}

function shouldLog ( testlevel , thresholdLevel ) { var allowed = logLevelAllowedGranular ( testlevel ) ; if ( allowed ) { return true ; } return logLevelAllowed ( testlevel , thresholdLevel ) ; }

Should I log?

Use this instead of older pattern of granular check then global check.


function() {
          if (attrs.type === 'radio') {
            return attrs.value || $parse(attrs.ngValue)(scope) || true;
          }
          var trueValue = ($parse(attrs.ngTrueValue)(scope));
          if (angular.isUndefined(trueValue)) {
            trueValue = true;
          }
          return trueValue;
        }

function ( ) { if ( attrs . type === 'radio' ) { return attrs . value || $parse ( attrs . ngValue ) ( scope ) || true ; } var trueValue = ( $parse ( attrs . ngTrueValue ) ( scope ) ) ; if ( angular . isUndefined ( trueValue ) ) { trueValue = true ; } return trueValue ; }

Return the true value for this specific checkbox.
@returns {Object} representing the true view value; if undefined, returns true.

Return the true value for this specific checkbox .


function(attrName) {
          var map = {
            'switchRadioOff': getBooleanFromStringDefTrue,
            'switchActive': function(value) {
              return !getBooleanFromStringDefTrue(value);
            },
            'switchAnimate': getBooleanFromStringDefTrue,
            'switchLabel': function(value) {
              return value ? value : ' ';
            },
            'switchIcon': function(value) {
              if (value) {
                return '';
              }
            },
            'switchWrapper': function(value) {
              return value || 'wrapper';
            },
            'switchInverse': getBooleanFromString,
            'switchReadonly': getBooleanFromString,
            'switchChange': getExprFromString
          };
          var transFn = map[attrName] || getValueOrUndefined;
          return transFn(attrs[attrName]);
        }

function
(
attrName
)
{
var
map
=
{
'switchRadioOff'
:
getBooleanFromStringDefTrue
,
'switchActive'
:
function
(
value
)
{
return
!
getBooleanFromStringDefTrue
(
value
)
;
}
,
'switchAnimate'
:
getBooleanFromStringDefTrue
,
'switchLabel'
:
function
(
value
)
{
return
value
value
:
' '
;
}
,
'switchIcon'
:
function
(
value
)
{
if
(
value
)
{
return
''
,
\'
,
'switchWrapper'
:
function
(
value
)
{
return
value
||
'wrapper'
;
}
,
'switchInverse'
:
getBooleanFromString
}
;
'switchReadonly'
:
getBooleanFromString
'switchChange'
:
getExprFromString
}

Get the value of the angular-bound attribute, given its name.
The returned value may or may not equal the attribute value, as it may be transformed by a function.

@param attrName  The angular-bound attribute name to get the value for
@returns {*}     The attribute value

Get the value of the angular - bound attribute given its name . The returned value may or may not equal the attribute value as it may be transformed by a function .


function() {
          // if it's the first initialization
          if (!isInit) {
            var viewValue = (controller.$modelValue === getTrueValue());
            isInit = !isInit;
            // Bootstrap the switch plugin
            element.bootstrapSwitch({
              radioAllOff: getSwitchAttrValue('switchRadioOff'),
              disabled: getSwitchAttrValue('switchActive'),
              state: viewValue,
              onText: getSwitchAttrValue('switchOnText'),
              offText: getSwitchAttrValue('switchOffText'),
              onColor: getSwitchAttrValue('switchOnColor'),
              offColor: getSwitchAttrValue('switchOffColor'),
              animate: getSwitchAttrValue('switchAnimate'),
              size: getSwitchAttrValue('switchSize'),
              labelText: attrs.switchLabel ? getSwitchAttrValue('switchLabel') : getSwitchAttrValue('switchIcon'),
              wrapperClass: getSwitchAttrValue('switchWrapper'),
              handleWidth: getSwitchAttrValue('switchHandleWidth'),
              labelWidth: getSwitchAttrValue('switchLabelWidth'),
              inverse: getSwitchAttrValue('switchInverse'),
              readonly: getSwitchAttrValue('switchReadonly')
            });
            if (attrs.type === 'radio') {
              controller.$setViewValue(controller.$modelValue);
            } else {
              controller.$setViewValue(viewValue);
            }
          }
        }

function ( ) { if ( ! isInit ) { var viewValue = ( controller . $modelValue === getTrueValue ( ) ) ; isInit = ! isInit ; element . bootstrapSwitch ( { radioAllOff : getSwitchAttrValue ( 'switchRadioOff' ) , disabled : getSwitchAttrValue ( 'switchActive' ) , state : viewValue , onText : getSwitchAttrValue ( 'switchOnText' ) , offText : getSwitchAttrValue ( 'switchOffText' ) , onColor : getSwitchAttrValue ( 'switchOnColor' ) , offColor : getSwitchAttrValue ( 'switchOffColor' ) , animate : getSwitchAttrValue ( 'switchAnimate' ) , size : getSwitchAttrValue ( 'switchSize' ) , labelText : attrs . switchLabel ? getSwitchAttrValue ( 'switchLabel' ) : getSwitchAttrValue ( 'switchIcon' ) , wrapperClass : getSwitchAttrValue ( 'switchWrapper' ) , handleWidth : getSwitchAttrValue ( 'switchHandleWidth' ) , labelWidth : getSwitchAttrValue ( 'switchLabelWidth' ) , inverse : getSwitchAttrValue ( 'switchInverse' ) , readonly : getSwitchAttrValue ( 'switchReadonly' ) } ) ; if ( attrs . type === 'radio' ) { controller . $setViewValue ( controller . $modelValue ) ; } else { controller . $setViewValue ( viewValue ) ; } } }

If the directive has not been initialized yet, do so.

If the directive has not been initialized yet do so .


function () {

          attrs.$observe('switchActive', function (newValue) {

            var active = getBooleanFromStringDefTrue(newValue);
            // if we are disabling the switch, delay the deactivation so that the toggle can be switched
            if (!active) {
              $timeout(setActive);
            } else {
              // if we are enabling the switch, set active right away
              setActive();
            }
          });

          // When the model changes
          controller.$render = function () {
            initMaybe();
            var newValue = controller.$modelValue;
            if (newValue !== undefined && newValue !== null) {
              element.bootstrapSwitch('state', newValue === getTrueValue(), true);
            } else {
              element.bootstrapSwitch('indeterminate', true, true);
              controller.$setViewValue(undefined);
            }
            switchChange();
          };

          // angular attribute to switch property bindings
          var bindings = {
            'switchRadioOff': 'radioAllOff',
            'switchOnText': 'onText',
            'switchOffText': 'offText',
            'switchOnColor': 'onColor',
            'switchOffColor': 'offColor',
            'switchAnimate': 'animate',
            'switchSize': 'size',
            'switchLabel': 'labelText',
            'switchIcon': 'labelText',
            'switchWrapper': 'wrapperClass',
            'switchHandleWidth': 'handleWidth',
            'switchLabelWidth': 'labelWidth',
            'switchInverse': 'inverse',
            'switchReadonly': 'readonly'
          };

          var observeProp = function(prop, bindings) {
            return function() {
              attrs.$observe(prop, function () {
                setSwitchParamMaybe(element, bindings[prop], prop);
              });
            };
          };

          // for every angular-bound attribute, observe it and trigger the appropriate switch function
          for (var prop in bindings) {
            attrs.$observe(prop, observeProp(prop, bindings));
          }
        }

function ( ) { attrs . $observe ( 'switchActive' , function ( newValue ) { var active = getBooleanFromStringDefTrue ( newValue ) ; if ( ! active ) { $timeout ( setActive ) ; } else { setActive ( ) ; } } ) ; controller . $render = function ( ) { initMaybe ( ) ; var newValue = controller . $modelValue ; if ( newValue !== undefined && newValue !== null ) { element . bootstrapSwitch ( 'state' , newValue === getTrueValue ( ) , true ) ; } else { element . bootstrapSwitch ( 'indeterminate' , true , true ) ; controller . $setViewValue ( undefined ) ; } switchChange ( ) ; } ; var bindings = { 'switchRadioOff' : 'radioAllOff' , 'switchOnText' : 'onText' , 'switchOffText' : 'offText' , 'switchOnColor' : 'onColor' , 'switchOffColor' : 'offColor' , 'switchAnimate' : 'animate' , 'switchSize' : 'size' , 'switchLabel' : 'labelText' , 'switchIcon' : 'labelText' , 'switchWrapper' : 'wrapperClass' , 'switchHandleWidth' : 'handleWidth' , 'switchLabelWidth' : 'labelWidth' , 'switchInverse' : 'inverse' , 'switchReadonly' : 'readonly' } ; var observeProp = function ( prop , bindings ) { return function ( ) { attrs . $observe ( prop , function ( ) { setSwitchParamMaybe ( element , bindings [ prop ] , prop ) ; } ) ; } ; } ; for ( var prop in bindings ) { attrs . $observe ( prop , observeProp ( prop , bindings ) ) ; } }


function () {

          if (attrs.type === 'radio') {
            // when the switch is clicked
            element.on('change.bootstrapSwitch', function (e) {
              // discard not real change events
              if ((controller.$modelValue === controller.$viewValue) && (e.target.checked !== $(e.target).bootstrapSwitch('state'))) {
                // $setViewValue --> $viewValue --> $parsers --> $modelValue
                // if the switch is indeed selected
                if (e.target.checked) {
                  // set its value into the view
                  controller.$setViewValue(getTrueValue());
                } else if (getTrueValue() === controller.$viewValue) {
                  // otherwise if it's been deselected, delete the view value
                  controller.$setViewValue(undefined);
                }
                switchChange();
              }
            });
          } else {
            // When the checkbox switch is clicked, set its value into the ngModel
            element.on('switchChange.bootstrapSwitch', function (e) {
              // $setViewValue --> $viewValue --> $parsers --> $modelValue
              controller.$setViewValue(e.target.checked);
              switchChange();
            });
          }
        }

function ( ) { if ( attrs . type === 'radio' ) { element . on ( 'change.bootstrapSwitch' , function ( e ) { if ( ( controller . $modelValue === controller . $viewValue ) && ( e . target . checked !== $ ( e . target ) . bootstrapSwitch ( 'state' ) ) ) { if ( e . target . checked ) { controller . $setViewValue ( getTrueValue ( ) ) ; } else if ( getTrueValue ( ) === controller . $viewValue ) { controller . $setViewValue ( undefined ) ; } switchChange ( ) ; } } ) ; } else { element . on ( 'switchChange.bootstrapSwitch' , function ( e ) { controller . $setViewValue ( e . target . checked ) ; switchChange ( ) ; } ) ; } }


function (n) {
                var r,
                    i,
                    c = parseCookies();

                if (typeof n === 'string') {
                    r = (c[n] !== undef) ? c[n] : null;
                } else if (typeof n === 'object' && n !== null) {
                    r = {};

                    for (i in n) {
                        if (Object.prototype.hasOwnProperty.call(n, i)) {
                            if (c[n[i]] !== undef) {
                                r[n[i]] = c[n[i]];
                            } else {
                                r[n[i]] = null;
                            }
                        }
                    }
                } else {
                    r = c;
                }

                return r;
            }

function ( n ) { var r , i , c = parseCookies ( ) ; if ( typeof n === 'string' ) { r = ( c [ n ] !== undef ) ? c [ n ] : null ; } else if ( typeof n === 'object' && n !== null ) { r = { } ; for ( i in n ) { if ( Object . prototype . hasOwnProperty . call ( n , i ) ) { if ( c [ n [ i ] ] !== undef ) { r [ n [ i ] ] = c [ n [ i ] ] ; } else { r [ n [ i ] ] = null ; } } } } else { r = c ; } return r ; }

get - get one, several, or all cookies

@access public
@static
@param {mixed} n {string} name of single cookie
{array} list of multiple cookie names
{void} if you want all cookies
@return {mixed} type/value of cookie as set
{null} if only one cookie is requested and is not found
{object} hash of multiple or all cookies (if multiple or all requested)


function (p) {
                var n,
                    r = {},
                    c = parseCookies();

                if (typeof p === 'string') {
                    p = new RegExp(p);
                }

                for (n in c) {
                    if (Object.prototype.hasOwnProperty.call(c, n) && n.match(p)) {
                        r[n] = c[n];
                    }
                }

                return r;
            }

function ( p ) { var n , r = { } , c = parseCookies ( ) ; if ( typeof p === 'string' ) { p = new RegExp ( p ) ; } for ( n in c ) { if ( Object . prototype . hasOwnProperty . call ( c , n ) && n . match ( p ) ) { r [ n ] = c [ n ] ; } } return r ; }

filter - get array of cookies whose names match the provided RegExp

@access public
@static
@param {RegExp} p The regular expression to match against cookie names
@return {object} hash of cookies whose names match the RegExp


function (n, v, o) {
                if (typeof o !== 'object' || o === null) {
                    o = {};
                }

                if (v === undef || v === null) {
                    v = '';
                    o.expires = new Date();
                    o.expires.setFullYear(1978);
                } else {
                    /* Logic borrowed from http://jquery.com/ dataAttr method and reversed */
                    v = (v === true)
                        ? 'true' : (v === false)
                            ? 'false' : !isNaN(v)
                                ? String(v) : v;

                    if (typeof v !== 'string') {
                        if (typeof JSON === 'object' && JSON !== null && typeof JSON.stringify === 'function') {
                            v = JSON.stringify(v);
                        } else {
                            throw new Error('cookies.set() could not be serialize the value');
                        }
                    }
                }

                document.cookie = n + '=' + encodeURIComponent(v) + cookieOptions(o);
            }

set - set or delete a cookie with desired options

@access public
@static
@param {string} n name of cookie to set
@param {mixed} v Any JS value. If not a string, will be JSON encoded (http://code.google.com/p/cookies/wiki/JSON)
{null} to delete
@param {object} o optional list of cookie options to specify
@return {void}


function () {
                var r = false,
                    n = 'test_cookies_jaaulde_js',
                    v = 'data';

                this.set(n, v);

                if (this.get(n) === v) {
                    this.del(n);
                    r = true;
                }

                return r;
            }

function ( ) { var r = false , n = 'test_cookies_jaaulde_js' , v = 'data' ; this . set ( n , v ) ; if ( this . get ( n ) === v ) { this . del ( n ) ; r = true ; } return r ; }

test - test whether the browser is accepting cookies

@access public
@static
@return {boolean}


function formatMessage (str) {
  return String(str).split('\n')
    .map(function(s) {
      return s.magenta;
    })
    .join('\n');
}

function formatMessage ( str ) { return String ( str ) . split ( '\n' ) . \n map . ( function ( s ) { return s . magenta ; } ) join ; }

Shared functions Allow an error message to retain its color when split across multiple lines.

Shared functions Allow an error message to retain its color when split across multiple lines .


function createZoomRangePath(options) {
      if (!angular.isObject(options.state)) {
        options.state = {};
      }
      if (!angular.isObject(options.state.range)) {
        options.state.range = [];
      }
    }

function createZoomRangePath ( options ) { if ( ! angular . isObject ( options . state ) ) { options . state = { } ; } if ( ! angular . isObject ( options . state . range ) ) { options . state . range = [ ] ; } }


function synchronizeZoom(options, configuration, watcher) {
      if (angular.isObject(options.chart) && angular.isObject(options.chart.zoom) && options.chart.zoom.enabled === true) {

        // setup onzoomend listener
        configuration.zoom.onzoomend = function (domain) {

          // update state
          AngularChartWatcher.updateState(watcher, function () {
            createZoomRangePath(options);
            options.state.range = domain;
          });

          // call user defined callback
          if (angular.isFunction(options.chart.zoom.onzoomend)) {
            AngularChartWatcher.applyFunction(watcher, function () {
              options.chart.zoom.onzoomend(domain);
            });
          }
        };
      }

      if (angular.isObject(options.chart) && angular.isObject(options.chart.subchart) && options.chart.subchart.show === true) {
        // setup onbrush listener
        configuration.subchart.onbrush = function (domain) {

          // update state
          AngularChartWatcher.updateState(watcher, function () {
            createZoomRangePath(options);
            options.state.range = domain;
          });

          // call user defined callback
          if (angular.isFunction(options.chart.subchart.onbrush)) {
            AngularChartWatcher.applyFunction(watcher, function () {
              options.chart.subchart.onbrush(domain);
            });
          }
        };
      }
    }

function synchronizeZoom ( options , configuration , watcher ) { if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . zoom ) && options . chart . zoom . enabled === true ) { configuration . zoom . onzoomend = function ( domain ) { AngularChartWatcher . updateState ( watcher , function ( ) { createZoomRangePath ( options ) ; options . state . range = domain ; } ) ; if ( angular . isFunction ( options . chart . zoom . onzoomend ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . zoom . onzoomend ( domain ) ; } ) ; } } ; } if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . subchart ) && options . chart . subchart . show === true ) { configuration . subchart . onbrush = function ( domain ) { AngularChartWatcher . updateState ( watcher , function ( ) { createZoomRangePath ( options ) ; options . state . range = domain ; } ) ; if ( angular . isFunction ( options . chart . subchart . onbrush ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . subchart . onbrush ( domain ) ; } ) ; } } ; } }

Setup zoom event listeners which update the state


function addSelections(chart, selections) {
      service.disableSelectionListener = true;
      selections.forEach(function (selection) {
        chart.select([selection.id], [selection.index]);
      });
      service.disableSelectionListener = false;
    }

function addSelections ( chart , selections ) { service . disableSelectionListener = true ; selections . forEach ( function ( selection ) { chart . select ( [ selection . id ] , [ selection . index ] ) ; } ) ; service . disableSelectionListener = false ; }


function applySelection(options, chart) {
      if (angular.isObject(options.state) && angular.isArray(options.state.selected)) {
        // TODO: get new selections
        // TODO: get removed selections
        // var chartSelections = chart.selected();
        //    // addedSelections
        //    var addedSelections = newSelections.filter(function (elm) {
        //      var isNew = true;
        //      oldSelections.forEach(function (old) {
        //        if (old.id === elm.id && old.index === elm.index) {
        //          isNew = false;
        //          return isNew;
        //        }
        //      });
        //      return isNew;
        //    });
        //
        //    // removedSelections
        //    var removedSelections = oldSelections.filter(function (elm) {
        //      var isOld = true;
        //      newSelections.forEach(function (old) {
        //        if (old.id === elm.id && old.index === elm.index) {
        //          isOld = false;
        //          return isOld;
        //        }
        //      });
        //      return isOld;
        //    });

        // alternative: deselect all and select again
        //removeAllSelections(chart);
        addSelections(chart, options.state.selected);

      } else {
        removeAllSelections(chart);
      }
    }

function applySelection ( options , chart ) { if ( angular . isObject ( options . state ) && angular . isArray ( options . state . selected ) ) { addSelections ( chart , options . state . selected ) ; } else { removeAllSelections ( chart ) ; } }


function createSelectionsPath(options) {
      if (!angular.isObject(options.state)) {
        options.state = {};
      }
      if (!angular.isArray(options.state.selected)) {
        options.state.selected = [];
      }
    }

function createSelectionsPath ( options ) { if ( ! angular . isObject ( options . state ) ) { options . state = { } ; } if ( ! angular . isArray ( options . state . selected ) ) { options . state . selected = [ ] ; } }