function() {
    var pos = this.position();
    if (this.input) return;
    var prev = this.prev();

    while (prev.type !== 'root' && !prev.visited) {
      if (this.options.strict === true) {
        throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2));
      }

      if (!hasDelims(prev)) {
        prev.parent.escaped = true;
        prev.escaped = true;
      }

      visit(prev, function(node) {
        if (!hasDelims(node.parent)) {
          node.parent.escaped = true;
          node.escaped = true;
        }
      });

      prev = prev.parent;
    }

    var tok = pos({
      type: 'eos',
      val: this.append || ''
    });

    define(tok, 'parent', this.ast);
    return tok;
  }

function
(
)
{
var
pos
=
this
.
position
(
)
;
if
(
this
.
input
)
return
;
var
prev
=
this
.
prev
(
)
;
while
(
prev
.
type
!==
'root'
&&
!
prev
.
visited
)
{
if
(
this
.
options
.
strict
===
true
)
{
throw
new
SyntaxError
(
'invalid syntax:'
+
util
.
inspect
(
prev
,
,
2
)
)
;
}
if
(
!
hasDelims
(
prev
)
)
{
prev
.
parent
.
escaped
=
true
;
prev
.
escaped
=
true
;
}
visit
(
prev
,
function
(
node
)
{
if
(
!
hasDelims
(
node
.
parent
)
)
{
node
.
parent
.
escaped
=
true
;
node
.
escaped
=
true
;
}
}
)
;
prev
=
prev
.
parent
;
}
var
tok
=
pos
(
{
type
:
'eos'
,
val
:
this
.
append
||
''
}
)
;
define
(
tok
,
'parent'
,
this
.
ast
)
;
return
tok
;
}


function() {
    var parsed = this.parsed;
    var len = this.types.length;
    var idx = -1;
    var tok;

    while (++idx < len) {
      if ((tok = this.parsers[this.types[idx]].call(this))) {
        define(tok, 'rest', this.input);
        define(tok, 'parsed', parsed);
        this.last = tok;
        return tok;
      }
    }
  }

function ( ) { var parsed = this . parsed ; var len = this . types . length ; var idx = - 1 ; var tok ; while ( ++ idx < len ) { if ( ( tok = this . parsers [ this . types [ idx ] ] . call ( this ) ) ) { define ( tok , 'rest' , this . input ) ; define ( tok , 'parsed' , parsed ) ; this . last = tok ; return tok ; } } }

Run parsers to advance the cursor position


function(input) {
    if (typeof input !== 'string') {
      throw new TypeError('expected a string');
    }

    this.init(this.options);
    this.orig = input;
    this.input = input;
    var self = this;

    function parse() {
      // check input before calling `.next()`
      input = self.input;

      // get the next AST ndoe
      var node = self.next();
      if (node) {
        var prev = self.prev();
        if (prev) {
          define(node, 'parent', prev);
          if (prev.nodes) {
            prev.nodes.push(node);
          }
        }

        if (self.sets.hasOwnProperty(prev.type)) {
          self.currentType = prev.type;
        }
      }

      // if we got here but input is not changed, throw an error
      if (self.input && input === self.input) {
        throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"');
      }
    }

    while (this.input) parse();
    if (this.stack.length && this.options.strict) {
      var node = this.stack.pop();
      throw this.error('missing opening ' + node.type + ': "' + this.orig + '"');
    }

    var eos = this.eos();
    var tok = this.prev();
    if (tok.type !== 'eos') {
      this.ast.nodes.push(eos);
    }

    return this.ast;
  }


function mixin(compiler) {
  define(compiler, '_comment', compiler.comment);
  compiler.map = new utils.SourceMap.SourceMapGenerator();
  compiler.position = { line: 1, column: 1 };
  compiler.content = {};
  compiler.files = {};

  for (var key in exports) {
    define(compiler, key, exports[key]);
  }
}

function mixin ( compiler ) { define ( compiler , '_comment' , compiler . comment ) ; compiler . map = new utils . SourceMap . SourceMapGenerator ( ) ; compiler . position = { line : 1 , column : 1 } ; compiler . content = { } ; compiler . files = { } ; for ( var key in exports ) { define ( compiler , key , exports [ key ] ) ; } }

Mixin source map support into `compiler`.

@param {Object} `compiler`
@api public

Mixin source map support into compiler .


function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

function utf8End ( buf ) { var r = buf && buf . length ? this . write ( buf ) : '' ; if ( this . lastNeed ) return r + '\ufffd' ; return r ; }

For UTF-8, a replacement character is added when ending on a partial character.

For UTF - 8 a replacement character is added when ending on a partial character .


function rangeToPattern(start, stop, options) {
  if (start === stop) {
    return {pattern: String(start), digits: []};
  }

  var zipped = zip(String(start), String(stop));
  var len = zipped.length, i = -1;

  var pattern = '';
  var digits = 0;

  while (++i < len) {
    var numbers = zipped[i];
    var startDigit = numbers[0];
    var stopDigit = numbers[1];

    if (startDigit === stopDigit) {
      pattern += startDigit;

    } else if (startDigit !== '0' || stopDigit !== '9') {
      pattern += toCharacterClass(startDigit, stopDigit);

    } else {
      digits += 1;
    }
  }

  if (digits) {
    pattern += options.shorthand ? '\\d' : '[0-9]';
  }

  return { pattern: pattern, digits: [digits] };
}

function rangeToPattern ( start , stop , options ) { if ( start === stop ) { return { pattern : String ( start ) , digits : [ ] } ; } var zipped = zip ( String ( start ) , String ( stop ) ) ; var len = zipped . length , i = - 1 ; var pattern = '' ; var digits = 0 ; while ( ++ i < len ) { var numbers = zipped [ i ] ; var startDigit = numbers [ 0 ] ; var stopDigit = numbers [ 1 ] ; if ( startDigit === stopDigit ) { pattern += startDigit ; } else if ( startDigit !== '0' || stopDigit !== '9' ) { pattern += toCharacterClass ( startDigit , stopDigit ) ; } else { digits += 1 ; } } if ( digits ) { pattern += options . shorthand ? '\\d' : '[0-9]' ; } return { pattern : pattern , digits : [ digits ] } ; }

Convert a range to a regex pattern
@param {Number} `start`
@param {Number} `stop`
@return {String}


function use(type, fn, options) {
    var offset = 1;

    if (typeof type === 'string' || Array.isArray(type)) {
      fn = wrap(type, fn);
      offset++;
    } else {
      options = fn;
      fn = type;
    }

    if (typeof fn !== 'function') {
      throw new TypeError('expected a function');
    }

    var self = this || app;
    var fns = self[prop];

    var args = [].slice.call(arguments, offset);
    args.unshift(self);

    if (typeof opts.hook === 'function') {
      opts.hook.apply(self, args);
    }

    var val = fn.apply(self, args);
    if (typeof val === 'function' && fns.indexOf(val) === -1) {
      fns.push(val);
    }
    return self;
  }

function
use
(
type
,
fn
,
options
)
{
var
offset
=
1
;
if
(
typeof
type
===
'string'
||
Array
.
isArray
(
type
)
)
{
fn
=
wrap
(
type
,
fn
)
;
offset
++
;
}
else
{
options
=
fn
;
fn
=
type
;
}
if
(
typeof
fn
!==
'function'
)
{
throw
new
TypeError
(
'expected a function'
)
;
}
var
self
=
this
||
app
;
var
fns
=
self
[
prop
]
;
var
args
=
[
]
.
slice
.
call
(
arguments
,
offset
)
;
args
.
unshift
(
self
)
;
if
(
typeof
opts
.
hook
===
'function'
)
{
opts
.
hook
.
apply
(
self
,
args
)
;
}
var
val
=
fn
.
apply
(
self
,
args
)
;
if
(
typeof
val
===
'function'
&&
fns
.
indexOf
(
val
)
===
1
)
{
fns
.
push
(
val
)
;
}
return
self
;
}

Call plugin `fn`. If a function is returned push it into the
`fns` array to be called by the `run` method.

Call plugin fn . If a function is returned push it into the fns array to be called by the run method .


function wrap(type, fn) {
    return function plugin() {
      return this.type === type ? fn.apply(this, arguments) : plugin;
    };
  }

function wrap ( type , fn ) { return function plugin ( ) { return this . type === type ? fn . apply ( this , arguments ) : plugin ; } ; }

Wrap a named plugin function so that it's only called on objects of the
given `type`

@param {String} `type`
@param {Function} `fn` Plugin function
@return {Function}

Wrap a named plugin function so that it s only called on objects of the given type


function memoize(fun) {
  // Making cache = {} an optional ES6 parameter breaks coverage. Why?

  /** @type {({ [key: string]: any })} */
  const cache = {};

  if (fun.length === 1) {
    return (/** @type {any} */ arg) => {
      if (arg in cache) {
        return cache[arg];
      }

      const result = fun(arg);
      cache[arg] = result;
      return result;
    };
  }

  return (/** @type {any} */ arg1, /** @type {any} */ arg2) => {
    if (cache[arg1] && arg2 in cache[arg1]) {
      return cache[arg1][arg2];
    }

    const result = fun(arg1, arg2);

    if (!cache[arg1]) {
      cache[arg1] = {};
    }

    cache[arg1][arg2] = result;

    return result;
  };
}

Caches results of unary or binary function.
@param {(arg1: any, arg2?: any) => any} fun

Caches results of unary or binary function .


function keyblade (obj, opts) {
  opts = Object.assign({
    message: _defaultMessage,
    logBeforeThrow: true,
    ignore: []
  }, opts)
  opts.ignore = (opts.ignore && Array.isArray(opts.ignore)) ? opts.ignore : []

  return new Proxy(obj, {
    get (target, propKey, receiver) {
      const useGetter = Reflect.has(target, propKey, receiver) || _isReserved(propKey, opts.ignore)
      if (useGetter) {
        return Reflect.get(target, propKey, receiver)
      }

      // Leave symbols alone.
      if (typeof propKey === 'symbol') {
        return Reflect.get(target, propKey, receiver)
      }

      const message = opts.message(propKey)
      if (opts.logBeforeThrow) {
        if (typeof opts.logBeforeThrow === 'function') {
          opts.logBeforeThrow(message, propKey)
        } else {
          console.error(message)
        }
      }

      throw new UndefinedKeyError(message)
    }
  })
}

function
keyblade
(
obj
,
opts
)
{
opts
=
Object
.
assign
(
{
message
:
_defaultMessage
,
logBeforeThrow
:
true
,
ignore
:
[
]
}
,
opts
)
opts
.
ignore
=
(
opts
.
ignore
&&
Array
.
isArray
(
opts
.
ignore
)
)
opts
.
ignore
:
[
]
return
new
Proxy
(
obj
,
{
get
(
target
,
propKey
,
receiver
)
{
const
useGetter
=
Reflect
.
has
(
target
,
propKey
,
receiver
)
||
_isReserved
(
propKey
,
opts
.
ignore
)
if
(
useGetter
)
{
return
Reflect
.
get
(
target
,
propKey
,
receiver
)
}
// Leave symbols alone.
if
(
typeof
propKey
===
'symbol'
)
{
return
Reflect
.
get
(
target
,
propKey
,
receiver
)
}
const
message
=
opts
.
message
(
propKey
)
if
(
opts
.
logBeforeThrow
)
{
if
(
typeof
opts
.
logBeforeThrow
===
'function'
)
{
opts
.
logBeforeThrow
(
message
,
propKey
)
}
else
{
console
.
error
(
message
)
}
}
throw
new
UndefinedKeyError
(
message
)
}
}
)
}

Protects the given object by wrapping it in a Proxy.

@param  {object} obj
The object to wrap.

@param  {(string) => string} opts.message
Optional function used to construct the error message.
Will get the key passed as the only argument.

@param {string[]} ignore
Fields to ignore.

@param {bool|Function(message: string, key: string)}
If specified, and is a function, is invoked before throwing.
If specified, and is truthy, `console.error` before throwing.

@return {Proxy<object>}

Protects the given object by wrapping it in a Proxy .


function subRegister(obj, name) {
  var res;
  res = isPrimitive(obj[name]) ? {} : obj[name];
  return obj[name] = mixable(res).mixin(proto, 'register', 'extend');
}

function subRegister ( obj , name ) { var res ; res = isPrimitive ( obj [ name ] ) ? { } : obj [ name ] ; return obj [ name ] = mixable ( res ) . mixin ( proto , 'register' , 'extend' ) ; }

