function inspectTopLevelDeclaration(emitted) {
            let body = emitted.node.body || [],
                levelOneIndentRegExp = new RegExp("^\\n" + BASE_INDENTATION_STYLE + "$"),
                endingLineRegExp = new RegExp("^" + BASE_INDENTATION_STYLE + "(\\S| \\*)$"),	//either a non-whitespace character or 1 extra whitespace followed by * (closing of multi-line comment)
                endingLineExtraIndentRegExp = new RegExp("^" + BASE_INDENTATION_STYLE.repeat(2) + "(\\S| \\*)$");

            if (emitted.exit) {
                return;
            }

            function inspectChild(child) {
                let prevChars = sourceCode.getPrevChars(child, BASE_INDENTATION_STYLE.length+1),
                    endingLineNum = sourceCode.getEndingLine(child);

                //if the start of node doesn't follow correct indentation
                if (!levelOneIndentRegExp.test(prevChars)) {
                    context.report({
                        node: child,
                        message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
                    });
                }

                // If the node starts & ends on same line, exit.
                if (sourceCode.getLine(child) === endingLineNum) {
                    return;
                }

                // If node starts & ends on diff lines, the ending line must also follow correct indentation.
                // Exception to this is an abstract function whose declaration spans over multiple lines. Eg-
                // function foo()
                //     payable
                //     returns (uint, string);

                if (child.type === "FunctionDeclaration" && child.is_abstract) {

                    if (!endingLineExtraIndentRegExp.test(
                        sourceCode.getTextOnLine(endingLineNum).slice(0, BASE_INDENTATION_STYLE.repeat(2).length+1))) {
                        context.report({
                            node: child,
                            location: {
                                line: endingLineNum,
                                column: 0
                            },
                            message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
                        });
                    }

                    return;
                }

                if (!endingLineRegExp.test(
                    sourceCode.getTextOnLine(endingLineNum).slice(0, BASE_INDENTATION_STYLE.length+1))) {
                    context.report({
                        node: child,
                        location: {
                            line: endingLineNum,
                            column: 0
                        },
                        message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
                    });
                }
            }

            body.forEach(inspectChild);
        }

Ensure level 1 indentation before all immediate children of top-level declarations

Ensure level 1 indentation before all immediate children of top - level declarations


function inspectBlockStatement(emitted) {
            let node = emitted.node;

            //if the complete block resides on the same line, no need to check for indentation
            if (emitted.exit || (sourceCode.getLine(node) === sourceCode.getEndingLine(node))) {
                return;
            }

            let parent = sourceCode.getParent(node),
                parentDeclarationLine = sourceCode.getLine(parent),
                parentDeclarationLineText = sourceCode.getTextOnLine(parentDeclarationLine),
                currentIndent, currentIndentLevel;

            function inspectBlockItem(blockIndent, blockIndentDesc, blockItem) {
                let prevChars = sourceCode.getPrevChars(blockItem, blockIndent.length+1),
                    endingLineNum = sourceCode.getEndingLine(blockItem),
                    endingLineRegExp = new RegExp("^" + blockIndent + "(" + BASE_INDENTATION_STYLE + ")?\\S.*$");

                if (prevChars !== ("\n" + blockIndent)) {
                    context.report({
                        node: blockItem,
                        message: `Only use indent of ${blockIndentDesc}.`
                    });
                }

                /**
				 * If the block item spans over multiple lines, make sure the ending line also follows the indent rule
				 * An exception to this is the if-else statements when they don't have BlockStatement as their body
				 * eg-
				 * if (a)
				 *     foo();
				 * else
				 *     bar();
				 *
				 * Another exception is chaining.
				 * eg-
				 * function() {
				 *   myObject
				 *     .funcA()
				 *     .funcB()
				 *     [0];
				 * }
				 * Ending line has 1 extra indentation but this is acceptable.
				 */
                if (
                    blockItem.type !== "IfStatement" &&
					sourceCode.getLine(blockItem) !== endingLineNum &&
					!endingLineRegExp.test(sourceCode.getTextOnLine(endingLineNum))
                ) {
                    context.report({
                        node: blockItem,
                        location: {
                            line: endingLineNum,
                            column: 0
                        },
                        message: `Only use indent of ${blockIndentDesc}.`
                    });
                }
            }

            currentIndent = parentDeclarationLineText.slice(
                0,
                parentDeclarationLineText.indexOf(parentDeclarationLineText.trim())
            );

            //in case of no match, match() returns null. Return [] instead to avoid crash
            currentIndentLevel = (currentIndent.match(BASE_INDENTATION_STYLE_REGEXP_GLOBAL) || []).length;

            //ensure that there is only whitespace of correct level before the block's parent's code
            if (getIndentString(BASE_INDENTATION_STYLE, currentIndentLevel) !== currentIndent) {
                return;	//exit now, we can' proceed further unless this is fixed
            }

            //indentation of items inside block should be 1 level greater than that of parent
            const blockIndent = getIndentString(BASE_INDENTATION_STYLE, currentIndentLevel + 1);
            const blockIndentDesc = getIndentDescription(BASE_INDENTATION_STYLE, currentIndentLevel + 1);

            node.body.forEach(inspectBlockItem.bind(null, blockIndent, blockIndentDesc));
        }

Ensure 1 extra indentation inside Block than before it


function(node, beforeCount, afterCount) {
        let sourceCodeText = this.text;

        if (node) {
            if (astUtils.isASTNode(node)) {

                return this.text.slice(
                    Math.max(0, node.start - (Math.abs(beforeCount) || 0)),
                    node.end + (Math.abs(afterCount) || 0)
                );

            }

            throw new Error("Invalid Node object");
        }

        return sourceCodeText;
    }

function
(
node
,
beforeCount
,
afterCount
)
{
let
sourceCodeText
=
this
.
text
;
if
(
node
)
{
if
(
astUtils
.
isASTNode
(
node
)
)
{
return
this
.
text
.
slice
(
Math
.
max
(
0
,
node
.
start
(
Math
.
abs
(
beforeCount
)
||
0
)
)
,
node
.
end
+
(
Math
.
abs
(
afterCount
)
||
0
)
)
;
}
throw
new
Error
(
"Invalid Node object"
)
;
}
return
sourceCodeText
;
}

Function to retrieve the source code text being linted. Returns the complete source code if no node specified
@param {Object} node The AST node whose source code (specifically) is needed
@param {int} beforeCount Include beforeCount number of characters prior to the node's code
@param {int} afterCount Include afterCount number of characters following the node's code
@returns {String} sourceCodeText source code of the specified node plus extra characters specified by beforeCount & afterCount

Function to retrieve the source code text being linted . Returns the complete source code if no node specified


function inspectVariableDeclaration(emitted) {
            let node = emitted.node, code = sourceCode.getText(node);

            if (emitted.exit) {
                return;
            }

            //if a particular character is '=', check its left and right for single space
            for (let i = 2; i < code.length; i++) {
                if (code [i] === "=") {
                    (!/^[^\/\s] $/.test(code.slice(i-2, i))) && context.report({
                        node: node,
                        message: "There should be only a single space between assignment operator '=' and its left side."
                    });

                    (!/^ [^\/\s]$/.test(code.slice(i+1, i+3))) && context.report({
                        node: node,
                        message: "There should be only a single space between assignment operator '=' and its right side."
                    });
                }
            }
        }

statement like `var x = 10` doesn't come under AssignmentExpression, so needs to be checked separately

statement like var x = 10 doesn t come under AssignmentExpression so needs to be checked separately


function RuleContext(ruleName, ruleDesc, ruleMeta, Solium) {
    let contextObject = this;

    // Set contect attribute 'options' iff options were provided.
    ruleDesc.options && Object.assign(contextObject, { options: ruleDesc.options });

    //set read-only properties of the context object
    Object.defineProperties(contextObject, {

        name: {
            value: ruleName,
            writable: false	//though the default is false anyway, I think its better to express your intention clearly
        },

        meta: {
            value: ruleDesc,
            writable: false
        }

    });

    //inherit all Solium methods which are of relevance to the rule
    INHERITABLE_METHODS.forEach(function(methodName) {
        contextObject [methodName] = function(s, z, a, b, o) {	//every method will receive 5 arguments tops
            return Solium [methodName].call(Solium, s, z, a, b, o);
        };
    });

    /**
     * wrapper around Solium.report () which adds some additional information to the error object
     * @param {Object} error An object describing the lint error, sent by the rule currently running
     */
    contextObject.report = function(error) {

        if (!isErrObjectValid(error)) {
            throw new Error(
                `Rule "${ruleName}": invalid error object was passed. AJV message:${EOL}${util.inspect(isErrObjectValid.errors)}`
            );
        }

        Object.assign(error, { ruleName: ruleName, ruleMeta: ruleMeta, type: contextObject.meta.type });
        Solium.report(error);

    };
}

context object Constructor to set read-only properties and provide additional functionality to the rules using it
@param {String} ruleName Name of the rule the object is for
@param {Object} ruleDesc Description of the rule the object is for
@param {Object} ruleMeta meta object defined inside the rule file by rule developer
@param {Object} Solium Main Solium object from which to inherit functionality to provide to the rules

context object Constructor to set read - only properties and provide additional functionality to the rules using it


function resolveUpstream(upstream) {
    let coreRulesetRegExp = /^solium:[a-z_]+$/;

    // Determine whether upstream is a solium core ruleset or a sharable config.
    if (coreRulesetRegExp.test(upstream)) {
        try {
            return require("../../config/rulesets/solium-" + upstream.split(":") [1]).rules;
        } catch (e) {
            throw new Error("\"" + upstream + "\" is not a core ruleset.");
        }
    }

    // If flow reaches here, it means upstream is a sharable config.
    let configName = constants.SOLIUM_SHARABLE_CONFIG_PREFIX + upstream, config;

    try {
        config = require(configName);
    } catch (e) {
        if (e.code === "MODULE_NOT_FOUND") {
            throw new Error(
                "The sharable config \"" + configName + "\" is not installed. " +
				"If Solium is installed globally, install the config globally using " +
				"\"npm install -g " + configName + "\". Else install locally using " +
				"\"npm install --save-dev " + configName + "\"."
            );
        }

        throw new Error("The sharable config \"" + configName + "\" could not be loaded: " + e.message);
    }

    if (isAValidSharableConfig(config)) {
        return config.rules;
    }

    throw new Error("Invalid sharable config \"" +
		configName + "\". AJV message:\n" + util.inspect(isAValidSharableConfig.errors));
}

Given a ruleset name, determine whether its a core set or a sharable config and load the rule config accordingly.
@param {String} upstream The ruleset to resolve
@returns {Object} ruleConfigs Set of rule configs exported by the upstream ruleset.

Given a ruleset name determine whether its a core set or a sharable config and load the rule config accordingly .


function resolvePluginConfig(name, plugin) {
    let config = {};

    Object.keys(plugin.rules).forEach(function(ruleName) {
        config [name + "/" + ruleName] = plugin.rules [ruleName].meta.docs.type;
    });

    return config;
}

function resolvePluginConfig ( name , plugin ) { let config = { } ; Object . keys ( plugin . rules ) . forEach ( function ( ruleName ) { config [ name + "/" + ruleName ] = plugin . rules [ ruleName ] . meta . docs . type ; } ) ; return config ; }

Create provided plugin's default rule configuration
@param {String} name Plugin name without 'solium-plugin-' prefix
@param {Object} plugin The plugin Object as exported by the solium plugin
@returns {Object} config Rule configuration object for the given plugin

Create provided plugin s default rule configuration


