function genBlockMethod(members, name) {
    var res = {
        name: name,
        description: '',
        params: [],
        returns: [],
        deprecated: false,
        final: false
    };
    members.filter({
        kind: 'function',
        name: name
    }).each(function(doclet) {
        if (doclet.description) {
            res.description += doclet.description + '\n';
        }

        if (!res.access) {
            res.access = doclet.access;
        }

        if (!res.scope) {
            res.scope = doclet.scope;
        }

        if (res.returns.length === 0) {
            res.returns = genMethodReturns(doclet.returns);
        }

        if (res.params.length === 0) {
            res.params  = genMethodParams(doclet.params);
        }

        if (doclet.deprecated) {
            res.deprecated = doclet.deprecated;
        }

        if (doclet.final) {
            res.final = doclet.final;
        }
    });

    res.scope = res.scope || 'instance';
    res.access = res.access || 'public';

    return res;
}

function genBlockMethod ( members , name ) { var res = { name : name , description : '' , params : [ ] , returns : [ ] , deprecated : false , final : false } ; members . filter ( { kind : 'function' , name : name } ) . each ( function ( doclet ) { if ( doclet . description ) { res . description += doclet . description + '\n' ; } if ( ! res . access ) { res . access = doclet . access ; } if ( ! res . scope ) { res . scope = doclet . scope ; } if ( res . returns . length === 0 ) { res . returns = genMethodReturns ( doclet . returns ) ; } if ( res . params . length === 0 ) { res . params = genMethodParams ( doclet . params ) ; } if ( doclet . deprecated ) { res . deprecated = doclet . deprecated ; } if ( doclet . final ) { res . final = doclet . final ; } } ) ; res . scope = res . scope || 'instance' ; res . access = res . access || 'public' ; return res ; }

Generates docs for a method.

Descriptions got merged from all levels. Other params
will not be merged and first non-empty value will be used


function genParam(param) {
    var res = {
        name: param.name || '',
        description: param.description || '',
        optional: !!param.optional
    };
    if (param.type) {
        res.types = param.type.names.slice(0);
    }

    if (param.defaultvalue) {
        res['default'] = param.defaultvalue;
    }
    return res;
}

function genParam ( param ) { var res = { name : param . name || '' , description : param . description || '' , optional : ! ! param . optional } ; if ( param . type ) { res . types = param . type . names . slice ( 0 ) ; } if ( param . defaultvalue ) { res [ 'default' ] = param . defaultvalue ; } return res ; }

Generates doc for method or event parameter


function genProperty(members, name) {
    var res = {
        name: name,
        deprecated: false,
        description: '',
        types: []
    };

    members.filter({
        kind: 'member',
        name: name
    }).each(function(doclet) {
        if (doclet.description) {
            res.description += doclet.description + '\n';
        }

        if (!res.access) {
            res.access = doclet.access;
        }

        if (!res.scope) {
            res.scope = doclet.scope;
        }

        if (doclet.deprected) {
            res.deprecated = true;
        }
        if (res.types.length === 0 && doclet.type) {
            res.types = doclet.type.names.slice(0);
        }
    });

    res.scope = res.scope || 'instance';
    res.access = res.acccess || 'public';

    return res;
}

function genProperty ( members , name ) { var res = { name : name , deprecated : false , description : '' , types : [ ] } ; members . filter ( { kind : 'member' , name : name } ) . each ( function ( doclet ) { if ( doclet . description ) { res . description += doclet . description + '\n' ; } if ( ! res . access ) { res . access = doclet . access ; } if ( ! res . scope ) { res . scope = doclet . scope ; } if ( doclet . deprected ) { res . deprecated = true ; } if ( res . types . length === 0 && doclet . type ) { res . types = doclet . type . names . slice ( 0 ) ; } } ) ; res . scope = res . scope || 'instance' ; res . access = res . acccess || 'public' ; return res ; }

Generates docs for a property.

Descriptions got merged from all levels. Other params
will not be merged and first non-empty value will be used


function IfCommand(args, define) {
    if (util.endsWith(args.toLowerCase(), ' then')) args = args.slice(0, args.length - 5).trim();
    else throw new SyntaxError('IF has no THEN');

    var parsed = new statements.ArgumentStatement(args, {
        separator: false
    }, define);

    this.condition = parsed.args[0];
    this.block = define({
        start: 'IF',
        then: 'ELSE',
        end: ['ENDIF', 'RETURN']
    });
}

function
IfCommand
(
args
,
define
)
{
if
(
util
.
endsWith
(
args
.
toLowerCase
(
)
,
' then'
)
)
args
=
args
.
slice
(
0
,
args
.
length
5
)
.
trim
(
)
;
else
throw
new
SyntaxError
(
'IF has no THEN'
)
;
var
parsed
=
new
statements
.
ArgumentStatement
(
args
,
{
separator
:
false
}
,
define
)
;
this
.
condition
=
parsed
.
args
[
0
]
;
this
.
block
=
define
(
{
start
:
'IF'
,
then
:
'ELSE'
,
end
:
[
'ENDIF'
,
'RETURN'
]
}
)
;
}

Executes the body if the condition is true

@param {String} args The arguments to the command
@param {Function} define
@constructor


function logger(stream){
	return (...text) => {
		text.map(text => {
			console.log(text)
			stream.write(`${Date.now()} - ${JSON.stringify(text)}\n`)
		})
	}
}

function logger ( stream ) { return ( ... text ) => { text . map ( text => { console . log ( text ) stream . write ( ` ${ Date . now ( ) } ${ JSON . stringify ( text ) } \n ` ) } ) } }

Constructs the log function.
@param {writeStream} stream


function forward(receiver, provider, keys) {
  keys = keys || allKeys(provider);
  keys = Array.isArray(keys) ? keys : [keys];

  keys.forEach(function (key) {
    var val = provider[key];

    if (typeof val === 'function') {
      receiver[key] = function () {
        return provider[key].apply(provider, arguments);
      };
    } else {
      receiver[key] = val;
    }
  });
  return receiver;
}

function forward ( receiver , provider , keys ) { keys = keys || allKeys ( provider ) ; keys = Array . isArray ( keys ) ? keys : [ keys ] ; keys . forEach ( function ( key ) { var val = provider [ key ] ; if ( typeof val === 'function' ) { receiver [ key ] = function ( ) { return provider [ key ] . apply ( provider , arguments ) ; } ; } else { receiver [ key ] = val ; } } ) ; return receiver ; }

Copy properties from an object to another object,
where properties with function values will be
invoked in the context of the provider, and properties
with non-function values are just copied.

```js
var receiver = {};
var provider = {
name: 'provider',
upper: function (str) {
return '[' + this.name + '] ' + str.toUpperCase();
}
};
var receiver = forward(receiver, provider);
receiver.name = 'receiver';
console.log(receiver.upper('foo'));
//=> [provider] FOO
```

@param  {Object} `receiver` Object to receive properties.
@param  {Object} `provider` Object providing properties.
@param  {Array} `keys` Optional array of keys to foward.
@return {Object} Modified `receiver` object with properties from `provider`
@api public

Copy properties from an object to another object where properties with function values will be invoked in the context of the provider and properties with non - function values are just copied .


function RegexFinderStrategy(config) {
	config = config || {};

	FinderStrategy.call(this, config);
	this.config = extend(true, this.config, {}, config);
}

function RegexFinderStrategy ( config ) { config = config || { } ; FinderStrategy . call ( this , config ) ; this . config = extend ( true , this . config , { } , config ) ; }

This finder strategy tries to identify
inclusions in source code by using
regexes. This approach may be hackish
but works well in most situations. The
only limitations are connected to regexes
being mostly stateless. For example
it may not be a great idea to parse
HTML with regexes.

@description
In addition to the default configuration
this finder supports the following
configuration:

pattern: The regex pattern that will
be used to find inclusions in source
code. The included file should be
captured by the first capture group
of the regex.

@class RegexFinderStrategy
@extends FinderStrategy
@param {Object} config The configuration
of this finder strategy

This finder strategy tries to identify inclusions in source code by using regexes . This approach may be hackish but works well in most situations . The only limitations are connected to regexes being mostly stateless . For example it may not be a great idea to parse HTML with regexes .


function SyncFile(path, flags, mode) {
  flags = flags || 'w';
  this.fd = fs.openSync(path, flags, mode);
  this.crc = new Crc64();
  this.converter = new Converter();
}

function SyncFile ( path , flags , mode ) { flags = flags || 'w' ; this . fd = fs . openSync ( path , flags , mode ) ; this . crc = new Crc64 ( ) ; this . converter = new Converter ( ) ; }


function write(obj) {
  if(obj.type === 'crc') return this.end();
  var buffer = this.converter.entry(obj);
  this.crc.push(buffer);
  return this.writeBuffer(buffer);
}

function write ( obj ) { if ( obj . type === 'crc' ) return this . end ( ) ; var buffer = this . converter . entry ( obj ) ; this . crc . push ( buffer ) ; return this . writeBuffer ( buffer ) ; }

Write an object to the file synchronously.

Write an object to the file synchronously .


function writeBuffer(buffer) {
  var written = fs.writeSync(this.fd, buffer, 0, buffer.length, null);
  fs.fsyncSync(this.fd);
  return written;
}

function writeBuffer ( buffer ) { var written = fs . writeSync ( this . fd , buffer , 0 , buffer . length , null ) ; fs . fsyncSync ( this . fd ) ; return written ; }

Write a buffer synchronously to the file and flush to disk.

Write a buffer synchronously to the file and flush to disk .


function end() {
  this.writeBuffer(this.crc.value());
  fs.closeSync(this.fd);

  this.fd = null;
  this.crc = null;
  this.converter = null;
}

function end ( ) { this . writeBuffer ( this . crc . value ( ) ) ; fs . closeSync ( this . fd ) ; this . fd = null ; this . crc = null ; this . converter = null ; }


function AbstractSyntaxTree(root, labels, manager) {
    this.root = root;
    this.labels = labels;
    this.manager = manager;

    manager.parse(this);
}

function AbstractSyntaxTree ( root , labels , manager ) { this . root = root ; this . labels = labels ; this . manager = manager ; manager . parse ( this ) ; }

Represents a tree that can be executed

@param {Array} root The root-level nodes
@param {Object} labels An object of label: line mappings
@param {BlockManager} manager The block manager


function execute(ast, ctx, done) {
    if (!done && !(ctx instanceof ExecutionContext)) {
        done = ctx;
        ctx = new ExecutionContext();
    }

    ast.execute(ctx, done);
}

function execute ( ast , ctx , done ) { if ( ! done && ! ( ctx instanceof ExecutionContext ) ) { done = ctx ; ctx = new ExecutionContext ( ) ; } ast . execute ( ctx , done ) ; }

Executes the abstract syntax tree

@param {AbstractSyntaxTree} ast The tree to execute
@param {exports.ExecutionContext|ExecutionContext|Function?} ctx The context
@param {Function?} done Called when execution is complete


function MarkLogicStore(options) {
    options = options || {};
    var collectionName = options.collection || defaultOptions.collection;
    this.baseUri = options.baseUri || encodeURI(collectionName.replace(/\s/g,'-'));

    Store.call(this, options);

    this.collectionName = collectionName;
    this.ttl =  options.ttl || defaultOptions.ttl || 0;

    // retain the client that was passed in, or create a new client
    this.db = options.client || marklogic.createDatabaseClient(options);

  }

Initialize MarkLogicStore with the given `options`.

@param {Object} options
@api public

Initialize MarkLogicStore with the given options .


function _vendorsList(vendors, ignore = false) {
  let vendorsList = ''
  let sign = (ignore) ? '-' : '+'

  for (let vendor of vendors) {
    vendorsList += ` ${sign} ${vendor}`
  }

  return vendorsList
}

function _vendorsList ( vendors , ignore = false ) { let vendorsList = '' let sign = ( ignore ) ? '-' : '+' for ( let vendor of vendors ) { vendorsList += ` ${ sign } ${ vendor } ` } return vendorsList }