Get or build a sub register for an object.

Get or build a sub register for an object .


function registerDir(leaf, dir, name) {
  var files;
  try {
    files = fs.readdirSync(dir);
  } catch (_error) {}
  if (files == null) {
    return false;
  }
  if (name != null) {
    leaf = subRegister(leaf, name);
  }
  for (var i = 0, len = files.length; i < len; i++) {
    name = files[i];
    leaf.register(dir, name);
  }
  return true;
}

function registerDir ( leaf , dir , name ) { var files ; try { files = fs . readdirSync ( dir ) ; } catch ( _error ) { } if ( files == null ) { return false ; } if ( name != null ) { leaf = subRegister ( leaf , name ) ; } for ( var i = 0 , len = files . length ; i < len ; i ++ ) { name = files [ i ] ; leaf . register ( dir , name ) ; } return true ; }


function containerStatus(original, status, parent) {

  var state = {
    topology: {
      containers: {}
    }
  };

  var container = {
    id: original.id
  };

  if (parent === null) {
    // nothing to do
  } else if (parent !== undefined) {
    container.containedBy = parent;
  } else {
    container.containedBy = original.containedBy;
  }

  if (typeof status === 'string') {

    switch(status) {
      case 'detached':
        container.added   = false;
        container.started = false;
        container.running = false;
        break;
      case 'added':
        container.added   = true;
        break;
      case 'started':
        container.started = true;
        break;
      case 'running':
        container.running = true;
        break;

      default:
        throw new Error('unknown state');
    }

  } else {
    _.forIn(status, function(value, key) {
      container[key] = value;
    });
  }

  if (container.added === false) {
    delete container.containedBy;
  }

  state.topology.containers[container.id] = container;

  return state;
}

function
containerStatus
(
original
,
status
,
parent
)
{
var
state
=
{
topology
:
{
containers
:
{
}
}
}
;
var
container
=
{
id
:
original
.
id
}
;
if
(
parent
===
)
{
// nothing to do
}
else
if
(
parent
!==
undefined
)
{
container
.
containedBy
=
parent
;
}
else
{
container
.
containedBy
=
original
.
containedBy
;
}
if
(
typeof
status
===
'string'
)
{
switch
(
status
)
{
case
'detached'
:
container
.
added
=
false
;
container
.
started
=
false
;
container
.
running
=
false
;
break
;
case
'added'
:
container
.
added
=
true
;
break
;
case
'started'
:
container
.
started
=
true
;
break
;
case
'running'
:
container
.
running
=
true
;
break
;
default
:
throw
new
Error
(
'unknown state'
)
;
}
}
else
{
_
.
forIn
(
status
,
function
(
value
,
key
)
{
container
[
key
]
=
value
;
}
)
;
}
if
(
container
.
added
===
false
)
{
delete
container
.
containedBy
;
}
state
.
topology
.
containers
[
container
.
id
]
=
container
;
return
state
;
}

Creates a container status to be used as a precondition

Valid values for the status parameters are:
- a string, such as 'detached', 'added', 'started', 'running'
- an object, such as { added: true, started: true, running: false }

@param {object} original - the container
@param {object|string} status - the status to set.
@param {object} parent - the parent container's id.


async function lstatFiles(dirPath, dirContent) {
  const readFiles = dirContent.map(async (relativePath) => {
    const path = join(dirPath, relativePath)
    const ls = await makePromise(lstat, path)
    return {
      lstat: ls,
      path,
      relativePath,
    }
  })
  const res = await Promise.all(readFiles)
  return res
}

async function lstatFiles ( dirPath , dirContent ) { const readFiles = dirContent . map ( async ( relativePath ) => { const path = join ( dirPath , relativePath ) const ls = await makePromise ( lstat , path ) return { lstat : ls , path , relativePath , } } ) const res = await Promise . all ( readFiles ) return res }

Update information about directory's content with lstat.
@param {string} dirPath Path to the root directory
@param {!Array<string>} dirContent
@returns {Promise<Array<_readDirStructure.File>>} An array with file objects.

Update information about directory s content with lstat .


async function readDirStructure(dirPath) {
  if (!dirPath) {
    throw new Error('Please specify a path to the directory')
  }
  const ls = await makePromise(lstat, dirPath)
  if (!ls.isDirectory()) {
    const err = new Error('Path is not a directory')
    err.code = 'ENOTDIR'
    throw err
  }
  const dir = /** @type {!Array<string>} */ (await makePromise(readdir, dirPath))
  const lsr = await lstatFiles(dirPath, dir)

  const directories = lsr.filter(isDirectory) // reduce at once
  const notDirectories = lsr.filter(isNotDirectory)

  const files = notDirectories.reduce((acc, current) => {
    const type = getType(current)
    return {
      ...acc,
      [current.relativePath]: {
        type,
      },
    }
  }, {})

  const dirs = await directories.reduce(async (acc, { path, relativePath }) => {
    const res = await acc
    const structure = await readDirStructure(path)
    return {
      ...res,
      [relativePath]: structure,
    }
  }, {})

  const content = {
    ...files,
    ...dirs,
  }
  return {
    content,
    type: 'Directory',
  }
}

Read a directory, and return its structure as an object. Only `Files`, `Directories` and `Symlinks` are included!
@param {string} dirPath Path to the directory.
@returns {Promise<_readDirStructure.DirectoryStructure>} An object reflecting the directory structure.
@example
```js
const res = await readDirStructure('dir')
result:
{
type: 'Directory',
content: {
'data.txt': {
type: 'File'
},
subdir: {
type: 'Directory',
content: {
'data-ln.txt': {
type: 'SymbolicLink'
},
}
}
}
}
```

Read a directory and return its structure as an object . Only Files Directories and Symlinks are included!


function propertyNameToAttribute(name) {
  var result = name.replace(/([A-Z])/g, function (match, letter) {
    return '-' + letter.toLowerCase();
  });
  return 'data-' + result;
}

function propertyNameToAttribute ( name ) { var result = name . replace ( / ([A-Z]) / g , function ( match , letter ) { return '-' + letter . toLowerCase ( ) ; } ) ; return 'data-' + result ; }

Function converts dataset property name "someValue" to "data-some-value".

@param {string} name
@returns {string}
 @function
@param name

Function converts dataset property name someValue to data - some - value .


function generateCommands(origin, dest) {
  var destCmds = _.chain(dest.topology.containers)
    .values()
    .filter(function(container) {
      return container.containedBy === container.id || !container.containedBy;
    })
    .map(function(container) {
      return {
        cmd: 'configure',
        id: container.id
      };
    })
    .value();

  var originCmds = _.chain(origin.topology.containers)
    .values()
    .map(function(container) {
      if (!dest.topology.containers[container.id]) {
        return {
          cmd: 'detach',
          id: container.id
        };
      }

      return null;
    }).filter(function(container) {
      return container !== null;
    })
    .value();

  return destCmds.concat(originCmds);
}

function generateCommands ( origin , dest ) { var destCmds = _ . chain ( dest . topology . containers ) . values ( ) . filter ( function ( container ) { return container . containedBy === container . id || ! container . containedBy ; } ) . map ( function ( container ) { return { cmd : 'configure' , id : container . id } ; } ) . value ( ) ; var originCmds = _ . chain ( origin . topology . containers ) . values ( ) . map ( function ( container ) { if ( ! dest . topology . containers [ container . id ] ) { return { cmd : 'detach' , id : container . id } ; } return null ; } ) . filter ( function ( container ) { return container !== null ; } ) . value ( ) ; return destCmds . concat ( originCmds ) ; }

Generate the configure and detach commands for all root elements.

@param {object} origin - The origin system definition
@param {object} dest - The destination system definition

Generate the configure and detach commands for all root elements .


function Limon (input, options) {
  if (!(this instanceof Limon)) {
    return new Limon(input, options)
  }

  lazy.use(this, {
    fn: function (app, opts) {
      app.options = lazy.utils.extend(app.options, opts)
    }
  })

  this.defaults(input, options)
  this.use(lazy.plugin.prevNext())
}

function Limon ( input , options ) { if ( ! ( this instanceof Limon ) ) { return new Limon ( input , options ) } lazy . use ( this , { fn : function ( app , opts ) { app . options = lazy . utils . extend ( app . options , opts ) } } ) this . defaults ( input , options ) this . use ( lazy . plugin . prevNext ( ) ) }

> Initialize `Limon` with `input` and `options`.
Both are completely optional. You can pass plugins
and tokens to `options`.

**Example**

```js
var Limon = require('limon').Limon
var lexer = new Limon('foo bar')

// or pass only options
var limon = new Limon({ foo: 'bar' })
var tokens = limon.tokenize('baz qux')
```

@param {String} `input` String value to tokenize, or if object it is assumed `options`.
@param {Object} `options` Optional options, use it to pass plugins or tokens.
@api public

> Initialize Limon with input and options . Both are completely optional . You can pass plugins and tokens to options .


function planner(origin, dest, opts)  {

  var tasks   = new TaskPlanner();
  var cmds    = generateCommands(origin, dest);
  var state   = _.cloneDeep(origin);
  var result;

  opts = xtend(defaults, opts);

  assert(opts.mode === 'quick' || opts.mode === 'safe', 'unknown mode');

  tasks.addTask({ cmd: 'nop' }, {});
  generateDetachTasks(tasks, origin, opts);
  generateDetachTasks(tasks, dest, opts); // needed because of safe mode
  generateConfigureTasks(tasks, origin, dest, opts);

  _.forIn(state.topology.containers, function(container) {
    container.running = true;
    container.started = true;
    container.added = true;
  });

  _.forIn(dest.topology.containers, function(container) {
    var containers = state.topology.containers;

    if (!containers[container.id]) {
      containers[container.id] = {
        id: container.id,
        containedBy: container.containedBy,
        running: false,
        started: false,
        added: false
      };
    }
  });

  result = cmds.reduce(function(acc, cmd) {
    var plan = tasks.plan(state, cmd);
    if (!plan) {
      throw new Error('unable to generate ' + cmd.cmd + ' for id ' + cmd.id);
    }
    return acc.concat(plan);
  }, []).filter(function(cmd) {
    return cmd && cmd.cmd !== 'nop';
  });

  if (!opts.noLinkUnlinkRemove) {
    result = linkFilter(result);
  }

  return result;
}

function
planner
(
origin
,
dest
,
opts
)
{
var
tasks
=
new
TaskPlanner
(
)
;
var
cmds
=
generateCommands
(
origin
,
dest
)
;
var
state
=
_
.
cloneDeep
(
origin
)
;
var
result
;
opts
=
xtend
(
defaults
,
opts
)
;
assert
(
opts
.
mode
===
'quick'
||
opts
.
mode
===
'safe'
,
'unknown mode'
)
;
tasks
.
addTask
(
{
cmd
:
'nop'
}
,
{
}
)
;
generateDetachTasks
(
tasks
,
origin
,
opts
)
;
generateDetachTasks
(
tasks
,
dest
,
opts
)
;
// needed because of safe mode
generateConfigureTasks
(
tasks
,
origin
,
dest
,
opts
)
;
_
.
forIn
(
state
.
topology
.
containers
,
function
(
container
)
{
container
.
running
=
true
;
container
.
started
=
true
;
container
.
added
=
true
;
}
)
;
_
.
forIn
(
dest
.
topology
.
containers
,
function
(
container
)
{
var
containers
=
state
.
topology
.
containers
;
if
(
!
containers
[
container
.
id
]
)
{
containers
[
container
.
id
]
=
{
id
:
container
.
id
,
containedBy
:
container
.
containedBy
,
running
:
false
,
started
:
false
,
added
:
false
}
;
}
}
)
;
result
=
cmds
.
reduce
(
function
(
acc
,
cmd
)
{
var
plan
=
tasks
.
plan
(
state
,
cmd
)
;
if
(
!
plan
)
{
throw
new
Error
(
'unable to generate '
+
cmd
.
cmd
+
' for id '
+
cmd
.
id
)
;
}
return
acc
.
concat
(
plan
)
;
}
,
[
]
)
.
filter
(
function
(
cmd
)
{
return
cmd
&&
cmd
.
cmd
!==
'nop'
;
}
)
;
if
(
!
opts
.
noLinkUnlinkRemove
)
{
result
=
linkFilter
(
result
)
;
}
return
result
;
}

Creates a new planner