function writeConfigFile(config) {
    try {
        fs.writeFileSync(
            SOLIUMRC_FILENAME_ABSOLUTE,
            JSON.stringify(config, null, 2)
        );
    } catch (e) {
        errorReporter.reportFatal(
            `An error occurred while writing to ${SOLIUMRC_FILENAME_ABSOLUTE}:${EOL}${e.message}`);
        process.exit(errorCodes.WRITE_FAILED);
    }
}

function writeConfigFile ( config ) { try { fs . writeFileSync ( SOLIUMRC_FILENAME_ABSOLUTE , JSON . stringify ( config , null , 2 ) ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME_ABSOLUTE } ${ EOL } ${ e . message } ` ) ; process . exit ( errorCodes . WRITE_FAILED ) ; } }

Synchronously write the passed configuration to the file whose absolute path is SOLIUMRC_FILENAME_ABSOLUTE
@param {Object} config User Configuration object
@returns {void}


function lintString(sourceCode, userConfig, errorReporter, fileName) {
    let lintErrors, fixesApplied;

    try {
        if (userConfig.options.autofix || userConfig.options.autofixDryrun) {
            let result = solium.lintAndFix(sourceCode, userConfig);

            lintErrors = result.errorMessages;
            if (userConfig.options.autofix) {
                applyFixes(fileName, result);
                fixesApplied = result.fixesApplied;
            } else {
                errorReporter.reportDiff(fileName,
                    sourceCode, result.fixedSourceCode, result.fixesApplied.length);
            }
        } else {
            lintErrors = solium.lint(sourceCode, userConfig);
        }
    } catch (e) {
        // Don't abort in case of a parse error, just report it as a normal lint issue.
        if (e.name !== "SyntaxError") {
            const messageOrStackrace = userConfig.options.debug ? e.stack : e.message;
            errorReporter.reportFatal(`An error occured while linting over ${fileName}:${EOL}${messageOrStackrace}`);
            process.exit(errorCodes.ERRORS_FOUND);
        }

        lintErrors = [{
            ruleName: "",
            type: "error",
            message: `Syntax error: unexpected token ${e.found}`,
            line: e.location.start.line,
            column: e.location.start.column
        }];
    }

    // If any lint/internal errors/warnings exist, report them
    lintErrors.length &&
        errorReporter.report(fileName, sourceCode, lintErrors, fixesApplied);

    return lintErrors.reduce(function(numOfErrors, err) {
        return err.type === "error" ? numOfErrors+1 : numOfErrors;
    }, 0);
}

Lint a source code string based on user settings. If autofix is enabled, write the fixed code back to file.
@param {String} sourceCode The source code to be linted
@param {Object} userConfig User configuration
@param {Object} errorReporter The error reporter to use
@param {String} fileName (optional) File name to use when reporting errors
@returns {Integer} numOfErrors Number of Lint ERRORS that occured.

Lint a source code string based on user settings . If autofix is enabled write the fixed code back to file .


function lintFile(fileName, userConfig, errorReporter) {
    let sourceCode;

    try {
        sourceCode = fs.readFileSync(fileName, "utf8");
    } catch (e) {
        errorReporter.reportFatal("Unable to read " + fileName + ": " + e.message);
        process.exit(errorCodes.FILE_NOT_FOUND);
    }

    return lintString(sourceCode, userConfig, errorReporter, fileName);
}

function
lintFile
(
fileName
,
userConfig
,
errorReporter
)
{
let
sourceCode
;
try
{
sourceCode
=
fs
.
readFileSync
(
fileName
,
"utf8"
)
;
}
catch
(
e
)
{
errorReporter
.
reportFatal
(
"Unable to read "
+
fileName
+
": "
+
e
.
message
)
;
process
.
exit
(
errorCodes
.
FILE_NOT_FOUND
)
;
}
return
lintString
(
sourceCode
,
userConfig
,
errorReporter
,
fileName
)
;
}

Lint a file based on user settings
@param {String} fileName The path to the file to be linted
@param {Object} userConfig User configuration
@param {Object} errorReporter The error reporter to use
@returns {Integer} numOfErrors Number of Lint ERRORS that occured (the result returned by lintString())


function createCliOptions(cliObject) {
    function collect(val, memo) {
        memo.push(val);
        return memo;
    }

    cliObject
        .version(`Solium version ${version}`)
        .description("Linter to find & fix style and security issues in Solidity smart contracts.")
        .usage("[options] <keyword>")

        .option("-i, --init", "Create default rule configuration files")
        .option("-f, --file [filepath::String]", "Solidity file to lint")
        .option("-d, --dir [dirpath::String]", "Directory containing Solidity files to lint")
        .option("-R, --reporter [name::String]", "Format to report lint issues in (pretty | gcc)", "pretty")
        .option("-c, --config [filepath::String]", "Path to the .soliumrc configuration file")
        .option("-, --stdin", "Read input file from stdin")
        .option("--fix", "Fix Lint issues where possible")
        .option("--fix-dry-run", "Output fix diff without applying it")
        .option("--debug", "Display debug information")
        .option("--watch", "Watch for file changes")
        .option("--hot", "(Deprecated) Same as --watch")
        .option("--no-soliumignore", "Do not look for .soliumignore file")
        .option("--no-soliumrc", "Do not look for soliumrc configuration file")
        .option(
            "--rule [rule]",
            "Rule to execute. This overrides the specified rule's configuration in soliumrc if present",
            collect,
            []
        )
        .option(
            "--plugin [plugin]",
            "Plugin to execute. This overrides the specified plugin's configuration in soliumrc if present",
            collect,
            []
        );
}

Function responsible for defining all the available commandline options & version information
@param {Object} cliObject Commander Object handling the cli


function(options, listItemsSchema) {
        let validateOptionsList = SchemaValidator.compile({
            type: "array",
            minItems: listItemsSchema.length,
            additionalItems: false,
            items: listItemsSchema
        });

        return validateOptionsList(options);
    }

function ( options , listItemsSchema ) { let validateOptionsList = SchemaValidator . compile ( { type : "array" , minItems : listItemsSchema . length , additionalItems : false , items : listItemsSchema } ) ; return validateOptionsList ( options ) ; }

Determine whether the options object supplied is valid according to the schema passed.
@param {Array} options List of options
@param {Array} listItemsSchema A list of schema objects defining schema for every item in the options list.
@returns {Boolean} isValid True if options list is valid, false otherwise.

Determine whether the options object supplied is valid according to the schema passed .


function inspectFD(emitted) {
            const { node } = emitted,
                visibilityModifiers = ["public", "external", "internal", "private"];
            const modifiers = (node.modifiers || []),
                firstVisibilityModifierIndex = modifiers.findIndex(m => visibilityModifiers.includes(m.name));

            // If no visibility modifiers exist in function declaration, exit now
            if (emitted.exit || firstVisibilityModifierIndex === -1) {
                return;
            }

            const firstNonVisModifBeforeFirstVisModif = modifiers.slice(0, firstVisibilityModifierIndex).find(m => !visibilityModifiers.includes(m.name));

            // TODO: Add fix() for this rule
            if (firstNonVisModifBeforeFirstVisModif) {
                const issue = {
                    node: modifiers[firstVisibilityModifierIndex],
                    message: `Visibility modifier "${modifiers[firstVisibilityModifierIndex].name}" should come before other modifiers.`
                };
                context.report(issue);
            }
        }

Find index of the first visibility modifier in declaration. Find the first non-VM before this first VM found above. If non-VM found, report the VM.

Find index of the first visibility modifier in declaration . Find the first non - VM before this first VM found above . If non - VM found report the VM .


function isHex(literal) {
    let reg = /^[0-9a-f]+$/i;

    //test for '0x' separately because hex notation should not be a part of the standard RegExp
    if (literal.slice(0, 2) !== "0x") {
        return false;
    }

    return reg.test(literal.slice(2));
}

Determine whether the provided literal is in Hex Notation
@param {String} literal The literal to test for Hex Notation
@returns {Boolean}


function Soundfont (ctx, nameToUrl) {
  console.warn('new Soundfont() is deprected')
  console.log('Please use Soundfont.instrument() instead of new Soundfont().instrument()')
  if (!(this instanceof Soundfont)) return new Soundfont(ctx)

  this.nameToUrl = nameToUrl || Soundfont.nameToUrl
  this.ctx = ctx
  this.instruments = {}
  this.promises = []
}

Create a Soundfont object

@param {AudioContext} context - the [audio context](https://developer.mozilla.org/en/docs/Web/API/AudioContext)
@param {Function} nameToUrl - (Optional) a function that maps the sound font name to the url
@return {Soundfont} a soundfont object


function oscillatorPlayer (ctx, defaultOptions) {
  defaultOptions = defaultOptions || {}
  return function (note, time, duration, options) {
    console.warn('The oscillator player is deprecated.')
    console.log('Starting with version 0.9.0 you will have to wait until the soundfont is loaded to play sounds.')
    var midi = note > 0 && note < 129 ? +note : parser.midi(note)
    var freq = midi ? parser.midiToFreq(midi, 440) : null
    if (!freq) return

    duration = duration || 0.2

    options = options || {}
    var destination = options.destination || defaultOptions.destination || ctx.destination
    var vcoType = options.vcoType || defaultOptions.vcoType || 'sine'
    var gain = options.gain || defaultOptions.gain || 0.4

    var vco = ctx.createOscillator()
    vco.type = vcoType
    vco.frequency.value = freq

    /* VCA */
    var vca = ctx.createGain()
    vca.gain.value = gain

    /* Connections */
    vco.connect(vca)
    vca.connect(destination)

    vco.start(time)
    if (duration > 0) vco.stop(time + duration)
    return vco
  }
}

Returns a function that plays an oscillator

@param {AudioContext} ac - the audio context
@param {Hash} defaultOptions - (Optional) a hash of options:
- vcoType: the oscillator type (default: 'sine')
- gain: the output gain value (default: 0.4)
- destination: the player destination (default: ac.destination)


function instrument (ac, name, options) {
  if (arguments.length === 1) return function (n, o) { return instrument(ac, n, o) }
  var opts = options || {}
  var isUrl = opts.isSoundfontURL || isSoundfontURL
  var toUrl = opts.nameToUrl || nameToUrl
  var url = isUrl(name) ? name : toUrl(name, opts.soundfont, opts.format)

  return load(ac, url, { only: opts.only || opts.notes }).then(function (buffers) {
    var p = player(ac, buffers, opts).connect(opts.destination ? opts.destination : ac.destination)
    p.url = url
    p.name = name
    return p
  })
}

function instrument ( ac , name , options ) { if ( arguments . length === 1 ) return function ( n , o ) { return instrument ( ac , n , o ) } var opts = options || { } var isUrl = opts . isSoundfontURL || isSoundfontURL var toUrl = opts . nameToUrl || nameToUrl var url = isUrl ( name ) ? name : toUrl ( name , opts . soundfont , opts . format ) return load ( ac , url , { only : opts . only || opts . notes } ) . then ( function ( buffers ) { var p = player ( ac , buffers , opts ) . connect ( opts . destination ? opts . destination : ac . destination ) p . url = url p . name = name return p } ) }

Load a soundfont instrument. It returns a promise that resolves to a
instrument object.

The instrument object returned by the promise has the following properties:

- name: the instrument name
- play: A function to play notes from the buffer with the signature
`play(note, time, duration, options)`

The valid options are:

- `format`: the soundfont format. 'mp3' by default. Can be 'ogg'
- `soundfont`: the soundfont name. 'MusyngKite' by default. Can be 'FluidR3_GM'
- `nameToUrl` <Function>: a function to convert from instrument names to URL
- `destination`: by default Soundfont uses the `audioContext.destination` but you can override it.
- `gain`: the gain of the player (1 by default)
- `notes`: an array of the notes to decode. It can be an array of strings
with note names or an array of numbers with midi note numbers. This is a
performance option: since decoding mp3 is a cpu intensive process, you can limit
limit the number of notes you want and reduce the time to load the instrument.

@param {AudioContext} ac - the audio context
@param {String} name - the instrument name. For example: 'acoustic_grand_piano'
@param {Object} options - (Optional) the same options as Soundfont.loadBuffers
@return {Promise}

@example
var Soundfont = require('sounfont-player')
Soundfont.instrument('marimba').then(function (marimba) {
marimba.play('C4')
})

Load a soundfont instrument . It returns a promise that resolves to a instrument object .


function hasSystemLib (lib) {
  var libName = 'lib' + lib + '.+(so|dylib)'
  var libNameRegex = new RegExp(libName)

    // Try using ldconfig on linux systems
  if (hasLdconfig()) {
    try {
      if (childProcess.execSync('ldconfig -p 2>/dev/null | grep -E "' + libName + '"').length) {
        return true
      }
    } catch (err) {
      // noop -- proceed to other search methods
    }
  }

    // Try checking common library locations
  return SYSTEM_PATHS.some(function (systemPath) {
    try {
      var dirListing = fs.readdirSync(systemPath)
      return dirListing.some(function (file) {
        return libNameRegex.test(file)
      })
    } catch (err) {
      return false
    }
  })
}

Checks for lib using ldconfig if present, or searching SYSTEM_PATHS
otherwise.
@param String library name, e.g. 'jpeg' in 'libjpeg64.so' (see first line)
@return Boolean exists

Checks for lib using ldconfig if present or searching SYSTEM_PATHS otherwise .


async function thenify(fn) {
  return await new Promise(function(resolve, reject) {
    function callback(err, res) {
      if (err) return reject(err);
      return resolve(res);
    }

    fn(callback);
  });
}

async function thenify ( fn ) { return await new Promise ( function ( resolve , reject ) { function callback ( err , res ) { if ( err ) return reject ( err ) ; return resolve ( res ) ; } fn ( callback ) ; } ) ; }

Helper function to convert a callback to a Promise.

Helper function to convert a callback to a Promise .


function startWatching(opts) {
    var chokidarOpts = createChokidarOpts(opts);
    var watcher = chokidar.watch(opts.patterns, chokidarOpts);

    var throttledRun = _.throttle(run, opts.throttle);
    var debouncedRun = _.debounce(throttledRun, opts.debounce);
    watcher.on('all', function(event, path) {
        var description = EVENT_DESCRIPTIONS[event] + ':';

        if (opts.verbose) {
            console.error(description, path);
        } else {
            if (!opts.silent) {
                console.log(event + ':' + path);
            }
        }

        // XXX: commands might be still run concurrently
        if (opts.command) {
            debouncedRun(
                opts.command
                    .replace(/\{path\}/ig, path)
                    .replace(/\{event\}/ig, event)
            );
        }
    });

    watcher.on('error', function(error) {
        console.error('Error:', error);
        console.error(error.stack);
    });

    watcher.once('ready', function() {
        var list = opts.patterns.join('", "');
        if (!opts.silent) {
            console.error('Watching', '"' + list + '" ..');
        }
    });
}

Estimates spent working hours based on commit dates


function _resolveIgnoreOpt(ignoreOpt) {
    if (!ignoreOpt) {
        return ignoreOpt;
    }

    var ignores = !_.isArray(ignoreOpt) ? [ignoreOpt] : ignoreOpt;

    return _.map(ignores, function(ignore) {
        var isRegex = ignore[0] === '/' && ignore[ignore.length - 1] === '/';
        if (isRegex) {
            // Convert user input to regex object
            var match = ignore.match(new RegExp('^/(.*)/(.*?)$'));
            return new RegExp(match[1], match[2]);
        }

        return ignore;
    });
}

function
_resolveIgnoreOpt
(
ignoreOpt
)
{
if
(
!
ignoreOpt
)
{
return
ignoreOpt
;
}
var
ignores
=
!
_
.
isArray
(
ignoreOpt
)
[
ignoreOpt
]
:
ignoreOpt
;
return
_
.
map
(
ignores
,
function
(
ignore
)
{
var
isRegex
=
ignore
[
0
]
===
'/'
&&
ignore
[
ignore
.
length
1
]
===
'/'
;
if
(
isRegex
)
{
// Convert user input to regex object
var
match
=
ignore
.
match
(
new
RegExp
(
'^/(.*)/(.*?)$'
)
)
;
return
new
RegExp
(
match
[
1
]
,
match
[
2
]
)
;
}
return
ignore
;
}
)
;
}


function requireProp(props, propName, componentName) {
  return isEmpty(props[propName])
    ? new Error(
        `The prop \`${propName}\` is required for \`${componentName}\`.`
      )
    : null
}