Make a string with jspm vendors.
@param {Array} vendors - List of dependencies used in jspm config
@param {boolean} ignore - Indicate what sign use in vendor list (- or +).
@returns {String} - jspm dependencies with sign - or + to use in arithmetic
param of jspm shell command.


function create (prototype, properties) {
  Ctor.prototype = prototype || {}
  return properties ? copy(new Ctor(), properties) : new Ctor()
}

function create ( prototype , properties ) { Ctor . prototype = prototype || { } return properties ? copy ( new Ctor ( ) , properties ) : new Ctor ( ) }

Portable Object.create that is not a shim and
drops the verbose property descriptor syntax.

@param {Object} prototype
The object which should be the prototype of the newly-created object.

@return {String}
New object with the specified prototype object.

Portable Object . create that is not a shim and drops the verbose property descriptor syntax .


function copy (target, source) {
  for (var key in Object(source)) target[key] = source[key]
  return target
}

function copy ( target , source ) { for ( var key in Object ( source ) ) target [ key ] = source [ key ] return target }

Copy properties from source to target.

@param {Object} target
Object to assign properties to.

@param {Object} source
Object to get properties from.

@return {Object}
New object.


function identity(iterable) {
    return __asyncGenerator(this, arguments, function* identity_1() {
        return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(iterable))));
    });
}

function identity ( iterable ) { return __asyncGenerator ( this , arguments , function * identity_1 ( ) { return yield __await ( yield __await ( yield * __asyncDelegator ( __asyncValues ( iterable ) ) ) ) ; } ) ; }


function scan(predicate, initial) {
    return function (iterable) {
        return __asyncGenerator(this, arguments, function* () {
            var e_7, _a;
            let index = 0;
            let prevState = initial;
            try {
                for (var iterable_5 = __asyncValues(iterable), iterable_5_1; iterable_5_1 = yield __await(iterable_5.next()), !iterable_5_1.done;) {
                    const value = iterable_5_1.value;
                    prevState = yield __await(Promise.resolve(predicate(prevState, value, index)));
                    yield yield __await(prevState);
                    index = index + 1;
                }
            }
            catch (e_7_1) { e_7 = { error: e_7_1 }; }
            finally {
                try {
                    if (iterable_5_1 && !iterable_5_1.done && (_a = iterable_5.return)) yield __await(_a.call(iterable_5));
                }
                finally { if (e_7) throw e_7.error; }
            }
            return yield __await(prevState);
        });
    };
}

function scan ( predicate , initial ) { return function ( iterable ) { return __asyncGenerator ( this , arguments , function * ( ) { var e_7 , _a ; let index = 0 ; let prevState = initial ; try { for ( var iterable_5 = __asyncValues ( iterable ) , iterable_5_1 ; iterable_5_1 = yield __await ( iterable_5 . next ( ) ) , ! iterable_5_1 . done ; ) { const value = iterable_5_1 . value ; prevState = yield __await ( Promise . resolve ( predicate ( prevState , value , index ) ) ) ; yield yield __await ( prevState ) ; index = index + 1 ; } } catch ( e_7_1 ) { e_7 = { error : e_7_1 } ; } finally { try { if ( iterable_5_1 && ! iterable_5_1 . done && ( _a = iterable_5 . return ) ) yield __await ( _a . call ( iterable_5 ) ) ; } finally { if ( e_7 ) throw e_7 . error ; } } return yield __await ( prevState ) ; } ) ; } ; }

Reduce the items in an iterable down to a single instance of initial type, yielding each step of the reduction

Reduce the items in an iterable down to a single instance of initial type yielding each step of the reduction


async function first(iterable) {
    var e_13, _a;
    try {
        for (var iterable_11 = __asyncValues(iterable), iterable_11_1; iterable_11_1 = await iterable_11.next(), !iterable_11_1.done;) {
            const item = iterable_11_1.value;
            return item;
        }
    }
    catch (e_13_1) { e_13 = { error: e_13_1 }; }
    finally {
        try {
            if (iterable_11_1 && !iterable_11_1.done && (_a = iterable_11.return)) await _a.call(iterable_11);
        }
        finally { if (e_13) throw e_13.error; }
    }
    return undefined;
}

async function first ( iterable ) { var e_13 , _a ; try { for ( var iterable_11 = __asyncValues ( iterable ) , iterable_11_1 ; iterable_11_1 = await iterable_11 . next ( ) , ! iterable_11_1 . done ; ) { const item = iterable_11_1 . value ; return item ; } } catch ( e_13_1 ) { e_13 = { error : e_13_1 } ; } finally { try { if ( iterable_11_1 && ! iterable_11_1 . done && ( _a = iterable_11 . return ) ) await _a . call ( iterable_11 ) ; } finally { if ( e_13 ) throw e_13 . error ; } } return undefined ; }

Take only the first item in an iterable sequence


function skipUntil(predicate) {
    return function (iterable) {
        return __asyncGenerator(this, arguments, function* () {
            var e_18, _a;
            let i = 0;
            let canReturn = false;
            try {
                for (var iterable_16 = __asyncValues(iterable), iterable_16_1; iterable_16_1 = yield __await(iterable_16.next()), !iterable_16_1.done;) {
                    const item = iterable_16_1.value;
                    if (!canReturn) {
                        canReturn = yield __await(predicate(item, i));
                        if (canReturn) {
                            yield yield __await(item);
                        }
                        i = i + 1;
                    }
                    else {
                        yield yield __await(item);
                    }
                }
            }
            catch (e_18_1) { e_18 = { error: e_18_1 }; }
            finally {
                try {
                    if (iterable_16_1 && !iterable_16_1.done && (_a = iterable_16.return)) yield __await(_a.call(iterable_16));
                }
                finally { if (e_18) throw e_18.error; }
            }
        });
    };
}

function skipUntil ( predicate ) { return function ( iterable ) { return __asyncGenerator ( this , arguments , function * ( ) { var e_18 , _a ; let i = 0 ; let canReturn = false ; try { for ( var iterable_16 = __asyncValues ( iterable ) , iterable_16_1 ; iterable_16_1 = yield __await ( iterable_16 . next ( ) ) , ! iterable_16_1 . done ; ) { const item = iterable_16_1 . value ; if ( ! canReturn ) { canReturn = yield __await ( predicate ( item , i ) ) ; if ( canReturn ) { yield yield __await ( item ) ; } i = i + 1 ; } else { yield yield __await ( item ) ; } } } catch ( e_18_1 ) { e_18 = { error : e_18_1 } ; } finally { try { if ( iterable_16_1 && ! iterable_16_1 . done && ( _a = iterable_16 . return ) ) yield __await ( _a . call ( iterable_16 ) ) ; } finally { if ( e_18 ) throw e_18 . error ; } } } ) ; } ; }

Skip items in an iterable until the passed predicate matches, then yield all items in the iterable

Skip items in an iterable until the passed predicate matches then yield all items in the iterable


function concat(...iterables) {
    return function (it) {
        return __asyncGenerator(this, arguments, function* () {
            var e_20, _a;
            yield __await(yield* __asyncDelegator(__asyncValues(it)));
            try {
                for (var iterables_1 = __asyncValues(iterables), iterables_1_1; iterables_1_1 = yield __await(iterables_1.next()), !iterables_1_1.done;) {
                    const iterable = iterables_1_1.value;
                    yield __await(yield* __asyncDelegator(__asyncValues(iterable)));
                }
            }
            catch (e_20_1) { e_20 = { error: e_20_1 }; }
            finally {
                try {
                    if (iterables_1_1 && !iterables_1_1.done && (_a = iterables_1.return)) yield __await(_a.call(iterables_1));
                }
                finally { if (e_20) throw e_20.error; }
            }
        });
    };
}

function concat ( ... iterables ) { return function ( it ) { return __asyncGenerator ( this , arguments , function * ( ) { var e_20 , _a ; yield __await ( yield * __asyncDelegator ( __asyncValues ( it ) ) ) ; try { for ( var iterables_1 = __asyncValues ( iterables ) , iterables_1_1 ; iterables_1_1 = yield __await ( iterables_1 . next ( ) ) , ! iterables_1_1 . done ; ) { const iterable = iterables_1_1 . value ; yield __await ( yield * __asyncDelegator ( __asyncValues ( iterable ) ) ) ; } } catch ( e_20_1 ) { e_20 = { error : e_20_1 } ; } finally { try { if ( iterables_1_1 && ! iterables_1_1 . done && ( _a = iterables_1 . return ) ) yield __await ( _a . call ( iterables_1 ) ) ; } finally { if ( e_20 ) throw e_20 . error ; } } } ) ; } ; }

Yields the passed iterables at the end of the current iterable


function distinct(it) {
    return __asyncGenerator(this, arguments, function* distinct_1() {
        var e_24, _a;
        const resultSet = new Set();
        try {
            for (var it_5 = __asyncValues(it), it_5_1; it_5_1 = yield __await(it_5.next()), !it_5_1.done;) {
                const item = it_5_1.value;
                if (!resultSet.has(item)) {
                    resultSet.add(item);
                    yield yield __await(item);
                }
            }
        }
        catch (e_24_1) { e_24 = { error: e_24_1 }; }
        finally {
            try {
                if (it_5_1 && !it_5_1.done && (_a = it_5.return)) yield __await(_a.call(it_5));
            }
            finally { if (e_24) throw e_24.error; }
        }
    });
}

function distinct ( it ) { return __asyncGenerator ( this , arguments , function * distinct_1 ( ) { var e_24 , _a ; const resultSet = new Set ( ) ; try { for ( var it_5 = __asyncValues ( it ) , it_5_1 ; it_5_1 = yield __await ( it_5 . next ( ) ) , ! it_5_1 . done ; ) { const item = it_5_1 . value ; if ( ! resultSet . has ( item ) ) { resultSet . add ( item ) ; yield yield __await ( item ) ; } } } catch ( e_24_1 ) { e_24 = { error : e_24_1 } ; } finally { try { if ( it_5_1 && ! it_5_1 . done && ( _a = it_5 . return ) ) yield __await ( _a . call ( it_5 ) ) ; } finally { if ( e_24 ) throw e_24 . error ; } } } ) ; }


function orderBy(keySelector, comparison) {
    const trueKeySelector = keySelector || defaultKeySelector;
    const trueComparison = comparison || defaultComparison;
    return function (item) {
        return __asyncGenerator(this, arguments, function* () {
            var e_25, _a;
            const keyedMapper = map((item, index) => ({ item, key: trueKeySelector(item, index) }));
            const keyed = keyedMapper(item);
            const keyedArray = yield __await(toWriteableArray(keyed));
            keyedArray.sort((a, b) => trueComparison(a.key, b.key));
            try {
                for (var keyedArray_1 = __asyncValues(keyedArray), keyedArray_1_1; keyedArray_1_1 = yield __await(keyedArray_1.next()), !keyedArray_1_1.done;) {
                    const { item } = keyedArray_1_1.value;
                    yield yield __await(item);
                }
            }
            catch (e_25_1) { e_25 = { error: e_25_1 }; }
            finally {
                try {
                    if (keyedArray_1_1 && !keyedArray_1_1.done && (_a = keyedArray_1.return)) yield __await(_a.call(keyedArray_1));
                }
                finally { if (e_25) throw e_25.error; }
            }
        });
    };
}

function orderBy ( keySelector , comparison ) { const trueKeySelector = keySelector || defaultKeySelector ; const trueComparison = comparison || defaultComparison ; return function ( item ) { return __asyncGenerator ( this , arguments , function * ( ) { var e_25 , _a ; const keyedMapper = map ( ( item , index ) => ( { item , key : trueKeySelector ( item , index ) } ) ) ; const keyed = keyedMapper ( item ) ; const keyedArray = yield __await ( toWriteableArray ( keyed ) ) ; keyedArray . sort ( ( a , b ) => trueComparison ( a . key , b . key ) ) ; try { for ( var keyedArray_1 = __asyncValues ( keyedArray ) , keyedArray_1_1 ; keyedArray_1_1 = yield __await ( keyedArray_1 . next ( ) ) , ! keyedArray_1_1 . done ; ) { const { item } = keyedArray_1_1 . value ; yield yield __await ( item ) ; } } catch ( e_25_1 ) { e_25 = { error : e_25_1 } ; } finally { try { if ( keyedArray_1_1 && ! keyedArray_1_1 . done && ( _a = keyedArray_1 . return ) ) yield __await ( _a . call ( keyedArray_1 ) ) ; } finally { if ( e_25 ) throw e_25 . error ; } } } ) ; } ; }