@param {object} origin - The origin system definition
@param {object} dest - The destination system definition
@param {object} opts - The options


function(strip) {

        if (!strip) {
            console.log(messagingTexts.noStrip);
        }

        if (!(strip instanceof pixel.Strip)) {
            console.log(messagingTexts.wrongStrip);
        }

        pattern.reset(strip, interval);
        interval = pattern.domino(strip, 'white');
    }

function ( strip ) { if ( ! strip ) { console . log ( messagingTexts . noStrip ) ; } if ( ! ( strip instanceof pixel . Strip ) ) { console . log ( messagingTexts . wrongStrip ) ; } pattern . reset ( strip , interval ) ; interval = pattern . domino ( strip , 'white' ) ; }

Set the strip to a loading pattern.
Triggered when the tests have started.

Set the strip to a loading pattern . Triggered when the tests have started .


function(strip) {

        if (!strip) {
            console.log(messagingTexts.noStrip);
        }

        if (!(strip instanceof pixel.Strip)) {
            console.log(messagingTexts.wrongStrip);
        }

        pattern.reset(strip, interval);
        setTimeout(function() {
            pattern.flash(strip, 'green', 2);
        }, 10);
    }

function ( strip ) { if ( ! strip ) { console . log ( messagingTexts . noStrip ) ; } if ( ! ( strip instanceof pixel . Strip ) ) { console . log ( messagingTexts . wrongStrip ) ; } pattern . reset ( strip , interval ) ; setTimeout ( function ( ) { pattern . flash ( strip , 'green' , 2 ) ; } , 10 ) ; }

Flash the strip with green lights,
indicating tests were successful.

Flash the strip with green lights indicating tests were successful .


function create(parent, baseUrl, params, callback) {
  parent.getClient().post(baseUrl, params, function(err, definition, response) {
    if (err) return callback(err);
    callback(null, new this(parent, definition));
  }.bind(this));
}

function create ( parent , baseUrl , params , callback ) { parent . getClient ( ) . post ( baseUrl , params , function ( err , definition , response ) { if ( err ) return callback ( err ) ; callback ( null , new this ( parent , definition ) ) ; } . bind ( this ) ) ; }

Creates a new resource.

@param {Function} parent The parent this resource should be attached to.
@param {String} baseUrl That's needed for sub resources (/api/v2/customers/1/cases).
@param {Object} params The params to use for the resource.
@param {Function} callback The callback called with the new resource or error.
@api public


function register ( type, lang, handler ) {
    if (Array.isArray(lang)) {
        lang.forEach((v) => store[type].langs[v] = handler);
        return;
    }
    store[type].langs[lang] = handler;
}

function register ( type , lang , handler ) { if ( Array . isArray ( lang ) ) { lang . forEach ( ( v ) => store [ type ] . langs [ v ] = handler ) ; return ; } store [ type ] . langs [ lang ] = handler ; }

Register Loader of different Language
@param {String | String[]} type | style | script | template |
@param {String} lang scss, ts, jade etc.
@param {Function} handler


function( kind, promisesDfd ) {
  return function() {
    // operate on this unless we forced a deferred to work on
    var dfd = promisesDfd || this;
    var fnSet = [].slice.call( arguments );

    // as long as this is a progress handler or the state isn't reached add it
    // otherwise call it right now
    if ( kind === 'progress' || dfd.state === 'pending' ) {
      dfd[ kind + 's' ].push( fnSet );
    } else {
      callSet.call( dfd, fnSet, this[ kind + 'Args' ] );
    }

    // if we forced a promiseDfd, return the promise
    if ( promisesDfd ) {
      return dfd.promise;
    }
    // otherwise return the root deferred like normal
    return dfd;
  };
}

generator to add callbacks to a bucked and possible fire them


function( set, args) {

  // nothing to see here folks
  if ( set.length <  1 ) {
    return;
  }

  // the args to call with
  var apply = [];

  // we passed inline arguments
  if ( set.length > 1 ) {
    for ( var i = 1; i < set.length; i++ ) {
      // is it one of those cool perform.arg(X) thingies?
      // if not, just put the passed args in there
      if ( set[i] instanceof Argument ) {
        apply[i] = args[ set[i].num ];
      } else {
        apply[i] = set[i];
      }
      apply = apply.slice(1);
    }
  } else {
    apply = args;
  }

  // actually call the fn with the appropriate args
  set[0].apply( this, apply );
}


function( kind, args ) {
  var bucket = this[ kind + 's' ];
  for ( var i = 0; i < bucket.length; i++ ) {
    callSet.call( this, bucket[i], args );
  }
}

function ( kind , args ) { var bucket = this [ kind + 's' ] ; for ( var i = 0 ; i < bucket . length ; i ++ ) { callSet . call ( this , bucket [ i ] , args ) ; } }

call all the callback sets in a callback bucket


function() {
  var dfd = this;
  // since people might be used to .promise()
  var promise = function(){
    return promise;
  };
  promise.done = stackNFire( 'done', dfd );
  promise.fail = stackNFire( 'fail', dfd );
  promise.progress = stackNFire( 'progress', dfd );
  promise.state = dfd.state;
  return promise;
}


function( kind ) {
  return function() {
    if ( this.state === 'pending' ) {
      if ( kind !== 'progress' ) {
        this[ kind + 'Args' ] = arguments;
        this.state = this.promise.state = kind;
      }
      callSets.call( this, kind, arguments );
    }
    return this;
  };
}

function ( kind ) { return function ( ) { if ( this . state === 'pending' ) { if ( kind !== 'progress' ) { this [ kind + 'Args' ] = arguments ; this . state = this . promise . state = kind ; } callSets . call ( this , kind , arguments ) ; } return this ; } ; }


function() {
  this.dones = [];
  this.doneArgs = [];
  this.fails = [];
  this.failArgs = [];
  this.pendings = [];
  this.pendingArgs = [];
  this.state = 'pending';

  // expose the promise
  this.promise = iPromise.call( this );

}

function
(
)
{
this
.
dones
=
[
]
;
this
.
doneArgs
=
[
]
;
this
.
fails
=
[
]
;
this
.
failArgs
=
[
]
;
this
.
pendings
=
[
]
;
this
.
pendingArgs
=
[
]
;
this
.
state
=
'pending'
;
// expose the promise
this
.
promise
=
iPromise
.
call
(
this
)
;
}


function( performer ) {
  // everything checks out
  var state = performer.state;

  // everything resolved
  if ( state.allCount === 0 ) {

    var args = [];
    for ( var i = 0; i < performer.args.length; i++ ) {
      args = args.concat( [].concat( performer.args[i].args ) );
    }
    // either fail/done are 0 or something went wrong
    if ( state.targetCount === 0 ) {
      performer._dfd.resolve.apply ( performer._dfd, args );
    } else {
      performer._dfd.reject.apply( performer._dfd, args );
    }
  }
}

upon any action on the dependencies, check the resolution

upon any action on the dependencies check the resolution


function(schema) {
  this._decoders = decoders;
  this._encoders = encoders;
  this._schemas = {};

  // Allow to pass the fields direclty
  if(Object.keys(schema).join(',') !== 'name,fields'){
    schema = {
      name: '_auto-' + new Date().getTime(),
      fields: schema
    };
  }

  this._schema = schema;
  this._fieldIndex = Object.keys(schema.fields);
  this._schemas[schema.name] = schema;
}

function
(
schema
)
{
this
.
_decoders
=
decoders
;
this
.
_encoders
=
encoders
;
this
.
_schemas
=
{
}
;
// Allow to pass the fields direclty
if
(
Object
.
keys
(
schema
)
.
join
(
','
)
!==
'name,fields'
)
{
schema
=
{
name
:
'_auto-'
+
new
Date
(
)
.
getTime
(
)
,
fields
:
schema
}
;
}
this
.
_schema
=
schema
;
this
.
_fieldIndex
=
Object
.
keys
(
schema
.
fields
)
;
this
.
_schemas
[
schema
.
name
]
=
schema
;
}

Bolty main class
@class
@param {object} schema The main schmma.
@example
```javascript
var Bolty = require('bolty');
var schema = {
name: 'string',
surname: 'string'
};
var template = new Bolty(schema);
```


function(selector, properties, value) {
    let rule = postcss.rule({selector: selector})

    let decls = _.map(properties, function(property) {
        return postcss.decl({prop: property, value: value})
    })

    rule.append(decls)

    return rule
}

function ( selector , properties , value ) { let rule = postcss . rule ( { selector : selector } ) let decls = _ . map ( properties , function ( property ) { return postcss . decl ( { prop : property , value : value } ) } ) rule . append ( decls ) return rule }