function requireProp ( props , propName , componentName ) { return isEmpty ( props [ propName ] ) ? new Error ( ` \` ${ propName } \` \` ${ componentName } \` ` ) : null }


function _0to1(props, propName, componentName) {
  if (isEmpty(props[propName])) {
    return null
  }
  if (
    typeof props[propName] === 'number' &&
    props[propName] >= 0 &&
    props[propName] <= 1
  ) {
    return null
  }
  return new Error(
    `Invalid prop \`${propName}\` supplied to \`${componentName}\`. Please provide a number in the 0-1 range.`
  )
}

function _0to1 ( props , propName , componentName ) { if ( isEmpty ( props [ propName ] ) ) { return null } if ( typeof props [ propName ] === 'number' && props [ propName ] >= 0 && props [ propName ] <= 1 ) { return null } return new Error ( ` \` ${ propName } \` \` ${ componentName } \` ` ) }


function babel(options = {}) {
  return (context, { addLoader }) =>
    addLoader({
      // setting `test` defaults here, in case there is no `context.match` data
      test: /\.(js|jsx)$/,
      use: [
        {
          loader: 'thread-loader',
          options: {
            // Keep workers alive for more effective watch mode
            ...(process.env.NODE_ENV === 'development' && { poolTimeout: Infinity }),
          },
        },
        {
          loader: 'babel-loader',
          options: Object.assign(babelLoaderOptions, options),
        },
      ],
      ...context.match,
    })
}

The thread-loader parallelizes code compilation, useful with babel since
it transpiles both application javascript and node_modules javascript

The thread - loader parallelizes code compilation useful with babel since it transpiles both application javascript and node_modules javascript


function imageLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(gif|ico|jpg|jpeg|png|webp)$/,
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

function imageLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \.(gif|ico|jpg|jpeg|png|webp)$ / , loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } ) }

Images smaller than 10kb are loaded as a base64 encoded url instead of file url


function csvLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.csv$/,
      loader: 'csv-loader',
      options: {
        dynamicTyping: true,
        header: true,
        skipEmptyLines: true,
      },
    })
}

function csvLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \.csv$ / , loader : 'csv-loader' , options : { dynamicTyping : true , header : true , skipEmptyLines : true , } , } ) }

Parse .csv files with PapaParse and return it in a JSON format

Parse . csv files with PapaParse and return it in a JSON format


function cssSvgLoader() {
  return (context, { addLoader }) =>
    addLoader({
      // This needs to be different form the reactSvgLoader, otherwise it will merge
      test: /(.*)\.svg$/,
      issuer: {
        test: /\.css$/,
      },
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}


function prependEntry(entry) {
  const blockFunction = (context, util) => {
    if (!context.entriesToPrepend) context.entriesToPrepend = []
    context.entriesToPrepend.unshift(entry)
    return config => config
  }
  return Object.assign(blockFunction, {
    post: prependEntryPostHook,
  })
}

function prependEntry ( entry ) { const blockFunction = ( context , util ) => { if ( ! context . entriesToPrepend ) context . entriesToPrepend = [ ] context . entriesToPrepend . unshift ( entry ) return config => config } return Object . assign ( blockFunction , { post : prependEntryPostHook , } ) }

Add entryPoint at beginning of 'entry' array

Add entryPoint at beginning of entry array


function build() {
  log.info(`Creating an optimized production build...`)
  const compiler = createWebpackCompiler(
    () => {
      log.ok(`The ${chalk.cyan(relativeAppBuildPath)} folder is ready to be deployed.`)
    },
    () => {
      log.err(`Aborting`)
      process.exit(2)
    }
  )

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err)
      }

      return resolve(stats)
    })
  })
}

function build ( ) { log . info ( ` ` ) const compiler = createWebpackCompiler ( ( ) => { log . ok ( ` ${ chalk . cyan ( relativeAppBuildPath ) } ` ) } , ( ) => { log . err ( ` ` ) process . exit ( 2 ) } ) return new Promise ( ( resolve , reject ) => { compiler . run ( ( err , stats ) => { if ( err ) { return reject ( err ) } return resolve ( stats ) } ) } ) }

Create the production build and print the deployment instructions.

Create the production build and print the deployment instructions .


function mergeData (to, from) {
	    if (!from) { return to }
	    var key, toVal, fromVal;
	    var keys = Object.keys(from);
	    for (var i = 0; i < keys.length; i++) {
	      key = keys[i];
	      toVal = to[key];
	      fromVal = from[key];
	      if (!hasOwn(to, key)) {
	        set(to, key, fromVal);
	      } else if (
	        toVal !== fromVal &&
	        isPlainObject(toVal) &&
	        isPlainObject(fromVal)
	      ) {
	        mergeData(toVal, fromVal);
	      }
	    }
	    return to
	  }