Play the given AsyncIterable ordered by a given key or itself


function flip(it) {
    return __asyncGenerator(this, arguments, function* flip_1() {
        yield __await(yield* __asyncDelegator(__asyncValues(yield __await(reduce((prev, next) => [next].concat(prev), [])(it)))));
    });
}

function flip ( it ) { return __asyncGenerator ( this , arguments , function * flip_1 ( ) { yield __await ( yield * __asyncDelegator ( __asyncValues ( yield __await ( reduce ( ( prev , next ) => [ next ] . concat ( prev ) , [ ] ) ( it ) ) ) ) ) ; } ) ; }

Play the given AsyncIterable in reverse order


function repeat(times) {
    return function (it) {
        return __asyncGenerator(this, arguments, function* () {
            var e_26, _a;
            const buffer = [];
            try {
                for (var it_6 = __asyncValues(it), it_6_1; it_6_1 = yield __await(it_6.next()), !it_6_1.done;) {
                    const item = it_6_1.value;
                    buffer.push(item);
                    yield yield __await(item);
                }
            }
            catch (e_26_1) { e_26 = { error: e_26_1 }; }
            finally {
                try {
                    if (it_6_1 && !it_6_1.done && (_a = it_6.return)) yield __await(_a.call(it_6));
                }
                finally { if (e_26) throw e_26.error; }
            }
            for (let i = 0; i < times; ++i) {
                yield __await(yield* __asyncDelegator(__asyncValues(buffer)));
            }
        });
    };
}

function repeat ( times ) { return function ( it ) { return __asyncGenerator ( this , arguments , function * ( ) { var e_26 , _a ; const buffer = [ ] ; try { for ( var it_6 = __asyncValues ( it ) , it_6_1 ; it_6_1 = yield __await ( it_6 . next ( ) ) , ! it_6_1 . done ; ) { const item = it_6_1 . value ; buffer . push ( item ) ; yield yield __await ( item ) ; } } catch ( e_26_1 ) { e_26 = { error : e_26_1 } ; } finally { try { if ( it_6_1 && ! it_6_1 . done && ( _a = it_6 . return ) ) yield __await ( _a . call ( it_6 ) ) ; } finally { if ( e_26 ) throw e_26 . error ; } } for ( let i = 0 ; i < times ; ++ i ) { yield __await ( yield * __asyncDelegator ( __asyncValues ( buffer ) ) ) ; } } ) ; } ; }

Play the given AsyncIterable, and then it N more times

Play the given AsyncIterable and then it N more times


function doppler(it) {
    return __asyncGenerator(this, arguments, function* doppler_1() {
        var e_27, _a;
        const buffer = [];
        try {
            for (var it_7 = __asyncValues(it), it_7_1; it_7_1 = yield __await(it_7.next()), !it_7_1.done;) {
                const item = it_7_1.value;
                buffer.push(item);
                yield yield __await(item);
            }
        }
        catch (e_27_1) { e_27 = { error: e_27_1 }; }
        finally {
            try {
                if (it_7_1 && !it_7_1.done && (_a = it_7.return)) yield __await(_a.call(it_7));
            }
            finally { if (e_27) throw e_27.error; }
        }
        buffer.reverse();
        yield __await(yield* __asyncDelegator(__asyncValues(buffer)));
    });
}

function doppler ( it ) { return __asyncGenerator ( this , arguments , function * doppler_1 ( ) { var e_27 , _a ; const buffer = [ ] ; try { for ( var it_7 = __asyncValues ( it ) , it_7_1 ; it_7_1 = yield __await ( it_7 . next ( ) ) , ! it_7_1 . done ; ) { const item = it_7_1 . value ; buffer . push ( item ) ; yield yield __await ( item ) ; } } catch ( e_27_1 ) { e_27 = { error : e_27_1 } ; } finally { try { if ( it_7_1 && ! it_7_1 . done && ( _a = it_7 . return ) ) yield __await ( _a . call ( it_7 ) ) ; } finally { if ( e_27 ) throw e_27 . error ; } } buffer . reverse ( ) ; yield __await ( yield * __asyncDelegator ( __asyncValues ( buffer ) ) ) ; } ) ; }

Play the given AsyncIterable, and then play back that AsyncIterable in reverse

Play the given AsyncIterable and then play back that AsyncIterable in reverse


async function count(source) {
    var e_33, _a;
    let i = 0;
    try {
        for (var source_4 = __asyncValues(source), source_4_1; source_4_1 = await source_4.next(), !source_4_1.done;) {
            const it = source_4_1.value;
            ++i;
        }
    }
    catch (e_33_1) { e_33 = { error: e_33_1 }; }
    finally {
        try {
            if (source_4_1 && !source_4_1.done && (_a = source_4.return)) await _a.call(source_4);
        }
        finally { if (e_33) throw e_33.error; }
    }
    return i;
}

async function count ( source ) { var e_33 , _a ; let i = 0 ; try { for ( var source_4 = __asyncValues ( source ) , source_4_1 ; source_4_1 = await source_4 . next ( ) , ! source_4_1 . done ; ) { const it = source_4_1 . value ; ++ i ; } } catch ( e_33_1 ) { e_33 = { error : e_33_1 } ; } finally { try { if ( source_4_1 && ! source_4_1 . done && ( _a = source_4 . return ) ) await _a . call ( source_4 ) ; } finally { if ( e_33 ) throw e_33 . error ; } } return i ; }

Returns a promise of the count of items returned by evaluating the provided iterable


async function empty(source) {
    var e_34, _a;
    let i = 0;
    try {
        for (var source_5 = __asyncValues(source), source_5_1; source_5_1 = await source_5.next(), !source_5_1.done;) {
            const it = source_5_1.value;
            return false;
        }
    }
    catch (e_34_1) { e_34 = { error: e_34_1 }; }
    finally {
        try {
            if (source_5_1 && !source_5_1.done && (_a = source_5.return)) await _a.call(source_5);
        }
        finally { if (e_34) throw e_34.error; }
    }
    return true;
}

async function empty ( source ) { var e_34 , _a ; let i = 0 ; try { for ( var source_5 = __asyncValues ( source ) , source_5_1 ; source_5_1 = await source_5 . next ( ) , ! source_5_1 . done ; ) { const it = source_5_1 . value ; return false ; } } catch ( e_34_1 ) { e_34 = { error : e_34_1 } ; } finally { try { if ( source_5_1 && ! source_5_1 . done && ( _a = source_5 . return ) ) await _a . call ( source_5 ) ; } finally { if ( e_34 ) throw e_34 . error ; } } return true ; }

Returns a promise of true if evaluating the iterable gives any items, false otherwise

Returns a promise of true if evaluating the iterable gives any items false otherwise


function CloseCommand(args, define) {
    var parsed = new statements.ExpressionStatement(args, define);
    if (!(parsed.child instanceof statements.PointerStatement)) throw new SyntaxError('Expected pointer');

    this.pointer = parsed;
}

function
CloseCommand
(
args
,
define
)
{
var
parsed
=
new
statements
.
ExpressionStatement
(
args
,
define
)
;
if
(
!
(
parsed
.
child
instanceof
statements
.
PointerStatement
)
)
throw
new
SyntaxError
(
'Expected pointer'
)
;
this
.
pointer
=
parsed
;
}

Closes a file in a pointer

@param {String} args The arguments to the command
@param {Function} define
@constructor


function Block(line, def, parent) {
    this.startNames = [];
    this.thenNames = [];
    this.endNames = [];
    for (var i = 0; i < def.start.length; i++) this.startNames.push(def.start[i].toLowerCase());
    for (var x = 0; x < def.end.length; x++) this.endNames.push(def.end[x].toLowerCase());
    for (var y = 0; y < def.then.length; y++) this.thenNames.push(def.then[y].toLowerCase());

    this.line = line;
    this.parent = parent;
    this.searchIndex = line;
    this.start = -1;
    this.intermediateIndexes = {};
    this.intermediateCursors = {};
    this.end = -1;
}

function Block ( line , def , parent ) { this . startNames = [ ] ; this . thenNames = [ ] ; this . endNames = [ ] ; for ( var i = 0 ; i < def . start . length ; i ++ ) this . startNames . push ( def . start [ i ] . toLowerCase ( ) ) ; for ( var x = 0 ; x < def . end . length ; x ++ ) this . endNames . push ( def . end [ x ] . toLowerCase ( ) ) ; for ( var y = 0 ; y < def . then . length ; y ++ ) this . thenNames . push ( def . then [ y ] . toLowerCase ( ) ) ; this . line = line ; this . parent = parent ; this . searchIndex = line ; this . start = - 1 ; this . intermediateIndexes = { } ; this . intermediateCursors = { } ; this . end = - 1 ; }

A block parser

@param {Number} line The current line number
@param {{start: Array, end: Array, then: Array}} def Properties for block definition
@param {BlockManager} parent


function ReadCommand(args) {
    var parsed = new statements.ArgumentStatement(args);
    for (var i = 0; i < parsed.args.length; i++) {
        var placeVar = parsed.args[i];
        if (!(placeVar.child instanceof statements.VariableStatement || placeVar.child instanceof statements.FunctionStatement))
            throw new SyntaxError('Expected variable');
    }
    this.items = parsed.args;
}

function
ReadCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
for
(
var
i
=
0
;
i
<
parsed
.
args
.
length
;
i
++
)
{
var
placeVar
=
parsed
.
args
[
i
]
;
if
(
!
(
placeVar
.
child
instanceof
statements
.
VariableStatement
||
placeVar
.
child
instanceof
statements
.
FunctionStatement
)
)
throw
new
SyntaxError
(
'Expected variable'
)
;
}
this
.
items
=
parsed
.
args
;
}

Shifts data from the stack

@param {String} args The arguments to the command
@constructor


function compileValue(value) {
		if (value.subtype === 'array') {
			return compileArray(value)
		} else if (value.subtype === 'object') {
			return compileObject(value)
		} else if (value.subtype === 'mixin') {
			return compileMixin(value)
		} else if (value.subtype === 'js') {
			return compileJS(value)
		} else if (value.subtype === 'function') {
			return compileFunction(value)
		}
		throw new Error('Invalid subtype: ' + value.subtype)
	}

function
compileValue
(
value
)
{
if
(
value
.
subtype
===
'array'
)
{
return
compileArray
(
value
)
}
else
if
(
value
.
subtype
===
'object'
)
{
return
compileObject
(
value
)
}
else
if
(
value
.
subtype
===
'mixin'
)
{
return
compileMixin
(
value
)
}
else
if
(
value
.
subtype
===
'js'
)
{
return
compileJS
(
value
)
}
else
if
(
value
.
subtype
===
'function'
)
{
return
compileFunction
(
value
)
}
throw
new
Error
(
'Invalid subtype: '
+
value
.
subtype
)
}

Compile a value and append to generated code
@param {Value} value
@returns {string} - the resulting variable name
@private


function DrawspriteCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 3) throw new SyntaxError('DRAWSPRITE command requires 3 arguments');
    this.id = parsed.args[0];
    this.x = parsed.args[1];
    this.y = parsed.args[2];
    this.scale = parsed.args.length === 4 ? parsed.args[3] : false;
    this.rotation = parsed.args.length === 5 ? parsed.args[4] : false;
}

Draws a sprite

@param {String} args The arguments to the command
@constructor


function (string) { // string.check check sting type and size

            return ((typeof string === 'string' || string instanceof String)
                    && string.length >= this.min
                    && string.length <= this.max
                    && (!this.match || string.match(this.match))
                   );
          }

string . max Maximum length of the string