Make a functional CSS rule
@param  {string} selector   The selector to use including a dot or hash (. or #)
@param  {array} properties The property names to assign to the declaration
@param  {string} value      The value for each declaration
@return {array}            an array of PostCSS Rules


function(breakpoints, spacingScale) {
    return _.map(breakpoints, function(breakpointValue, breakpointKey) {
        let mediaQuery = postcss.atRule({
            name: 'media',
            params: breakpointValue,
        })

        let rules = _.flatMap(spacingScale, function(scaleValue, scaleKey) {
            return _.map(helpers, function(helperValues, helperKey) {
                return makeFunctionalRule(
                    `.${breakpointKey}-${helperKey}${scaleKey}`,
                    helperValues,
                    scaleValue
                )
            })
        })

        return mediaQuery.append(rules)
    })
}

function ( breakpoints , spacingScale ) { return _ . map ( breakpoints , function ( breakpointValue , breakpointKey ) { let mediaQuery = postcss . atRule ( { name : 'media' , params : breakpointValue , } ) let rules = _ . flatMap ( spacingScale , function ( scaleValue , scaleKey ) { return _ . map ( helpers , function ( helperValues , helperKey ) { return makeFunctionalRule ( ` ${ breakpointKey } ${ helperKey } ${ scaleKey } ` , helperValues , scaleValue ) } ) } ) return mediaQuery . append ( rules ) } ) }

Generate a complete set of responsive spacing helpers
@param  {object} breakpoints A set of breakpoints to generate the spacer for
@param  {object} spacingScale The spacing scale to use
@return {array}             Rules


function destroy(callback) {
  this.getClient().destroy(this.definition._links.self.href, function(err, definition, response) {
    if (err) return callback(err);
    callback();
  }.bind(this));
}

function destroy ( callback ) { this . getClient ( ) . destroy ( this . definition . _links . self . href , function ( err , definition , response ) { if ( err ) return callback ( err ) ; callback ( ) ; } . bind ( this ) ) ; }

Allows a resource to be deleted.

@param {Function} callback The callback to call with an error message if there was an error
@api public


function load_config () {
	let config = {};
	if (fs.existsSync(pgrunner_config_file)) {
		config = JSON.parse(fs.readFileSync(pgrunner_config_file, {'encoding':'utf8'}));
		if (argv.v) {
			debug.log('Loaded from ', pgrunner_config_file);
		}
	}
	if (!is.array(config.servers)) {
		config.servers = [];
	}
	return config;
}

function
load_config
(
)
{
let
config
=
{
}
;
if
(
fs
.
existsSync
(
pgrunner_config_file
)
)
{
config
=
JSON
.
parse
(
fs
.
readFileSync
(
pgrunner_config_file
,
{
'encoding'
:
'utf8'
}
)
)
;
if
(
argv
.
v
)
{
debug
.
log
(
'Loaded from '
,
pgrunner_config_file
)
;
}
}
if
(
!
is
.
array
(
config
.
servers
)
)
{
config
.
servers
=
[
]
;
}
return
config
;
}


function save_config (config) {
	fs.writeFileSync(pgrunner_config_file, JSON.stringify(config, null, 2), {'encoding':'utf8'});
	if (argv.v) {
		debug.log('Saved to ', pgrunner_config_file);
	}
}

function
save_config
(
config
)
{
fs
.
writeFileSync
(
pgrunner_config_file
,
JSON
.
stringify
(
config
,
,
2
)
,
{
'encoding'
:
'utf8'
}
)
;
if
(
argv
.
v
)
{
debug
.
log
(
'Saved to '
,
pgrunner_config_file
)
;
}
}


function get_server_opts (opts) {
	debug.assert(opts).is('object');
	debug.assert(opts.settings).is('object');
	return {
		'dbconfig': opts.dbconfig,
		'host': opts.settings.host,
		'port': opts.settings.port,
		'user': opts.settings.user,
		'database': opts.settings.database
	};
}

function get_server_opts ( opts ) { debug . assert ( opts ) . is ( 'object' ) ; debug . assert ( opts . settings ) . is ( 'object' ) ; return { 'dbconfig' : opts . dbconfig , 'host' : opts . settings . host , 'port' : opts . settings . port , 'user' : opts . settings . user , 'database' : opts . settings . database } ; }

Returns server options

@param opts
@returns {{database: *, port: (*|number), dbconfig: *, host: (*|string), user: *}}


function getResources(domains) {
  return store.getResources().then(rsrcs => {
    return rsrcs.filter(e => domains.includes(e.domain));
  });
}

function getResources ( domains ) { return store . getResources ( ) . then ( rsrcs => { return rsrcs . filter ( e => domains . includes ( e . domain ) ) ; } ) ; }


function urlFormat(obj) {
    // ensure it's an object, and not a string url.
    // If it's an obj, this is a no-op.
    // this way, you can call url_format() on strings
    // to clean up potentially wonky urls.
    if (isString(obj)) {
        obj = urlParse(obj);
    } else if (!isObject(obj) || isNull(obj)) {
        throw new TypeError('Parameter "urlObj" must be an object, not ' +
            isNull(obj) ? 'null' : typeof obj);
    } else if (!(obj instanceof Url)) {
        return Url.prototype.format.call(obj);
    } else {
        return obj.format();
    }
}

format a parsed object into a url string


function rayLineVsCircle(ray, circle) {
  var rayLine = new Line2(
    ray.start.x,
    ray.start.y,
    ray.end.x,
    ray.end.y
  );

  return rayLine.intersectCircle(circle.position, circle.radius);
}

function rayLineVsCircle ( ray , circle ) { var rayLine = new Line2 ( ray . start . x , ray . start . y , ray . end . x , ray . end . y ) ; return rayLine . intersectCircle ( circle . position , circle . radius ) ; }

Treats ray like an infinite line see where it intersects circle.

@param {object} ray - ray-like
@param {Circle2} circle
@return {Array} containing 0, 1, or 2 Vec2 where line hits circle

Treats ray like an infinite line see where it intersects circle .


function scopeUrl(options, inst) {
    options = _.extend(_.clone(options || {}), inst)
    if (typeof options !== 'object' && (!options.tournament_id || !options.flight_id))
      throw new Error('tournament_id or flight_id required to make tibreak preference api calls')

    var url = ''
    if (options.tournament_id) {
      url += ngin.Tournament.urlRoot() + '/' + options.tournament_id
    } else if (options.flight_id) {
      url += ngin.Flight.urlRoot() + '/' + options.flight_id
    }
    return url + TiebreakPreference.urlRoot()
  }

Scopes the url to the tournament, league, or flight

@param {Object} options
@returns {String}
@api public

Scopes the url to the tournament league or flight


function(options, callback) {
      var url = scopeUrl(options, this)
      return Super.fetch.call(this, url, options, callback)
    }

function ( options , callback ) { var url = scopeUrl ( options , this ) return Super . fetch . call ( this , url , options , callback ) }

Fetch is used by Tournament and list is being used by Flight. Can those be consolidated?

Fetch is used by Tournament and list is being used by Flight . Can those be consolidated?


function(module, debug) {
  this.debug = debug || false;
  this.jsonrpc = "2.0";
  // check & load the methods in module
  this.methods = module;
  if(handy.getType(module)=='string') {
    this.methods = require(module);
  }
  if(this.debug) {
    logger.debug('Loaded with methods:'+_.functions(this.methods));
  }
}

function
(
module
,
debug
)
{
this
.
debug
=
debug
||
false
;
this
.
jsonrpc
=
"2.0"
;
// check & load the methods in module
this
.
methods
=
module
;
if
(
handy
.
getType
(
module
)
==
'string'
)
{
this
.
methods
=
require
(
module
)
;
}
if
(
this
.
debug
)
{
logger
.
debug
(
'Loaded with methods:'
+
_
.
functions
(
this
.
methods
)
)
;
}
}


function _getParamNames(func) {
  var funStr = func.toString();
  return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
}

function _getParamNames ( func ) { var funStr = func . toString ( ) ; return funStr . slice ( funStr . indexOf ( '(' ) + 1 , funStr . indexOf ( ')' ) ) . match ( / ([^\s,]+) / g ) ; }


function _getChangedProperties() {
  var retVal = {}, key;
  for (key in this._changed) {
    retVal[key] = this._changed[key];
  }
  return retVal;
}

function _getChangedProperties ( ) { var retVal = { } , key ; for ( key in this . _changed ) { retVal [ key ] = this . _changed [ key ] ; } return retVal ; }

Get only changed properties as a hash.

@return {Object}
@api private


function update(properties, callback) {
  if (typeof properties == 'function') {
    callback = properties;
    properties = {};
  }

  var key, changed;
  var exceptions = ['addresses_update_action', 'emails_update_action', 'phone_numbers_update_action'];
  for (key in properties) {
    if ('set' + inflection.camelize(key) in this) {
      this['set' + inflection.camelize(key)](properties[key]);
    } else if(exceptions.indexOf(key) != -1) {
      this._changed[key] = properties[key];
    }
  }

  changed = this._getChangedProperties();
  this.getClient().patch(this.definition._links.self.href, changed, function(err, definition, response) {
    if (err) return callback(err);
    this.definition = definition;
    this._setup();
    callback(null, this);
  }.bind(this));
}

function update ( properties , callback ) { if ( typeof properties == 'function' ) { callback = properties ; properties = { } ; } var key , changed ; var exceptions = [ 'addresses_update_action' , 'emails_update_action' , 'phone_numbers_update_action' ] ; for ( key in properties ) { if ( 'set' + inflection . camelize ( key ) in this ) { this [ 'set' + inflection . camelize ( key ) ] ( properties [ key ] ) ; } else if ( exceptions . indexOf ( key ) != - 1 ) { this . _changed [ key ] = properties [ key ] ; } } changed = this . _getChangedProperties ( ) ; this . getClient ( ) . patch ( this . definition . _links . self . href , changed , function ( err , definition , response ) { if ( err ) return callback ( err ) ; this . definition = definition ; this . _setup ( ) ; callback ( null , this ) ; } . bind ( this ) ) ; }

Allows a resource to be updated.

@param {Object|Function} properties A hash of fields to be updated or the callback.
@param {Function} callback The callback to call with the updated resource or an error message.
@api public


function byClass (c) {
  c = classnames(c)
  if (/^\./.test(c)) {
    throw new Error('No need to "." on start')
  }
  return bySelector(`.${c}`)
}

function
byClass
(
c
)
{
c
=
classnames
(
c
)
if
(
/
^\.
/
.
test
(
c
)
)
{
throw
new
Error
(
'No need to "." on start'
)
}
return
bySelector
(
`
${
c
}
`
)
}

By class name
@param {string} c - Class name
@returns {string} Selector by class


function subtemplate(template, data) {
	try {
		return new JSDOC.JsPlate(publish.conf.templatesDir+template).process(data);
	}
	catch(e) { print(e.message); quit(); }
}

function subtemplate ( template , data ) { try { return new JSDOC . JsPlate ( publish . conf . templatesDir + template ) . process ( data ) ; } catch ( e ) { print ( e . message ) ; quit ( ) ; } }

Include a sub-template in the current template, specifying a data object

Include a sub - template in the current template specifying a data object


function makeSignature(params) {
	if (!params) return "()";
	var signature = "("
	+
	params.filter(
		function($) {
      return !/\w+\.\w+/.test($.name);
		}
	).map(
		function($) {
      var name = $.isOptional ?
          '[' + $.name + ']' : $.name;
			return name;
		}
	).join(", ")
	+
	")";
	return signature;
}

function
makeSignature
(
params
)
{
if
(
!
params
)
return
"()"
;
var
signature
=
"("
+
params
.
filter
(
function
(
$
)
{
return
!
/
\w+\.\w+
/
.
test
(
$
.
name
)
;
}
)
.
map
(
function
(
$
)
{
var
name
=
$
.
isOptional
'['
+
$
.
name
+
']'
:
$
.
name
;
return
name
;
}
)
.
join
(
", "
)
+
")"
;
return
signature
;
}

Build output for displaying function parameters.

Build output for displaying function parameters .


function approach(index, x, onAxis)
        {
            while (0 <= x && x <= 1) {
                candidateHSVA[index] = x;
                WebInspector.Color.hsva2rgba(candidateHSVA, candidateRGBA);
                WebInspector.Color.blendColors(candidateRGBA, bgRGBA, blendedRGBA);
                var fgLuminance = WebInspector.Color.luminance(blendedRGBA);
                var dLuminance = fgLuminance - desiredLuminance;

                if (Math.abs(dLuminance) < (onAxis ? epsilon / 10 : epsilon))
                    return x;
                else
                    x += (index === V ? -dLuminance : dLuminance);
            }
            return null;
        }

function approach ( index , x , onAxis ) { while ( 0 <= x && x <= 1 ) { candidateHSVA [ index ] = x ; WebInspector . Color . hsva2rgba ( candidateHSVA , candidateRGBA ) ; WebInspector . Color . blendColors ( candidateRGBA , bgRGBA , blendedRGBA ) ; var fgLuminance = WebInspector . Color . luminance ( blendedRGBA ) ; var dLuminance = fgLuminance - desiredLuminance ; if ( Math . abs ( dLuminance ) < ( onAxis ? epsilon / 10 : epsilon ) ) return x ; else x += ( index === V ? - dLuminance : dLuminance ) ; } return null ; }

Approach the desired contrast ratio by modifying the given component
from the given starting value.
@param {number} index
@param {number} x
@param {boolean} onAxis
@return {?number}

Approach the desired contrast ratio by modifying the given component from the given starting value .


function updateNodeColor(data) {
  d3.selectAll('.node').select('.node-symbol')
    .style('fill', d => d3scale.scaleFunction(data.scale)(d[data.column.key]));
}

function updateNodeColor ( data ) { d3 . selectAll ( '.node' ) . select ( '.node-symbol' ) . style ( 'fill' , d => d3scale . scaleFunction ( data . scale ) ( d [ data . column . key ] ) ) ; }


function mainControlBox() {
  d3.select('#show-struct')
    .on('change', function () {
      const data = nodeContentInput();
      d3.select('#main-control').datum(data);
      updateNodeStructure(data);
    })
    .dispatch('change');
}

function mainControlBox ( ) { d3 . select ( '#show-struct' ) . on ( 'change' , function ( ) { const data = nodeContentInput ( ) ; d3 . select ( '#main-control' ) . datum ( data ) ; updateNodeStructure ( data ) ; } ) . dispatch ( 'change' ) ; }


function centerGraph(newScale, duration, delay)
   {
      if (typeof delay === 'function') { delay = delay.call(this); }

      delay = typeof delay === 'number' ? delay : 0;

      setTimeout(function()
      {
         if (typeof newScale === 'function') { newScale = newScale.call(this); }
         if (typeof duration === 'function') { duration = duration.call(this); }

         newScale = typeof newScale === 'number' ? newScale : zoom.scale();
         duration = typeof duration === 'number' ? duration : 200;

         if (typeof newScale !== 'number') { throw new TypeError("centerGraph error: 'newScale' is not a 'number'."); }
         if (typeof duration !== 'number') { throw new TypeError("centerGraph error: 'duration' is not a 'number'."); }

         var bounds = graph.node().getBBox();

         var centerSVGX = (graphWidth * newScale / 2);
         var centerSVGY = (graphHeight * newScale / 2);

         var centerGraphX = (bounds.x * newScale) + (bounds.width * newScale / 2);
         var centerGraphY = (bounds.y * newScale) + (bounds.height * newScale / 2);

         // Translate
         var centerTranslate =
         [
            (graphWidth / 2) - centerSVGX + (centerSVGX - centerGraphX),
            (graphHeight / 2) - centerSVGY + (centerSVGY - centerGraphY)
         ];

         // Store values
         zoom
          .translate(centerTranslate)
          .scale(newScale);

         // Render transition
         graph.transition()
          .duration(duration)
          .attr('transform', 'translate(' + zoom.translate() + ')' + ' scale(' + zoom.scale() + ')');

         // Hides any existing node context menu.
         hideNodeContextMenu();

      }, delay);
   }

Centers the graph. All parameters can be either a number or a function evaluated for a number result.

`newScale` and `duration` are evaluated in the centering anonymous function allowing values to be determined
after debounce.

@param {number|function}   newScale - New scale value for graph.
@param {number|function}   duration - Duration of centering transition.
@param {number|function}   delay - Delay for debounce before centering occurs.

Centers the graph . All parameters can be either a number or a function evaluated for a number result .


function detectAllNodesFixed()
   {
      if (data)
      {
         var currentNodesFixed = data.allNodesFixed;
         var allNodesFixed = true;
         data.nodes.forEach(function(node) { if (!node.fixed) { allNodesFixed = false; } });
         data.allNodesFixed = allNodesFixed;
         if (currentNodesFixed !== allNodesFixed) { updateMenuUI(); } // Update freeze / unfreeze menu option.
      }
   }

Helper function to determin if all nodes are fixed. This is run after any node is dragged and set to fixed.

Helper function to determin if all nodes are fixed . This is run after any node is dragged and set to fixed .


function fadeRelatedNodes(targetNode, selected, nodes, links)
   {
      var opacity = selected ? 0.1 : 1;

      var elm = findElementByNode('circle', targetNode);

      // Highlight circle
      elm.classed('selected', opacity < 1);

      // Clean links
      $('path.link').removeAttr('data-show');

      // Traverse all nodes and set `dimmed` class to nodes that are dimmed / not connected in addition to setting
      // fill and stroke opacity.
      nodes.style('stroke-opacity', function(otherNode)
      {
         var thisOpacity = isConnected(targetNode, otherNode) ? 1 : opacity;

         this.setAttribute('fill-opacity', thisOpacity);
         this.setAttribute('stroke-opacity', thisOpacity);

         // Depending on opacity add or remove 'dimmed' class.
         this.classList[thisOpacity === 1 ? 'remove' : 'add']('dimmed');

         return thisOpacity;
      });

      // Traverse all links and set `data-show` and `marker-end` for connected links given the `targetNode`.
      links.style('stroke-opacity', function(otherNode)
      {
         if (otherNode.source === targetNode)
         {
            // Highlight target / sources of the link
            var elmNodes = graph.selectAll('.' + formatClassName('node', otherNode.target));
            elmNodes.attr('fill-opacity', 1);
            elmNodes.attr('stroke-opacity', 1);

            elmNodes.classed('dimmed', false);

            // Highlight arrows
            var elmCurrentLink = $('path.link[data-source=' + otherNode.source.index + ']');
            elmCurrentLink.attr('data-show', true);
            elmCurrentLink.attr('marker-end', 'url(#regular)');

            return 1;
         }
         else
         {
            return opacity;
         }
      });

      // Modify all links that have not had 'data-show' added above.
      var elmAllLinks = $('path.link:not([data-show])');
      elmAllLinks.attr('marker-end', opacity === 1 ? 'url(#regular)' : '');
   }

Fades and unfades connected nodes to a given `targetNode`.

@param {object}   targetNode - The target node from which fading occurs / connections are calculated.
@param {boolean}  selected - Indicates if the fade is in / out; true fades nodes / false un-fades nodes.
@param {Array}    nodes - An array of all graph nodes.
@param {Array}    links - An array of all graph links.

Fades and unfades connected nodes to a given targetNode .


function findElementByNode(prefix, node)
   {
      var selector = '.' + formatClassName(prefix, node);
      return graph.select(selector);
   }

function findElementByNode ( prefix , node ) { var selector = '.' + formatClassName ( prefix , node ) ; return graph . select ( selector ) ; }

A helper to select a given SVG element from given node data.

@param {string}   prefix - String prefix.
@param {object}   node - Node object

A helper to select a given SVG element from given node data .


function getElementCoords(element)
   {
      var ctm = element.getCTM();

      return { x: ctm.e + element.getAttribute('cx') * ctm.a, y: ctm.f + element.getAttribute('cy') * ctm.d };
   }

function getElementCoords ( element ) { var ctm = element . getCTM ( ) ; return { x : ctm . e + element . getAttribute ( 'cx' ) * ctm . a , y : ctm . f + element . getAttribute ( 'cy' ) * ctm . d } ; }

Pass in the element and the screen coordinates are returned.

@param element

@returns {{x: number, y: number}}

Pass in the element and the screen coordinates are returned .


function getSVG(elementType)
   {
      var returnVal;
      var svgElement;
      var cached;

      switch (elementType)
      {
         case 'circle':
         case 'g':
         case 'path':
         case 'text':
            returnVal = function(data)
            {
               svgElement = svgElementMap[elementType].pop();

               cached = svgElement != null;

               svgElement = svgElement != null ? svgElement : document.createElementNS('http://www.w3.org/2000/svg',
                elementType);

               // Copy data to SVG element.
               if (typeof data === 'object') { for (var key in data) { svgElement.setAttribute(key, data[key]); } }

               return svgElement;
            };
            break;

         default:
            throw new TypeError('getSVG error: unknown elementType.');
      }

      return returnVal;
   }

function
getSVG
(
elementType
)
{
var
returnVal
;
var
svgElement
;
var
cached
;
switch
(
elementType
)
{
case
'circle'
:
case
'g'
:
case
'path'
:
case
'text'
:
returnVal
=
function
(
data
)
{
svgElement
=
svgElementMap
[
elementType
]
.
pop
(
)
;
cached
=
svgElement
!=
;
svgElement
=
svgElement
!=
svgElement
:
document
.
createElementNS
(
'http://www.w3.org/2000/svg'
,
elementType
)
;
// Copy data to SVG element.
if
(
typeof
data
===
'object'
)
{
for
(
var
key
in
data
)
{
svgElement
.
setAttribute
(
key
,
data
[
key
]
)
;
}
}
return
svgElement
;
}
;
break
;
default
:
throw
new
TypeError
(
'getSVG error: unknown elementType.'
)
;
}
return
returnVal
;
}

Gets a recycled SVG element from the pool, `svgElementMap`, or creates a new element for the given type. Any
data specified by D3 will be copied to the element. Returns a function which is evaluated by D3.

@param {string}   elementType - SVG element: `circle`, `g`, `path`, or `text`.

@returns {*}

Gets a recycled SVG element from the pool svgElementMap or creates a new element for the given type . Any data specified by D3 will be copied to the element . Returns a function which is evaluated by D3 .


function hideNodeContextMenu(event)
   {
      // Provide an early out if there is no selected context node.
      if (typeof selectedContextNode === 'undefined') { return; }

      var contextMenuButton = $('#context-menu');
      var popupmenu = $('#contextpopup .mdl-menu__container');

      // If an event is defined then make sure it isn't targeting the context menu.
      if (event)
      {
         event.preventDefault();

         // Picked element is not the menu
         if (!$(event.target).parents('#contextpopup').length > 0)
         {
            // Hide menu if currently visible
            if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }

            fadeRelatedNodes(selectedContextNode, false, nodes, links);
            selectedContextNode = undefined;
         }
      }
      else // No event defined so always close context menu and remove node highlighting.
      {
         // Hide menu if currently visible
         if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }

         fadeRelatedNodes(selectedContextNode, false, nodes, links);
         selectedContextNode = undefined;
      }
   }