function mergeData ( to , from ) { if ( ! from ) { return to } var key , toVal , fromVal ; var keys = Object . keys ( from ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { key = keys [ i ] ; toVal = to [ key ] ; fromVal = from [ key ] ; if ( ! hasOwn ( to , key ) ) { set ( to , key , fromVal ) ; } else if ( toVal !== fromVal && isPlainObject ( toVal ) && isPlainObject ( fromVal ) ) { mergeData ( toVal , fromVal ) ; } } return to }

Helper that recursively merges two data objects together.

Helper that recursively merges two data objects together .


function withDefault(type) {
	  return Object.defineProperty(type, 'def', {
	    value: function value(def) {
	      if (def === undefined && !this.default) {
	        return this;
	      }

	      if (!isFunction(def) && !validateType(this, def)) {
	        warn(this._vueTypes_name + " - invalid default value: \"" + def + "\"", def);
	        return this;
	      }

	      if (isArray(def)) {
	        this.default = function () {
	          return [].concat(def);
	        };
	      } else if (isPlainObject_1(def)) {
	        this.default = function () {
	          return Object.assign({}, def);
	        };
	      } else {
	        this.default = def;
	      }

	      return this;
	    },
	    enumerable: false,
	    writable: false
	  });
	}

function
withDefault
(
type
)
{
return
Object
.
defineProperty
(
type
,
'def'
,
{
value
:
function
value
(
def
)
{
if
(
def
===
undefined
&&
!
this
.
default
)
{
return
this
;
}
if
(
!
isFunction
(
def
)
&&
!
validateType
(
this
,
def
)
)
{
warn
(
this
.
_vueTypes_name
+
" - invalid default value: \""
+
def
+
"\""
,
def
)
;
return
this
;
}
if
(
isArray
(
def
)
)
{
this
.
default
=
function
(
)
{
return
[
]
.
concat
(
def
)
;
}
;
}
else
if
(
isPlainObject_1
(
def
)
)
{
this
.
default
=
function
(
)
{
return
Object
.
assign
(
{
}
,
def
)
;
}
;
}
else
{
this
.
default
=
def
;
}
return
this
;
}
,
enumerable
:
false
,
writable
:
false
}
)
;
}

Adds a `def` method to the object returning a new object with passed in argument as `default` property

@param {object} type - Object to enhance
@returns {object} the passed-in prop type

Adds a def method to the object returning a new object with passed in argument as default property


function withValidate(type) {
	  return Object.defineProperty(type, 'validate', {
	    value: function value(fn) {
	      this.validator = fn.bind(this);
	      return this;
	    },
	    enumerable: false
	  });
	}

function withValidate ( type ) { return Object . defineProperty ( type , 'validate' , { value : function value ( fn ) { this . validator = fn . bind ( this ) ; return this ; } , enumerable : false } ) ; }

Adds a validate method useful to set the prop `validator` function.

@param {object} type Prop type to extend
@returns {object} the passed-in prop type

Adds a validate method useful to set the prop validator function .


function toType(name, obj, validateFn) {
	  if (validateFn === void 0) {
	    validateFn = false;
	  }

	  Object.defineProperty(obj, '_vueTypes_name', {
	    enumerable: false,
	    writable: false,
	    value: name
	  });
	  withDefault(withRequired(obj));

	  if (validateFn) {
	    withValidate(obj);
	  }

	  if (isFunction(obj.validator)) {
	    obj.validator = obj.validator.bind(obj);
	  }

	  return obj;
	}

function toType ( name , obj , validateFn ) { if ( validateFn === void 0 ) { validateFn = false ; } Object . defineProperty ( obj , '_vueTypes_name' , { enumerable : false , writable : false , value : name } ) ; withDefault ( withRequired ( obj ) ) ; if ( validateFn ) { withValidate ( obj ) ; } if ( isFunction ( obj . validator ) ) { obj . validator = obj . validator . bind ( obj ) ; } return obj ; }

Adds `isRequired` and `def` modifiers to an object

@param {string} name - Type internal name
@param {object} obj - Object to enhance
@returns {object}

Adds isRequired and def modifiers to an object


function validateType(type, value, silent) {
	  if (silent === void 0) {
	    silent = false;
	  }

	  var typeToCheck = type;
	  var valid = true;
	  var expectedType;

	  if (!isPlainObject_1(type)) {
	    typeToCheck = {
	      type: type
	    };
	  }

	  var namePrefix = typeToCheck._vueTypes_name ? typeToCheck._vueTypes_name + ' - ' : '';

	  if (hasOwn.call(typeToCheck, 'type') && typeToCheck.type !== null) {
	    if (isArray(typeToCheck.type)) {
	      valid = typeToCheck.type.some(function (type) {
	        return validateType(type, value, true);
	      });
	      expectedType = typeToCheck.type.map(function (type) {
	        return getType(type);
	      }).join(' or ');
	    } else {
	      expectedType = getType(typeToCheck);

	      if (expectedType === 'Array') {
	        valid = isArray(value);
	      } else if (expectedType === 'Object') {
	        valid = isPlainObject_1(value);
	      } else if (expectedType === 'String' || expectedType === 'Number' || expectedType === 'Boolean' || expectedType === 'Function') {
	        valid = getNativeType(value) === expectedType;
	      } else {
	        valid = value instanceof typeToCheck.type;
	      }
	    }
	  }

	  if (!valid) {
	    silent === false && warn(namePrefix + "value \"" + value + "\" should be of type \"" + expectedType + "\"");
	    return false;
	  }

	  if (hasOwn.call(typeToCheck, 'validator') && isFunction(typeToCheck.validator)) {
	    // swallow warn
	    var oldWarn;

	    if (silent) {
	      oldWarn = warn;
	      warn = noop;
	    }

	    valid = typeToCheck.validator(value);
	    oldWarn && (warn = oldWarn);
	    if (!valid && silent === false) warn(namePrefix + "custom validation failed");
	    return valid;
	  }

	  return valid;
	}

function
validateType
(
type
,
value
,
silent
)
{
if
(
silent
===
void
0
)
{
silent
=
false
;
}
var
typeToCheck
=
type
;
var
valid
=
true
;
var
expectedType
;
if
(
!
isPlainObject_1
(
type
)
)
{
typeToCheck
=
{
type
:
type
}
;
}
var
namePrefix
=
typeToCheck
.
_vueTypes_name
typeToCheck
.
_vueTypes_name
+
' - '
:
''
;
if
(
hasOwn
.
call
(
typeToCheck
,
'type'
)
&&
typeToCheck
.
type
!==
)
{
if
(
isArray
(
typeToCheck
.
type
)
)
{
valid
=
typeToCheck
.
type
.
some
(
function
(
type
)
{
return
validateType
(
type
,
value
,
true
)
;
}
)
;
expectedType
=
typeToCheck
.
type
.
map
(
function
(
type
)
{
return
getType
(
type
)
;
}
)
.
join
(
' or '
)
;
}
else
{
expectedType
=
getType
(
typeToCheck
)
;
if
(
expectedType
===
'Array'
)
{
valid
=
isArray
(
value
)
;
}
else
if
(
expectedType
===
'Object'
)
{
valid
=
isPlainObject_1
(
value
)
;
}
else
if
(
expectedType
===
'String'
||
expectedType
===
'Number'
||
expectedType
===
'Boolean'
||
expectedType
===
'Function'
)
{
valid
=
getNativeType
(
value
)
===
expectedType
;
}
else
{
valid
=
value
instanceof
typeToCheck
.
type
;
}
}
}
if
(
!
valid
)
{
silent
===
false
&&
warn
(
namePrefix
+
"value \""
+
value
+
"\" should be of type \""
+
expectedType
+
"\""
)
;
return
false
;
}
if
(
hasOwn
.
call
(
typeToCheck
,
'validator'
)
&&
isFunction
(
typeToCheck
.
validator
)
)
{
// swallow warn
var
oldWarn
;
if
(
silent
)
{
oldWarn
=
warn
;
warn
=
noop
;
}
valid
=
typeToCheck
.
validator
(
value
)
;
oldWarn
&&
(
warn
=
oldWarn
)
;
if
(
!
valid
&&
silent
===
false
)
warn
(
namePrefix
+
"custom validation failed"
)
;
return
valid
;
}
return
valid
;
}

Validates a given value against a prop type object

@param {Object|*} type - Type to use for validation. Either a type object or a constructor
@param {*} value - Value to check
@param {boolean} silent - Silence warnings
@returns {boolean}


function CustomEvent(type, eventInitDict) {
        /*jshint eqnull:true */
        var event = document.createEvent(eventName);
        if (typeof type != 'string') {
          throw new Error('An event name must be provided');
        }
        if (eventName == 'Event') {
          event.initCustomEvent = initCustomEvent;
        }
        if (eventInitDict == null) {
          eventInitDict = defaultInitDict;
        }
        event.initCustomEvent(
          type,
          eventInitDict.bubbles,
          eventInitDict.cancelable,
          eventInitDict.detail
        );
        return event;
      }

function
CustomEvent
(
type
,
eventInitDict
)
{
/*jshint eqnull:true */
var
event
=
document
.
createEvent
(
eventName
)
;
if
(
typeof
type
!=
'string'
)
{
throw
new
Error
(
'An event name must be provided'
)
;
}
if
(
eventName
==
'Event'
)
{
event
.
initCustomEvent
=
initCustomEvent
;
}
if
(
eventInitDict
==
)
{
eventInitDict
=
defaultInitDict
;
}
event
.
initCustomEvent
(
type
,
eventInitDict
.
bubbles
,
eventInitDict
.
cancelable
,
eventInitDict
.
detail
)
;
return
event
;
}


function initCustomEvent(
        type, bubbles, cancelable, detail
      ) {
        /*jshint validthis:true*/
        this.initEvent(type, bubbles, cancelable);
        this.detail = detail;
      }

function
initCustomEvent
(
type
,
bubbles
,
cancelable
,
detail
)
{
/*jshint validthis:true*/
this
.
initEvent
(
type
,
bubbles
,
cancelable
)
;
this
.
detail
=
detail
;
}


function cleanUpRuntimeEvents() {
            // Remove all touch events added during 'onDown' as well.
            document.removeEventListener('touchmove', onMove, getPassiveSupported() ? { passive: false } : false);
            document.removeEventListener('touchend', onUp);
            document.removeEventListener('touchcancel', stopTracking);
            document.removeEventListener('mousemove', onMove, getPassiveSupported() ? { passive: false } : false);
            document.removeEventListener('mouseup', onUp);
        }

Removes all events set by this instance during runtime


function addRuntimeEvents() {
            cleanUpRuntimeEvents();

            // @see https://developers.google.com/web/updates/2017/01/scrolling-intervention
            document.addEventListener('touchmove', onMove, getPassiveSupported() ? { passive: false } : false);
            document.addEventListener('touchend', onUp);
            document.addEventListener('touchcancel', stopTracking);
            document.addEventListener('mousemove', onMove, getPassiveSupported() ? { passive: false } : false);
            document.addEventListener('mouseup', onUp);
        }


function normalizeEvent(ev) {
            if (ev.type === 'touchmove' || ev.type === 'touchstart' || ev.type === 'touchend') {
                var touch = ev.targetTouches[0] || ev.changedTouches[0];
                return {
                    x: touch.clientX,
                    y: touch.clientY,
                    id: touch.identifier
                };
            } else {
                // mouse events
                return {
                    x: ev.clientX,
                    y: ev.clientY,
                    id: null
                };
            }
        }

function
normalizeEvent
(
ev
)
{
if
(
ev
.
type
===
'touchmove'
||
ev
.
type
===
'touchstart'
||
ev
.
type
===
'touchend'
)
{
var
touch
=
ev
.
targetTouches
[
0
]
||
ev
.
changedTouches
[
0
]
;
return
{
x
:
touch
.
clientX
,
y
:
touch
.
clientY
,
id
:
touch
.
identifier
}
;
}
else
{
// mouse events
return
{
x
:
ev
.
clientX
,
y
:
ev
.
clientY
,
id
:
}
;
}
}

Creates a custom normalized event object from touch and mouse events
@param  {Event} ev
@returns {Object} with x, y, and id properties


function onDown(ev) {
            var event = normalizeEvent(ev);
            if (!pointerActive && !paused) {
                pointerActive = true;
                decelerating = false;
                pointerId = event.id;

                pointerLastX = pointerCurrentX = event.x;
                pointerLastY = pointerCurrentY = event.y;
                trackingPoints = [];
                addTrackingPoint(pointerLastX, pointerLastY);

                addRuntimeEvents();
            }
        }

function onDown ( ev ) { var event = normalizeEvent ( ev ) ; if ( ! pointerActive && ! paused ) { pointerActive = true ; decelerating = false ; pointerId = event . id ; pointerLastX = pointerCurrentX = event . x ; pointerLastY = pointerCurrentY = event . y ; trackingPoints = [ ] ; addTrackingPoint ( pointerLastX , pointerLastY ) ; addRuntimeEvents ( ) ; } }

Initializes movement tracking
@param  {Object} ev Normalized event


function onMove(ev) {
            ev.preventDefault();
            var event = normalizeEvent(ev);

            if (pointerActive && event.id === pointerId) {
                pointerCurrentX = event.x;
                pointerCurrentY = event.y;
                addTrackingPoint(pointerLastX, pointerLastY);
                requestTick();
            }
        }

function onMove ( ev ) { ev . preventDefault ( ) ; var event = normalizeEvent ( ev ) ; if ( pointerActive && event . id === pointerId ) { pointerCurrentX = event . x ; pointerCurrentY = event . y ; addTrackingPoint ( pointerLastX , pointerLastY ) ; requestTick ( ) ; } }

Handles move events
@param  {Object} ev Normalized event


function addTrackingPoint(x, y) {
            var time = Date.now();
            while (trackingPoints.length > 0) {
                if (time - trackingPoints[0].time <= 100) {
                    break;
                }
                trackingPoints.shift();
            }

            trackingPoints.push({ x: x, y: y, time: time });
        }

function addTrackingPoint ( x , y ) { var time = Date . now ( ) ; while ( trackingPoints . length > 0 ) { if ( time - trackingPoints [ 0 ] . time <= 100 ) { break ; } trackingPoints . shift ( ) ; } trackingPoints . push ( { x : x , y : y , time : time } ) ; }

Records movement for the last 100ms
@param {number} x
@param {number} y [description]


function updateAndRender() {
            var pointerChangeX = pointerCurrentX - pointerLastX;
            var pointerChangeY = pointerCurrentY - pointerLastY;

            targetX += pointerChangeX * multiplier;
            targetY += pointerChangeY * multiplier;

            if (bounce) {
                var diff = checkBounds();
                if (diff.x !== 0) {
                    targetX -= pointerChangeX * dragOutOfBoundsMultiplier(diff.x) * multiplier;
                }
                if (diff.y !== 0) {
                    targetY -= pointerChangeY * dragOutOfBoundsMultiplier(diff.y) * multiplier;
                }
            } else {
                checkBounds(true);
            }

            callUpdateCallback();

            pointerLastX = pointerCurrentX;
            pointerLastY = pointerCurrentY;
            ticking = false;
        }

function updateAndRender ( ) { var pointerChangeX = pointerCurrentX - pointerLastX ; var pointerChangeY = pointerCurrentY - pointerLastY ; targetX += pointerChangeX * multiplier ; targetY += pointerChangeY * multiplier ; if ( bounce ) { var diff = checkBounds ( ) ; if ( diff . x !== 0 ) { targetX -= pointerChangeX * dragOutOfBoundsMultiplier ( diff . x ) * multiplier ; } if ( diff . y !== 0 ) { targetY -= pointerChangeY * dragOutOfBoundsMultiplier ( diff . y ) * multiplier ; } } else { checkBounds ( true ) ; } callUpdateCallback ( ) ; pointerLastX = pointerCurrentX ; pointerLastY = pointerCurrentY ; ticking = false ; }

Calculate new values, call update function

Calculate new values call update function


function startDecelAnim() {
            var firstPoint = trackingPoints[0];
            var lastPoint = trackingPoints[trackingPoints.length - 1];

            var xOffset = lastPoint.x - firstPoint.x;
            var yOffset = lastPoint.y - firstPoint.y;
            var timeOffset = lastPoint.time - firstPoint.time;

            var D = timeOffset / 15 / multiplier;

            decVelX = xOffset / D || 0; // prevent NaN
            decVelY = yOffset / D || 0;

            var diff = checkBounds();

            if (Math.abs(decVelX) > 1 || Math.abs(decVelY) > 1 || !diff.inBounds) {
                decelerating = true;
                requestAnimFrame(stepDecelAnim);
            }
        }

function
startDecelAnim
(
)
{
var
firstPoint
=
trackingPoints
[
0
]
;
var
lastPoint
=
trackingPoints
[
trackingPoints
.
length
1
]
;
var
xOffset
=
lastPoint
.
x
firstPoint
.
x
;
var
yOffset
=
lastPoint
.
y
firstPoint
.
y
;
var
timeOffset
=
lastPoint
.
time
firstPoint
.
time
;
var
D
=
timeOffset
/
15
/
multiplier
;
decVelX
=
xOffset
/
D
||
0
;
// prevent NaN
decVelY
=
yOffset
/
D
||
0
;
var
diff
=
checkBounds
(
)
;
if
(
Math
.
abs
(
decVelX
)
>
1
||
Math
.
abs
(
decVelY
)
>
1
||
!
diff
.
inBounds
)
{
decelerating
=
true
;
requestAnimFrame
(
stepDecelAnim
)
;
}
}

Initialize animation of values coming to a stop


function stepDecelAnim() {
            if (!decelerating) {
                return;
            }

            decVelX *= friction;
            decVelY *= friction;

            targetX += decVelX;
            targetY += decVelY;

            var diff = checkBounds();

            if (Math.abs(decVelX) > stopThreshold || Math.abs(decVelY) > stopThreshold || !diff.inBounds) {

                if (bounce) {
                    var reboundAdjust = 2.5;

                    if (diff.x !== 0) {
                        if (diff.x * decVelX <= 0) {
                            decVelX += diff.x * bounceDeceleration;
                        } else {
                            var adjust = diff.x > 0 ? reboundAdjust : -reboundAdjust;
                            decVelX = (diff.x + adjust) * bounceAcceleration;
                        }
                    }
                    if (diff.y !== 0) {
                        if (diff.y * decVelY <= 0) {
                            decVelY += diff.y * bounceDeceleration;
                        } else {
                            var adjust = diff.y > 0 ? reboundAdjust : -reboundAdjust;
                            decVelY = (diff.y + adjust) * bounceAcceleration;
                        }
                    }
                } else {
                    if (diff.x !== 0) {
                        if (diff.x > 0) {
                            targetX = boundXmin;
                        } else {
                            targetX = boundXmax;
                        }
                        decVelX = 0;
                    }
                    if (diff.y !== 0) {
                        if (diff.y > 0) {
                            targetY = boundYmin;
                        } else {
                            targetY = boundYmax;
                        }
                        decVelY = 0;
                    }
                }

                callUpdateCallback();

                requestAnimFrame(stepDecelAnim);
            } else {
                decelerating = false;
            }
        }

function stepDecelAnim ( ) { if ( ! decelerating ) { return ; } decVelX *= friction ; decVelY *= friction ; targetX += decVelX ; targetY += decVelY ; var diff = checkBounds ( ) ; if ( Math . abs ( decVelX ) > stopThreshold || Math . abs ( decVelY ) > stopThreshold || ! diff . inBounds ) { if ( bounce ) { var reboundAdjust = 2.5 ; if ( diff . x !== 0 ) { if ( diff . x * decVelX <= 0 ) { decVelX += diff . x * bounceDeceleration ; } else { var adjust = diff . x > 0 ? reboundAdjust : - reboundAdjust ; decVelX = ( diff . x + adjust ) * bounceAcceleration ; } } if ( diff . y !== 0 ) { if ( diff . y * decVelY <= 0 ) { decVelY += diff . y * bounceDeceleration ; } else { var adjust = diff . y > 0 ? reboundAdjust : - reboundAdjust ; decVelY = ( diff . y + adjust ) * bounceAcceleration ; } } } else { if ( diff . x !== 0 ) { if ( diff . x > 0 ) { targetX = boundXmin ; } else { targetX = boundXmax ; } decVelX = 0 ; } if ( diff . y !== 0 ) { if ( diff . y > 0 ) { targetY = boundYmin ; } else { targetY = boundYmax ; } decVelY = 0 ; } } callUpdateCallback ( ) ; requestAnimFrame ( stepDecelAnim ) ; } else { decelerating = false ; } }


function checkBounds(restrict) {
            var xDiff = 0;
            var yDiff = 0;

            if (boundXmin !== undefined && targetX < boundXmin) {
                xDiff = boundXmin - targetX;
            } else if (boundXmax !== undefined && targetX > boundXmax) {
                xDiff = boundXmax - targetX;
            }

            if (boundYmin !== undefined && targetY < boundYmin) {
                yDiff = boundYmin - targetY;
            } else if (boundYmax !== undefined && targetY > boundYmax) {
                yDiff = boundYmax - targetY;
            }

            if (restrict) {
                if (xDiff !== 0) {
                    targetX = (xDiff > 0) ? boundXmin : boundXmax;
                }
                if (yDiff !== 0) {
                    targetY = (yDiff > 0) ? boundYmin : boundYmax;
                }
            }

            return {
                x: xDiff,
                y: yDiff,
                inBounds: xDiff === 0 && yDiff === 0
            };
        }

function checkBounds ( restrict ) { var xDiff = 0 ; var yDiff = 0 ; if ( boundXmin !== undefined && targetX < boundXmin ) { xDiff = boundXmin - targetX ; } else if ( boundXmax !== undefined && targetX > boundXmax ) { xDiff = boundXmax - targetX ; } if ( boundYmin !== undefined && targetY < boundYmin ) { yDiff = boundYmin - targetY ; } else if ( boundYmax !== undefined && targetY > boundYmax ) { yDiff = boundYmax - targetY ; } if ( restrict ) { if ( xDiff !== 0 ) { targetX = ( xDiff > 0 ) ? boundXmin : boundXmax ; } if ( yDiff !== 0 ) { targetY = ( yDiff > 0 ) ? boundYmin : boundYmax ; } } return { x : xDiff , y : yDiff , inBounds : xDiff === 0 && yDiff === 0 } ; }

Determine position relative to bounds
@param {Boolean} restrict Whether to restrict target to bounds


function initCompDirs(){
  var compRoot = path.resolve(process.cwd(),'src/components'),
      compReg  = /^[A-Z]\w+$/;

  //['Button', 'Select']
  compDirs = fs.readdirSync(compRoot).filter(function(filename){
    return compReg.test(filename)
  })

  return compDirs
}

function
initCompDirs
(
)
{
var
compRoot
=
path
.
resolve
(
process
.
cwd
(
)
,
'src/components'
)
,
compReg
=
/
^[A-Z]\w+$
/
;
//['Button', 'Select']
compDirs
=
fs
.
readdirSync
(
compRoot
)
.
filter
(
function
(
filename
)
{
return
compReg
.
test
(
filename
)
}
)
return
compDirs
}


function appendLogToFileStream(fileName, newLog, headerLineCount) {
    const filePath = path.join(__dirname, '../../', fileName)
    const oldChangelog = grunt.file.read(filePath)
      .toString()
      .split('\n');

    let wStr = fs.createWriteStream(filePath)
    /** lines used by the default header */
    let logHeader = oldChangelog.slice(0, headerLineCount);
    /** previous changelog entries */
    let prevLogs = oldChangelog.slice(headerLineCount);
    var s = new Readable;
    s.pipe(wStr);
    s.push(logHeader.join('\n') + '\n');
    s.push(newLog);
    s.push(prevLogs.join('\n'));
    s.push(null); // indicates end-of-file basically - the end of the stream)
    return wStr;
  }

Writes a log to a file
@param  {string} fileName  filename/path to write to
@param  {string} newLog  new Changelog entry to add
@param  {number} headerLineCount  Number of lines the header occupies


function doSeek(length, eocdrNotFoundCallback) {
				reader.readUint8Array(reader.size - length, length, function(bytes) {
					for (var i = bytes.length - EOCDR_MIN; i >= 0; i--) {
						if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) {
							eocdrCallback(new DataView(bytes.buffer, i, EOCDR_MIN));
							return;
						}
					}
					eocdrNotFoundCallback();
				}, function() {
					onerror(ERR_READ);
				});
			}