function sprintf (fstr, array) {
  // check the formatted string is for JSON and confirm is a valid JSON
  array.forEach(function (value) {
    fstr = format(fstr, value);
  });
  return fstr;
}

HELP FUNCTIONS format string from array source


function deepLook(obj, types) {
  if (typeof (obj) !== 'object') return obj;
  for (var key in obj) {
    if (!obj[key].type) {
      obj[key] = deepLook(obj[key], types);
    } else {
      if (!types[obj[key].type]) {
        throw new Error('No type ' + obj[key].type + ' in Types: key ' + key);
      }

      // check for range in new object
      if (typeof obj[key].min !== 'undefined'
        && typeof types[obj[key].type].min !== 'undefined'
        && types[obj[key].type].min > obj[key].min) {
        throw new Error('Key ' + key + ' minimal value (' + obj[key].min
          + ') is less than acceptable minimal in Types ('
          + types[obj[key].type].min + ')');
      }

      if (typeof obj[key].max !== 'undefined'
        && typeof types[obj[key].type].max !== 'undefined'
        && types[obj[key].type].max < obj[key].max) {
        throw new Error('Key ' + key + ' maximal value (' + obj[key].max
          + ') is in excess of maximal acceptable value in Types ('
          + types[obj[key].type].max + ')');
      }
    }

    // get properties and methods from Types
    for (var keyParent in types[obj[key].type]) {
      if (!obj[key][keyParent]) {
        obj[key][keyParent] = types[obj[key].type][keyParent];
      }
    }
  }

  return obj;
}


function validateObjectRequired(options, modelObject, entity, parents, errors) {
  for (var key in modelObject) {
    if (!modelObject[key].type && entity) {
      validateObjectRequired(
        options,
        modelObject[key],
        entity[key],
        parents + '.' + key,
        errors);
    } else if (!options.notRequired && modelObject[key].required && (!entity || !entity[key])) {
      if (!errors.notFound) errors.notFound = [];
      var fieldName = parents + '.' + key;
      errors.notFound.push(fieldName);
      errors.text.push('Field ' + fieldName + ' not found');
    }
  }

  return errors;
}

function
validateObjectRequired
(
options
,
modelObject
,
entity
,
parents
,
errors
)
{
for
(
var
key
in
modelObject
)
{
if
(
!
modelObject
[
key
]
.
type
&&
entity
)
{
validateObjectRequired
(
options
,
modelObject
[
key
]
,
entity
[
key
]
,
parents
+
'.'
+
key
,
errors
)
;
}
else
if
(
!
options
.
notRequired
&&
modelObject
[
key
]
.
required
&&
(
!
entity
||
!
entity
[
key
]
)
)
{
if
(
!
errors
.
notFound
)
errors
.
notFound
=
[
]
;
var
fieldName
=
parents
+
'.'
+
key
;
errors
.
notFound
.
push
(
fieldName
)
;
errors
.
text
.
push
(
'Field '
+
fieldName
+
' not found'
)
;
}
}
return
errors
;
}


function validateObjectEntity(modelObject, entity, parents, errors) {
  if (!errors) errors = {};
  if (!errors.text) errors.text = [];
  if (!parents) parents = [];

  for (var key in entity) {
    var fieldName = parents + '.' + key;
    if (!modelObject || !modelObject[key]) {
      if (!errors.notRequired) errors.notRequired = [];
      errors.notRequired.push(fieldName);
      errors.text.push('Field ' + fieldName + ' not required');
    } else if (!modelObject[key].type) {
      validateObjectEntity(modelObject[key], entity[key], [parents, key], errors);
    } else if (!modelObject[key].check(entity[key])) {
      if (!errors.notMatched) errors.notMatched = {};
      errors.notMatched[fieldName] = modelObject[key].type;
      errors.text.push('Field ' + fieldName + ' not matched with type ' + modelObject[key].type);
    }
  }

  return errors;
}

function
validateObjectEntity
(
modelObject
,
entity
,
parents
,
errors
)
{
if
(
!
errors
)
errors
=
{
}
;
if
(
!
errors
.
text
)
errors
.
text
=
[
]
;
if
(
!
parents
)
parents
=
[
]
;
for
(
var
key
in
entity
)
{
var
fieldName
=
parents
+
'.'
+
key
;
if
(
!
modelObject
||
!
modelObject
[
key
]
)
{
if
(
!
errors
.
notRequired
)
errors
.
notRequired
=
[
]
;
errors
.
notRequired
.
push
(
fieldName
)
;
errors
.
text
.
push
(
'Field '
+
fieldName
+
' not required'
)
;
}
else
if
(
!
modelObject
[
key
]
.
type
)
{
validateObjectEntity
(
modelObject
[
key
]
,
entity
[
key
]
,
[
parents
,
key
]
,
errors
)
;
}
else
if
(
!
modelObject
[
key
]
.
check
(
entity
[
key
]
)
)
{
if
(
!
errors
.
notMatched
)
errors
.
notMatched
=
{
}
;
errors
.
notMatched
[
fieldName
]
=
modelObject
[
key
]
.
type
;
errors
.
text
.
push
(
'Field '
+
fieldName
+
' not matched with type '
+
modelObject
[
key
]
.
type
)
;
}
}
return
errors
;
}

check for extra fields and match recursively


function (params) {
    var res = [];
    if (typeof (params) === 'undefined') params = { displayEverything: false };
    if (!this.registeredModels || Object.keys(this.registeredModels).length === 0) {
      res.push('There is no registered models');
    } else {
      res.push('List of registered models');
      for (var modelName in this.registeredModels) {
        res.push('  - ' + modelName);
        if (params.displayEverything) {
          for (var key in this.registeredModels[modelName]) {
            res.push('      ' + key + ' : ' + this.registeredModels[modelName][key].type);
          }
        }
      }
    }

    return res.join('\n');
  }

function
(
params
)
{
var
res
=
[
]
;
if
(
typeof
(
params
)
===
'undefined'
)
params
=
{
displayEverything
:
false
}
;
if
(
!
this
.
registeredModels
||
Object
.
keys
(
this
.
registeredModels
)
.
length
===
0
)
{
res
.
push
(
'There is no registered models'
)
;
}
else
{
res
.
push
(
'List of registered models'
)
;
for
(
var
modelName
in
this
.
registeredModels
)
{
res
.
push
(
'  - '
+
modelName
)
;
if
(
params
.
displayEverything
)
{
for
(
var
key
in
this
.
registeredModels
[
modelName
]
)
{
res
.
push
(
'      '
+
key
+
' : '
+
this
.
registeredModels
[
modelName
]
[
key
]
.
type
)
;
}
}
}
}
return
res
.
join
(
'\n'
)
;
}

Show information of registered models. All registered models are stored in .registeredModels If params.displayEverything is true, module will show additional info

Show information of registered models . All registered models are stored in . registeredModels If params . displayEverything is true module will show additional info


function (modelName, entity, options, next) {
    if (typeof options === 'function') next = options;
    if (!options) options = {};

    var modelObject = this.registeredModels[modelName];

    if (typeof modelName === 'object') {
      modelObject = deepLook(modelName, this.types);
    } else if (this.types[modelName]) {
      if (options.one) this.types[modelName].one = options.one;
      var result = this.types[modelName].check(entity) ? null : { notMatched: modelName };
      return typeof next === 'function' ? next(result) : result;
    }

    var errors = validateObjectRequired(
      options, modelObject, entity, [],
      validateObjectEntity(modelObject, entity)
    );
    if (!errors.text[0]) errors = {};
    if (errors && errors.text) errors.text = errors.text.join('. ');

    if (typeof next === 'function') {
      next(Object.keys(errors).length ? errors : null);
    } else {
      return Object.keys(errors).length ? errors : {};
    }
  }

function
(
modelName
,
entity
,
options
,
next
)
{
if
(
typeof
options
===
'function'
)
next
=
options
;
if
(
!
options
)
options
=
{
}
;
var
modelObject
=
this
.
registeredModels
[
modelName
]
;
if
(
typeof
modelName
===
'object'
)
{
modelObject
=
deepLook
(
modelName
,
this
.
types
)
;
}
else
if
(
this
.
types
[
modelName
]
)
{
if
(
options
.
one
)
this
.
types
[
modelName
]
.
one
=
options
.
one
;
var
result
=
this
.
types
[
modelName
]
.
check
(
entity
)
:
{
notMatched
:
modelName
}
;
return
typeof
next
===
'function'
next
(
result
)
:
result
;
}
var
errors
=
validateObjectRequired
(
options
,
modelObject
,
entity
,
[
]
,
validateObjectEntity
(
modelObject
,
entity
)
)
;
if
(
!
errors
.
text
[
0
]
)
errors
=
{
}
;
if
(
errors
&&
errors
.
text
)
errors
.
text
=
errors
.
text
.
join
(
'. '
)
;
if
(
typeof
next
===
'function'
)
{
next
(
Object
.
keys
(
errors
)
.
length
errors
:
)
;
}
else
{
return
Object
.
keys
(
errors
)
.
length
errors
:
{
}
;
}
}

Check if entity pass modelName's validation

Check if entity pass modelName s validation


function (type) {
    var examples = this.getExamples(type);
    return examples[Math.floor(Math.random() * examples.length)];
  }

function ( type ) { var examples = this . getExamples ( type ) ; return examples [ Math . floor ( Math . random ( ) * examples . length ) ] ; }


function SleepCommand(args, define) {
    this.duration = new statements.ExpressionStatement(args, define);
    if (this.duration.error) throw this.duration.error;
}

function SleepCommand ( args , define ) { this . duration = new statements . ExpressionStatement ( args , define ) ; if ( this . duration . error ) throw this . duration . error ; }

Sleeps for a certain amount of seconds

@param {String} args The arguments to the command
@param {Function} define
@constructor


function(callback,compilationSource){
		if( compilationSource && this.cache.compilationSource && this.cache.compilationSource === compilationSource ) return;
		var callbackError=function(type,strOrErr){
			/*if(strOrErr instanceof Array){
				var i,finalStr='Errors :';
				for(i in strOrErr){
					console.error(strOrErr[i].stack);
					finalStr+=+"\n"+strOrErr[i].toString().slice(7);
				}
				strOrErr=finalStr;
			}*/
			//var error=new Error(strOrErr instanceof Error ? strOrErr.toString().slice(7) : strOrErr);
			var error=strOrErr instanceof Error ? strOrErr : new Error(strOrErr);
			error._Type=type;
			t.cache.error=error;
			callback(error);
		},t=this;

		if(t.compiler){
			(t.compiler.read||function(path,callback){
				fs.readFile(t.srcPath,function(err,buffer){
					if(err) return callback(err);
					callback(null,buffer.toString());
				});
			})(t.srcPath,function(err,fileContent){
				if(err) return callbackError('Reading',err);
				t.lint(t,fileContent,function(err){
					if(err) return callbackError('Linting',err);

					t.parse(fileContent,function(err,data){
						if(err) return callbackError('Parsing',err);
						try{
							t._compile(data,function(err,results,dependencies){
								if(err) return callbackError('Compiling',err);
								if(err===false) return callback();
								t.optimize(t,results,function(err,optimizedResults){
									if(err) return callbackError('Optimizing',err);
									t.cache.error=null;
									t.cache.compilationTime=Date.now();
									t.cache.compilationSource=compilationSource;
									if(err===false){
										t.cache.dependencies=null;
										return callback();
									}
									t.cache.dependencies=!dependencies || dependencies.app ? dependencies : {app:dependencies};
									t.write(optimizedResults,callback);
								});
							});
						}catch(err){
							return callbackError('Compiling',err);
						}
					});
				});
			});
		}else{
			t.copy(callback);
		}
	}

Reads file and compiles it with compiler. Data is cached

Reads file and compiles it with compiler . Data is cached


function errorHandler(response, error) {
    response
      .status(500)
      .send(error !== undefined && error !== null ? error.toString() : '')
  }

function errorHandler ( response , error ) { response . status ( 500 ) . send ( error !== undefined && error !== null ? error . toString ( ) : '' ) }