Hides the node context menu if visible and removes any node highlighting. If an event is supplied it is checked
against any existing context menu and is ignored if the context menu is within the parent hierarchy.

@param {object|undefined}  event - Optional event

Hides the node context menu if visible and removes any node highlighting . If an event is supplied it is checked against any existing context menu and is ignored if the context menu is within the parent hierarchy .


function isConnected(targetNode, otherNode)
   {
      return targetNode.index === otherNode.index || linkedByIndex[targetNode.index + ',' + otherNode.index];
   }

function isConnected ( targetNode , otherNode ) { return targetNode . index === otherNode . index || linkedByIndex [ targetNode . index + ',' + otherNode . index ] ; }

Checks if a target node is connected to another given node by checking `index` or the `linkedByIndex` map.

@param {object}   targetNode
@param {object}   otherNode

@returns {boolean}

Checks if a target node is connected to another given node by checking index or the linkedByIndex map .


function onControlDepsClicked()
   {
      // Do nothing if scope has not changed
      if (this.value === appOptions.currentScope) { return; }

      // If max depth is set to sticky and current level is equal max level of old scope then set max level for
      // the new scope.
      if (appOptions.maxDepthSticky && appOptions.currentLevel === dataPackageMap[appOptions.currentScope].maxLevel)
      {
         appOptions.currentLevel = dataPackageMap[this.value].maxLevel
      }

      appOptions.currentScope = this.value;

      var maxLevel = dataPackageMap[appOptions.currentScope].maxLevel;

      // Adjust current level if it is greater than max level for current scope.
      if (appOptions.currentLevel > maxLevel) { appOptions.currentLevel = maxLevel; }

      // Update control level UI based on current and max level for given scope.
      $('.control-level input').attr({ max: maxLevel });
      $('.control-level input').val(appOptions.currentLevel);
      $('.control-level label').html(appOptions.currentLevel);

      // Redraw graph data
      updateAll({ redrawOnly: true });

      // Center graph w/ zoom fit w/ 1 second transition applied after a potential 2 seconds delay for debounce.
      centerGraph(zoomFit, 1000, data.allNodesFixed ? 0 : 2000);
   }

Handles responding to the dependencies radio group.

Handles responding to the dependencies radio group .


function onControlLevelChanged()
   {
      appOptions.currentLevel = parseInt(this.value);

      $('.control-level input').val(appOptions.currentLevel);
      $('.control-level label').html(appOptions.currentLevel);

      // Redraw graph data
      updateAll({ redrawOnly: true });

      // Center graph w/ zoom fit w/ 1 second transition applied after a potential 2 seconds delay for debounce.
      centerGraph(zoomFit, 1000, data.allNodesFixed ? 0 : 2000);
   }

Handles responding to the level slider .


function onControlMenuClicked()
   {
      switch ($(this).data('action'))
      {
         case 'toggleFreezeAllNodes':
            setNodesFixed(!data.allNodesFixed);
            break;

         case 'showFullNames':
            appOptions.showFullNames = !appOptions.showFullNames;
            updateAll({ redrawOnly: true });
            break;

         case 'showTableView':
            appOptions.showTableView = !appOptions.showTableView;
            $('.control-table').toggleClass('hidden', !appOptions.showTableView);
            updateTableUIExtent();
            break;

         case 'maxDepthSticky':
            appOptions.maxDepthSticky = !appOptions.maxDepthSticky;
            break;
      }

      // Defer updating menu UI until menu is hidden.
      setTimeout(updateMenuUI, 200);
   }

Handles responding to overflow menu selections.

Handles responding to overflow menu selections .


function onControlTableRowContextClick(node, event)
   {
      event.preventDefault(); // Prevents default browser context menu from showing.
      onNodeContextClick(node, { x: event.pageX, y: event.pageY });
   }

Handles a context click on a table row showing the related node context menu.

@param {object}   node - Target node.
@param {object}   event - mouse event

Handles a context click on a table row showing the related node context menu .


function onControlTableRowMouseOver(nodes, links, node, enter)
   {
      // Hide the node context menu if currently showing when a new table row / node is moused over.
      if (node !== selectedContextNode) { hideNodeContextMenu(event); }

      onNodeMouseOverOut(nodes, links, enter, node);
   }

Handles a context click on a table row showing the related node context menu. Defers to `onNodeMouseOverOut`.

@param {Array}    nodes - All graph nodes.
@param {Array}    links - All graph links.
@param {object}   node - Target node.
@param {boolean}  enter - true when mouse entering / false when mouse exiting.

Handles a context click on a table row showing the related node context menu . Defers to onNodeMouseOverOut .


function onControlZoomClicked()
   {
      var newScale = 1;
      var scalePercentile = 0.20;

      // Add or subtract scale percentile from current scale value.
      switch ($(this).data('action'))
      {
         case 'zoom_in':
            newScale = Math.max(Math.min(zoom.scale() * (1 + scalePercentile), maxScaleExtent), minScaleExtent);
            break;

         case 'zoom_out':
            newScale = Math.max(zoom.scale() * (1 - scalePercentile), minScaleExtent);
            break;

         case 'zoom_all_out':
            newScale = zoomFit();
            break;
      }

      centerGraph(newScale);
   }

Handles clicks on zoom control buttons and invokes `centerGraph` with new scale value.

Handles clicks on zoom control buttons and invokes centerGraph with new scale value .