function doSeek ( length , eocdrNotFoundCallback ) { reader . readUint8Array ( reader . size - length , length , function ( bytes ) { for ( var i = bytes . length - EOCDR_MIN ; i >= 0 ; i -- ) { if ( bytes [ i ] === 0x50 && bytes [ i + 1 ] === 0x4b && bytes [ i + 2 ] === 0x05 && bytes [ i + 3 ] === 0x06 ) { eocdrCallback ( new DataView ( bytes . buffer , i , EOCDR_MIN ) ) ; return ; } } eocdrNotFoundCallback ( ) ; } , function ( ) { onerror ( ERR_READ ) ; } ) ; }

seek last length bytes of file for EOCDR


function CronJob (sandbox, job) {
    /**
     * @property name - The name of the cron job
     * @property schedule - The cron schedule of the job
     * @property next_scheduled_at - The next time this job is scheduled
     */
    assign(this, job);

    /**
     * @property claims - The claims embedded in the Webtask's token
     */
    if (job.token) {
        this.claims = Decode(job.token);
    }
    else {
        this.claims = {
            jtn: job.name,
            ten: this.container,
        };
    }

    /**
     * @property sandbox - The {@see Sandbox} instance used to create this Webtask instance
     */
    this.sandbox = sandbox;

    /**
     * @property url - The public url that can be used to invoke webtask that the cron job runs
     */
    Object.defineProperty(this, 'url', {
        enumerable: true,
        get: function () {
            return this.sandbox.url + '/api/run/' + this.container + '/' + this.name;
        }
    });
}