function(cb) {
      Person.find('Scott', function(err, person) {
        if (err) { return cb(err); }

        assert(person.uuid);
        assert(person.name === 'Scott');
        scott = person;
        cb();
      });
    }

function ( cb ) { Person . find ( 'Scott' , function ( err , person ) { if ( err ) { return cb ( err ) ; } assert ( person . uuid ) ; assert ( person . name === 'Scott' ) ; scott = person ; cb ( ) ; } ) ; }


function(cb) {
      var calli = Dog.new({ name: 'Calli' });
      // saves and creates connection
      scott.addDog(calli, function(err) {
        if (err) { return cb(err); }

        scott.fetchDogs(function(err) {
          if (err) { return cb(err); }

          assert(scott.dogs);
          var dog = scott.dogs[0];
          assert(dog.uuid);
          assert(dog.name === 'Calli');
          cb();
        });
      });
    }

function
(
cb
)
{
var
calli
=
Dog
.
new
(
{
name
:
'Calli'
}
)
;
// saves and creates connection
scott
.
addDog
(
calli
,
function
(
err
)
{
if
(
err
)
{
return
cb
(
err
)
;
}
scott
.
fetchDogs
(
function
(
err
)
{
if
(
err
)
{
return
cb
(
err
)
;
}
assert
(
scott
.
dogs
)
;
var
dog
=
scott
.
dogs
[
0
]
;
assert
(
dog
.
uuid
)
;
assert
(
dog
.
name
===
'Calli'
)
;
cb
(
)
;
}
)
;
}
)
;
}


function CircleCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 3) throw new SyntaxError('CIRCLE command requires 3 arguments');
    this.x = parsed.args[0];
    this.y = parsed.args[1];
    this.radius = parsed.args[2];
    this.stroke = parsed.args.length > 3 ? parsed.args[3] : false;
}

function
CircleCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
3
)
throw
new
SyntaxError
(
'CIRCLE command requires 3 arguments'
)
;
this
.
x
=
parsed
.
args
[
0
]
;
this
.
y
=
parsed
.
args
[
1
]
;
this
.
radius
=
parsed
.
args
[
2
]
;
this
.
stroke
=
parsed
.
args
.
length
>
3
parsed
.
args
[
3
]
:
false
;
}

Draws a filled or stroked circle

@param {String} args The arguments to the command


function Polling (objGoogleCheckout) {
	var self = this;

	//todo: check the constructor name
	assert.ok(objGoogleCheckout, "A GoogleCheckout object is the only required argument");

	self.gc = objGoogleCheckout;
	self.settings = self.gc.settings;
	self.continueToken = null;
}

Instantiate an instance of the GoogleCheckout Polling prototype

Examples:

var gc = new GoogleCheckout({ merchantNumber : '1234', merchantKey : 'ABCD', currency : 'USD'});
var p = new Polling(gc);

This is not really necessary though because an instance of GoogleCheckout contains
an instance of Polling

var gc = new GoogleCheckout({ merchantNumber : '1234', merchantKey : 'ABCD', currency : 'USD'});

gc.Polling.on('newOrderNotification', function (order) {
console.log(order)
});

gc.Polling.run();

Continue Token Events:

- notificationDataTokenResponse - 'Raw'
- continueToken

Notification Events:

- notificationDataResponse - 'Raw'
- newOrderNotification
- authorizationAmountNotification
- riskInformationNotification
- orderStateChangeNotification
- chargeAmountNotification
- refundAmountNotification
- chargebackAmountNotification

@param {Object} objGoogleCheckout An instance of a GoogleCheckout object
@return {Object} Polling Object
@api public


function TriangleCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 6) throw new SyntaxError('TRIANGLE command requires 6 arguments');
    this.x1 = parsed.args[0];
    this.y1 = parsed.args[1];
    this.x2 = parsed.args[2];
    this.y2 = parsed.args[3];
    this.x3 = parsed.args[4];
    this.y3 = parsed.args[5];
    this.stroke = parsed.args.length > 6 ? parsed.args[6] : false;
}

function
TriangleCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
6
)
throw
new
SyntaxError
(
'TRIANGLE command requires 6 arguments'
)
;
this
.
x1
=
parsed
.
args
[
0
]
;
this
.
y1
=
parsed
.
args
[
1
]
;
this
.
x2
=
parsed
.
args
[
2
]
;
this
.
y2
=
parsed
.
args
[
3
]
;
this
.
x3
=
parsed
.
args
[
4
]
;
this
.
y3
=
parsed
.
args
[
5
]
;
this
.
stroke
=
parsed
.
args
.
length
>
6
parsed
.
args
[
6
]
:
false
;
}

Draws a filled or stroked triangle

@param {String} args The arguments to the command


function processFile(file) {
		var changed = true;

		while(changed && !file.processed) {
			changed = false;
			changed = processWraps(file);
			changed = processInserts(file);
		}
		file.processed = true;
	}

function processFile ( file ) { var changed = true ; while ( changed && ! file . processed ) { changed = false ; changed = processWraps ( file ) ; changed = processInserts ( file ) ; } file . processed = true ; }

this function will be called within processWraps and processInserts


function Service(name) {
  debug('new service: %s', name);
  assert(name, "service not supplied with name");

  this.name       = name;
  this.middleware = [];
  this.uri        = new Uri();
  this.status     = new Status();

  this.initialize();

  return this;
}

function
Service
(
name
)
{
debug
(
'new service: %s'
,
name
)
;
assert
(
name
,
"service not supplied with name"
)
;
this
.
name
=
name
;
this
.
middleware
=
[
]
;
this
.
uri
=
new
Uri
(
)
;
this
.
status
=
new
Status
(
)
;
this
.
initialize
(
)
;
return
this
;
}

Service constructor.

Instances will contain a map to all of the
services that have been mounted onto the
system.


function Analyzer(config, state) {
	config = config || {};

	this.state = state;

	this.config = extend(true, {
		finders: {
			styl : [
				{
					name: 'regex',
					config: {
						pattern: /^\s*(?:@import|@require)\s+['"](.+?)['"](?:$|;)/gm,
						exclude: ['nib']
					}
				}
			],

			coffee: [
				{
					name: 'regex',
					config: {
						pattern: /^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*(?:\()?['"]([^'"]+)['"](?:\))?/gm
					}
				}
			],

			cjsx: [
				{
					name: 'regex',
					config: {
						pattern: /^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*(?:\()?['"]([^'"]+)['"](?:\))?/gm
					}
				}
			],

			js: [
				{
					name: 'regex',
					config: {
						pattern: [
							/^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*\(?['"]([^'"]+)['"]\)?/gm,
							/\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/gm
						]
					}
				}
			],

			jsx: [
				{
					name: 'regex',
					config: {
						pattern: [
							/^\s*(?:.+?\s*[=\:\(\{\;])?\s*require\s*\(?['"]([^'"]+)['"]\)?/gm,
							/\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/gm
						]
					}
				}
			]
		},

		resolvers: {
			styl : [
				{
					name: 'basic',
					config: {
						extensions: [
							'styl',
							'css'
						]
					}
				}
			],

			coffee: [
				{
					name: 'common-js',
					config: {
						extensions: [
							'coffee',
							'js',
							'cjsx',
							'jsx'
						]
					}
				}
			],

			cjsx: [
				{
					name: 'common-js',
					config: {
						extensions: [
							'coffee',
							'js',
							'cjsx',
							'jsx'
						]
					}
				}
			],

			js: [
				{
					name: 'common-js',
					config: {
						extensions: [
							'coffee',
							'js',
							'cjsx',
							'jsx'
						]
					}
				}
			],

			jsx: [
				{
					name: 'common-js',
					config: {
						extensions: [
							'coffee',
							'js',
							'cjsx',
							'jsx'
						]
					}
				}
			]
		}
	}, config);

	this.finders = {};
	this.resolvers = {};

	this.createFinders();
	this.createResolvers();
}

This class finds and resolves all the dependencies
within a set of source files. In order to do
so finders' and resolvers' strategies are used
and the results are collected.

The state of the analyzer is externalized in order
to preserve the dependencies graph within different
instances of the analyzer.

@description
The configuration of the analyzer has the following
structure:

{
finders: {
fileExt: [
{
name: 'finder-name',
config: {
// Finder configuration
}
}
],

fileExt2: [
//...
]
},

resolvers: {
fileExt: [
{
name: 'resolver-name',
config: {
// Resolver configuration
}
}
],

fileExt2: [
//...
]
}
}

If multiple resolvers/finders are specified
their result will be aggregated.

@class Analyzer
@param {Object} config The configuration of this
analyzer instance
@param {AnalyzerState} state The state to be used
in the analysis

This class finds and resolves all the dependencies within a set of source files . In order to do so finders and resolvers strategies are used and the results are collected .


function RrectCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 5) throw new SyntaxError('RRECT command requires 5 arguments');
    this.x1 = parsed.args[0];
    this.y1 = parsed.args[1];
    this.x2 = parsed.args[2];
    this.y2 = parsed.args[3];
    this.radius = parsed.args[4];
    this.stroke = parsed.args.length > 5 ? parsed.args[5] : false;
}

function
RrectCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
5
)
throw
new
SyntaxError
(
'RRECT command requires 5 arguments'
)
;
this
.
x1
=
parsed
.
args
[
0
]
;
this
.
y1
=
parsed
.
args
[
1
]
;
this
.
x2
=
parsed
.
args
[
2
]
;
this
.
y2
=
parsed
.
args
[
3
]
;
this
.
radius
=
parsed
.
args
[
4
]
;
this
.
stroke
=
parsed
.
args
.
length
>
5
parsed
.
args
[
5
]
:
false
;
}

Draws a filled or stroked rounded rectangle

@param {String} args The arguments to the command


function cons (b, value, next) {
  var free = readValue(b, 0) || 8
  updateValue(b, free, value); updateNext(b, free, next)
  updateValue(b, 0, free+8) //update free pointer
  return free
}

function
cons
(
b
,
value
,
next
)
{
var
free
=
readValue
(
b
,
0
)
||
8
updateValue
(
b
,
free
,
value
)
;
updateNext
(
b
,
free
,
next
)
updateValue
(
b
,
0
,
free
+
8
)
//update free pointer
return
free
}


function insert (b, node, value) {
  return updateNext(b, node, cons(b, value, readNext(b, node)))
}

function insert ( b , node , value ) { return updateNext ( b , node , cons ( b , value , readNext ( b , node ) ) ) }


function init(pathToModels, cb, addToSwagger) {
	modelPath = pathToModels;
	glob(modelPath + '/**/*.js', function(err, files) {
		if (err) return cb && cb(err);

		files.forEach(function(file) {
			var Model = require(file)(),
				modelSwagger = null;

            if (Model.init) {
                Model.init();
            }

            modelSwagger = Model.getSwagger();

			if (modelSwagger && addToSwagger) {
				modelSwagger.forEach(function(swaggerResource) {
					swagger[swaggerMethodName[swaggerResource.spec.method.toLowerCase()]](swaggerResource);
				});
			}
			models.push(Model);
		});

		return cb && cb(null, models);
	});
}

function init ( pathToModels , cb , addToSwagger ) { modelPath = pathToModels ; glob ( modelPath + '/**/*.js' , function ( err , files ) { if ( err ) return cb && cb ( err ) ; files . forEach ( function ( file ) { var Model = require ( file ) ( ) , modelSwagger = null ; if ( Model . init ) { Model . init ( ) ; } modelSwagger = Model . getSwagger ( ) ; if ( modelSwagger && addToSwagger ) { modelSwagger . forEach ( function ( swaggerResource ) { swagger [ swaggerMethodName [ swaggerResource . spec . method . toLowerCase ( ) ] ] ( swaggerResource ) ; } ) ; } models . push ( Model ) ; } ) ; return cb && cb ( null , models ) ; } ) ; }

gets all model files and adds them to swagger
it will then add those to swagger as the proper resource

@author Tim Golen 2014-12-17

@param  {Function} cb