function onNodeContextMenuClick()
   {
      // When a context menu is selected remove node highlighting.
      hideNodeContextMenu();
console.log('!! action: ' + $(this).data('action') + '; link: ' + $(this).data('link'));

      switch ($(this).data('action'))
      {
         case 'openLink':
            var link = $(this).data('link');

            if (typeof link === 'string')
            {
               window.open(link, '_blank', 'location=yes,menubar=yes,scrollbars=yes,status=yes');
            }
            break;
      }
   }

Handles clicks on the node context menu invoking any active actions.

Handles clicks on the node context menu invoking any active actions .


function onNodeContextClick(targetNode, coords)
   {
      // Hides any existing node context menu.
      hideNodeContextMenu();

      if (typeof coords !== 'object') { coords = getElementCoords(this); }

      var popupmenu = $('#contextpopup .mdl-menu__container');

      var packageData = targetNode.packageData;

      var packageLink, packageType, scmLink, scmType;

      if (packageData)
      {
         if (packageData.packageLink)
         {
            packageLink = packageData.packageLink.link;
            packageType = packageData.packageLink.type;

            // Create proper name for package type.
            switch (packageType)
            {
               case 'npm':
                  packageType = 'NPM';
                  break;
            }
         }

         if (packageData.scmLink)
         {
            scmLink = packageData.scmLink.link;
            scmType = packageData.scmLink.type;

            // Create proper name for SCM type.
            switch (scmType)
            {
               case 'github':
                  scmType = 'Github';
                  break;
            }
         }
      }

      // Populate data for the context menu.
      popupmenu.find('li').each(function(index)
      {
         var liTarget = $(this);

         switch (index)
         {
            case 0:
               if (scmLink && scmType)
               {
                  liTarget.text('Open on ' + scmType);
                  liTarget.data('link', scmLink);
                  liTarget.removeClass('hidden');
               }
               else
               {
                  liTarget.addClass('hidden');
               }
               break;

            case 1:
               if (packageLink && packageType)
               {
                  liTarget.text('Open on ' + packageType);
                  liTarget.data('link', packageLink);
                  liTarget.removeClass('hidden');
               }
               else
               {
                  liTarget.addClass('hidden');
               }
               break;

            case 2:
               if (packageData && packageData.version)
               {
                  liTarget.text('Version: ' + packageData.version);
                  liTarget.removeClass('hidden');
               }
               else
               {
                  liTarget.addClass('hidden');
               }
               break;
         }
      });

      // Wrapping in a 100ms timeout allows MDL to draw animation when showing a context menu after one has been hidden.
      setTimeout(function()
      {
         // Assign new selected context node and highlight related nodes.
         selectedContextNode = targetNode;

         fadeRelatedNodes(selectedContextNode, true, nodes, links);

         // For MDL a programmatic click of the hidden context menu.
         var contextMenuButton = $("#context-menu");
         contextMenuButton.click();

         // Necessary to defer reposition of the context menu.
         setTimeout(function()
         {
            popupmenu.parent().css({ position: 'relative' });
            popupmenu.css({ left: coords.x, top: coords.y, position:'absolute' });
         }, 0);
      }, 100);
   }

Shows the node context menu

@param {object}   targetNode - The target node.

@param {object}   coords - Object containing x / y position for context menu; if not provided Node position
determines coords.


function onNodeMouseDown(nodes, links, targetNode)
   {
      hideNodeContextMenu();

      // Only select / drag nodes with left clicked otherwise stop propagation of event.
      if (d3.event.button === 0)
      {
         selectedDragNode = targetNode;

         // Select / highlight related nodes or remove attributes based on enter state.
         fadeRelatedNodes(targetNode, true, nodes, links);
      }
      else
      {
         d3.event.stopPropagation();
      }
   }

Handles a mouse down action on a graph node. Hides any showing context menu. For left clicks the selected node
becomes the drag target and related nodes are faded. Any other mouse button is ignored.

@param {Array}    nodes - All graph nodes.
@param {Array}    links - All graph links.
@param {object}   targetNode - The target node.

Handles a mouse down action on a graph node . Hides any showing context menu . For left clicks the selected node becomes the drag target and related nodes are faded . Any other mouse button is ignored .


function onNodeMouseOverOut(nodes, links, enter, targetNode)
   {
      // If there is an existing selected node then exit early.
      if (isNodeSelected()) { return; }

      // Select / highlight related nodes or remove attributes based on enter state.
      fadeRelatedNodes(targetNode, enter, nodes, links);
   }

Handles fading related nodes to the given `targetNode` if there is no currently selected node.

@param {Array}    nodes - All graph nodes.
@param {Array}    links - All graph links.
@param {boolean}  enter - true when mouse entering / false when mouse exiting.
@param {object}   targetNode - The target node.

Handles fading related nodes to the given targetNode if there is no currently selected node .


function onResize()
   {
      // Update graph parameters.
      graphWidth = window.innerWidth;
      graphHeight = window.innerHeight;

      graph.attr('width', graphWidth).attr('height', graphHeight);

      layout.size([graphWidth, graphHeight]).resume();

      updateMenuUI();

      updateTableUIExtent();

      // Hides any existing node context menu.
      hideNodeContextMenu();

      centerGraph(zoomFit, 1000, data.allNodesFixed ? 0 : 2000);
   }


function onTick()
   {
      nodes.attr('cx', function(node) { return node.x; })
       .attr('cy', function(node) { return node.y; })
       .attr('transform', function(node) { return 'translate(' + node.x + ',' + node.y + ')'; });

      // Pull data from data.nodes array. Provides a curve to the links.
      links.attr('d', function(link)
      {
         var sourceX = data.nodes[link.source.index].x;
         var sourceY = data.nodes[link.source.index].y;
         var targetX = data.nodes[link.target.index].x;
         var targetY = data.nodes[link.target.index].y;

         var dx = targetX - sourceX,
          dy = targetY - sourceY,
          dr = Math.sqrt(dx * dx + dy * dy);
         return 'M' + sourceX + ',' + sourceY + 'A' + dr + ',' + dr + ' 0 0,1 ' + targetX + ',' + targetY;
      });
   }

D3 tick handler for the forced graph layout.

D3 tick handler for the forced graph layout .


function recycleGraph()
   {
      var childNodes = graph.selectAll('g > *').remove();

      if (!Array.isArray(childNodes) && !Array.isArray(childNodes['0'])) { return; }

      // Get the child nodes group from selection.
      childNodes = childNodes['0'];

      for (var cntr = 0; cntr < childNodes.length; cntr++)
      {
         var childNode = childNodes[cntr];

         if (childNode instanceof SVGPathElement) { svgElementMap['path'].push(childNode); }
         else if (childNode instanceof SVGCircleElement) { svgElementMap['circle'].push(childNode); }
         else if (childNode instanceof SVGTextElement) { svgElementMap['text'].push(childNode); }
         else if (childNode instanceof SVGGElement)
         {
            childNode.removeAttribute('transform');  // Must remove current transform.
            svgElementMap['g'].push(childNode);
         }
      }
   }

Recycles all SVG elements above the top level SVGGElement defining the graph.

Recycles all SVG elements above the top level SVGGElement defining the graph .


function reverseGraphLinks()
   {
      for (var key in dataPackageMap)
      {
         var graphData = dataPackageMap[key];

         graphData.links.forEach(function(link)
         {
            var linkSource = link.source;
            link.source = link.target;
            link.target = linkSource;
         });
      }
   }

function reverseGraphLinks ( ) { for ( var key in dataPackageMap ) { var graphData = dataPackageMap [ key ] ; graphData . links . forEach ( function ( link ) { var linkSource = link . source ; link . source = link . target ; link . target = linkSource ; } ) ; } }


function updateMenuUI()
   {
      if (data)
      {
         $('.control-menu li[data-action=toggleFreezeAllNodes]').html(data.allNodesFixed ?
          'Unfreeze nodes' : 'Freeze nodes');
      }

      appMenuToggleOptions.forEach(function(key)
      {
         var icon = appOptions[key] ? 'check_box' : 'check_box_outline_blank';
         $('.control-menu li[data-action=' + key + '] i').html(icon);
      });
   }

Provides handling of changing menu text & material icons based on current state.

Provides handling of changing menu text & material icons based on current state .