Creates an object representing a CronJob

@constructor


function Sandbox (options) {
    var securityVersion = 'v1';

    this.url = options.url;
    this.container = options.container;
    this.token = options.token;
    this.onBeforeRequest = []
        .concat(options.onBeforeRequest)
        .filter(hook => typeof hook === 'function');

    try {
        var typ = Decode(options.token, { header: true }).typ;

        if (typ && typ.toLowerCase() === 'jwt') {
            securityVersion = 'v2';
        }
    } catch (_) {
        // Ignore jwt decoding failures and assume v1 opaque token
    }

    this.securityVersion = securityVersion;
}

Creates an object representing a user's webtask.io credentials

@constructor
@param {Object} options - Options used to configure the profile
@param {String} options.url - The url of the webtask cluster where code will run
@param {String} options.container - The name of the container in which code will run
@param {String} options.token - The JWT (see: http://jwt.io) issued by webtask.io that grants rights to run code in the indicated container
@param {String} [options.onBeforeRequest] - An array of hook functions to be invoked with a prepared request

Creates an object representing a user s webtask . io credentials


function Webtask (sandbox, token, options) {
    if (!options) options = {};

    if (sandbox.securityVersion === 'v1') {
        try {
            /**
             * @property claims - The claims embedded in the Webtask's token
             */
            this.claims = Decode(token);

            /**
             * @property token - The token associated with this webtask
             */
            this.token = token;
        }
        catch (_) {
            throw new Error('token must be a valid JWT');
        }
    }

    if (sandbox.securityVersion === 'v2') {
        if (typeof options.name !== 'string') {
            throw new Error('name must be a valid string');
        }

        this.claims = {
            jtn: options.name,
            ten: options.container || sandbox.container,
        }
    }

    /**
     * @property sandbox - The {@see Sandbox} instance used to create this Webtask instance
     */
    this.sandbox = sandbox;

    /**
     * @property meta - The metadata associated with this webtask
     */
    this.meta = options.meta || {};

    /**
     * @property secrets - The secrets associated with this webtask if `decrypt=true`
     */
    this.secrets = options.secrets;

    /**
     * @property code - The code associated with this webtask if `fetch_code=true`
     */
    this.code = options.code;

    /**
     * @property container - The container name in which the webtask will run
     */
    Object.defineProperty(this, 'container', {
        enumerable: true,
        get: function () {
            return options.container || this.sandbox.container;
        }
    });

    /**
     * @property url - The public url that can be used to invoke this webtask
     */
    Object.defineProperty(this, 'url', {
        enumerable: true,
        get: function () {
            var url = options.webtask_url;
            if (!url) {
                if (this.claims.host) {
                   var surl = Url.parse(this.sandbox.url);
                   url = surl.protocol + '//' + this.claims.host + (surl.port ? (':' + surl.port) : '') + '/' + this.sandbox.container;
                }
                else {
                   url = this.sandbox.url + '/api/run/' + this.sandbox.container;
                }

                if (this.claims.jtn) url += '/' + this.claims.jtn;
                else url += '?key=' + this.token;
            }

            return url;
        }
    });
}

Creates an object representing a Webtask

@constructor


function wrappedPromise(executor) {
    if (!(this instanceof wrappedPromise)) {
      return Promise(executor);
    }

    if (typeof executor !== 'function') {
      return new Promise(executor);
    }

    var context, args;
    var promise = new Promise(wrappedExecutor);
    promise.__proto__ = wrappedPromise.prototype;

    try {
      executor.apply(context, args);
    } catch (err) {
      args[1](err);
    }

    return promise;

    function wrappedExecutor(resolve, reject) {
      context = this;
      args = [wrappedResolve, wrappedReject];

      // These wrappers create a function that can be passed a function and an argument to
      // call as a continuation from the resolve or reject.
      function wrappedResolve(val) {
        ensureAslWrapper(promise, false);
        return resolve(val);
      }

      function wrappedReject(val) {
        ensureAslWrapper(promise, false);
        return reject(val);
      }
    }
  }

Updates to this class should also be applied to the the ES6 version in es6-wrapped-promise.js.

Updates to this class should also be applied to the the ES6 version in es6 - wrapped - promise . js .


function union(dest, added) {
  var destLength = dest.length;
  var addedLength = added.length;
  var returned = [];

  if (destLength === 0 && addedLength === 0) return returned;

  for (var j  = 0; j < destLength; j++) returned[j] = dest[j];

  if (addedLength === 0) return returned;

  for (var i = 0; i < addedLength; i++) {
    var missing = true;
    for (j = 0; j < destLength; j++) {
      if (dest[j].uid === added[i].uid) {
        missing = false;
        break;
      }
    }
    if (missing) returned.push(added[i]);
  }

  return returned;
}

function union ( dest , added ) { var destLength = dest . length ; var addedLength = added . length ; var returned = [ ] ; if ( destLength === 0 && addedLength === 0 ) return returned ; for ( var j = 0 ; j < destLength ; j ++ ) returned [ j ] = dest [ j ] ; if ( addedLength === 0 ) return returned ; for ( var i = 0 ; i < addedLength ; i ++ ) { var missing = true ; for ( j = 0 ; j < destLength ; j ++ ) { if ( dest [ j ] . uid === added [ i ] . uid ) { missing = false ; break ; } } if ( missing ) returned . push ( added [ i ] ) ; } return returned ; }

Simple helper function that's probably faster than using Array
filter methods and can be inlined.

Simple helper function that s probably faster than using Array filter methods and can be inlined .


function simpleWrap(original, list, length) {
  inAsyncTick = true;
  for (var i = 0; i < length; ++i) {
    var listener = list[i];
    if (listener.create) listener.create(listener.data);
  }
  inAsyncTick = false;

  // still need to make sure nested async calls are made in the context
  // of the listeners active at their creation
  return function () {
    listenerStack.push(listeners);
    listeners = union(list, listeners);

    var returned = original.apply(this, arguments);

    listeners = listenerStack.pop();

    return returned;
  };
}

for performance in the case where there are no handlers, just the listener

for performance in the case where there are no handlers just the listener


function wrapCallback(original) {
  var length = listeners.length;

  // no context to capture, so avoid closure creation
  if (length === 0) return original;

  // capture the active listeners as of when the wrapped function was called
  var list = listeners.slice();

  for (var i = 0; i < length; ++i) {
    if (list[i].flags > 0) return asyncWrap(original, list, length);
  }

  return simpleWrap(original, list, length);
}

Called each time an asynchronous function that's been monkeypatched in
index.js is called. If there are no listeners, return the function
unwrapped.  If there are any asyncListeners and any of them have callbacks,
pass them off to asyncWrap for later use, otherwise just call the listener.

Called each time an asynchronous function that s been monkeypatched in index . js is called . If there are no listeners return the function unwrapped . If there are any asyncListeners and any of them have callbacks pass them off to asyncWrap for later use otherwise just call the listener .


function (dir, options, internal) {

    // Parse arguments.
    options = options || largest.options;

    // Get all file stats in parallel.
    return fs.readdirAsync(dir)
    .then (function (files) {
        var paths = _.map(files, function (file) { return path.join(dir, file); });
        return Promise.all(_.map(paths, function (path) { return fs.statAsync(path); }))
        .then(function (stats) { return [paths, stats]; });
    })

    // Build up a list of possible candidates, recursing into subfolders if requested.
    .spread(function (paths, stats) {
        return Promise.all(
            _.map(stats, function (stat, i) {
                if (stat.isFile()) return Promise.resolve({ path: paths[i], size: stat.size, searched: 1 });
                return options.recurse ? largest(paths[i], options, true) : Promise.resolve(null);
            })
        );
    })

    // Choose the best candidate.
    .then(function (candidates) {
        return _(candidates)
        .compact()
        .reduce(function (best, cand) {
            if (cand.size > best.size) var temp = cand, cand = best, best = temp;
            best.searched += cand.searched;
            return best;
        });
    })

    // Add a preview if requested (but skip if this is an internal step in a recursive search).
    .then(function (result) {
        if (result && options.preview && !internal) {
            var fd_;
            return fs.openAsync(result.path, 'r')
            .then(function (fd) {
                fd_ = fd;
                var buffer = new Buffer(40);
                return fs.readAsync(fd, buffer, 0, 40, 0);
            })
            .spread(function (bytesRead, buffer) {
                result.preview = buffer.toString('utf-8', 0, bytesRead);
                return fs.closeAsync(fd_);
            })
            .then(function () {
                return result;
            });
        } else {
            return result; // Return without adding preview.
        }
    });
}

Finds the largest file in the given directory, optionally performing a recursive search.
@param {string} dir - the directory to search.
@param {object?} options - optional settings: { recurse?: boolean; preview?: boolean }.
@returns {object?} null if no files found, otherwise an object of the form
{ path: string; size: number; preview?: string, searched: number; }

Finds the largest file in the given directory optionally performing a recursive search .


function makeAsyncFunc(config) {
    // Validate the specified configuration
    config.validate();
    // Create an async function tailored to the given options.
    var result = function async(bodyFunc) {
        // Create a semaphore for limiting top-level concurrency, if specified in options.
        var semaphore = config.maxConcurrency ? new Semaphore(config.maxConcurrency) : Semaphore.unlimited;
        // Choose and run the appropriate function factory based on whether the result should be iterable.
        var makeFunc = config.isIterable ? makeAsyncIterator : makeAsyncNonIterator;
        var result = makeFunc(bodyFunc, config, semaphore);
        // Ensure the suspendable function's arity matches that of the function it wraps.
        var arity = bodyFunc.length;
        if (config.acceptsCallback)
            ++arity;
        result = makeFuncWithArity(result, arity);
        return result;
    };
    // Add the mod() function, and return the result.
    result.mod = makeModFunc(config);
    return result;
}

Function for creating a specific variant of the async function.

Function for creating a specific variant of the async function .


function makeAsyncIterator(bodyFunc, config, semaphore) {
    // Return a function that returns an iterator.
    return function iterable() {
        // Capture the initial arguments used to start the iterator, as an array.
        var startupArgs = new Array(arguments.length + 1); // Reserve 0th arg for the yield function.
        for (var i = 0, len = arguments.length; i < len; ++i)
            startupArgs[i + 1] = arguments[i];
        // Create a yield() function tailored for this iterator.
        var yield_ = function (expr) {
            // Ensure this function is executing inside a fiber.
            if (!Fiber.current) {
                throw new Error('await functions, yield functions, and value-returning suspendable ' +
                    'functions may only be called from inside a suspendable function. ');
            }
            // Notify waiters of the next result, then suspend the iterator.
            if (runContext.callback)
                runContext.callback(null, { value: expr, done: false });
            if (runContext.resolver)
                runContext.resolver.resolve({ value: expr, done: false });
            Fiber.yield();
        };
        // Insert the yield function as the first argument when starting the iterator.
        startupArgs[0] = yield_;
        // Create the iterator.
        var runContext = new RunContext(bodyFunc, this, startupArgs);
        var iterator = new AsyncIterator(runContext, semaphore, config.returnValue, config.acceptsCallback);
        // Wrap the given bodyFunc to properly complete the iteration.
        runContext.wrapped = function () {
            var len = arguments.length, args = new Array(len);
            for (var i = 0; i < len; ++i)
                args[i] = arguments[i];
            bodyFunc.apply(this, args);
            iterator.destroy();
            return { done: true };
        };
        // Return the iterator.
        return iterator;
    };
}

Function for creating iterable suspendable functions.

Function for creating iterable suspendable functions .


function makeAsyncNonIterator(bodyFunc, config, semaphore) {
    // Return a function that executes fn in a fiber and returns a promise of fn's result.
    return function nonIterable() {
        // Get all the arguments passed in, as an array.
        var argsAsArray = new Array(arguments.length);
        for (var i = 0; i < argsAsArray.length; ++i)
            argsAsArray[i] = arguments[i];
        // Remove concurrency restrictions for nested calls, to avoid race conditions.
        if (FiberMgr.isExecutingInFiber())
            this._semaphore = Semaphore.unlimited;
        // Configure the run context.
        var runContext = new RunContext(bodyFunc, this, argsAsArray, function () { return semaphore.leave(); });
        if (config.returnValue !== Config.NONE) {
            var resolver = defer();
            runContext.resolver = resolver;
        }
        if (config.acceptsCallback && argsAsArray.length && _.isFunction(argsAsArray[argsAsArray.length - 1])) {
            var callback = argsAsArray.pop();
            runContext.callback = callback;
        }
        // Execute bodyFunc to completion in a coroutine. For thunks, this is a lazy operation.
        if (config.returnValue === Config.THUNK) {
            var thunk = function (done) {
                if (done)
                    resolver.promise.then(function (val) { return done(null, val); }, function (err) { return done(err); });
                semaphore.enter(function () { return FiberMgr.create().run(runContext); });
            };
        }
        else {
            semaphore.enter(function () { return FiberMgr.create().run(runContext); });
        }
        // Return the appropriate value.
        switch (config.returnValue) {
            case Config.PROMISE: return resolver.promise;
            case Config.THUNK: return thunk;
            case Config.RESULT: return await(resolver.promise);
            case Config.NONE: return;
        }
    };
}

Function for creating non-iterable suspendable functions.

Function for creating non - iterable suspendable functions .


function traverseClone(o, visitor) {
    var result;
    if (_.isArray(o)) {
        var len = o.length;
        result = new Array(len);
        for (var i = 0; i < len; ++i) {
            result[i] = traverseClone(o[i], visitor);
            visitor(result, i);
        }
    }
    else if (_.isPlainObject(o)) {
        result = {};
        for (var key in o) {
            if (o.hasOwnProperty(key)) {
                result[key] = traverseClone(o[key], visitor);
                visitor(result, key);
            }
        }
    }
    else {
        result = o;
    }
    return result;
}

function traverseClone ( o , visitor ) { var result ; if ( _ . isArray ( o ) ) { var len = o . length ; result = new Array ( len ) ; for ( var i = 0 ; i < len ; ++ i ) { result [ i ] = traverseClone ( o [ i ] , visitor ) ; visitor ( result , i ) ; } } else if ( _ . isPlainObject ( o ) ) { result = { } ; for ( var key in o ) { if ( o . hasOwnProperty ( key ) ) { result [ key ] = traverseClone ( o [ key ] , visitor ) ; visitor ( result , key ) ; } } } else { result = o ; } return result ; }


function thunkToPromise(thunk) {
    return new Promise(function (resolve, reject) {
        var callback = function (err, val) { return (err ? reject(err) : resolve(val)); };
        thunk(callback);
    });
}

function thunkToPromise ( thunk ) { return new Promise ( function ( resolve , reject ) { var callback = function ( err , val ) { return ( err ? reject ( err ) : resolve ( val ) ) ; } ; thunk ( callback ) ; } ) ; }


function (dir) {
    var files = fs.readdirSync(dir);

    // Get all file stats in parallel.
    var paths = _.map(files, function (file) { return path.join(dir, file); });
    var stats = _.map(paths, function (path) { return fs.statSync(path); });

    // Count the files.
    return _.filter(stats, function (stat) { return stat.isFile(); }).length;
}

function
(
dir
)
{
var
files
=
fs
.
readdirSync
(
dir
)
;
// Get all file stats in parallel.
var
paths
=
_
.
map
(
files
,
function
(
file
)
{
return
path
.
join
(
dir
,
file
)
;
}
)
;
var
stats
=
_
.
map
(
paths
,
function
(
path
)
{
return
fs
.
statSync
(
path
)
;
}
)
;
// Count the files.
return
_
.
filter
(
stats
,
function
(
stat
)
{
return
stat
.
isFile
(
)
;
}
)
.
length
;
}

Returns the number of files in the given directory.

Returns the number of files in the given directory .


async function scopedCopyIndex(client, sourceIndex, targetIndex) {
  const { taskID } = await client.copyIndex(
    sourceIndex.indexName,
    targetIndex.indexName,
    ['settings', 'synonyms', 'rules']
  );
  return targetIndex.waitTask(taskID);
}

async function scopedCopyIndex ( client , sourceIndex , targetIndex ) { const { taskID } = await client . copyIndex ( sourceIndex . indexName , targetIndex . indexName , [ 'settings' , 'synonyms' , 'rules' ] ) ; return targetIndex . waitTask ( taskID ) ; }

Copy the settings, synonyms, and rules of the source index to the target index
@param client
@param sourceIndex
@param targetIndex
@return {Promise}

Copy the settings synonyms and rules of the source index to the target index


async function moveIndex(client, sourceIndex, targetIndex) {
  const { taskID } = await client.moveIndex(
    sourceIndex.indexName,
    targetIndex.indexName
  );
  return targetIndex.waitTask(taskID);
}

async function moveIndex ( client , sourceIndex , targetIndex ) { const { taskID } = await client . moveIndex ( sourceIndex . indexName , targetIndex . indexName ) ; return targetIndex . waitTask ( taskID ) ; }

moves the source index to the target index
@param client
@param sourceIndex
@param targetIndex
@return {Promise}


async function indexExists(index) {
  try {
    const { nbHits } = await index.search();
    return nbHits > 0;
  } catch (e) {
    return false;
  }
}

async function indexExists ( index ) { try { const { nbHits } = await index . search ( ) ; return nbHits > 0 ; } catch ( e ) { return false ; } }

Does an Algolia index exist already

@param index


function loadModule(moduleName) {
  var module = modules[moduleName];

  if (module !== undefined) {
    return module;
  }

  // This uses a switch for static require analysis
  switch (moduleName) {
    case 'charset':
      module = require('./lib/charset');
      break;
    case 'encoding':
      module = require('./lib/encoding');
      break;
    case 'language':
      module = require('./lib/language');
      break;
    case 'mediaType':
      module = require('./lib/mediaType');
      break;
    default:
      throw new Error('Cannot find module \'' + moduleName + '\'');
  }

  // Store to prevent invoking require()
  modules[moduleName] = module;

  return module;
}


function parseAcceptLanguage(accept) {
  var accepts = accept.split(',');

  for (var i = 0, j = 0; i < accepts.length; i++) {
    var language = parseLanguage(accepts[i].trim(), i);

    if (language) {
      accepts[j++] = language;
    }
  }

  // trim accepts
  accepts.length = j;

  return accepts;
}

function
parseAcceptLanguage
(
accept
)
{
var
accepts
=
accept
.
split
(
','
)
;
for
(
var
i
=
0
,
j
=
0
;
i
<
accepts
.
length
;
i
++
)
{
var
language
=
parseLanguage
(
accepts
[
i
]
.
trim
(
)
,
i
)
;
if
(
language
)
{
accepts
[
j
++
]
=
language
;
}
}
// trim accepts
accepts
.
length
=
j
;
return
accepts
;
}

Parse the Accept-Language header.
@private


function parseLanguage(str, i) {
  var match = simpleLanguageRegExp.exec(str);
  if (!match) return null;

  var prefix = match[1],
    suffix = match[2],
    full = prefix;

  if (suffix) full += "-" + suffix;

  var q = 1;
  if (match[3]) {
    var params = match[3].split(';')
    for (var j = 0; j < params.length; j++) {
      var p = params[j].split('=');
      if (p[0] === 'q') q = parseFloat(p[1]);
    }
  }

  return {
    prefix: prefix,
    suffix: suffix,
    q: q,
    i: i,
    full: full
  };
}

function parseLanguage ( str , i ) { var match = simpleLanguageRegExp . exec ( str ) ; if ( ! match ) return null ; var prefix = match [ 1 ] , suffix = match [ 2 ] , full = prefix ; if ( suffix ) full += "-" + suffix ; var q = 1 ; if ( match [ 3 ] ) { var params = match [ 3 ] . split ( ';' ) for ( var j = 0 ; j < params . length ; j ++ ) { var p = params [ j ] . split ( '=' ) ; if ( p [ 0 ] === 'q' ) q = parseFloat ( p [ 1 ] ) ; } } return { prefix : prefix , suffix : suffix , q : q , i : i , full : full } ; }

Parse a language from the Accept-Language header.
@private

Parse a language from the Accept - Language header .


function getLanguagePriority(language, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};

  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(language, accepted[i], index);

    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }

  return priority;
}