function ArgumentStatement(args, options, define) {
    options = options || {};
    this.value = args;
    this.flags = {};
    this.args = [];
    this.options = options;

    if (typeof options.parse === 'undefined') options.parse = true;
    if (typeof options.separator === 'undefined') options.separator = ',';
    if (typeof options.parseArgs === 'undefined') options.parseArgs = true;

    if (options.parse) {
        if (options.flags) {
            var isFlag = true;

            // Find all matching flags  until no flag is found
            while(isFlag) {
                var firstFlagEnd = args.indexOf(' ');
                if (firstFlagEnd === -1) firstFlagEnd = args.length;
                var firstFlag = args.substring(0, firstFlagEnd).trim().toUpperCase();

                if (options.flags.indexOf(firstFlag) !== -1) {
                    this.flags[firstFlag] = true;
                    args = args.substring(firstFlagEnd).trim();
                }
                else isFlag = false;
            }
        }

        this.rawArgs = args;

        args = args.trim();
        var argList = [args];
        if (options.separator) {
            if (!args.length) argList = [];
            else {
                var positions = util.findPositions(args, [
                    {'start': '"', 'end': '"'},
                    {'start': '(', 'end': ')'}
                ]);
                argList = util.splitOutside(args, options.separator, positions);
            }
        }
        for (var i = 0; i < argList.length; i++) {
            var arg = argList[i].trim();
            if (options.parseArgs) arg = new statements.ExpressionStatement(arg, define);
            this.args.push(arg);
        }
    }
}

Represents a set of arguments to a command call

@param {String} args The arguments to parse
@param {Object} options Command options
@param {Function?} define


function OpenCommand(args, define) {
    var lowerArgs = args.toLowerCase();
    var forIndex = lowerArgs.indexOf(' for ');
    if (forIndex === -1) throw new SyntaxError('OPEN without FOR');
    var filename = new statements.ExpressionStatement(args.substring(0, forIndex).trim(), define);

    var asIndex = lowerArgs.indexOf(' as ');
    if (asIndex === -1) throw new SyntaxError('OPEN without AS');
    var type = args.substring(forIndex + 5, asIndex).trim().toLowerCase();
    if (type !== 'input' && type !== 'output' && type !== 'append') throw new SyntaxError('Invalid mode');

    var pointer = new statements.ExpressionStatement(args.substring(asIndex + 4).trim(), define);
    if (!(pointer.child instanceof statements.PointerStatement)) throw new SyntaxError('Expected pointer');

    this.filename = filename;
    this.type = type;
    this.pointer = pointer;
}

function
OpenCommand
(
args
,
define
)
{
var
lowerArgs
=
args
.
toLowerCase
(
)
;
var
forIndex
=
lowerArgs
.
indexOf
(
' for '
)
;
if
(
forIndex
===
1
)
throw
new
SyntaxError
(
'OPEN without FOR'
)
;
var
filename
=
new
statements
.
ExpressionStatement
(
args
.
substring
(
0
,
forIndex
)
.
trim
(
)
,
define
)
;
var
asIndex
=
lowerArgs
.
indexOf
(
' as '
)
;
if
(
asIndex
===
1
)
throw
new
SyntaxError
(
'OPEN without AS'
)
;
var
type
=
args
.
substring
(
forIndex
+
5
,
asIndex
)
.
trim
(
)
.
toLowerCase
(
)
;
if
(
type
!==
'input'
&&
type
!==
'output'
&&
type
!==
'append'
)
throw
new
SyntaxError
(
'Invalid mode'
)
;
var
pointer
=
new
statements
.
ExpressionStatement
(
args
.
substring
(
asIndex
+
4
)
.
trim
(
)
,
define
)
;
if
(
!
(
pointer
.
child
instanceof
statements
.
PointerStatement
)
)
throw
new
SyntaxError
(
'Expected pointer'
)
;
this
.
filename
=
filename
;
this
.
type
=
type
;
this
.
pointer
=
pointer
;
}

Opens a file in a pointer

@param {String} args The arguments to the command
@param {Function} define
@constructor


function CommonJSResolverStrategy(config) {
	BasicResolverStrategy.call(this, config);
	this.config = extend(true, this.config, {}, config);
}

function CommonJSResolverStrategy ( config ) { BasicResolverStrategy . call ( this , config ) ; this . config = extend ( true , this . config , { } , config ) ; }

A resolving strategy that supports CommonJS style
requires, as seen in Node.js and Browserify.

@class
@extends BasicResolverStrategy
@param {Object} config A configuration object.

A resolving strategy that supports CommonJS style requires as seen in Node . js and Browserify .


function WhileCommand(args, define) {
    var parsed = new statements.ArgumentStatement(args, {
        separator: false
    });

    this.condition = parsed.args[0];
    this.block = define({
        start: 'WHILE',
        end: 'WEND'
    });
}

function WhileCommand ( args , define ) { var parsed = new statements . ArgumentStatement ( args , { separator : false } ) ; this . condition = parsed . args [ 0 ] ; this . block = define ( { start : 'WHILE' , end : 'WEND' } ) ; }

Iterates over the commands body until the condition is true

@param {String} args The arguments to the command
@param {Function} define
@constructor


function load(file, options) {
  var stream = fs.createReadStream(file, options);
  function onEnd() {
    this.emit('load');
  }
  function onError(err) {
    this.emit('error', err);
  }

  //stream.on('data', function onData(buf) {
    //console.dir('got buffer length: ' + buf.length);
  //})

  stream.on('end', onEnd.bind(this));
  stream.on('error', onError.bind(this));
  stream.pipe(this);
  return this;
}

Read a file and pipe it to this decoder.

Read a file and pipe it to this decoder .


function(cb) {
            // Callback is optional
            cb = util.optional(cb);

            // Grab policies config & policy modules and trigger callback
            this.loadMiddleware(function (err) {
                if (err) return cb(err);

                sails.log.verbose('Finished loading policy middleware logic.');
                cb();
            }.bind(this));

            // Before routing, curry controller functions with appropriate policy chains
            sails.on('router:before', this.bindPolicies);
        }

Initialize is fired first thing when the hook is loaded

@api public


function() {
            // Build / normalize policy config
            this.mapping = this.buildPolicyMap();
            _bindPolicies(this.mapping, sails.middleware.controllers);

            // Emit event to let other hooks know we're ready to go
            sails.log.verbose('Policy-controller bindings complete!');
            sails.emit('hook:policies:bound');
        }

Curry the policy chains into the appropriate controller functions

@api private


function () {
            var mapping = { };
            _.each(sails.config.policies, function (_policy, controllerId) {

                // Accept `FooController` or `foo`
                // Case-insensitive
                controllerId = util.normalizeControllerId(controllerId);

                // Controller-level policy ::
                // Just map the policy to the controller directly
                if (!util.isDictionary(_policy)) {
                    mapping[controllerId] = policyHookDef.normalizePolicy(_policy);
                    return;
                }

                // Policy mapping contains a sub-object ::
                // So we need to dive in and build/normalize the policy mapping from here
                // Mapping each policy to each action for this controller
                mapping[controllerId] = {};
                _.each( _policy, function (__policy, actionId) {

                    // Case-insensitive
                    actionId = actionId.toLowerCase();

                    mapping[controllerId][actionId] = policyHookDef.normalizePolicy(__policy);
                });
            });

            return mapping;
        }

Build normalized, hook-internal representation of policy mapping
by performing a non-destructive parse of `sails.config.policies`

@returns {Object} mapping
@api private

Build normalized hook - internal representation of policy mapping by performing a non - destructive parse of sails . config . policies


function (event) {
            // Only pay attention to delegated route events
            // if `policy` is declared in event.target
            if ( !event.target || !event.target.policy ) {
                return;
            }

            // Bind policy function to route
            var fn = this.lookupFn(event.target.policy, 'config.routes');
            sails.router.bind(event.path, fn, event.verb, _.merge(event.options, event.target));
        }


function FunctionStatement(name, args) {
    if (name[name.length - 1] === '$') {
        this.type = 'string';
        this.name = name.substring(0, name.length - 1);
    } else {
        this.type = 'number';
        this.name = name;
    }

    var positions = util.findPositions(args, [
        { 'start': '"', 'end': '"' },
        { 'start': '(', 'end': ')' }
    ]);
    var argList = util.splitOutside(args, ",", positions);

    this.args = [];
    for (var i = 0; i < argList.length; i++) {
        this.args.push(new statements.ExpressionStatement(argList[i].trim()));
    }
}

function FunctionStatement ( name , args ) { if ( name [ name . length - 1 ] === '$' ) { this . type = 'string' ; this . name = name . substring ( 0 , name . length - 1 ) ; } else { this . type = 'number' ; this . name = name ; } var positions = util . findPositions ( args , [ { 'start' : '"' , 'end' : '"' } , { 'start' : '(' , 'end' : ')' } ] ) ; var argList = util . splitOutside ( args , "," , positions ) ; this . args = [ ] ; for ( var i = 0 ; i < argList . length ; i ++ ) { this . args . push ( new statements . ExpressionStatement ( argList [ i ] . trim ( ) ) ) ; } }

Represents a function call

@param {String} name The name of the function
@param {String} args The arguments to the function


function LoadspriteCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 2) throw new SyntaxError('LOADSPRITE command requires 2 arguments');
    else if (parsed.args.length > 2 && parsed.args.length < 5) throw new SyntaxError('LOADSPRITE command requires 5 arguments');

    this.id = parsed.args[0];

    if (parsed.args.length > 2) {
        this.x1 = parsed.args[1];
        this.y1 = parsed.args[2];
        this.x2 = parsed.args[3];
        this.y2 = parsed.args[4];
    } else {
        this.fileName = parsed.args[1];
    }
}

Loads a sprite from a file

@param {String} args The arguments to the command
@constructor


function(verb, path, controller, method){

        // Only add the route if we recognise the verb.
        if (this.__verbs.indexOf(verb) >= 0){

            // Create an actual object.
            var entry = {
                verb: verb,
                path: path,
                controller: controller,
                method: method
            };

            this.routes.push(entry);
        }

        // Otherwise, they've made a mistake in their config, so throw an error.
        else {
            throw new Error('Unrecognised HTTP verb for route: ' + path);
        }

    }

Add a new route entry that's been parsed.
@param {String} verb The HTTP verb for the route.
@param {String} path The relative URL for the route.
@param {String} controller The path to the controller to use for serving the route.
@param {String} method The name of the method on the controller to use for serving the route.

Add a new route entry that s been parsed .


function(url, val){

        // Create a new object that we can manipulate safely.
        var object = extend({}, val);

        // Flag so we remember to append any attributes that can't be bound.
        var append = false;

        // If there are still parameters to bind, pull them out.
        // Note: We use a different regex here because we need the global flag to ensure we pull all remaining bindings.
        var remaining = url.match(/:\w+/ig);
        if (remaining && remaining.length > 0){

            // Iterate over the remaining potential bindings, looking for matches by name.
            for (var j = 0; j < remaining.length; j++){

                // Grab the key, stripping the : character.
                var key = remaining[j].replace(':', '');

                // Does our object contain that key?
                if (object[key] !== undefined){

                    // Is it a type we can serialise?
                    if (this.canSerialise(object[key])){

                        // If it is, replace that value.
                        var keyRegex = new RegExp(':' + key);
                        url = url.replace(keyRegex, object[key]);
                    }

                    // Even if it wasn't, delete the value so we don't try again later.
                    delete object[key];
                }
            }

            // If there are still fields left on our object, they need to become query parameters.
            if (object !== {}){
                append = true;
            }
        }

        // Otherwise, we're going to append the object's values as key/value pairs.
        else {
            append = true;
        }

        // If we need to append key/values, do so.
        if (append){

            for (var attr in object){

                // If the value is an object or a function, ignore it.
                if (this.canSerialise(object[attr])){

                    // How are we appending?
                    var joiner = (url.indexOf('?') >= 0) ? "&" : "?";

                    // Append.
                    url += joiner + attr + "=" + object[attr];
                }
            }
        }

        return url;
    }

Handles binding the fields of an object into a URL.
@param {string} url The URL to bind against.
@param {object} val The object from which to draw properties.
@return {string} The updated URL.

Handles binding the fields of an object into a URL .