function updateTableUI()
   {
      var table = $('.control-table tbody');

      table.off('mouseenter', 'tr', onControlTableRowMouseOver);
      table.off('mouseleave', 'tr', onControlTableRowMouseOver);
      table.off('contextmenu', 'tr', onControlTableRowContextClick);

      table.empty();

      if (data)
      {
         data.nodes.forEach(function(node)
         {
            var nd = node.packageData;
            var name = appOptions.showFullNames ? nd.actualPackageName : nd.packageName;
            var isAliased = nd.isAlias ? ' isAliased' : '';

            var tr = $(
             '
' +
                '' + name + '	' +
                '' + nd.jspmType + '	' +
                '' + nd.version + '	' +
                '' + node.minLevel + '	' +
             '
');

            table.append(tr);

            tr.on('mouseenter', onControlTableRowMouseOver.bind(this, nodes, links, node, true));
            tr.on('mouseleave', onControlTableRowMouseOver.bind(this, nodes, links, node, false));
            tr.on('contextmenu', onControlTableRowContextClick.bind(this, node));
         });

         // Removes sort order for any header and signals update for new data
         $('#nodeTable th').removeClass('headerSortDown');
         $('#nodeTable th').removeClass('headerSortUp');
         $('#nodeTable').trigger('update');

         updateTableUIExtent();
      }
   }

Builds the table UI with all current node data and associates the active events on each row.

Builds the table UI with all current node data and associates the active events on each row .


function updateTableUIExtent()
   {
      var tableDiv = $('.control-table-inner');
      var nodeTable = $('#nodeTable');

      var tableHeight = nodeTable.height();

      var offset = tableDiv.offset();
      var maxTableHeight = window.innerHeight - offset.top - 20;

      tableDiv.css('max-height', maxTableHeight);
      nodeTable.css('margin-right', tableHeight > maxTableHeight ? '10px' : '0px');
   }

function updateTableUIExtent ( ) { var tableDiv = $ ( '.control-table-inner' ) ; var nodeTable = $ ( '#nodeTable' ) ; var tableHeight = nodeTable . height ( ) ; var offset = tableDiv . offset ( ) ; var maxTableHeight = window . innerHeight - offset . top - 20 ; tableDiv . css ( 'max-height' , maxTableHeight ) ; nodeTable . css ( 'margin-right' , tableHeight > maxTableHeight ? '10px' : '0px' ) ; }

Updates the node table max-height enabling scrolling as necessary.

Updates the node table max - height enabling scrolling as necessary .


function zoomFit()
   {
      var bounds = graph.node().getBBox();
      var parent = graph.node().parentElement;
      var fullWidth = parent.clientWidth, fullHeight = parent.clientHeight;
      var width = bounds.width, height = bounds.height;

      if (width === 0 || height === 0) { return 1; } // nothing to fit

      var scale = 0.75 / Math.max(width / fullWidth, height / fullHeight);

      scale = Math.max(Math.min(scale, maxScaleExtent), minScaleExtent);

      return scale;
   }

function
zoomFit
(
)
{
var
bounds
=
graph
.
node
(
)
.
getBBox
(
)
;
var
parent
=
graph
.
node
(
)
.
parentElement
;
var
fullWidth
=
parent
.
clientWidth
,
fullHeight
=
parent
.
clientHeight
;
var
width
=
bounds
.
width
,
height
=
bounds
.
height
;
if
(
width
===
0
||
height
===
0
)
{
return
1
;
}
// nothing to fit
var
scale
=
0.75
/
Math
.
max
(
width
/
fullWidth
,
height
/
fullHeight
)
;
scale
=
Math
.
max
(
Math
.
min
(
scale
,
maxScaleExtent
)
,
minScaleExtent
)
;
return
scale
;
}

Determines a new scale that fits the entire graph into view.

@returns {number}

Determines a new scale that fits the entire graph into view .


function getWindowWidth() {
		if (window.innerWidth) {
			return window.innerWidth;
		} else if (document.documentElement.clientWidth) {
			return document.documentElement.clientWidth;
		} else if (document.body.clientWidth) {
			return document.body.clientWidth;
		} else{
			return 0;
		}
	}

function getWindowWidth ( ) { if ( window . innerWidth ) { return window . innerWidth ; } else if ( document . documentElement . clientWidth ) { return document . documentElement . clientWidth ; } else if ( document . body . clientWidth ) { return document . body . clientWidth ; } else { return 0 ; } }

Get the the inner width of the browser window


function(cssScreen, cssHandheld, mobileMaxWidth) {
			// Set config values
			if (typeof(cssScreen) != "undefined") {
				config.cssScreen = cssScreen;
			}
			if (typeof(cssHandheld) != "undefined") {
				config.cssHandheld = cssHandheld;
			}
			if (typeof(mobileMaxWidth) != "undefined") {
				config.mobileMaxWidth = mobileMaxWidth;
			}

			// Check if CSS is loaded
			var cssloadCheckNode = document.createElement('div');
			cssloadCheckNode.className = config.testDivClass;
			document.getElementsByTagName("body")[0].appendChild(cssloadCheckNode);
			if (cssloadCheckNode.offsetWidth != 100 && noMediaQuery == false) {
				noMediaQuery = true;
			}
			cssloadCheckNode.parentNode.removeChild(cssloadCheckNode)

			if (noMediaQuery == true) {
				// Browser does not support Media Queries, so JavaScript will supply a fallback
				var cssHref = "";

				// Determines what CSS file to load
				if (getWindowWidth() <= config.mobileMaxWidth) {
					cssHref = config.cssHandheld;
					newCssMediaType = "handheld";
				} else {
					cssHref = config.cssScreen;
					newCssMediaType = "screen";
				}

				// Add CSS link to <head> of page
				if (cssHref != "" && currentCssMediaType != newCssMediaType) {
					var currentCssLinks = document.styleSheets
					for (var i = 0; i < currentCssLinks.length; i++) {
						for (var ii = 0; ii < currentCssLinks[i].media.length; ii++) {
							if (typeof(currentCssLinks[i].media) == "object") {
								if (currentCssLinks[i].media.item(ii) == "fallback") {
									currentCssLinks[i].ownerNode.parentNode.removeChild(currentCssLinks[i].ownerNode)
									i--
									break;
								}
							} else {
								if (currentCssLinks[i].media.indexOf("fallback") >= 0) {
									currentCssLinks[i].owningElement.parentNode.removeChild(currentCssLinks[i].owningElement)
									i--
									break;
								}
							}
						}
					}
					if (typeof(cssHref) == "object") {
						for (var i = 0; i < cssHref.length; i++) {
							addCssLink(cssHref[i])
						}
					} else {
						addCssLink(cssHref)
					}

					currentCssMediaType = newCssMediaType;
				}

				// Check screen size again if user resizes window
				addEvent(window, wbos.CssTools.MediaQueryFallBack.LoadCssDelayed, 'onresize')
			}
		}

Adds link to CSS in the head if no CSS is loaded

@since 1.0 - 2010-08-21
@version 1.0 - 2010-08-21
@param {String|Object} cssScreen URL to CSS file for larger screens
@param {String|Object} cssHandheld URL to CSS file for smaller screens
@param {Number} mobileMaxWidth Maximum  width for handheld devices
@example
wbos.CssTools.MediaQueryFallBack.LoadCss(['screen.css', 'screen2.css'], 'mobile.css', 480)


function do_success(req, res, msg) {
	res.writeHead(200, {'Content-Type': ((typeof msg === 'string') ? 'text/plain' : 'application/json')});
	msg = (typeof msg === 'string') ? msg : helpers.stringify(msg);
	res.end(msg);
}

function do_success ( req , res , msg ) { res . writeHead ( 200 , { 'Content-Type' : ( ( typeof msg === 'string' ) ? 'text/plain' : 'application/json' ) } ) ; msg = ( typeof msg === 'string' ) ? msg : helpers . stringify ( msg ) ; res . end ( msg ) ; }


function do_failure(req, res, opts) {
	opts = opts || {};
	var obj = {
		'type': opts.type || 'error',
		'code': opts.code || 501,
		'desc': opts.desc || (''+opts)
	};

	res.writeHead(obj.code, {'Content-Type': 'application/json'});
	res.end(helpers.stringify(obj) + '\n');
}

function do_failure ( req , res , opts ) { opts = opts || { } ; var obj = { 'type' : opts . type || 'error' , 'code' : opts . code || 501 , 'desc' : opts . desc || ( '' + opts ) } ; res . writeHead ( obj . code , { 'Content-Type' : 'application/json' } ) ; res . end ( helpers . stringify ( obj ) + '\n' ) ; }


function do_create_req(config, routes) {
	routes = routes || {};

	var version = routes.version || {};
	if(version && (typeof version === 'object')) {
	} else {
		version = {'self':routes.version || config.pkg.version};
	}

	if(!version.api) {
		version.api = api_config.pkg.version;
	}

	routes.version = version;

	var router = new RequestRouter(routes);
	var req_counter = 0;

	/* Inner Request handler */
	function do_req(req, res) {
		req_counter += 1;
		return router.resolve( req, res );
	} // do_req

	return do_req;
}

function
do_create_req
(
config
,
routes
)
{
routes
=
routes
||
{
}
;
var
version
=
routes
.
version
||
{
}
;
if
(
version
&&
(
typeof
version
===
'object'
)
)
{
}
else
{
version
=
{
'self'
:
routes
.
version
||
config
.
pkg
.
version
}
;
}
if
(
!
version
.
api
)
{
version
.
api
=
api_config
.
pkg
.
version
;
}
routes
.
version
=
version
;
var
router
=
new
RequestRouter
(
routes
)
;
var
req_counter
=
0
;
/* Inner Request handler */
function
do_req
(
req
,
res
)
{
req_counter
+=
1
;
return
router
.
resolve
(
req
,
res
)
;
}
// do_req
return
do_req
;
}

Builder for generic HTTP Request Handler


function do_create_server(config, do_req) {
	var http = require('http');
	if(config.host) {
		http.createServer(do_req).listen(config.port, config.host);
		//console.log("Server running at http://"+config.host+":"+config.port+"/");
	} else {
		http.createServer(do_req).listen(config.port);
		//console.log("Server running at http://0.0.0.0:"+config.port);
	}
	return http;
}


function setup_server(config, opts) {
	config._def('port', 3000);
	var req_handler = do_create_req(config, opts);
	var server = do_create_server(config, function(req, res) {
		req_handler(req, res).then(function(obj) {
			if(obj === api.replySent) {
				// Silently return since reply has been handler already.
				return;
			} else if(obj === api.notFound) {
				do_failure(req, res, {'verb': 'notFound', 'desc':'The requested resource could not be found.', 'code':404});
			} else {
				do_success(req, res, obj);
			}
		}).fail(function(err) {
			do_failure(req, res, err);
			if(!(err instanceof errors.HTTPError)) {
				require('prettified').errors.print(err);
			}
		}).done();
	});
	return server;
}


function(element, ev, fn){
	if(element.addEventListener)
		element.addEventListener(ev, fn, false);
	else element.attachEvent("on" + ev, fn);
}

function ( element , ev , fn ) { if ( element . addEventListener ) element . addEventListener ( ev , fn , false ) ; else element . attachEvent ( "on" + ev , fn ) ; }


function Reply(parent, definition) {
  var key;
  for (key in updateMixin) {
    this[key] = updateMixin[key];
  }
  Reply.super_.apply(this, arguments);
}

function Reply ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } Reply . super_ . apply ( this , arguments ) ; }

Initialize a new `Reply` with the given `parent` and `definition`.

@param {Function} parent The parent this resource is attached to.
@param {Object} definition The resource definition.
@api private

Initialize a new Reply with the given parent and definition .


function serveGitFile(repo, tree, parts, res, next) {
  //console.log("Serving git file: " + parts);
  var thisPart = parts.shift();
  var isLastPart = parts.length === 0;
  var entryIndex = -1;
  for (var i=0; i < tree.entries.length; i++) {
    if (tree.entries[i].name === thisPart) {
      entryIndex = i;
      break;
    }
  }
  if (entryIndex < 0) return next();
  var entry = tree.entries[entryIndex];
  if (isLastPart) {
    repo.getBlob(entry.id, function(err, buf) {
      if (err) return next(err);
      if (!buf.data) return next();
      serveBuffer(buf.data, res, thisPart);
    });
  } else {
    repo.getTree(entry.id, function(err, entryTree) {
      if (err) return next(err);
      serveGitFile(repo, entryTree, parts, res, next);
    });
  }
}

Returns a Buffer of the specified file from the specified repo and commit reference. Recursively gets the tree instances until the last part, which is gets the rawObject for and serves back over HTTP.

Returns a Buffer of the specified file from the specified repo and commit reference . Recursively gets the tree instances until the last part which is gets the rawObject for and serves back over HTTP .


function processFileList(files, base, settings, state) {

    for (var i = 0; i < files.length; i++) {

        var modulePath = path.join(base, files[i]);

        var stats = fs.statSync(modulePath);

        if (stats.isFile()) {

            // Try to load the module
            var module = require(modulePath);
            var relative = path.relative(settings.source, modulePath);

            __log('Relative path: %s', relative);

            var pathWithoutExtension = relative.substr(0, relative.lastIndexOf('.'));
            var routeName = pathWithoutExtension.replace(/\\/g, '/').replace(/\./g, '_');

            var isRoot = new RegExp(settings.rootModule + '/?$', 'g').test(routeName);
            var routePath = routeName;

            // Special case for an index file - put these in the root of the api
            if (isRoot) {

                if(routePath.lastIndexOf('/') > -1)
                    routePath = routePath.substr(0, routePath.lastIndexOf('/'));
                else
                    routePath = undefined;
            }

            __log('%s (%s)', routeName, routePath);

            var apiPath = utils.combineApiPath(settings.root, routePath);

            state.endpoints[routeName] = {
                baseUrl: apiPath,
                filename: modulePath,
                routeName: routeName
            };

            __log(state.endpoints[routeName]);

            settings.app.use(apiPath, module);
        }
        else if (stats.isDirectory()) {
            var dirFiles = fs.readdirSync(modulePath);
            processFileList(dirFiles, modulePath, settings, state);
        }
    }
}

Processes a list of files and produces the api routing for them
@param files The list of files to process
@param settings express-autoapi settings
@param state The process state


function packageModule(global, name, api) {
  if (global.define && global.define.amd) {
    define([], api);
  } else if (typeof exports !== "undefined") {
    module.exports = api;
  } else {
    global[name] = api;
  }
}

function packageModule ( global , name , api ) { if ( global . define && global . define . amd ) { define ( [ ] , api ) ; } else if ( typeof exports !== "undefined" ) { module . exports = api ; } else { global [ name ] = api ; } }

package module for different environments


function Ebus(p) {
	"use strict";

	this.debug = false;
	this.yields = false;
	this.handlers = {};

	if (p) {
		this.priorities = p;
	} else {
		this.priorities = {};
	}
}

function
Ebus
(
p
)
{
"use strict"
;
this
.
debug
=
false
;
this
.
yields
=
false
;
this
.
handlers
=
{
}
;
if
(
p
)
{
this
.
priorities
=
p
;
}
else
{
this
.
priorities
=
{
}
;
}
}


function ApiClient(config) {
  var self = this
  this.config = _.extend({}, config, {client:this})
  config.headers = _.extend({}, config.headers, { Accept: 'application/json' })

  this.auth = config.auth

  models.sync = require('./sync')
  models.Model = require('./modelbase')
  models.NginModel = require('./nginModel')

  // add each model to the ApiClient
  Object.keys(models).forEach(function(modelName) {
    Object.defineProperty(self, modelName, {
      get: function() { return models[modelName](self) },
      enumerable:true,
      configurable:true
    })
  })
  _.extend(this, models)
}

function
ApiClient
(
config
)
{
var
self
=
this
this
.
config
=
_
.
extend
(
{
}
,
config
,
{
client
:
this
}
)
config
.
headers
=
_
.
extend
(
{
}
,
config
.
headers
,
{
Accept
:
'application/json'
}
)
this
.
auth
=
config
.
auth
models
.
sync
=
require
(
'./sync'
)
models
.
Model
=
require
(
'./modelbase'
)
models
.
NginModel
=
require
(
'./nginModel'
)
// add each model to the ApiClient
Object
.
keys
(
models
)
.
forEach
(
function
(
modelName
)
{
Object
.
defineProperty
(
self
,
modelName
,
{
get
:
function
(
)
{
return
models
[
modelName
]
(
self
)
}
,
enumerable
:
true
,
configurable
:
true
}
)
}
)
_
.
extend
(
this
,
models
)
}