function getLanguagePriority ( language , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( language , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }

Get the priority of a language.
@private


function specify(language, spec, index) {
  var p = parseLanguage(language)
  if (!p) return null;
  var s = 0;
  if(spec.full.toLowerCase() === p.full.toLowerCase()){
    s |= 4;
  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
    s |= 2;
  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
    s |= 1;
  } else if (spec.full !== '*' ) {
    return null
  }

  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s
  }
}

function specify ( language , spec , index ) { var p = parseLanguage ( language ) if ( ! p ) return null ; var s = 0 ; if ( spec . full . toLowerCase ( ) === p . full . toLowerCase ( ) ) { s |= 4 ; } else if ( spec . prefix . toLowerCase ( ) === p . full . toLowerCase ( ) ) { s |= 2 ; } else if ( spec . full . toLowerCase ( ) === p . prefix . toLowerCase ( ) ) { s |= 1 ; } else if ( spec . full !== '*' ) { return null } return { i : index , o : spec . i , q : spec . q , s : s } }

Get the specificity of the language.
@private


function preferredLanguages(accept, provided) {
  // RFC 2616 sec 14.4: no header = *
  var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');

  if (!provided) {
    // sorted list of all languages
    return accepts
      .filter(isQuality)
      .sort(compareSpecs)
      .map(getFullLanguage);
  }

  var priorities = provided.map(function getPriority(type, index) {
    return getLanguagePriority(type, accepts, index);
  });

  // sorted list of accepted languages
  return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
    return provided[priorities.indexOf(priority)];
  });
}

function
preferredLanguages
(
accept
,
provided
)
{
// RFC 2616 sec 14.4: no header = *
var
accepts
=
parseAcceptLanguage
(
accept
===
undefined
'*'
:
accept
||
''
)
;
if
(
!
provided
)
{
// sorted list of all languages
return
accepts
.
filter
(
isQuality
)
.
sort
(
compareSpecs
)
.
map
(
getFullLanguage
)
;
}
var
priorities
=
provided
.
map
(
function
getPriority
(
type
,
index
)
{
return
getLanguagePriority
(
type
,
accepts
,
index
)
;
}
)
;
// sorted list of accepted languages
return
priorities
.
filter
(
isQuality
)
.
sort
(
compareSpecs
)
.
map
(
function
getLanguage
(
priority
)
{
return
provided
[
priorities
.
indexOf
(
priority
)
]
;
}
)
;
}

Get the preferred languages from an Accept-Language header.
@public

Get the preferred languages from an Accept - Language header .


function compareSpecs(a, b) {
  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
}