function(app, route){

        var self = this;

        var controller;
        var controllerPath = self.options.controllersPath + route.controller;

        // Load the controller.
        try {
            controller = require(self.options.rootPath + controllerPath);
        }
        catch (e) {
            throw new Error('The specified controller (' + controllerPath + ') does not exist.');
        }

        if (controller) {

            // If the specified method does not exist, throw an exception.
            if (controller[route.method] === undefined) {
                throw new Error('The specified method (' + route.method + ') does not exist on the controller (' + controllerPath + ').');
            }

            // Bind the route.
            app[route.verb](route.path, controller[route.method]);
        }
    }

Handles binding a regular, boring route => controller combination on the provided app.
@param {Object} app The application to bind against.
@param {Object} route The details of the route to bind.

Handles binding a regular boring route = > controller combination on the provided app .


function(app, route){

        var self = this;

        // Figure out the folder they want to bind.
        var folderPath = route.controller.replace(/staticDir:/g, '');
        var folder = self.options.rootPath + folderPath;

        // Make sure that's actually a folder.
        try {
            var info = fs.lstatSync(folder);
            if (info.isDirectory()) {
                app.use(express.static(folder));
            }
        }
        catch (e) {
            throw new Error('The specified static path (' + folderPath + ') does not exist or is not a directory.');
        }
    }

Handles binding a particular folder to be served statically by Express.
@param {Object} app The application to bind against.
@param {Object} route The details of the route to bind.

Handles binding a particular folder to be served statically by Express .


function(app){

        // Cache the instance.
        var self = this;

        // Insert the instance into app.locals so it can be used in views.
        app.locals[self.options.templateVar] = self;

        // Grab the routes.
        var routes = self.getRoutes();

        // Bind them.
        routes.forEach(function(route){

            // If the controller begins with 'staticDir:', it's a static route.
            if (route.controller.indexOf('staticDir:') === 0) {
                self.bindStaticRoute(app, route);
            }

            else {
                self.bindRegularRoute(app, route);
            }
        });
    }

Binds the loaded routes against the passed app.
@param {object} app An Express app instance to bind routes against.

Binds the loaded routes against the passed app .


function(){

        // If we've already loaded the routes, skip.
        if (this.routes.length === 0){

            // Grab the entries.
            var routes;
            try {
                routes = this.readFile(this.options.rootPath + this.options.routesFile);
            }
            catch (e) {
                throw new Error('The specified routes file (' + this.options.routesFile + ') does not exist or could not be read.');
            }

            // Turn them into actual route entries.
            for (var i = 0; i < routes.length; i++){

                // Split it up into its component parts (VERB /path controller.method).
                // TODO: An equivalent to PHP's list() would be really awesome too.
                var bits = routes[i].split(/\s+/);

                // Split the controller up further, so we can store the file and method separately.
                var controller = bits[2].split('.');

                // If the controller contains a wildcard, we handle it differently.
                if (controller[1] == '{method}') {
                    this.getWildcardRoutes(bits[0].toLowerCase(), bits[1], controller[0]);
                }

                else {
                    this.addNewRouteEntry(bits[0].toLowerCase(), bits[1], controller[0], controller[1]);
                }
            }
        }

        return this.routes;
    }

Returns an array of objects encapsulating the routes to be configured.
@return {Array} The routes to configure, as objects.

Returns an array of objects encapsulating the routes to be configured .


function(verb, path, controllerName){

        // Load the referenced controller.
        var controllerPath = this.options.controllersPath + controllerName;
        try {
            var controller = require(this.options.rootPath + controllerPath);

            // Iterate over the controller, creating new route entries for each function.
            for (var field in controller) {

                if (typeof controller[field] == 'function') {
                    this.addNewRouteEntry(verb, path.replace(/{method}/, field), controllerName, field);
                }
            }
        }
        catch (e) {
            throw new Error('The specified controller (' + controllerPath + ') does not exist.');
        }
    }

Generate the various routes represented by a wildcard controller entry.
@param {String} verb The HTTP verb for the route.
@param {String} path The relative URL for the route.
@param {String} controllerName The path to the controller to use for serving the route.

Generate the various routes represented by a wildcard controller entry .


function(path){

        // Define the array we'll return.
        var routes = [];

        // Grab the FS library.
        var fs = require('fs');

        // Read the contents from disk.
        var array = fs.readFileSync(path).toString().split("\n");

        // We need to post-process since there might have been empty lines, or comments.
        array.forEach(function(route){

            // If it's not an empty line or a comment, add it.
            if (route !== "" && route.match(/^#/) === null) {
                routes.push(route);
            }
        });

        return routes;
    }

Reads a config file from disk, skipping empty lines and commented ones.
@param {string} path The path to the file to read.

Reads a config file from disk skipping empty lines and commented ones .


function(action){

        var url;
        var error;

        // Iterate over the routes, looking for a match.
        var routes = this.getRoutes();
        for (var i = 0; url === undefined && i < routes.length; i++){

            try {

                // Simplify access.
                var route = routes[i];

                // Check the controller + method. If we find one, figure out the URL to return.
                if (action == route.controller + '.' + route.method){

                    var params = [];

                    // If there are parameters, bind them.
                    if (arguments.length > 1) {

                        // Turn them into a proper array.
                        params = Array.prototype.slice.apply(arguments);

                        // And drop the first entry (which was the action itself).
                        params = params.slice(1);
                    }

                    // We always call bind, even with an empty array, to see if we generate an error.
                    url = this.bindUrl(route.path, params);
                }
            }

            catch(e) {

                // Store the error in case we need to rethrow it.
                error = e;
            }

        }

        // If we found a match, return it.
        if (url !== undefined) {
            return url;
        }

        // Otherwise, throw an exception.
        else {

            // If we captured an earlier error, reuse that (since it implies we found a match but couldn't bind it).
            if (error !== undefined) {
                throw error;
            }

            else {
                throw new Error("No matching action was found.");
            }
        }
    }

Given an action and an optional set of parameters, returns the URL to be used.
@param {string} action The URL to bind.
@return {string} A function which accepts a variable number of parameters and binds those to places in the URL.

Given an action and an optional set of parameters returns the URL to be used .


function(value){
		/*#if BROWSER*/ if(this._label) this._label.text(value); else /*#/if*/
		this._label=$.create('label').attr('for',this.getAttr('id'))/*#if BROWSER*/.prependTo(this._container)/*#/if*/.text(value);
		return this;
	}

function
(
value
)
{
/*#if BROWSER*/
if
(
this
.
_label
)
this
.
_label
.
text
(
value
)
;
else
/*#/if*/
this
.
_label
=
$
.
create
(
'label'
)
.
attr
(
'for'
,
this
.
getAttr
(
'id'
)
)
/*#if BROWSER*/
.
prependTo
(
this
.
_container
)
/*#/if*/
.
text
(
value
)
;
return
this
;
}


function parse(code) {
    try {
        var labels = {};
        var root = [];
        var manager = new BlockManager();

        var lines = code.split('\n');
        for (var i = 0; i < lines.length; i++) {
            try {
                var line = parseLine(lines[i].trim(), i, labels, false, manager);
                if (line instanceof SyntaxError) throw createLineError(line, i);
                if (line.error instanceof SyntaxError) throw createLineError(line.error, i);
                root[i] = line;
            } catch (ex) {
                throw createLineError(ex, i);
            }
        }

        return new AbstractSyntaxTree(root, labels, manager);
    } catch (ex) {
        return { "error": ex };
    }
}

function parse ( code ) { try { var labels = { } ; var root = [ ] ; var manager = new BlockManager ( ) ; var lines = code . split ( '\n' ) ; for ( var i = 0 ; i < lines . length ; i ++ ) { try { var line = parseLine ( lines [ i ] . trim ( ) , i , labels , false , manager ) ; if ( line instanceof SyntaxError ) throw createLineError ( line , i ) ; if ( line . error instanceof SyntaxError ) throw createLineError ( line . error , i ) ; root [ i ] = line ; } catch ( ex ) { throw createLineError ( ex , i ) ; } } return new AbstractSyntaxTree ( root , labels , manager ) ; } catch ( ex ) { return { "error" : ex } ; } }

Parses BASIC code and returns an abstract syntax tree

@param {String} code
@returns {AbstractSyntaxTree|{error: String}} The resulting AST


function CommandStatement(name, args, manager, line) {
    this.name = name;
    this.args = args;

    if (!commands[name]) throw new SyntaxError('Unknown command: ' + name);
    this.command = new commands[name](args, manager.create(line));
}

function
CommandStatement
(
name
,
args
,
manager
,
line
)
{
this
.
name
=
name
;
this
.
args
=
args
;
if
(
!
commands
[
name
]
)
throw
new
SyntaxError
(
'Unknown command: '
+
name
)
;
this
.
command
=
new
commands
[
name
]
(
args
,
manager
.
create
(
line
)
)
;
}

Represents a command call

@param {String} name The name of the command
@param {String} args The arguments to the command
@param {BlockManager} manager The block manager
@param {Number} line The line number


function BasicResolverStrategy(config) {
	ResolverStrategy.call(this, config);
	this.config = extend(true, this.config, {}, config);
}

function BasicResolverStrategy ( config ) { ResolverStrategy . call ( this , config ) ; this . config = extend ( true , this . config , { } , config ) ; }

This class implements a basic approach to
path resolution that aims at being as flexible
as possible.

For possible configuration values see
the documentation for the ResolverStrategy class.

@class
@extends ResolverStrategy
@param {String} config The configuration of this
path resolver

This class implements a basic approach to path resolution that aims at being as flexible as possible .


function toArray() {
    return Object
      .keys(data)
      .map(function(name) { return data[name]; })
      .sort(function(a, b) {
        return a.compareTo(b);
      });
  }

function toArray ( ) { return Object . keys ( data ) . map ( function ( name ) { return data [ name ] ; } ) . sort ( function ( a , b ) { return a . compareTo ( b ) ; } ) ; }

convert internal data object to Array
@return {Array}


function add(snapshot) {
    return Promise
      .resolve(mapFn(snapshot))
      .then(function(val) {
        data[snapshot.key()] = val;
      });
  }

function add ( snapshot ) { return Promise . resolve ( mapFn ( snapshot ) ) . then ( function ( val ) { data [ snapshot . key ( ) ] = val ; } ) ; }

add a snapshot to data

@param {DataSnapshot} snapshot
@return {Promise}


function emitValue() {
    var arr = toArray();
    marker = arr[arr.length - 1];
    setTimeout(function() {
      emitter.emit('value', arr);
    }, 0);
  }

function emitValue ( ) { var arr = toArray ( ) ; marker = arr [ arr . length - 1 ] ; setTimeout ( function ( ) { emitter . emit ( 'value' , arr ) ; } , 0 ) ; }


function onChildAdd(newData) {

    // ignore all events before first read
    if (!started) return;

    // ignore already added item
    if (data[newData.key()]) return;

    // ignore older items that are not loaded
    if ( !ended
      && !data[newData.key()]
      && marker && newData.compareTo(marker) > 0) return;

    return add(newData).then(emitValue);
  }

add child to data buffer, and emit value

@return {Promise}


function addChildren(newData) {
    var promises = [];
    newData.forEach(function (child) {
      promises.push(add(child));
    });

    return Promise.all(promises).then(emitValue);
  }

function addChildren ( newData ) { var promises = [ ] ; newData . forEach ( function ( child ) { promises . push ( add ( child ) ) ; } ) ; return Promise . all ( promises ) . then ( emitValue ) ; }

add children to data buffer, and emit value

@return {Promise}

add children to data buffer and emit value


function modalOpen (options) {
    if (isString(options)) options = optionsFromTarget(options);
    var modal = select('#d3-view-modal');
    if (!modal.size())
        select('body').append('modal').mount(options, vm => vm.model.$showModal());
    else
        modal.model().$update(options).$showModal();
}

function modalOpen ( options ) { if ( isString ( options ) ) options = optionsFromTarget ( options ) ; var modal = select ( '#d3-view-modal' ) ; if ( ! modal . size ( ) ) select ( 'body' ) . append ( 'modal' ) . mount ( options , vm => vm . model . $showModal ( ) ) ; else modal . model ( ) . $update ( options ) . $showModal ( ) ; }

function for opening a modal inject this method to the root model


function ColorCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 3) throw new SyntaxError('COLOR command requires 3 arguments');
    this.red = parsed.args[0];
    this.green = parsed.args[1];
    this.blue = parsed.args[2];
    this.alpha = parsed.args.length > 3 ? parsed.args[3] : false;
}