Common entry point for all API models

@param {Object} config
@api public


function getFirstIndexOf(value, array) {
    error_if_not_primitive_or_array_1.errorIfNotPrimitiveOrArray(value);
    if (isArray_notArray_1.isArray(value)) {
        return getFirstIndexOfArray_1.getFirstIndexOfArray(value, array);
    }
    else { // if primitive...
        return getIndexOfPrimitive_1.getIndexOfPrimitive(value, array);
    }
}

function
getFirstIndexOf
(
value
,
array
)
{
error_if_not_primitive_or_array_1
.
errorIfNotPrimitiveOrArray
(
value
)
;
if
(
isArray_notArray_1
.
isArray
(
value
)
)
{
return
getFirstIndexOfArray_1
.
getFirstIndexOfArray
(
value
,
array
)
;
}
else
{
// if primitive...
return
getIndexOfPrimitive_1
.
getIndexOfPrimitive
(
value
,
array
)
;
}
}

returns -1 if value being searched for isn't found. value cannot be object.

returns - 1 if value being searched for isn t found . value cannot be object .


function scopeUrl(options, inst) {
    options = _.extend({}, inst, options)
    if (!options.season_id)
      throw new Error('season_id required to make division instance api calls')

    return ngin.Season.urlRoot() + '/' + options.season_id + Division.urlRoot()
  }

Scopes the url to the season

@param {Object} options
@returns {String}
@api public


function Customer(parent, definition) {
  var key;
  for (key in updateMixin) {
    this[key] = updateMixin[key];
  }
  Customer.super_.apply(this, arguments);
}

function Customer ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } Customer . super_ . apply ( this , arguments ) ; }

Initialize a new `Customer` with the given `parent` and `definition`.

@param {Function} parent The parent this resource is attached to.
@param {Object} definition The resource definition.
@api private

Initialize a new Customer with the given parent and definition .


function copy(obj) {
    return Object.getOwnPropertyNames(obj || {}).reduce((a, c) => {
        a[c] = obj[c];
        return a;
    }, {});
}

function copy ( obj ) { return Object . getOwnPropertyNames ( obj || { } ) . reduce ( ( a , c ) => { a [ c ] = obj [ c ] ; return a ; } , { } ) ; }

This does a shallow copy of objects. This is needed for objects such as Errors Otherwise some properties may not be available.

This does a shallow copy of objects . This is needed for objects such as Errors Otherwise some properties may not be available .


function formatWith(options) {
        options = Object.assign({}, DEFAULTS, options);
        return (message, ...args) => {
            return _formatter(options, message, ...args);
        };
    }

function formatWith ( options ) { options = Object . assign ( { } , DEFAULTS , options ) ; return ( message , ... args ) => { return _formatter ( options , message , ... args ) ; } ; }

Formats a message using the specified options.

@param options pass options for this instance of formatting.

Formats a message using the specified options .


function(sourceDir, destFile, opts) {
        opts = opts || { archive_path: '/' };
        return new Promise(function (resolve, reject) {
            try {
                var archive = archiver.create('zip', {
                    zlib: {
                        level: 9
                    }
                });
                var output = fs.createWriteStream(destFile);
                output.on('finish', function () {
                    resolve(destFile);
                });
                archive.pipe(output);
                archive.directory(sourceDir, opts.archive_path);
                archive.finalize();
            } catch(err) {
                reject(err);
            }
        });
    }

function ( sourceDir , destFile , opts ) { opts = opts || { archive_path : '/' } ; return new Promise ( function ( resolve , reject ) { try { var archive = archiver . create ( 'zip' , { zlib : { level : 9 } } ) ; var output = fs . createWriteStream ( destFile ) ; output . on ( 'finish' , function ( ) { resolve ( destFile ) ; } ) ; archive . pipe ( output ) ; archive . directory ( sourceDir , opts . archive_path ) ; archive . finalize ( ) ; } catch ( err ) { reject ( err ) ; } } ) ; }

Zips up a directory.

@param sourceDir {string} the directory to be zipped
@param destFile {string} the output file
@param opts {{}}
@returns {Promise.<string>} path to the archive


function(sourceFile, destDir) {
        return new Promise(function(resolve, reject) {
            var zip = new AdmZip(sourceFile);
            try {
                zip.extractAllTo(destDir);
                resolve(destDir);
            } catch(err) {
                reject(err);
            }
        });
    }

function ( sourceFile , destDir ) { return new Promise ( function ( resolve , reject ) { var zip = new AdmZip ( sourceFile ) ; try { zip . extractAllTo ( destDir ) ; resolve ( destDir ) ; } catch ( err ) { reject ( err ) ; } } ) ; }

Extracts a zip to a directory.
This will fail if the destination already exists.

@param sourceFile {string}
@param destDir {string}
@returns {Promise.<string>} path to the destination

Extracts a zip to a directory . This will fail if the destination already exists .


function(sourceDir, destFile, opts) {
        opts = opts || { archive_path: '/' };
        return new Promise(function(resolve, reject) {
            // pack
            var tempFile = destFile + '.tmp.tar';
            try {
                var archive = archiver.create('tar');
                var output = fs.createWriteStream(tempFile);
                output.on('finish', function () {
                    resolve(tempFile);
                });
                archive.pipe(output);
                archive.directory(sourceDir, opts.archive_path);
                archive.finalize();
            } catch (err) {
                reject(err);
            }
        })
        .then(function(tempFile) {
            // compress
            try {
                var data = new Buffer(fs.readFileSync(tempFile), 'utf8');
                var compressed = new Buffer(Bzip2.compressFile(data));
                fs.writeFileSync(destFile, compressed);
                return destFile;
            } catch(err) {
                throw err;
            } finally {
                rimraf.sync(tempFile);
            }
        });
    }

function
(
sourceDir
,
destFile
,
opts
)
{
opts
=
opts
||
{
archive_path
:
'/'
}
;
return
new
Promise
(
function
(
resolve
,
reject
)
{
// pack
var
tempFile
=
destFile
+
'.tmp.tar'
;
try
{
var
archive
=
archiver
.
create
(
'tar'
)
;
var
output
=
fs
.
createWriteStream
(
tempFile
)
;
output
.
on
(
'finish'
,
function
(
)
{
resolve
(
tempFile
)
;
}
)
;
archive
.
pipe
(
output
)
;
archive
.
directory
(
sourceDir
,
opts
.
archive_path
)
;
archive
.
finalize
(
)
;
}
catch
(
err
)
{
reject
(
err
)
;
}
}
)
.
then
(
function
(
tempFile
)
{
// compress
try
{
var
data
=
new
Buffer
(
fs
.
readFileSync
(
tempFile
)
,
'utf8'
)
;
var
compressed
=
new
Buffer
(
Bzip2
.
compressFile
(
data
)
)
;
fs
.
writeFileSync
(
destFile
,
compressed
)
;
return
destFile
;
}
catch
(
err
)
{
throw
err
;
}
finally
{
rimraf
.
sync
(
tempFile
)
;
}
}
)
;
}

Create a Bzip2 compressed tar of a directory.

@param sourceDir {string} the directory to be compressed
@param destFile {string} the output file
@param opts {{}}
@returns {Promise.<string>} path to the archive

Create a Bzip2 compressed tar of a directory .


function(sourceFile, destDir) {
        return new Promise(function(resolve, reject) {
            // expand
            var tempFile = sourceFile + '.tmp.tar';
            try {
                var data = new Buffer(fs.readFileSync(sourceFile));
                var expanded = Bzip2.decompressFile(data);
                fs.writeFileSync(tempFile, new Buffer(expanded));
                resolve(tempFile);
            } catch(err) {
                reject(err);
            }
        }).then(function(tempFile) {
            // un-pack
            return new Promise(function(resolve, reject) {
                try {
                    var rs = fs.createReadStream(tempFile);
                    rs.pipe(tar.extract(destDir).on('finish', function() {
                        rimraf.sync(tempFile);
                        resolve(destDir);
                    }));
                } catch (err) {
                    rimraf.sync(tempFile);
                    reject(err);
                }
            });
        });
    }

function
(
sourceFile
,
destDir
)
{
return
new
Promise
(
function
(
resolve
,
reject
)
{
// expand
var
tempFile
=
sourceFile
+
'.tmp.tar'
;
try
{
var
data
=
new
Buffer
(
fs
.
readFileSync
(
sourceFile
)
)
;
var
expanded
=
Bzip2
.
decompressFile
(
data
)
;
fs
.
writeFileSync
(
tempFile
,
new
Buffer
(
expanded
)
)
;
resolve
(
tempFile
)
;
}
catch
(
err
)
{
reject
(
err
)
;
}
}
)
.
then
(
function
(
tempFile
)
{
// un-pack
return
new
Promise
(
function
(
resolve
,
reject
)
{
try
{
var
rs
=
fs
.
createReadStream
(
tempFile
)
;
rs
.
pipe
(
tar
.
extract
(
destDir
)
.
on
(
'finish'
,
function
(
)
{
rimraf
.
sync
(
tempFile
)
;
resolve
(
destDir
)
;
}
)
)
;
}
catch
(
err
)
{
rimraf
.
sync
(
tempFile
)
;
reject
(
err
)
;
}
}
)
;
}
)
;
}

Extracts a tar to a directory.

@param sourceFile {string}
@param destDir {string}
@returns {Promise.<string>} path to the destination


async function make(dir) {
  try {
    await makePromise(mkdir, dir)
  } catch (err) {
    if (err.code == 'ENOENT') {
      const parentDir = dirname(dir)
      await make(parentDir)
      await make(dir)
    } else if (err.code != 'EEXIST') { // created in parallel
      throw err
    }
  }
}

async
function
make
(
dir
)
{
try
{
await
makePromise
(
mkdir
,
dir
)
}
catch
(
err
)
{
if
(
err
.
code
==
'ENOENT'
)
{
const
parentDir
=
dirname
(
dir
)
await
make
(
parentDir
)
await
make
(
dir
)
}
else
if
(
err
.
code
!=
'EEXIST'
)
{
// created in parallel
throw
err
}
}
}

Recursive promise-based mkdir.
@param {string} dir Path to the directory to be created


function fabricator(stack, options) {
  options = options || {};

  //
  // Empty strings, arrays or objects should not be processed, return early.
  //
  if (empty(stack)) return [];

  switch (is(stack)) {
    case 'string':
      stack = read(stack, options);
    break;

    case 'object':
      stack = Object.keys(stack).reduce(iterator(read, stack, options), []);
    break;

    case 'array':
      stack = stack.reduce(iterator(read, null, options), []);
    break;

    default:
      if ('function' !== typeof stack) {
        throw new Error('Unsupported type, cannot fabricate an: '+ is(stack));
      }

      stack = [init(stack, undefined, options)];
  }

  return (stack || []).filter(Boolean);
}

Expose small fabrication helper.

Possible options:

- source:    {String}   Absolute path to be used to resolve file paths.
- recursive: {Boolean}  Should file paths be recursively discovered.
- name:      {String}   Force a name for a given constructor.

@param {Mixed} stack String, array or object that contains constructible entities
@param {Object} options Optional options.
@returns {Array} collection of constructors.
@api public


function read(filepath, options) {
  if ('string' !== is(filepath)) return fabricator(filepath, options);
  if (options.source) filepath = path.resolve(options.source, filepath);

  //
  // Check if the provided string is a JS file or when recursion is not allowed.
  //
  if (js(filepath) || options.recursive === false) return [
    init(filepath, path.basename(filepath, '.js'), options)
  ];

  //
  // Read the directory, only process files.
  //
  if (!fs.existsSync(filepath)) return false;
  return fs.readdirSync(filepath).map(function locate(file) {
    file = path.resolve(filepath, file);

    var stat = fs.statSync(file);

    if (stat.isDirectory() && fs.existsSync(path.join(file, 'index.js'))) {
      //
      // Use the directory name instead of `index` for name as it probably has
      // more meaning then just `index` as a name.
      //
      return init(path.join(file, 'index.js'), path.basename(file, '.js'), options);
    }

    //
    // Only allow JS files, init determines if it is a constructible instance.
    //
    if (!stat.isFile() || !js(file)) return;

    return init(file, path.basename(file, '.js'), options);
  });
}

Read directory and initialize JavaScript files.

@param {String} filepath Full directory path.
@param {Object} options Additional configuration.
@return {Array} collection of constructor
@api private

Read directory and initialize JavaScript files .