function compareSpecs ( a , b ) { return ( b . q - a . q ) || ( b . s - a . s ) || ( a . o - b . o ) || ( a . i - b . i ) || 0 ; }


function parseAcceptCharset(accept) {
  var accepts = accept.split(',');

  for (var i = 0, j = 0; i < accepts.length; i++) {
    var charset = parseCharset(accepts[i].trim(), i);

    if (charset) {
      accepts[j++] = charset;
    }
  }

  // trim accepts
  accepts.length = j;

  return accepts;
}

function
parseAcceptCharset
(
accept
)
{
var
accepts
=
accept
.
split
(
','
)
;
for
(
var
i
=
0
,
j
=
0
;
i
<
accepts
.
length
;
i
++
)
{
var
charset
=
parseCharset
(
accepts
[
i
]
.
trim
(
)
,
i
)
;
if
(
charset
)
{
accepts
[
j
++
]
=
charset
;
}
}
// trim accepts
accepts
.
length
=
j
;
return
accepts
;
}

Parse the Accept-Charset header.
@private


function parseCharset(str, i) {
  var match = simpleCharsetRegExp.exec(str);
  if (!match) return null;

  var charset = match[1];
  var q = 1;
  if (match[2]) {
    var params = match[2].split(';')
    for (var j = 0; j < params.length; j++) {
      var p = params[j].trim().split('=');
      if (p[0] === 'q') {
        q = parseFloat(p[1]);
        break;
      }
    }
  }

  return {
    charset: charset,
    q: q,
    i: i
  };
}

function parseCharset ( str , i ) { var match = simpleCharsetRegExp . exec ( str ) ; if ( ! match ) return null ; var charset = match [ 1 ] ; var q = 1 ; if ( match [ 2 ] ) { var params = match [ 2 ] . split ( ';' ) for ( var j = 0 ; j < params . length ; j ++ ) { var p = params [ j ] . trim ( ) . split ( '=' ) ; if ( p [ 0 ] === 'q' ) { q = parseFloat ( p [ 1 ] ) ; break ; } } } return { charset : charset , q : q , i : i } ; }

Parse a charset from the Accept-Charset header.
@private

Parse a charset from the Accept - Charset header .


function getCharsetPriority(charset, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};

  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(charset, accepted[i], index);

    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }

  return priority;
}

function getCharsetPriority ( charset , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( charset , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }


function specify(charset, spec, index) {
  var s = 0;
  if(spec.charset.toLowerCase() === charset.toLowerCase()){
    s |= 1;
  } else if (spec.charset !== '*' ) {
    return null
  }

  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s
  }
}

function specify ( charset , spec , index ) { var s = 0 ; if ( spec . charset . toLowerCase ( ) === charset . toLowerCase ( ) ) { s |= 1 ; } else if ( spec . charset !== '*' ) { return null } return { i : index , o : spec . i , q : spec . q , s : s } }

Get the specificity of the charset.
@private


function preferredCharsets(accept, provided) {
  // RFC 2616 sec 14.2: no header = *
  var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');

  if (!provided) {
    // sorted list of all charsets
    return accepts
      .filter(isQuality)
      .sort(compareSpecs)
      .map(getFullCharset);
  }

  var priorities = provided.map(function getPriority(type, index) {
    return getCharsetPriority(type, accepts, index);
  });

  // sorted list of accepted charsets
  return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
    return provided[priorities.indexOf(priority)];
  });
}

function
preferredCharsets
(
accept
,
provided
)
{
// RFC 2616 sec 14.2: no header = *
var
accepts
=
parseAcceptCharset
(
accept
===
undefined
'*'
:
accept
||
''
)
;
if
(
!
provided
)
{
// sorted list of all charsets
return
accepts
.
filter
(
isQuality
)
.
sort
(
compareSpecs
)
.
map
(
getFullCharset
)
;
}
var
priorities
=
provided
.
map
(
function
getPriority
(
type
,
index
)
{
return
getCharsetPriority
(
type
,
accepts
,
index
)
;
}
)
;
// sorted list of accepted charsets
return
priorities
.
filter
(
isQuality
)
.
sort
(
compareSpecs
)
.
map
(
function
getCharset
(
priority
)
{
return
provided
[
priorities
.
indexOf
(
priority
)
]
;
}
)
;
}

Get the preferred charsets from an Accept-Charset header.
@public

Get the preferred charsets from an Accept - Charset header .


function parseEncoding(str, i) {
  var match = simpleEncodingRegExp.exec(str);
  if (!match) return null;

  var encoding = match[1];
  var q = 1;
  if (match[2]) {
    var params = match[2].split(';');
    for (var j = 0; j < params.length; j++) {
      var p = params[j].trim().split('=');
      if (p[0] === 'q') {
        q = parseFloat(p[1]);
        break;
      }
    }
  }

  return {
    encoding: encoding,
    q: q,
    i: i
  };
}

function parseEncoding ( str , i ) { var match = simpleEncodingRegExp . exec ( str ) ; if ( ! match ) return null ; var encoding = match [ 1 ] ; var q = 1 ; if ( match [ 2 ] ) { var params = match [ 2 ] . split ( ';' ) ; for ( var j = 0 ; j < params . length ; j ++ ) { var p = params [ j ] . trim ( ) . split ( '=' ) ; if ( p [ 0 ] === 'q' ) { q = parseFloat ( p [ 1 ] ) ; break ; } } } return { encoding : encoding , q : q , i : i } ; }

Parse an encoding from the Accept-Encoding header.
@private

Parse an encoding from the Accept - Encoding header .


function getEncodingPriority(encoding, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};

  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(encoding, accepted[i], index);

    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }

  return priority;
}

function getEncodingPriority ( encoding , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( encoding , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }

Get the priority of an encoding.
@private


function preferredEncodings(accept, provided) {
  var accepts = parseAcceptEncoding(accept || '');

  if (!provided) {
    // sorted list of all encodings
    return accepts
      .filter(isQuality)
      .sort(compareSpecs)
      .map(getFullEncoding);
  }

  var priorities = provided.map(function getPriority(type, index) {
    return getEncodingPriority(type, accepts, index);
  });

  // sorted list of accepted encodings
  return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) {
    return provided[priorities.indexOf(priority)];
  });
}

function
preferredEncodings
(
accept
,
provided
)
{
var
accepts
=
parseAcceptEncoding
(
accept
||
''
)
;
if
(
!
provided
)
{
// sorted list of all encodings
return
accepts
.
filter
(
isQuality
)
.
sort
(
compareSpecs
)
.
map
(
getFullEncoding
)
;
}
var
priorities
=
provided
.
map
(
function
getPriority
(
type
,
index
)
{
return
getEncodingPriority
(
type
,
accepts
,
index
)
;
}
)
;
// sorted list of accepted encodings
return
priorities
.
filter
(
isQuality
)
.
sort
(
compareSpecs
)
.
map
(
function
getEncoding
(
priority
)
{
return
provided
[
priorities
.
indexOf
(
priority
)
]
;
}
)
;
}

Get the preferred encodings from an Accept-Encoding header.
@public

Get the preferred encodings from an Accept - Encoding header .


function parseAccept(accept) {
  var accepts = splitMediaTypes(accept);

  for (var i = 0, j = 0; i < accepts.length; i++) {
    var mediaType = parseMediaType(accepts[i].trim(), i);

    if (mediaType) {
      accepts[j++] = mediaType;
    }
  }

  // trim accepts
  accepts.length = j;

  return accepts;
}

function
parseAccept
(
accept
)
{
var
accepts
=
splitMediaTypes
(
accept
)
;
for
(
var
i
=
0
,
j
=
0
;
i
<
accepts
.
length
;
i
++
)
{
var
mediaType
=
parseMediaType
(
accepts
[
i
]
.
trim
(
)
,
i
)
;
if
(
mediaType
)
{
accepts
[
j
++
]
=
mediaType
;
}
}
// trim accepts
accepts
.
length
=
j
;
return
accepts
;
}


function parseMediaType(str, i) {
  var match = simpleMediaTypeRegExp.exec(str);
  if (!match) return null;

  var params = Object.create(null);
  var q = 1;
  var subtype = match[2];
  var type = match[1];

  if (match[3]) {
    var kvps = splitParameters(match[3]).map(splitKeyValuePair);

    for (var j = 0; j < kvps.length; j++) {
      var pair = kvps[j];
      var key = pair[0].toLowerCase();
      var val = pair[1];

      // get the value, unwrapping quotes
      var value = val && val[0] === '"' && val[val.length - 1] === '"'
        ? val.substr(1, val.length - 2)
        : val;

      if (key === 'q') {
        q = parseFloat(value);
        break;
      }

      // store parameter
      params[key] = value;
    }
  }

  return {
    type: type,
    subtype: subtype,
    params: params,
    q: q,
    i: i
  };
}

function
parseMediaType
(
str
,
i
)
{
var
match
=
simpleMediaTypeRegExp
.
exec
(
str
)
;
if
(
!
match
)
return
;
var
params
=
Object
.
create
(
)
;
var
q
=
1
;
var
subtype
=
match
[
2
]
;
var
type
=
match
[
1
]
;
if
(
match
[
3
]
)
{
var
kvps
=
splitParameters
(
match
[
3
]
)
.
map
(
splitKeyValuePair
)
;
for
(
var
j
=
0
;
j
<
kvps
.
length
;
j
++
)
{
var
pair
=
kvps
[
j
]
;
var
key
=
pair
[
0
]
.
toLowerCase
(
)
;
var
val
=
pair
[
1
]
;
// get the value, unwrapping quotes
var
value
=
val
&&
val
[
0
]
===
'"'
&&
val
[
val
.
length
1
]
===
'"'
val
.
substr
(
1
,
val
.
length
2
)
:
val
;
if
(
key
===
'q'
)
{
q
=
parseFloat
(
value
)
;
break
;
}
// store parameter
params
[
key
]
=
value
;
}
}
return
{
type
:
type
,
subtype
:
subtype
,
params
:
params
,
q
:
q
,
i
:
i
}
;
}

Parse a media type from the Accept header.
@private

Parse a media type from the Accept header .


function getMediaTypePriority(type, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};

  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(type, accepted[i], index);

    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }

  return priority;
}

function getMediaTypePriority ( type , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( type , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }

Get the priority of a media type.
@private


function specify(type, spec, index) {
  var p = parseMediaType(type);
  var s = 0;

  if (!p) {
    return null;
  }

  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
    s |= 4
  } else if(spec.type != '*') {
    return null;
  }

  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
    s |= 2
  } else if(spec.subtype != '*') {
    return null;
  }

  var keys = Object.keys(spec.params);
  if (keys.length > 0) {
    if (keys.every(function (k) {
      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
    })) {
      s |= 1
    } else {
      return null
    }
  }

  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s,
  }
}

function specify ( type , spec , index ) { var p = parseMediaType ( type ) ; var s = 0 ; if ( ! p ) { return null ; } if ( spec . type . toLowerCase ( ) == p . type . toLowerCase ( ) ) { s |= 4 } else if ( spec . type != '*' ) { return null ; } if ( spec . subtype . toLowerCase ( ) == p . subtype . toLowerCase ( ) ) { s |= 2 } else if ( spec . subtype != '*' ) { return null ; } var keys = Object . keys ( spec . params ) ; if ( keys . length > 0 ) { if ( keys . every ( function ( k ) { return spec . params [ k ] == '*' || ( spec . params [ k ] || '' ) . toLowerCase ( ) == ( p . params [ k ] || '' ) . toLowerCase ( ) ; } ) ) { s |= 1 } else { return null } } return { i : index , o : spec . i , q : spec . q , s : s , } }

Get the specificity of the media type.
@private