function
ColorCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
3
)
throw
new
SyntaxError
(
'COLOR command requires 3 arguments'
)
;
this
.
red
=
parsed
.
args
[
0
]
;
this
.
green
=
parsed
.
args
[
1
]
;
this
.
blue
=
parsed
.
args
[
2
]
;
this
.
alpha
=
parsed
.
args
.
length
>
3
parsed
.
args
[
3
]
:
false
;
}

Sets the draw color of the canvas

@param {String} args The arguments to the command
@constructor


function onChange () {
    if (props.onChange) {
      var changeHandlers = [...props.onChange]
      var value = editor.getValue()
      return changeHandlers.map((f) => f(value))
    }
  }

function onChange ( ) { if ( props . onChange ) { var changeHandlers = [ ... props . onChange ] var value = editor . getValue ( ) return changeHandlers . map ( ( f ) => f ( value ) ) } }


function PrintCommand(args, define) {
    if (args[args.length - 1] === ";") {
        this.noLine = true;
        args = args.substr(-1);
    } else this.noLine = false;

    var parsed = new statements.ArgumentStatement(args, {
        flags: ['USING'],
        parseArgs: false
    });

    if (parsed.flags.USING) {
        if (parsed.args.length !== 1) throw new SyntaxError('PRINT USING command requires 1 argument');
        if (parsed.args.length > 1) throw new SyntaxError('Unexpected comma');

        var semicolonIndex = parsed.args[0].indexOf(';');
        if (semicolonIndex === -1) throw new SyntaxError('Expected semicolon');

        var formatExpression = new statements.ExpressionStatement(parsed.args[0].substring(0, semicolonIndex).trim(), define);
        var numberExpression = new statements.ExpressionStatement(parsed.args[0].substring(semicolonIndex + 1).trim(), define);
        if (formatExpression.error instanceof SyntaxError) throw formatExpression.error;
        if (numberExpression.error instanceof SyntaxError) throw numberExpression.error;

        this.formatExpr = formatExpression;
        this.numberExpr = numberExpression;
    } else {
        var items = [];
        for (var i = 0; i < parsed.args.length; i++) {
            var expr = new statements.ExpressionStatement(parsed.args[i], define);
            if (expr.error instanceof SyntaxError) throw expr.error;
            items.push(expr);
        }
        this.items = items;
    }
}

Outputs or formats and outputs a string

@param {String} args The arguments to the command
@param {Function} define
@constructor


function intoExport(obj) {
    for (var k in obj) {
        if (!obj.hasOwnProperty(k)) continue;
        exports[k] = obj[k];
    }
}

function intoExport ( obj ) { for ( var k in obj ) { if ( ! obj . hasOwnProperty ( k ) ) continue ; exports [ k ] = obj [ k ] ; } }

Copies the properties of an object to the exports

@param {Object} obj The object to copy


function charAt(index) {
    return value => value.length <= index ? undefined : value.charAt(index);
}

function charAt ( index ) { return value => value . length <= index ? undefined : value . charAt ( index ) ; }


function replace(target, replaceWith) {
    function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
    }
    return target instanceof RegExp
        ? value => value.replace(target, replaceWith)
        : replace(new RegExp(escapeRegExp(target), "g"), replaceWith);
}

function
replace
(
target
,
replaceWith
)
{
function
escapeRegExp
(
str
)
{
return
str
.
replace
(
/
[.*+?^${}()|[\]\\]
/
g
,
"\\$&"
)
;
// $& means the whole matched string
}
return
target
instanceof
RegExp
value
=>
value
.
replace
(
target
,
replaceWith
)
:
replace
(
new
RegExp
(
escapeRegExp
(
target
)
,
"g"
)
,
replaceWith
)
;
}

Replace all instances in a string that match a given string or regular expression


function ExpressionStatement(data, define) {
    this.child = parseExpression(data, define ? define.line : 'unknown');

    if (this.child instanceof SyntaxError) throw this.child;
    else if (this.child.error) throw this.child.error;
}

function ExpressionStatement ( data , define ) { this . child = parseExpression ( data , define ? define . line : 'unknown' ) ; if ( this . child instanceof SyntaxError ) throw this . child ; else if ( this . child . error ) throw this . child . error ; }

Represents some form of expression to find a value

@param {String} data The code to parse
@param {Function} define


function cleanLines(block, lines) {
		var removeFirst = false
		if (lines.length && emptyRegex.test(lines[0].str)) {
			block.line += 1
			block.size -= 1
			removeFirst = true
		}

		return lines.filter(function (each, i) {
			return !(!i && removeFirst) && !commentRegex.test(each.str)
		})
	}

function cleanLines ( block , lines ) { var removeFirst = false if ( lines . length && emptyRegex . test ( lines [ 0 ] . str ) ) { block . line += 1 block . size -= 1 removeFirst = true } return lines . filter ( function ( each , i ) { return ! ( ! i && removeFirst ) && ! commentRegex . test ( each . str ) } ) }

Remove first line if empty and remove comment lines
@param {Value} block
@param {Array<{line: number, str: string}>} lines
@returns {Array<{line: number, str: string}>}


function drawAllDataPoints(animationDecimal){
			var rotationDegree = (2*Math.PI)/data.datasets[0].data.length;

			ctx.save();
			//translate to the centre of the canvas.
			ctx.translate(width/2,height/2);

			//We accept multiple data sets for radar charts, so show loop through each set
			for (var i=0; i<data.datasets.length; i++){
				ctx.beginPath();

				ctx.moveTo(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[0],calculatedScale,scaleHop)));
				for (var j=1; j<data.datasets[i].data.length; j++){
					ctx.rotate(rotationDegree);
					ctx.lineTo(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)));

				}
				ctx.closePath();

				ctx.fillStyle = data.datasets[i].fillColor;
				ctx.strokeStyle = data.datasets[i].strokeColor;
				ctx.lineWidth = config.datasetStrokeWidth;
				ctx.fill();
				ctx.stroke();

				if (config.pointDot){
					ctx.fillStyle = data.datasets[i].pointColor;
					ctx.strokeStyle = data.datasets[i].pointStrokeColor;
					ctx.lineWidth = config.pointDotStrokeWidth;
					for (var k=0; k<data.datasets[i].data.length; k++){
						ctx.rotate(rotationDegree);
						ctx.beginPath();
						ctx.arc(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[k],calculatedScale,scaleHop)),config.pointDotRadius,2*Math.PI,false);
						ctx.fill();
						ctx.stroke();
					}

				}
				ctx.rotate(rotationDegree);

			}
			ctx.restore();

		}


function populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue) {
        if (labelTemplateString) {
            //Fix floating point errors by setting to fixed the on the same decimal as the stepValue.
            for (var i = 1; i < numberOfSteps + 1; i++) {
                labels.push(tmpl(labelTemplateString, {value: (graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))}));
            }
        }
    }

Populate an array of all the labels by interpolating the string.

Populate an array of all the labels by interpolating the string .


function(path){
	var xhr=new XMLHttpRequest;
	xhr.open('GET',baseUrl+'web/'+path+'.js', false);
	xhr.send();
	if(xhr.status !== 200) new FatalError(/*#if DEV*/'Unable to load: '+path+'.js'/*#/if*/);
	var s = document.createElement('script');
	s.type = "text/javascript";
	s.text = xhr.responseText;
	document.getElementsByTagName('head')[0].appendChild(s);
}

function
(
path
)
{
var
xhr
=
new
XMLHttpRequest
;
xhr
.
open
(
'GET'
,
baseUrl
+
'web/'
+
path
+
'.js'
,
false
)
;
xhr
.
send
(
)
;
if
(
xhr
.
status
!==
200
)
new
FatalError
(
/*#if DEV*/
'Unable to load: '
+
path
+
'.js'
/*#/if*/
)
;
var
s
=
document
.
createElement
(
'script'
)
;
s
.
type
=
"text/javascript"
;
s
.
text
=
xhr
.
responseText
;
document
.
getElementsByTagName
(
'head'
)
[
0
]
.
appendChild
(
s
)
;
}


function TcolorCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 3) throw new SyntaxError('TCOLOR command requires 3 arguments');
    this.red = parsed.args[0];
    this.green = parsed.args[1];
    this.blue = parsed.args[2];
}

function
TcolorCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
3
)
throw
new
SyntaxError
(
'TCOLOR command requires 3 arguments'
)
;
this
.
red
=
parsed
.
args
[
0
]
;
this
.
green
=
parsed
.
args
[
1
]
;
this
.
blue
=
parsed
.
args
[
2
]
;
}

Sets the color of text

@param {String} args The arguments to the command


function publish(subject, op, target) {
  try {
    var type = (_.isString(target)) ? target : target.type;
    var topic = getTopic(type);
    // optimization: would be nice to tell if there are subscribers before I bother to create
    var event = new Event(subject, op, target);
    provider.publish(topic, event);
  }
  catch (err) {
    logger.error('unable to publish event', err);
  }
}


function ExecutionContext(options) {
    EventEmitter.call(this);

    this.stringVars = {};
    this.numberVars = {};
    this.pointers = {};
    this.gosubs = [];
    this.private = {
        rnd_seed: Math.random(),
        sprites: [],
        data: []
    };
    this.constants = require('./constants');
    this.running = false;
    options = options || {};
    this.options = options;

    if (typeof options.delay === 'undefined') options.delay = false;

    // Copy all functions as constants
    for (var k in functions) {
        if (!functions.hasOwnProperty(k)) continue;
        this.constants[k] = functions[k];
    }

    // Stop multiple contexts conflicting with constants
    this.constants = pUtil.shallowClone(this.constants);
}

An object that provides modification and reading of the current execution
context, as well as the ability to execute an AST in the context

@param {Object?} options Options for execution
@constructor

An object that provides modification and reading of the current execution context as well as the ability to execute an AST in the context


function setArrayIndexAt(arr, dimensions, val, data) {
    var currentDimension = dimensions[0].execute(data);
    data.validate(currentDimension, 'number');
    currentDimension -= 1;
    if (currentDimension < 0) currentDimension = 0;

    if (arr.length <= currentDimension) throw new Error('Invalid array bounds');
    var item = arr[currentDimension];
    if (dimensions.length > 1) {
        if (!Array.isArray(item)) throw new Error('Invalid array dimensions');
        return setArrayIndexAt(arr[currentDimension], dimensions.slice(1), val,  data);
    } else arr[currentDimension] = val;
}

function
setArrayIndexAt
(
arr
,
dimensions
,
val
,
data
)
{
var
currentDimension
=
dimensions
[
0
]
.
execute
(
data
)
;
data
.
validate
(
currentDimension
,
'number'
)
;
currentDimension
-=
1
;
if
(
currentDimension
<
0
)
currentDimension
=
0
;
if
(
arr
.
length
<=
currentDimension
)
throw
new
Error
(
'Invalid array bounds'
)
;
var
item
=
arr
[
currentDimension
]
;
if
(
dimensions
.
length
>
1
)
{
if
(
!
Array
.
isArray
(
item
)
)
throw
new
Error
(
'Invalid array dimensions'
)
;
return
setArrayIndexAt
(
arr
[
currentDimension
]
,
dimensions
.
slice
(
1
)
,
val
,
data
)
;
}
else
arr
[
currentDimension
]
=
val
;
}

Sets the array item at a certain index, including multiple dimensions

@param {Array} arr The array to search
@param {Array<ExpressionStatement>} dimensions An array of indexes
@param {String|Number} val The value to put in the array
@param {ExecutionContext} data The execution data context
@private

Sets the array item at a certain index including multiple dimensions