Input: If given key is set in the object it returns the associated value otherwise it sets the value to val and returns it . [CODESPLIT] function setDefault ( obj , key , val ) { if ( _ . isUndefined ( obj [ key ] ) ) { obj [ key ] = val ; return val ; } return obj [ key ] ; }


Input: Read and Parse XML file from given path pass result to finish Any error that occurs is simpy thrown . [CODESPLIT] function getXml ( path , finish ) { fs . readFile ( path , function ( err , data ) { if ( err ) throw err ; xmlParser . parseString ( data , function ( err , result ) { if ( err ) throw err ; finish ( result ) ; } ) ; } ) ; }


Input: Convert a pair of key / value to an array if the value is true only the key is kept Example : toParameter ( lineBreak 2 ) // = > [ -- line - break 2 ] toParameter ( preserveComments true ) // = > [ -- preserve - comments ] [CODESPLIT] function toParameter ( val , key ) { var str = '--' + key . replace ( / ([A-Z]) / g , function ( a ) { return '-' + a . toLowerCase ( ) ; } ) ; return ( val === true ) ? [ str ] : [ str , val ] ; }


Input: hookIt ( authorize proto . authorize ) ; [CODESPLIT] function injectDependencies ( func , args , callback ) { var declaredArguments = toolbox . parseDeclaredArguments ( func ) ; declaredArguments = declaredArguments . replace ( / \s+ / g , "" ) . split ( "," ) ; logger . trace ( "injectDependencies() declaredArguments: " , declaredArguments , "provided args:" , args ) ; var useCallback = false ; var len = args . length > declaredArguments . length ? args . length : declaredArguments . length ; for ( var i = 0 ; i < len ; i ++ ) { // this is problematic: functions may be wrapped and lost the arguments data /** if client did not provide enough number of arguments, we fill it with null*/ if ( typeof ( args [ i ] ) == 'undefined' ) args [ i ] = undefined ; else if ( args [ i ] === "$callback" ) { useCallback = true ; args [ i ] = callback ; } switch ( declaredArguments [ i ] ) { case '$callback' : logger . debug ( "Injecting callback handler" ) ; args [ i ] = callback ; useCallback = true ; break ; case '$context' : logger . debug ( "Injecting angoose context" ) ; args [ i ] = angoose ( ) . getContext ( ) ; break ; default : break ; } } return useCallback ; }


Input: append angoose - ui sources [CODESPLIT] function appendUISource ( client ) { angoose . getLogger ( 'angoose' ) . debug ( "Appending angoose-ui sources" ) ; //    client.source += " \n;console.log('####################----------- angoose-ui -----------##############');\n"; var output = "" ; output += readFile ( path . resolve ( __dirname , 'angular-modules.js' ) ) ; output += concatFilesInDirectory ( [ 'services' , 'controllers' , 'directives' , 'filters' ] ) ; //'directives', output += concatTemplates ( ) ; client . source += "\n\n" + output ; }


Input: Show an error [CODESPLIT] function error ( msg , addHint ) { console . log ( '\x1b[31m' ) ; console . log ( 'The compiler has stopped on an error' ) console . log ( ` \x1b ${ msg } \x1b ` ) ; if ( addHint ) console . log ( ` \n ` ) ; process . exit ( 1 ) ; }


Input:
compile the model based on the server side schema [CODESPLIT] function compile ( modelName , schema , dependencies ) { logger . trace ( "Compiling schema " , modelName ) var model = function AngooseModule ( data ) { //@todo proper clone for ( var i in data ) { this [ i ] = data [ i ] ; } } ; model . toString = function ( ) { return "PROXY: function " + modelName + "()" ; } // static methods for ( var name in schema . statics ) { model [ name ] = createProxy ( model , name , schema . statics [ name ] , 'static' ) ; } for ( var name in schema . methods ) { model . prototype [ name ] = createProxy ( model , name , schema . methods [ name ] , 'instance' ) ; } //model.angoose$ = staticInvoker; model . dependencies$ = dependencies ; model . schema = schema ; //model.prototype.angoose$ = instanceInvoker; //model.prototype.classname$ = modelName; //model.prototype.schema$ = schema; model . prototype . get = getter ; model . prototype . set = setter ; model . modelName = modelName ; // this is to be compatible with backend mongoose
 model . name = modelName ; // merge data into this instance model . prototype . mergeData = function ( source ) { if ( typeof source != "object" ) throw "Invalid source object, must be an model instance" ; //@todo: proper implementation for ( var i in source ) { this [ i ] = source [ i ] ; } } AngooseClient . models = AngooseClient . models || { } ; AngooseClient . models [ modelName ] = model ; return model ; }


Input: Loop through all the top level props [CODESPLIT] function addProps ( props , options ) { if ( ! props ) return '## No props' const keys = Object . keys ( props ) . filter ( key => filterProps ( key , props [ key ] , options ) , ) const filteredProps = keys . reduce ( ( last , key ) => ( { ... last , [ key ] : props [ key ] } ) , { } , ) let output = '\n## Props\n' let isFlow = false const items = [ TABLE_HEADERS , ... keys . map ( key => { const prop = filteredProps [ key ] if ( isFlowType ( prop ) ) isFlow = true const row = [ isFlowType ( prop ) ? key : getKey ( key , getType ( prop ) ) , getTypeName ( getType ( prop ) ) , getDefaultValue ( prop ) , prop . required , prop . description , ] return row . map ( rowValue => { if ( typeof rowValue === 'string' ) { return rowValue . split ( '\n' ) . join ( '<br>' ) } return rowValue } ) } ) , ] output += ` ${ table ( items ) } \n ` // Add subtypes if ( ! isFlow ) { const subTypes = describeSubTypes ( filteredProps ) if ( subTypes . length ) { output += '\n## Complex Props\n' output += subTypes } } return output }


Input: Debounces a function . Returns a function that calls the original fn function only if no invocations have been made within the last quietMillis milliseconds . [CODESPLIT] function debounce ( quietMillis , fn , ctx ) { ctx = ctx || undefined ; var timeout ; return function ( ) { var args = arguments ; clearTimeout ( timeout ) ; timeout = setTimeout ( function ( ) { fn . apply ( ctx , args ) ; } , quietMillis ) ; } ; }


Input: Workaround for Q module with CLS [CODESPLIT] function matroshka ( fn ) { var babushka = fn ; Object . keys ( process . namespaces ) . forEach ( function ( name ) { babushka = process . namespaces [ name ] . bind ( babushka ) ; } ) ; return babushka ; }


Input: end directiveFunc get a list of fields with a specific tag [CODESPLIT] function findTagged ( modelClass , tag ) { if ( ! modelClass || ! modelClass . schema ) return [ ] ; var cols = [ ] ; Object . keys ( modelClass . schema . paths ) . forEach ( function ( path ) { var data = modelClass . schema . paths [ path ] ; if ( data . options . tags && data . options . tags . indexOf ( tag ) >= 0 ) cols . push ( data ) ; } ) ; return cols ; }


Input: scope wrapper [CODESPLIT] function enterscope ( scope , name , arg1 ) { angoose . logger . trace ( "Entering scope " , name , scope . $id , arg1 ) window [ 'scope' + scope . $id ] = scope ; }


Input: end invoke [CODESPLIT] function postPack ( next , invocation ) { //console.log("In mongoose post pack", invocation) if ( ! invocation . redacted ) return next ( ) ; var type = getValueType ( invocation . redacted ) ; if ( type ) invocation . packed . datatype = type ; next ( ) ; }


Input: Emit an error [CODESPLIT] function error ( msg ) { if ( exports . error ) exports . error ( msg ) ; else console . log ( 'Error: ' + msg ) ; }


Input: Call a command [CODESPLIT] function call ( name , isLong ) { var obj = isLong ? long [ name ] : short [ name ] ; if ( ! obj ) return error ( ` ${ name } ` ) ; if ( n + obj . length > count ) return error ( ` ${ name } ` ) ; var arr = process . argv . slice ( n , n + obj . length ) ; n += obj . length ; obj . callback ( arr ) ; }


Input: ** extend ** This static method is used to create Angoose model or service classes . All classes created using this method is a subclass of Remotable [CODESPLIT] function extend ( target , options ) { options = options || { } ; var parentClass = this ; logger . trace ( "Extending from " , parentClass . _angoosemeta . name , options ) ; var rv = null ; if ( typeof ( target ) == 'function' ) { rv = target ; mixinInstance ( parentClass , rv , options ) ; /**@todo: temp hack */ bindMongooseMethods ( rv ) ; } else { /** schema object */ rv = parentClass . $extend ( target ) ; } /** mixin Angoose class level functions */ rv = mixinStatic ( parentClass , rv , options ) ; if ( rv . _angoosemeta . name ) { /**  register it with Angoose */ //require("./angoose").registerClass(rv._angoosemeta.name, rv); } return rv ; }


Input: synchronous hooks [CODESPLIT] function addHook ( loc , method , func ) { var tmp = hooks [ loc ] [ method ] ; logger . debug ( "ADdding bundle hook to" , loc , method , tmp ) ; if ( ! tmp ) return false ; tmp . push ( func ) ; return true ; }


Input: Find the input element in the template . It will be one of input select or textarea . We need to ensure it is wrapped in jqLite \ jQuery [CODESPLIT] function findInputElement ( templateElement ) { return angular . element ( templateElement . find ( 'input' ) [ 0 ] || templateElement . find ( 'select' ) [ 0 ] || templateElement . find ( 'textarea' ) [ 0 ] ) ; }


Input: Search through the originalDirective s element for elements that contain information about how to map validation keys to messages [CODESPLIT] function getValidationMessageMap ( originalElement ) { // Find all the <validator> child elements and extract their (key, message) info var validationMessages = { } ; angular . forEach ( originalElement . find ( 'validator' ) , function ( element ) { // Wrap the element in jqLite/jQuery element = angular . element ( element ) ; // Store the message info to be provided to the scope later // The content of the validation element may include interpolation {{}} // so we will actually store a function created by the $interpolate service // To get the interpolated message we will call this function with the scope. e.g. //   var messageString = getMessage(scope); validationMessages [ element . attr ( 'key' ) ] = $interpolate ( element . text ( ) ) ; } ) ; return validationMessages ; }


Input: - list of sub schemas : deform - sublist - single subschema object : deform - subschema [CODESPLIT] function mapDirective ( path , pathSchema , modelSchema , itemIndex ) { if ( itemIndex !== undefined ) return null ; // we're in a array if ( pathSchema && pathSchema . options && Array . isArray ( pathSchema . options . type ) ) { if ( pathSchema . schema ) return "deform-sublist" if ( pathSchema . caster && ( ! pathSchema . caster . options || ! pathSchema . caster . options . ref ) ) { // !pathSchema.options.ref filters out CustomRef, ugly! /** array of simple types */ //console.log("Simple array type!!!",pathSchema, pathSchema.options.ref, pathSchema.options.type); return "ang-array" } } else if ( pathSchema . schema ) return "deform-subschema" return null ; }


Input: ** mapTemplate ** Default mapping for Mongoose schema type - > form field - ObjectID : selector - Boolean : Checkbox - String : input - Number : input - Date : ? - Array of simple types : selector multi - Array of ref objects : selector multi - String / Number with enum values : Select - Mixed : ?? [CODESPLIT] function mapTemplate ( path , pathSchema , modelSchema ) { if ( pathSchema . options . template ) return pathSchema . options . template ; if ( pathSchema . options . multiline ) return "textarea" var template = 'input' ; var opts = pathSchema . options || { } ; //@todo: refactor them into subclasses switch ( pathSchema . instance || ( pathSchema . options && pathSchema . options . type ) ) { case 'ObjetcID' : if ( opts . ref ) template = 'selector' ; break ; case 'Boolean' : template = 'checkbox' ; break ; case 'Date' : case 'String' : case 'Number' : default : break ; } if ( getRef ( pathSchema ) ) template = "selector" ; if ( Array . isArray ( opts [ 'enum' ] ) && opts [ 'enum' ] . length > 0 ) { template = "select" ; } if ( Array . isArray ( opts . type ) ) { if ( pathSchema . caster ) { /** array of simple types */ // console.log("Simple types", pathSchema) } } angoose . logger . trace ( "Path " , path , " Type " , pathSchema , " template: " , template ) return template ; }


Input: ** init ( app options ) ** Initialize Angoose . This function should be called in the express app * [CODESPLIT] function init ( app , conf , force ) { if ( this . initialized && ! force ) return ; //beans = {}; /** configurations*/ initialConfig ( conf ) ; logger . info ( "Angoose Initialization Start" ) ; logger . trace ( "Init options:" , conf ) ; /** connect to Mongo if necessary */ connectMongo ( options ) ; /** register initial hooks */ //registerHooks();         /** pre-load models/services from directories */ harvestModules ( options ) ; /** plugin extensions */ hookupExtensions ( ) ; /** build client side schemas */ generateClient ( ) ; /** configure the routes for handling RMI and client loading*/ /**@todo: middleware*/ configureRoutes ( app , options ) ; logger . info ( "Angoose Initialization Complete" ) ; }


Input: ** module ( name function_or_object ) ** Retrieve an Angoose module or register one If only one argument name is provided returns the registered module with that name . This form is same as angoose . getClass () If two arguments are provided register the function / object as Angular module under that name . [CODESPLIT] function lookupOrRegister ( name , target ) { if ( arguments . length == 0 ) return null ; if ( arguments . length == 1 ) return getClass ( name ) ; if ( arguments . length == 2 ) return registerClass ( name , target ) ; }


Input: register module with angoose so it knows to publish it [CODESPLIT] function registerClass ( nameOrOpts , claz ) { var opts = typeof ( nameOrOpts ) == 'object' ? nameOrOpts : { name : nameOrOpts } ; var className = opts . name ; if ( ! className ) throw "Missing module name: " + className if ( beans [ className ] ) logger . warn ( "Overriding existing bean: " , className ) ; if ( claz . _angoosemeta && ( claz . _angoosemeta . baseClass == 'Service' || claz . _angoosemeta . baseClass == 'Model' ) ) { // already mixed } else { if ( typeof ( claz ) === 'function' && claz . schema && claz . modelName ) opts . baseClass = 'Model' ; else if ( claz instanceof getMongoose ( ) . Schema ) { opts . baseClass = 'Model' ; claz = getMongoose ( ) . model ( className , claz ) ; } else opts . baseClass = 'Service' ; angoose . Remotable . mixin ( opts , claz ) ; } _ . extend ( claz . _angoosemeta , nameOrOpts ) ; beans [ className ] = claz ; //if(!nameOrOpts.isExtension) logger . debug ( "Registered module" , claz . _angoosemeta . baseClass , className ) ; return claz ; // if(claz._angoosemeta && (claz._angoosemeta.baseClass == 'Service' || claz._angoosemeta.baseClass == 'Model') ){ //          // } // else{ // throw "Invalid class: must be a Model or Service class: " + claz; // } }


Input: ** getContext () ** Returns the current execution context . This methods returns a Context object which allows you to get a reference to the current request object and / or login user s Principal object . If the callee isn t inside Angoose execution context an error will be thrown . See [ Context ] ( Context . html ) for more . [CODESPLIT] function getContext ( ) { if ( ! domain . active || ! domain . active . context ) { if ( this . mockContext ) return this . mockContext logger . error ( "getContext called but no active domain" , domain . active ) ; logger . error ( "Caller is " , arguments . callee && arguments . callee . caller && arguments . callee . caller . name , arguments . callee && arguments . callee . caller ) ; throw "Context not available. This may happen if the code was not originated by Angoose" ; } return domain . active . context ; }


Input: sample model [CODESPLIT] function scanDir ( dirname ) { if ( ! dirname || dirname . indexOf ( "node_modules" ) >= 0 ) return ; logger . debug ( "Scanning directory for modules: " , dirname ) ; if ( fs . existsSync ( path . resolve ( dirname , 'index.js' ) ) ) { files . push ( path . resolve ( dirname , 'index.js' ) ) ; return ; } fs . readdirSync ( dirname ) . forEach ( function ( file ) { var fullpath = path . resolve ( dirname , file ) ; if ( ! fs . statSync ( fullpath ) . isFile ( ) ) scanDir ( fullpath ) ; else if ( file . match ( / .+\.js / g ) !== null ) { files . push ( fullpath ) ; } } ) ; }


Input: ** geneateClient () ** Generates the client file to be served as the contents of resource / angoose / angoose - client . js [CODESPLIT] function generateClient ( ) { logger . debug ( "Generating angoose client file: " ) ; var bundle = new Bundle ( ) ; var client = { } ; bundle . generateClient ( client ) ; var filename = angoose . config ( ) [ 'client-file' ] ; writeToFile ( filename , client . source ) //compressFile(filename, client.source); logger . info ( "Generated  angoose client file: " , filename ) ; return client . source ; }


Input: Set or get configurations . [CODESPLIT] function config ( path , val ) { if ( ! path ) return options ; /**@todo: probably a deep copy */ if ( ! angoose . initialized && typeof ( path ) == 'string' ) throw "Cannot call config(" + path + ") before angoose is intialized" ; //if(angoose.initialized && typeof(conf) == 'object') throw "Cannot config Angoose after startup"; if ( typeof ( path ) === 'string' ) { if ( val === undefined ) return toolbox . getter ( options , path ) ; toolbox . setter ( options , path , val ) ; } if ( typeof ( path ) === 'object' ) { // deep merge options = toolbox . merge ( options , path ) ; } }


Input: Creates a connection to the given url . [CODESPLIT] function connect ( url , next ) { log ( 'connecting to %s' , url ) ; mongo . Db . connect ( url , { db : { w : 1 } } , next ) ; }


Input: Starts up a shell with the given context . [CODESPLIT] function startShell ( db , program , files ) { var repl = global . repl = term ( db ) ; createContext ( db , repl , function ( ) { var code = program . eval ; if ( code ) { executeJS ( code ) ; if ( ! program . shell ) { repl . emit ( 'exit' ) ; return ; } } if ( files . length ) { executeFiles ( files ) ; printCloseMsg ( ) ; } repl . prompt = prompt ; repl . displayPrompt ( ) } ) ; }


Input: Execute the given files in the context shared with the shell when started . [CODESPLIT] function executeFiles ( files ) { var dir = process . cwd ( ) ; files . forEach ( function ( file ) { require ( dir + '/' + file ) ; } ) ; }


Input: Executes javascript passed by -- eval [CODESPLIT] function executeJS ( script ) { if ( ! script ) return ; try { var ret = vm . runInThisContext ( script , '[eval]' ) ; if ( 'undefined' != typeof ret ) { console . log ( ret ) ; } } catch ( err ) { if ( ! ( err instanceof Error ) ) { err = new Error ( err ) ; } console . log ( err . stack . split ( '\n' ) [ 0 ] ) ; process . exit ( 1 ) ; } }


Input: / * :: const callAssign = { call ( thisFn : any arg : string ) { [CODESPLIT] function ErrorFunction ( message : string ) { const Err = /*::Object.assign({}, callAssign, */ Error /*::)*/ Err . call ( this , message ) if ( noFallback ) { Error . captureStackTrace ( this , ErrorFunction ) } else { this . stack = ( new Error ( ) ) . stack } this . name = this . constructor . name this . message = message }


Input:
We create DB constructors dynamically to avoid assigning the db or collections directly to the database instance thereby avoiding them displaying in autocomplete mixed together with the collection names . [CODESPLIT] function createConstructor ( db ) { var collections = [ ] ; function DB ( ) { this . cols ( false , noop ) ; } /**
   * Logs help text for all db methods
   */ ; ( DB . prototype . help = function ( ) { var proto = this . constructor . prototype ; var len = 0 ; var msgs = [ ] ; Object . keys ( proto ) . forEach ( function ( method ) { if ( proto [ method ] . help ) { var msg = proto [ method ] . help ( true ) ; len = Math . max ( len , method . length ) ; msgs . push ( { method : method , text : msg } ) } } ) msgs . sort ( function ( a , b ) { return a . method > b . method ? 1 : a . method < b . method ? - 1 : 0 } ) msgs . forEach ( function ( msg ) { var space = Array ( len - msg . method . length + 1 ) . join ( ' ' ) ; log ( "db." + msg . method + "() " + space + msg . text ) ; } ) } ) . help = help ( "Logs help text for all db methods" ) ; /**
   * Drop this database
   *
   * @param {Function} [cb]
   */ ; ( DB . prototype . drop = function ( cb ) { var name = db . databaseName ; db . dropDatabase ( cb || function ( err ) { if ( err ) { return console . error ( err ) ; } db . collections ( function ( ) { log ( 'database "%s" was dropped' , name ) ; } ) ; } ) ; } ) . help = help ( "Drops the database" ) ; wrap ( DB . prototype , 'drop' ) ; /**
   * Close this database connection
   *
   * @param {Function} [cb]
   */ ; ( DB . prototype . close = function ( cb ) { if ( 'function' != typeof cb ) { cb = handleError ; } db . close ( true , cb ) ; } ) . help = help ( "Closes the database connection" ) ; wrap ( DB . prototype , 'close' ) ; /**
   * Open the database connection
   *
   * @param {Function} [cb]
   */ ; ( DB . prototype . open = function ( cb ) { db . open ( function ( err ) { if ( err ) { return handleError ( err , cb ) ; } if ( 'function' == typeof cb ) { cb ( ) ; } } ) ; } ) . help = help ( "Opens the database connection" ) wrap ( DB . prototype , 'open' ) ; /**
   * Use a different database
   */ ; ( DB . prototype . use = function ( name ) { return create ( db . db ( name ) ) ; } ) . help = help ( "Changes to a different database" ) /**
   * Access a collection
   */ ; ( DB . prototype . col = function ( name , opts ) { if ( this [ name ] ) { return this [ name ] ; } // accessor management collections . push ( name ) ; return this [ name ] = db . collection ( name , opts ) ; } ) . help = help ( "Accesses a collection" ) /**
   * Creates a collection
   *
   * @param {String} name
   * @param {Object} [options]
   * @param {Function} [cb]
   */ ; ( DB . prototype . createCol = function ( name , opts , cb ) { if ( 'function' == typeof opts ) { cb = opts ; opts = { } ; } if ( 'string' != typeof name ) { error ( new TypeError ( 'collection name must be a string' ) ) ; return ; } if ( ! opts ) opts = { } ; // force error if collection exists if ( ! ( 'strict' in opts ) ) opts . strict = true ; var self = this ; db . createCollection ( name , opts , function ( err , col ) { if ( err ) { if ( / already exists / . test ( err ) ) { // remove the "safe mode" message err . message = 'collection "' + name + '" already exists' ; } return handleError ( err ) ; } // register name for accessor management collections . push ( name ) ; return self [ name ] = col ; } ) ; } ) . help = help ( "Creates a collection" ) wrap ( DB . prototype , 'createCol' ) ; /**
   * Refresh and return the list of collections on this database
   *
   * @param {Boolean} [print] if the collection names should be printed
   * @param {Function} [cb] passed any error and the result array
   */ ; ( DB . prototype . cols = function ( print , cb ) { var self = this ; if ( 'function' == typeof print ) { cb = print ; print = false ; } if ( undefined == print ) print = true db . collectionNames ( { namesOnly : true } , function ( err , names ) { if ( err ) { if ( cb ) return cb ( err ) ; console . error ( err . stack ) ; return ; } if ( ! Array . isArray ( names ) ) { names = [ ] ; } // remove cached collections collections . forEach ( function ( name ) { delete self [ name ] ; } ) ; // strip db from name var ns = db . databaseName ; var len = ns . length + 1 ; names = names . map ( function ( name ) { return name . substring ( len ) ; } ) ; collections = names ; // expose collection access from `db` // TODO abstract collection names . forEach ( function ( name ) { self [ name ] = db . collection ( name ) ; // handle system.indexes etc if ( / \. / . test ( name ) ) { var parts = name . split ( '.' ) ; parts . reduce ( function ( out , part , i ) { if ( i == parts . length - 1 ) { out [ part ] = self [ name ] ; } else { if ( ! out [ part ] ) { out [ part ] = { } ; } } return out [ part ] ; } , self ) ; } } ) ; if ( cb ) return cb ( err , names ) ; if ( print ) { console . log ( ) ; names . forEach ( function ( name ) { log ( name ) ; } ) global . repl . displayPrompt ( ) ; } } ) ; } ) . help = help ( "Retreives an array of collection names in the db" ) wrap ( DB . prototype , 'cols' ) ; /**
   * Execute a command on the database
   *
   * @param {Object} cmd
   * @param {Object} [opts]
   * @param {Function} [cb]
   */ ; ( DB . prototype . runCommand = function ( cmd , opts , cb ) { if ( 'function' == typeof opts ) { cb = opts ; opts = { } ; } if ( ! cmd ) { var err = new Error ( 'missing command' ) ; if ( cb ) return cb ( err ) ; console . error ( err ) ; return ; } if ( ! cb ) cb = p ; if ( ! opts ) opts = { } ; var admin = ! ! opts . admin ; delete opts . admin ; var method = admin ? 'executeDbAdminCommand' : 'executeDbCommand' db [ method ] ( cmd , opts , cb ) ; } ) . help = help ( "Runs a command on the database" ) wrap ( DB . prototype , 'runCommand' ) ; /**
   * Retreive database stats
   */ ; ( DB . prototype . stats = function ( scale , cb ) { if ( 'function' == typeof scale ) cb = scale ; scale |= 0 ; db . stats ( function ( err , stats ) { cb ( err , stats ) ; } ) } ) . help = help ( 'Retreive database stats' ) ; wrap ( DB . prototype , 'stats' ) ; /**
   * console.log helper
   */ ; ( DB . prototype . inspect = function ( ) { return db . databaseName ; } ) . help = help ( "Returns the name of the database" ) ; return DB ; }


Input: Wrap async functions with animation etc [CODESPLIT] function wrap ( proto , name ) { var old = proto [ name ] ; proto [ name ] = function ( ) { if ( global . repl ) global . repl . bufferStart ( ) ; var args = slice ( arguments ) ; var last = args [ args . length - 1 ] ; if ( 'function' == typeof last ) { args [ args . length - 1 ] = function ( ) { if ( global . repl ) global . repl . bufferEnd ( ) if ( p != last ) console . log ( ) ; last . apply ( null , arguments ) if ( global . repl ) { global . repl . displayPrompt ( ) ; global . repl . moveCursorToEnd ( ) ; } } } else { args . push ( function ( ) { if ( global . repl ) global . repl . bufferEnd ( ) p . apply ( null , arguments ) ; if ( global . repl ) global . repl . moveCursorToEnd ( ) ; } ) ; } old . apply ( this , args ) ; } if ( old . help ) { proto [ name ] . help = old . help ; } }


Input: Error reporting helper [CODESPLIT] function handleError ( err , cb ) { if ( err ) { if ( cb ) { return process . nextTick ( function ( ) { cb ( err ) ; } ) ; } console . error ( err ) ; } }


Input: Display values in a table . [CODESPLIT] function tablature ( conf ) { const { keys = [ ] , data = [ ] , headings = { } , replacements = { } , centerValues = [ ] , centerHeadings = [ ] , } = conf const [ i ] = data if ( ! i ) return '' const cv = makeBinaryHash ( centerValues ) const hv = makeBinaryHash ( centerHeadings ) const k = Object . keys ( i ) . reduce ( ( acc , key ) => { const h = headings [ key ] return { ... acc , [ key ] : h ? h . length : key . length , // initialise with titles lengths } } , { } ) const widths = data . reduce ( ( dac , d ) => { const res = Object . keys ( d ) . reduce ( ( acc , key ) => { const maxLength = dac [ key ] const val = d [ key ] const r = getReplacement ( replacements , key ) const { length } = r ( val ) return { ... acc , [ key ] : Math . max ( length , maxLength ) , } } , { } ) return res } , k ) const kk = keys . reduce ( ( acc , key ) => { const h = headings [ key ] return { ... acc , [ key ] : h || key , } } , { } ) const hr = keys . reduce ( ( acc , key ) => { return { ... acc , [ key ] : heading , } } , { } ) const hl = getLine ( keys , kk , widths , hr , hv ) const rl = data . map ( ( row ) => { const line = getLine ( keys , row , widths , replacements , cv ) return line } ) return [ hl , ... rl , ] . join ( '\n' ) }


Input: Add Test : Add proper test to ensure the format of the metric mocking logger was giving troubles [CODESPLIT] function metric ( name , val , message ) { // val is not a NaN should log the metric if ( isNaN ( val ) ) { return message ; } var metadata = _ . pick ( message , [ 'type' , 'rid' , 'address' , 'status' , 'client' , 'clientId' , 'transaction' ] ) ; metadata [ 'micrometric' ] = { name : name , value : val } log . info ( metadata , 'Publishing metric "%s":%sms' , name , val ) ; return metadata ; }


Input: ============================================================================== -- constructor [CODESPLIT] function StdError ( message ) { if ( ! ( this instanceof StdError ) ) { return new StdError ( message ) ; } Error . captureStackTrace ( this , this . constructor ) ; this . code = this . _defaults . code ; this . name = this . _defaults . name ; this . message = this . _defaults . message ; switch ( typeof ( message ) ) { case "string" : this . message = message ; break ; case "object" : ( message . code ) && ( this . code = message . code ) ; ( message . name ) && ( this . name = message . name ) ; ( message . message ) && ( this . message = message . message ) ; break ; } }


Input: -- constructor [CODESPLIT] function ( ) { var args = Array . prototype . slice . call ( arguments ) ; if ( ! ( this instanceof child ) ) { var obj = Object . create ( child . prototype ) ; child . apply ( obj , args ) ; return obj ; } self . apply ( this , args ) ; }


Input: console . log ( pathPart pathPart ) ; [CODESPLIT] function sanatize ( str ) { return str . replace ( / \.\w+$ / , '' ) // remove .html . replace ( / %[\dA-Z]+ / g , '' ) // remove %20 . replace ( / \ban?\b / g , '' ) // ignore a/an . replace ( / \bthe\b / g , '' ) // ignore the . replace ( / \bof\b / g , '' ) // ignore of . replace ( / [^a-z0-9] / g , '' ) // remove non-alphanumerics ; }


Input: console . log ( fixRedir request . url ) ; [CODESPLIT] function fixRedirectPost ( ) { // Permament Redirect response . statusCode = 301 ; response . setHeader ( 'Location' , path . normalize ( servepath + '/' + permalinkify ( request . query . blogger ) ) ) ; response . end ( ) ; }


Input: Returns a lodash chain that calls . value () automatically after the first . method () It also returns a promise or value For example : lowChain ( _ array save ) . method () is the same as : _ . chain ( array ) . method () . value () [CODESPLIT] function lowChain ( _ , array , save ) { var chain = _ . chain ( array ) ; _ . functionsIn ( chain ) . forEach ( function ( method ) { chain [ method ] = _ . flow ( chain [ method ] , function ( arg ) { var v = void 0 ; if ( arg ) { v = _ . isFunction ( arg . value ) ? arg . value ( ) : arg ; } var s = save ( ) ; if ( s ) return s . then ( function ( ) { return Promise . resolve ( v ) ; } ) ; return v ; } ) ; } ) ; return chain ; }


Input: Return a promise or nothing in sync mode or if the database hasn t changed [CODESPLIT] function _save ( ) { if ( db . source && db . write && writeOnChange ) { var str = JSON . stringify ( db . object ) ; if ( str !== db . _checksum ) { db . _checksum = str ; return db . write ( db . source , db . object ) ; } } }


Input: The Picklr object . [CODESPLIT] function Picklr ( startDir , options ) { options = options || { } ; let defaultExcludeDirsRe ; if ( / ^\. / . test ( startDir ) ) { defaultExcludeDirsRe = / \/\.|node_modules / i ; } else { defaultExcludeDirsRe = / ^\.|\/\.|node_modules / i ; } this . totalFileCount = 0 ; this . matchedFileCount = 0 ; this . startDir = startDir || '.' ; this . targetText = options . targetText || '' ; this . replacementText = options . replacementText || '' ; this . action = options . action || 'echo' ; this . includeExts = options . includeExts || [ '.js' ] ; this . excludeDirs = options . excludeDirsRe || defaultExcludeDirsRe ; this . logger = options . logger || console . log ; this . picklrActions = picklrActions ; }


Input: Recursively process files . [CODESPLIT] function ( p ) { fs . readdirSync ( p ) . forEach ( function ( file ) { const curPath = path . join ( p , path . sep , file ) ; const stats = fs . statSync ( curPath ) ; if ( this . isDirectory ( stats , curPath ) ) { this . recurseFiles ( curPath ) ; } else if ( this . isFile ( stats , curPath ) ) { this . picklrActions [ this . action ] . call ( this , curPath ) ; } } , this ) ; if ( p === this . startDir ) { this . logger ( 'Total file count = ' + this . totalFileCount ) ; if ( this . action !== 'echo' ) { this . logger ( 'Matched file count = ' + this . matchedFileCount ) ; } } }


Input: File type determination . [CODESPLIT] function ( stats , p ) { let result = stats . isFile ( ) ; if ( result ) { const ext = path . extname ( p ) ; result = this . includeExts . indexOf ( ext ) !== - 1 ; } return result ; }


Input: Directory type determination . [CODESPLIT] function ( stats , p ) { let result = stats . isDirectory ( ) ; if ( result ) { result = ! this . excludeDirs . test ( p ) ; } return result ; }


Input: Process all files under startDir using options . [CODESPLIT] function processAllFiles ( startDir , options ) { const picklr = new Picklr ( startDir , options ) ; picklr . recurseFiles ( startDir ) ; }


Input: Does the actual audit or update of a single file . [CODESPLIT] function processFile ( filePath , update ) { let change , found = false ; const lines = fs . readFileSync ( filePath , { encoding : 'utf8' } ) . split ( '\n' ) ; for ( let i = 0 ; i < lines . length ; i ++ ) { if ( lines [ i ] . indexOf ( this . targetText ) !== - 1 ) { found = true ; change = lines [ i ] . replace ( this . targetText , this . replacementText ) ; if ( update ) { lines [ i ] = change ; } else { // log the line that would be edited. this . logger ( '*** File:   ' + filePath ) ; this . logger ( '@@@ Found:  ' + lines [ i ] ) ; this . logger ( '--- Change: ' + change ) ; } this . matchedFileCount ++ ; break ; } } if ( ! found && ! update ) { // log the file that would be omitted this . logger ( '*** Omitted: ' + filePath ) ; } if ( found && update ) { fs . writeFileSync ( filePath , lines . join ( '\n' ) , { encoding : 'utf8' } ) ; // log the updated file this . logger ( '@@@ Updated: ' + filePath ) ; } this . totalFileCount ++ ; }


Input: Private ---------------------------------------------------------------------------- [CODESPLIT] function extractEncoding ( headers ) { var type = headers [ "content-type" ] ; if ( ! type ) { return "utf8" ; } var split = type . split ( '=' ) ; return split . length == 2 ? split [ 1 ] : "utf8" ; }


Input: Extracts parts of a string beginning at the character at the specified position and returns the specified number of characters . The substr () does not change the original string . [CODESPLIT] function substr ( string , start , length ) { if ( ! isString ( string ) ) { return string ; } return string . substr ( start , length ) ; }


Input: Initialize an HTTP server [CODESPLIT] async function initHTTPServer ( { ENV = { } , HOST = '127.0.0.1' , PORT = 8080 , MAX_HEADERS_COUNT = 800 , KEEP_ALIVE_TIMEOUT = ms ( '5m' ) , TIMEOUT = ms ( '2m' ) , MAX_CONNECTIONS , httpRouter , log = noop , } ) { const sockets = ENV . DESTROY_SOCKETS ? new Set ( ) : { } . undef ; const httpServer = http . createServer ( httpRouter ) ; const listenPromise = new Promise ( resolve => { httpServer . listen ( PORT , HOST , ( ) => { log ( 'info' , ` ${ HOST } ${ PORT } ` ) ; resolve ( httpServer ) ; } ) ; } ) ; const errorPromise = new Promise ( ( resolve , reject ) => { httpServer . once ( 'error' , reject ) ; } ) ; httpServer . timeout = TIMEOUT ; httpServer . keepAliveTimeout = KEEP_ALIVE_TIMEOUT ; httpServer . maxHeadersCount = MAX_HEADERS_COUNT ; httpServer . maxConnections = MAX_CONNECTIONS ; if ( 'undefined' !== typeof MAX_CONNECTIONS ) { httpServer . maxConnections = MAX_CONNECTIONS ; } if ( ENV . DESTROY_SOCKETS ) { httpServer . on ( 'connection' , socket => { sockets . add ( socket ) ; socket . on ( 'close' , ( ) => { sockets . delete ( socket ) ; } ) ; } ) ; } return Promise . race ( [ listenPromise , errorPromise ] ) . then ( ( ) => ( { service : httpServer , errorPromise , dispose : ( ) => new Promise ( ( resolve , reject ) => { log ( 'debug' , 'Closing HTTP server.' ) ; // Avoid to keepalive connections on shutdown httpServer . timeout = 1 ; httpServer . keepAliveTimeout = 1 ; httpServer . close ( err => { if ( err ) { reject ( err ) ; return ; } log ( 'debug' , 'HTTP server closed' ) ; resolve ( ) ; } ) ; if ( ENV . DESTROY_SOCKETS ) { for ( const socket of sockets . values ( ) ) { socket . destroy ( ) ; } } } ) , } ) ) ; }


Input: Sort an array by the name of existing property and add a first element into array [CODESPLIT] function sortAndAddFirstElement ( array , sortBy , element ) { return _ ( array ) . sortBy ( sortBy ) . unshift ( element ) . value ( ) ; }


Input: Interface for building an object by configuration [CODESPLIT] function objectInterface ( config ) { return function ( obj ) { var result = { } ; for ( var i = 0 ; i < config . length ; i ++ ) { var OR , NEXT , REAL ; if ( ( OR = config [ i ] . split ( '/' ) ) && OR [ 1 ] ) { result [ OR [ 0 ] ] = obj [ OR [ 0 ] ] || Function ( 'return ' + OR [ 1 ] ) ( ) ; } else if ( ( NEXT = config [ i ] . split ( '|' ) ) && NEXT [ 1 ] ) { result [ NEXT [ 0 ] ] = Function ( 'return ' + NEXT [ 1 ] ) . call ( obj ) ; } else if ( ( REAL = config [ i ] . split ( ':' ) ) && REAL [ 1 ] ) { result [ REAL [ 0 ] ] = Function ( 'return ' + REAL [ 1 ] ) ( ) ; } else { result [ config [ i ] ] = obj [ config [ i ] ] ; } } return result ; } }


Input:
Instantiate the httpTransaction service @param { Object } services The services to inject @param { Number } [ services . TIMEOUT = 30000 ] A number indicating how many ms the transaction should take to complete before being cancelled . @param { Object } [ services . TRANSACTIONS = {} ] A hash of every current transactions @param { Function } services . time A timing function @param { Object } services . delay A delaying service @param { Function } [ services . log ] A logging function @param { Function } [ services . uniqueId ] A function returning unique identifiers @return { Promise<Function > } A promise of the httpTransaction function @example import { initHTTPTransaction } from swagger - http - router ; [CODESPLIT] function initHTTPTransaction ( { TIMEOUT = DEFAULT_TIMEOUT , TRANSACTIONS , log = noop , time , delay , uniqueId = createIncrementor ( ) , } ) { // Not using default value to always // get an empty object here and avoid // conflicts between instances spawned // with defaults TRANSACTIONS = TRANSACTIONS || { } ; log ( 'debug' , 'HTTP Transaction initialized.' ) ; return Promise . resolve ( httpTransaction ) ; /**
   * Create a new HTTP transaction
   * @param  {HTTPRequest}  req
   * A raw NodeJS HTTP incoming message
   * @param  {HTTPResponse} res
   * A raw NodeJS HTTP response
   * @return {Array}
   * The normalized request and the HTTP
   * transaction created in an array.
   */ function httpTransaction ( req , res ) { let initializationPromise ; /* Architecture Note #3.1: New Transaction
    The idea is to maintain a hash of each pending
     transaction. To do so, we create a transaction
     object that contains useful informations about
     the transaction and we store it into the
     `TRANSACTIONS` hash.

    Each transaction has a unique id that is either
     generated or picked up in the `Transaction-Id`
     request header. This allows to trace
     transactions end to end with that unique id.
    */ return Promise . resolve ( ) . then ( ( ) => { const request = { url : req . url , method : req . method . toLowerCase ( ) , headers : req . headers , body : req , } ; const transaction = { protocol : req . connection . encrypted ? 'https' : 'http' , ip : ( req . headers [ 'x-forwarded-for' ] || '' ) . split ( ',' ) [ 0 ] || req . connection . remoteAddress , startInBytes : req . socket . bytesRead , startOutBytes : req . socket . bytesWritten , startTime : time ( ) , url : req . url , method : req . method , reqHeaders : req . headers , errored : false , } ; const delayPromise = delay . create ( TIMEOUT ) ; let id = req . headers [ 'transaction-id' ] || uniqueId ( ) ; // Handle bad client transaction ids if ( TRANSACTIONS [ id ] ) { initializationPromise = Promise . reject ( new HTTPError ( 400 , 'E_TRANSACTION_ID_NOT_UNIQUE' , id ) , ) ; id = uniqueId ( ) ; } else { initializationPromise = Promise . resolve ( ) ; } transaction . id = id ; TRANSACTIONS [ id ] = transaction ; return [ request , { id , start : startTransaction . bind ( null , { id , req , res , delayPromise } , initializationPromise , ) , catch : catchTransaction . bind ( null , { id , req , res } ) , end : endTransaction . bind ( null , { id , req , res , delayPromise } ) , } , ] ; } ) ; } function startTransaction ( { id , delayPromise } , initializationPromise , buildResponse , ) { /* Architecture Note #3.2: Transaction start
    Once initiated, the transaction can be started. It
     basically spawns a promise that will be resolved
     to the actual response or rejected if the timeout
     is reached.
    */ return Promise . race ( [ initializationPromise . then ( ( ) => buildResponse ( ) ) , delayPromise . then ( ( ) => { throw new HTTPError ( 504 , 'E_TRANSACTION_TIMEOUT' , TIMEOUT , id ) ; } ) , ] ) ; } function catchTransaction ( { id , req } , err ) { /* Architecture Note #3.3: Transaction errors
    Here we are simply casting and logging errors.
     It is important for debugging but also for
     ending the transaction properly if an error
     occurs.
    */ err = HTTPError . cast ( err , err . httpCode || 500 ) ; log ( 'error' , 'An error occured' , { guruMeditation : id , request : TRANSACTIONS [ id ] . protocol + '://' + ( req . headers . host || 'localhost' ) + TRANSACTIONS [ id ] . url , verb : req . method , status : err . httpCode , code : err . code , stack : err . stack , details : err . params , } ) ; TRANSACTIONS [ id ] . errored = true ; throw err ; } function endTransaction ( { id , req , res , delayPromise } , response ) { /* Architecture Note #3.4: Transaction end
    We end the transaction by writing the final status
     and headers and piping the response body if any.

    The transaction can till error at that time but it
     is too late for changing the response status so
     we are just logging the event.
     This could be handled with
     [HTTP trailers](https://nodejs.org/api/http.html#http_response_addtrailers_headers)
     but the lack of client side support for now is
     preventing us to use them.

     Once terminated, the transaction is removed
      from the `TRANSACTIONS` hash.
    */ return new Promise ( ( resolve , reject ) => { res . on ( 'error' , reject ) ; res . on ( 'finish' , resolve ) ; res . writeHead ( response . status , statuses [ response . status ] , Object . assign ( { } , response . headers , { 'Transaction-Id' : id } ) , ) ; if ( response . body && response . body . pipe ) { response . body . pipe ( res ) ; } else { res . end ( ) ; } } ) . catch ( err => { TRANSACTIONS [ id ] . errored = true ; log ( 'error' , 'An error occured' , { guruMeditation : id , request : TRANSACTIONS [ id ] . protocol + '://' + ( req . headers . host || 'localhost' ) + TRANSACTIONS [ id ] . url , method : req . method , stack : err . stack || err , } ) ; } ) . then ( ( ) => { TRANSACTIONS [ id ] . endTime = time ( ) ; TRANSACTIONS [ id ] . endInBytes = req . socket . bytesRead ; TRANSACTIONS [ id ] . endOutBytes = req . socket . bytesWritten ; TRANSACTIONS [ id ] . statusCode = response . status ; TRANSACTIONS [ id ] . resHeaders = response . headers || { } ; log ( 'info' , TRANSACTIONS [ id ] ) ; delete TRANSACTIONS [ id ] ; return delay . clear ( delayPromise ) ; } ) ; } }


Input:
Create a new HTTP transaction [CODESPLIT] function httpTransaction ( req , res ) { let initializationPromise ; /* Architecture Note #3.1: New Transaction
    The idea is to maintain a hash of each pending
     transaction. To do so, we create a transaction
     object that contains useful informations about
     the transaction and we store it into the
     `TRANSACTIONS` hash.

    Each transaction has a unique id that is either
     generated or picked up in the `Transaction-Id`
     request header. This allows to trace
     transactions end to end with that unique id.
    */ return Promise . resolve ( ) . then ( ( ) => { const request = { url : req . url , method : req . method . toLowerCase ( ) , headers : req . headers , body : req , } ; const transaction = { protocol : req . connection . encrypted ? 'https' : 'http' , ip : ( req . headers [ 'x-forwarded-for' ] || '' ) . split ( ',' ) [ 0 ] || req . connection . remoteAddress , startInBytes : req . socket . bytesRead , startOutBytes : req . socket . bytesWritten , startTime : time ( ) , url : req . url , method : req . method , reqHeaders : req . headers , errored : false , } ; const delayPromise = delay . create ( TIMEOUT ) ; let id = req . headers [ 'transaction-id' ] || uniqueId ( ) ; // Handle bad client transaction ids if ( TRANSACTIONS [ id ] ) { initializationPromise = Promise . reject ( new HTTPError ( 400 , 'E_TRANSACTION_ID_NOT_UNIQUE' , id ) , ) ; id = uniqueId ( ) ; } else { initializationPromise = Promise . resolve ( ) ; } transaction . id = id ; TRANSACTIONS [ id ] = transaction ; return [ request , { id , start : startTransaction . bind ( null , { id , req , res , delayPromise } , initializationPromise , ) , catch : catchTransaction . bind ( null , { id , req , res } ) , end : endTransaction . bind ( null , { id , req , res , delayPromise } ) , } , ] ; } ) ; }


Input: Difference between dates which are passed in formats milliseconds days hours minutes [CODESPLIT] function dateDifference ( date1 , date2 , differenceType ) { var diffMilliseconds = Math . abs ( date1 - date2 ) ; switch ( differenceType ) { case 'days' : return dates . _getDaysDiff ( diffMilliseconds ) ; case 'hours' : return dates . _differenceInHours ( diffMilliseconds ) ; case 'minutes' : return dates . _differenceInMinutes ( diffMilliseconds ) ; case 'milliseconds' : return diffMilliseconds ; default : return { days : dates . _getDaysDiff ( diffMilliseconds ) , hours : dates . _getHoursDiff ( diffMilliseconds ) , minutes : dates . _getMinutesDiff ( diffMilliseconds ) , milliseconds : diffMilliseconds } } }


Input:
Initialize an error handler for the HTTP router [CODESPLIT] function initErrorHandler ( { ENV = { } , DEBUG_NODE_ENVS = DEFAULT_DEBUG_NODE_ENVS , STRINGIFYERS = DEFAULT_STRINGIFYERS , } ) { return Promise . resolve ( errorHandler ) ; /**
   * Handle an HTTP transaction error and
   * map it to a serializable response
   * @param  {String}  transactionId
   * A raw NodeJS HTTP incoming message
   * @param  {Object} responseSpec
   * The response specification
   * @param  {HTTPError} err
   * The encountered error
   * @return {Promise}
   * A promise resolving when the operation
   *  completes
   */ function errorHandler ( transactionId , responseSpec , err ) { return Promise . resolve ( ) . then ( ( ) => { const response = { } ; response . status = err . httpCode || 500 ; response . headers = Object . assign ( { } , err . headers || { } , { // Avoid caching errors 'cache-control' : 'private' , // Fallback to the default stringifyer to always be // able to display errors 'content-type' : responseSpec && responseSpec . contentTypes [ 0 ] && STRINGIFYERS [ responseSpec . contentTypes [ 0 ] ] ? responseSpec . contentTypes [ 0 ] : Object . keys ( STRINGIFYERS ) [ 0 ] , } ) ; response . body = { error : { code : err . code || 'E_UNEXPECTED' , // Enjoy nerdy stuff: // https://en.wikipedia.org/wiki/Guru_Meditation guruMeditation : transactionId , } , } ; if ( ENV && DEBUG_NODE_ENVS . includes ( ENV . NODE_ENV ) ) { response . body . error . stack = err . stack ; response . body . error . params = err . params ; } return response ; } ) ; } }


Input: Difference between now and date which is passed in formats milliseconds days hours minutes [CODESPLIT] function dateDifferenceFromNow ( date , differenceType ) { var now = new Date ( ) , diffMilliseconds = Math . abs ( date - now ) ; switch ( differenceType ) { case 'days' : return dates . _getDaysDiff ( diffMilliseconds ) ; case 'hours' : return dates . _differenceInHours ( diffMilliseconds ) ; case 'minutes' : return dates . _differenceInMinutes ( diffMilliseconds ) ; case 'milliseconds' : return diffMilliseconds ; default : return { days : dates . _getDaysDiff ( diffMilliseconds ) , hours : dates . _getHoursDiff ( diffMilliseconds ) , minutes : dates . _getMinutesDiff ( diffMilliseconds ) , milliseconds : diffMilliseconds } } }


Input:
Initialize an HTTP router [CODESPLIT] function initHTTPRouter ( { ENV = { } , DEBUG_NODE_ENVS = DEFAULT_DEBUG_NODE_ENVS , BUFFER_LIMIT = DEFAULT_BUFFER_LIMIT , HANDLERS , API , PARSERS = DEFAULT_PARSERS , STRINGIFYERS = DEFAULT_STRINGIFYERS , DECODERS = DEFAULT_DECODERS , ENCODERS = DEFAULT_ENCODERS , QUERY_PARSER = strictQs , log = noop , httpTransaction , errorHandler , } ) { const bufferLimit = bytes . parse ( BUFFER_LIMIT ) ; const ajv = new Ajv ( { verbose : ENV && DEBUG_NODE_ENVS . includes ( ENV . NODE_ENV ) , } ) ; const consumableCharsets = Object . keys ( DECODERS ) ; const produceableCharsets = Object . keys ( ENCODERS ) ; const defaultResponseSpec = { contentTypes : Object . keys ( STRINGIFYERS ) , charsets : produceableCharsets , } ; return flattenSwagger ( API ) . then ( _createRouters . bind ( null , { HANDLERS , ajv } ) ) . then ( routers => { let handleFatalError ; log ( 'debug' , 'HTTP Router initialized.' ) ; return { service : httpRouter , fatalErrorPromise : { promise : new Promise ( ( resolve , reject ) => { handleFatalError = reject ; } ) , } , } ; /**
       * Handle an HTTP incoming message
       * @param  {HTTPRequest}  req
       * A raw NodeJS HTTP incoming message
       * @param  {HTTPResponse} res
       * A raw NodeJS HTTP response
       * @return {Promise}
       * A promise resolving when the operation
       *  completes
       */ function httpRouter ( req , res ) { let operation ; let responseSpec = defaultResponseSpec ; return httpTransaction ( req , res ) . then ( ( [ request , transaction ] ) => transaction . start ( ( ) => Promise . resolve ( ) . then ( ( ) => { const method = request . method ; const path = request . url . split ( SEARCH_SEPARATOR ) [ 0 ] ; const search = request . url . substr ( path . length ) ; const parts = path . split ( '/' ) . filter ( a => a ) ; let [ result , pathParameters ] = routers [ method ] ? routers [ method ] . find ( parts ) : [ ] ; // Second chance for HEAD calls if ( ! result && 'head' === method ) { [ result , pathParameters ] = routers . get ? routers . get . find ( parts ) : [ ] ; } const { handler , operation : _operation_ , validators } = result || { } ; if ( ! handler ) { log ( 'debug' , 'No handler found for: ' , method , parts ) ; throw new HTTPError ( 404 , 'E_NOT_FOUND' , method , parts ) ; } operation = _operation_ ; return { search , pathParameters , validators , operation , handler , } ; } ) . then ( ( { search , pathParameters , validators , operation , handler , } ) => { const consumableMediaTypes = operation . consumes || API . consumes || [ ] ; const produceableMediaTypes = ( operation && operation . produces ) || API . produces || [ ] ; const bodySpec = extractBodySpec ( request , consumableMediaTypes , consumableCharsets , ) ; responseSpec = extractResponseSpec ( operation , request , produceableMediaTypes , produceableCharsets , ) ; return getBody ( { DECODERS , PARSERS , bufferLimit , } , operation , request . body , bodySpec , ) . then ( body => Object . assign ( body ? { body } : { } , pathParameters , QUERY_PARSER ( operation . parameters , search ) , filterHeaders ( operation . parameters , request . headers , ) , ) , ) . then ( parameters => { applyValidators ( operation , validators , parameters ) ; return parameters ; } ) . catch ( err => { throw HTTPError . cast ( err , 400 ) ; } ) . then ( executeHandler . bind ( null , operation , handler ) ) . then ( response => { if ( response . body ) { response . headers [ 'content-type' ] = response . headers [ 'content-type' ] || responseSpec . contentTypes [ 0 ] ; } // Check the stringifyer only when a schema is // specified const responseHasSchema = operation . responses && operation . responses [ response . status ] && operation . responses [ response . status ] . schema ; if ( responseHasSchema && ! STRINGIFYERS [ response . headers [ 'content-type' ] ] ) { return Promise . reject ( new HTTPError ( 500 , 'E_STRINGIFYER_LACK' , response . headers [ 'content-type' ] , ) , ) ; } if ( response . body ) { checkResponseCharset ( request , responseSpec , produceableCharsets , ) ; checkResponseMediaType ( request , responseSpec , produceableMediaTypes , ) ; } return response ; } ) ; } , ) , ) . catch ( transaction . catch ) . catch ( errorHandler . bind ( null , transaction . id , responseSpec ) ) . then ( response => { if ( response . body && 'head' === request . method ) { log ( 'warning' , 'Body stripped:' , response . body instanceof Stream ? 'Stream' : response . body , ) ; return Object . keys ( response ) . filter ( key => 'body' !== key ) . reduce ( ( cleanedResponse , key ) => { cleanedResponse [ key ] = response [ key ] ; return cleanedResponse ; } , { } ) ; } return response ; } ) // Here sendBody is not binded since we need // the `operation` value at the exact moment // of the then stage execution . then ( response => sendBody ( { DEBUG_NODE_ENVS , ENV , API , ENCODERS , STRINGIFYERS , log , ajv , } , operation , response , ) , ) . then ( transaction . end ) , ) . catch ( handleFatalError ) ; } } ) ; }


Input: Handle an HTTP incoming message [CODESPLIT] function httpRouter ( req , res ) { let operation ; let responseSpec = defaultResponseSpec ; return httpTransaction ( req , res ) . then ( ( [ request , transaction ] ) => transaction . start ( ( ) => Promise . resolve ( ) . then ( ( ) => { const method = request . method ; const path = request . url . split ( SEARCH_SEPARATOR ) [ 0 ] ; const search = request . url . substr ( path . length ) ; const parts = path . split ( '/' ) . filter ( a => a ) ; let [ result , pathParameters ] = routers [ method ] ? routers [ method ] . find ( parts ) : [ ] ; // Second chance for HEAD calls if ( ! result && 'head' === method ) { [ result , pathParameters ] = routers . get ? routers . get . find ( parts ) : [ ] ; } const { handler , operation : _operation_ , validators } = result || { } ; if ( ! handler ) { log ( 'debug' , 'No handler found for: ' , method , parts ) ; throw new HTTPError ( 404 , 'E_NOT_FOUND' , method , parts ) ; } operation = _operation_ ; return { search , pathParameters , validators , operation , handler , } ; } ) . then ( ( { search , pathParameters , validators , operation , handler , } ) => { const consumableMediaTypes = operation . consumes || API . consumes || [ ] ; const produceableMediaTypes = ( operation && operation . produces ) || API . produces || [ ] ; const bodySpec = extractBodySpec ( request , consumableMediaTypes , consumableCharsets , ) ; responseSpec = extractResponseSpec ( operation , request , produceableMediaTypes , produceableCharsets , ) ; return getBody ( { DECODERS , PARSERS , bufferLimit , } , operation , request . body , bodySpec , ) . then ( body => Object . assign ( body ? { body } : { } , pathParameters , QUERY_PARSER ( operation . parameters , search ) , filterHeaders ( operation . parameters , request . headers , ) , ) , ) . then ( parameters => { applyValidators ( operation , validators , parameters ) ; return parameters ; } ) . catch ( err => { throw HTTPError . cast ( err , 400 ) ; } ) . then ( executeHandler . bind ( null , operation , handler ) ) . then ( response => { if ( response . body ) { response . headers [ 'content-type' ] = response . headers [ 'content-type' ] || responseSpec . contentTypes [ 0 ] ; } // Check the stringifyer only when a schema is // specified const responseHasSchema = operation . responses && operation . responses [ response . status ] && operation . responses [ response . status ] . schema ; if ( responseHasSchema && ! STRINGIFYERS [ response . headers [ 'content-type' ] ] ) { return Promise . reject ( new HTTPError ( 500 , 'E_STRINGIFYER_LACK' , response . headers [ 'content-type' ] , ) , ) ; } if ( response . body ) { checkResponseCharset ( request , responseSpec , produceableCharsets , ) ; checkResponseMediaType ( request , responseSpec , produceableMediaTypes , ) ; } return response ; } ) ; } , ) , ) . catch ( transaction . catch ) . catch ( errorHandler . bind ( null , transaction . id , responseSpec ) ) . then ( response => { if ( response . body && 'head' === request . method ) { log ( 'warning' , 'Body stripped:' , response . body instanceof Stream ? 'Stream' : response . body , ) ; return Object . keys ( response ) . filter ( key => 'body' !== key ) . reduce ( ( cleanedResponse , key ) => { cleanedResponse [ key ] = response [ key ] ; return cleanedResponse ; } , { } ) ; } return response ; } ) // Here sendBody is not binded since we need // the `operation` value at the exact moment // of the then stage execution . then ( response => sendBody ( { DEBUG_NODE_ENVS , ENV , API , ENCODERS , STRINGIFYERS , log , ajv , } , operation , response , ) , ) . then ( transaction . end ) , ) . catch ( handleFatalError ) ; }


Input: Returns new line index which is right after characters beyound pos that editor will likely automatically close e . g . } ] and quotes [CODESPLIT] function offsetPastAutoClosed ( line , pos , options ) { // closing quote is allowed only as a next character if ( isQuote ( line . charCodeAt ( pos ) ) ) { pos ++ ; } // offset pointer until non-autoclosed character is found while ( isCloseBrace ( line . charCodeAt ( pos ) , options . syntax ) ) { pos ++ ; } return pos ; }


Input: Returns start offset ( left limit ) in line where we should stop looking for abbreviation : it’s nearest to pos location of prefix token [CODESPLIT] function getStartOffset ( line , pos , prefix ) { if ( ! prefix ) { return 0 ; } const stream = new StreamReader ( line ) ; const compiledPrefix = String ( prefix ) . split ( '' ) . map ( code ) ; stream . pos = pos ; let result ; while ( ! stream . sol ( ) ) { if ( consumePair ( stream , SQUARE_BRACE_R , SQUARE_BRACE_L ) || consumePair ( stream , CURLY_BRACE_R , CURLY_BRACE_L ) ) { continue ; } result = stream . pos ; if ( consumeArray ( stream , compiledPrefix ) ) { return result ; } stream . pos -- ; } return - 1 ; }


Input: Consumes full character pair if possible [CODESPLIT] function consumePair ( stream , close , open ) { const start = stream . pos ; if ( stream . eat ( close ) ) { while ( ! stream . sol ( ) ) { if ( stream . eat ( open ) ) { return true ; } stream . pos -- ; } } stream . pos = start ; return false ; }


Input: Consumes all character codes from given array right - to - left if possible [CODESPLIT] function consumeArray ( stream , arr ) { const start = stream . pos ; let consumed = false ; for ( let i = arr . length - 1 ; i >= 0 && ! stream . sol ( ) ; i -- ) { if ( ! stream . eat ( arr [ i ] ) ) { break ; } consumed = i === 0 ; } if ( ! consumed ) { stream . pos = start ; } return consumed ; }


Input: Check if given character code belongs to HTML identifier [CODESPLIT] function isIdent ( c ) { return c === COLON || c === DASH || isAlpha ( c ) || isNumber ( c ) ; }


Input: > Controls merges and resolves all tasks from config files > and passed through opts . tasks . > > All opts are passed to [ execa - pro ] [] and to [ execa ] [] > so you can pass opts . stdio : inherit for example > to output the result of each command in the console useful for things like prompt inputs . > Resolving works recursively and support ESLint style presets through > the opts . extends . The extends property can be string ( the name of the preset > prefixed with hela - config - ) a function ( that is passed with { extends tasks } object ) > or an object containing another extends and / or tasks properties . > > Configuration is handled by [ @tunnckocore / pretty - config ] ( https : // github . com / tunnckoCore / pretty - config ) > which is pretty similar to the [ cosmiconfig ] [] package and so the config > files lookup order is : > - . helarc . { json yaml yml js } > - hela . config . js > - . hela . config . js > - . helarc - YAML or JSON syntax > - package . json - one of hela helaConfig or config . hela fields [CODESPLIT] async function hela ( opts ) { const options = Object . assign ( { argv : { } , prefix : 'hela-config-' , stdio : 'inherit' } , opts ) if ( options . tasks || ( options . presets || options . extends ) ) { return presetResolver ( options ) } return prettyConfig ( 'hela' , options ) . then ( ( config ) => { if ( ! config ) { throw new Error ( 'hela: no config' ) } return presetResolver ( Object . assign ( { } , config , options ) ) } ) }


Input: Utils [CODESPLIT] function factory ( type , opts ) { return ( cmds , options ) => { const cmd = { exec : execa . exec , shell : execa . shell } return cmd [ type ] ( cmds , Object . assign ( { } , opts , options ) ) } }


Input: todo : externalize as hela - resolver ? [CODESPLIT] function presetResolver ( opts ) { const presets = arrayify ( opts . presets || opts . extends ) if ( presets . length > 0 ) { const arg = Object . assign ( { } , opts ) const options = Object . assign ( { first : arg } , opts ) const tasks = resolvePlugins ( presets , options ) . reduce ( ( acc , preset ) => presetReducer ( acc , preset ) , { } ) return transformTasks ( opts , Object . assign ( { } , tasks , opts . tasks ) ) } return transformTasks ( opts , opts . tasks ) }


Input: if ( !isNyc && !isCov && !isEslint ) { console . error ( hela : task $ { name } failed ) console . error ( er . stack || er . message ) } } [CODESPLIT] async function run ( ) { const pkg = await readJson ( path . join ( options . cwd , 'package.json' ) ) const tasks = await hela ( { pkg , ... options } ) const name = options . taskName if ( Object . keys ( tasks ) . length === 0 ) { throw new Error ( 'hela: no tasks' ) } const hasOwn = ( o , k ) => Object . prototype . hasOwnProperty . call ( o , k ) if ( ! hasOwn ( tasks , name ) ) { throw new Error ( ` ${ name } ` ) } return tasks [ name ] ( ) }


Input: ### default [CODESPLIT] function plugin ( options ) { if ( ! options ) throw new Error ( 'no options passed' ) if ( ! options . src ) throw new Error ( 'required: options.src' ) if ( ! options . dest ) throw new Error ( 'required: options.dest' ) if ( ! options . auth ) throw new Error ( 'required: options.auth' ) // if (options.cache !== undefined) cache = options.cache if ( options . invalidateCache ) { initCache ( ) . then ( ( ) => { dbg ( 'invalidating cache' ) fileCache . collection . clear ( ) valueCache . collection . clear ( ) } ) } const folder = new Folder ( options ) return folder . googleDrive . bind ( folder ) }


Input: don t change this ## _write this is where the parallel stream magic happens .. pay attention each time _write is called we either call next immediately ( if we haven t yet reached concurrency limit ) or we call next once the worker has finished . [CODESPLIT] function _write ( file , encoding , next ) { this . workers ++ vow . resolve ( file ) . then ( ( file ) => folder . downloadFile ( file ) ) . then ( ( file ) => folder . frontMatter ( file ) ) . then ( ( file ) => folder . storeFile ( file ) ) . catch ( dbg ) . then ( ( ) => { this . workers -- next ( ) } ) // if not at concurrency limit, call next immediately (don't wait for // worker to finish) if ( this . workers < this . concurrency ) { next ( ) next = ( ) => { } } }


Input: ### _doAuth [CODESPLIT] function _doAuth ( auth ) { if ( oauth ) return vow . resolve ( ) dbg ( 'doing oAuth2' ) const googleAuth = new GoogleAuth ( ) oauth = new googleAuth . OAuth2 ( auth . client_id , auth . client_secret , [ 'urn:ietf:wg:oauth:2.0:oob' , 'http://localhost' ] ) return vow . resolve ( ) . then ( ( ) => { // see if token has been recorded in config let configToken = config . get ( 'metalsmith-google-drive' ) . token // no idea why google auth needs the token to be writable, but whatever if ( configToken ) configToken = config . util . cloneDeep ( configToken ) // fall back to cache (params), then do token flow return configToken || valueCache . retrieve ( 'token' ) || _tokenFlow ( ) } ) . then ( ( token ) => { oauth . credentials = token } ) . catch ( ( err ) => { // if some failure occurred invalidate oauth object so we don't simply // try to use it next time. oauth = false return vow . reject ( err ) } ) }


Input: ### _tokenFlow [CODESPLIT] function _tokenFlow ( ) { const defer = vow . defer ( ) let prompt const authUrl = oauth . generateAuthUrl ( { access_type : 'offline' , scope : [ 'https://www.googleapis.com/auth/drive.readonly' ] } ) console . log ( 'authorise metalsmith-google-drive by visiting: ' , authUrl ) prompt = readline . createInterface ( { input : process . stdin , output : process . stdout } ) prompt . question ( 'Enter the code from that page here (or "ok" to skip scrape): ' , ( code ) => { prompt . close ( ) if ( code === 'ok' ) return defer . reject ( 'skip' ) oauth . getToken ( code , ( err , result ) => { if ( err ) { dbg ( err ) defer . reject ( err ) } else { console . log ( '---------- snip ----------' ) console . log ( hjson . stringify ( { 'metalsmith-google-drive' : { token : result } } , { separator : true , spaces : 2 , bracesSameLine : true , quotes : 'all' } ) ) console . log ( '---------- snip ----------' ) console . log ( 'this token is cached automatically, but you can store' ) console . log ( 'it in a config file like config/local.js if you want.' ) valueCache . store ( 'token' , result ) defer . resolve ( result ) } } ) } ) return defer . promise ( ) }


Input: pool for testing in place camelizeKeys [CODESPLIT] function onCycle ( event ) { if ( objectPool . length == 0 ) { throw new Error ( 'Pool ran out of objects' ) ; } console . log ( String ( event . target ) ) ; initPool ( ) ; }


Input: / * The only way to modify state is to trigger an action the modifer function is where you change state based on the type of an action [CODESPLIT] function modifier ( action , state ) { if ( action . type === 'example' ) { return extend ( state , { example : true } ) } else if ( action . type === 'title' ) { return extend ( state , { title : action . title } ) } }


Input: Load JSON data from a companion file and store in file data . [CODESPLIT] function json ( file ) { var filename = path . basename ( file . path , path . extname ( file . path ) ) + ".json" ; return optional ( path . join ( path . dirname ( file . path ) , filename ) ) || { } ; }


Input:
Our Elevator implementation implements 3 states : - open : the elevator doors are opened - closed : the elevator doors are closed - moving : the elevator is moving towards a level [CODESPLIT] function ( ) { const self = this ; const TIME_PER_LEVEL = 1 * 1000 ; this . level = 0 ; this . stack = [ ] ; this . fsm = new Fsm ( ) ; /**
   * The elevator is in a stationary state
   * and its doors are opened.
   */ const open = new Fsm . State ( { fsm : self . fsm , name : 'open' , onEntry : function ( ) { const state = this ; console . log ( 'Door opened at level' , self . level ) ; setTimeout ( function ( ) { state . transitionTo ( closed ) ; } , 2000 ) ; } , /**
     * As the elevator's doors are currently opened
     * we push any user request to go to
     * a level on the level stack.
     */ onEvent : function ( event ) { if ( event . name === 'goToLevel' && event . level !== self . level ) { self . pushLevel ( event . level ) ; } } } ) ; /**
   * The elevator is in a stationary state
   * and its doors are closed.
   */ const closed = new Fsm . State ( { fsm : self . fsm , name : 'closed' , onEntry : function ( ) { console . log ( 'Door closed' ) ; // If there is a channel in the stack, // we move to that channel. if ( self . stack [ 0 ] ) { this . transitionTo ( moving ) ; } } , /**
     * When the elevator's doors are closed,
     * we wait for a request to move to another
     * level.
     */ onEvent : function ( event ) { if ( event . name === 'goToLevel' ) { if ( event . level === self . level ) { this . transitionTo ( open ) ; } else { self . pushLevel ( event . level ) ; this . transitionTo ( moving ) ; } } } } ) ; /**
   * The elevator is currently moving from a
   * level to another.
   */ const moving = new Fsm . State ( { fsm : self . fsm , name : 'moving' , onEntry : function ( ) { const state = this ; const next = self . stack . shift ( ) ; console . log ( 'Moving to level' , next ) ; setTimeout ( function ( ) { console . log ( 'Reached level' , next ) ; self . level = next ; state . transitionTo ( open ) ; } , TIME_PER_LEVEL * Math . abs ( next - self . level ) ) ; } , /**
     * As the elevator is currently moving and
     * cannot change direction nor open the
     * doors, we push any user request to go to
     * a level on the level stack.
     */ onEvent : function ( event ) { if ( event . name === 'goToLevel' ) { self . pushLevel ( event . level ) ; } } } ) ; // Starting the elevator in the `closed` state. this . fsm . start ( closed ) ; }


Input: As the elevator s doors are currently opened we push any user request to go to a level on the level stack . [CODESPLIT] function ( event ) { if ( event . name === 'goToLevel' && event . level !== self . level ) { self . pushLevel ( event . level ) ; } }


Input: When the elevator s doors are closed we wait for a request to move to another level . [CODESPLIT] function ( event ) { if ( event . name === 'goToLevel' ) { if ( event . level === self . level ) { this . transitionTo ( open ) ; } else { self . pushLevel ( event . level ) ; this . transitionTo ( moving ) ; } } }


Input: Encrypted content components [CODESPLIT] function decryptCBC ( encryptedComponents , keyDerivationInfo ) { // Extract the components const encryptedContent = encryptedComponents . content ; const iv = new Buffer ( encryptedComponents . iv , "hex" ) ; const salt = encryptedComponents . salt ; const hmacData = encryptedComponents . auth ; // Get HMAC tool const hmacTool = crypto . createHmac ( HMAC_ALGORITHM , keyDerivationInfo . hmac ) ; // Generate the HMAC hmacTool . update ( encryptedContent ) ; hmacTool . update ( encryptedComponents . iv ) ; hmacTool . update ( salt ) ; const newHmaxHex = hmacTool . digest ( "hex" ) ; // Check hmac for tampering if ( constantTimeCompare ( hmacData , newHmaxHex ) !== true ) { throw new Error ( "Authentication failed while decrypting content" ) ; } // Decrypt const decryptTool = crypto . createDecipheriv ( ENC_ALGORITHM_CBC , keyDerivationInfo . key , iv ) ; const decryptedText = decryptTool . update ( encryptedContent , "base64" , "utf8" ) ; return Promise . resolve ( ` ${ decryptedText } ${ decryptTool . final ( "utf8" ) } ` ) ; }


Input: Decrypt text using AES - GCM [CODESPLIT] function decryptGCM ( encryptedComponents , keyDerivationInfo ) { // Extract the components const encryptedContent = encryptedComponents . content ; const iv = new Buffer ( encryptedComponents . iv , "hex" ) ; const { auth : tagHex , salt } = encryptedComponents ; // Prepare tool const decryptTool = crypto . createDecipheriv ( ENC_ALGORITHM_GCM , keyDerivationInfo . key , iv ) ; // Add additional auth data decryptTool . setAAD ( new Buffer ( ` ${ encryptedComponents . iv } ${ keyDerivationInfo . salt } ` , "utf8" ) ) ; // Set auth tag decryptTool . setAuthTag ( new Buffer ( tagHex , "hex" ) ) ; // Perform decryption const decryptedText = decryptTool . update ( encryptedContent , "base64" , "utf8" ) ; return Promise . resolve ( ` ${ decryptedText } ${ decryptTool . final ( "utf8" ) } ` ) ; }


Input: Encrypt text using AES - CBC [CODESPLIT] function encryptCBC ( text , keyDerivationInfo , iv ) { return Promise . resolve ( ) . then ( ( ) => { const ivHex = iv . toString ( "hex" ) ; const encryptTool = crypto . createCipheriv ( ENC_ALGORITHM_CBC , keyDerivationInfo . key , iv ) ; const hmacTool = crypto . createHmac ( HMAC_ALGORITHM , keyDerivationInfo . hmac ) ; const { rounds } = keyDerivationInfo ; // Perform encryption let encryptedContent = encryptTool . update ( text , "utf8" , "base64" ) ; encryptedContent += encryptTool . final ( "base64" ) ; // Generate hmac hmacTool . update ( encryptedContent ) ; hmacTool . update ( ivHex ) ; hmacTool . update ( keyDerivationInfo . salt ) ; const hmacHex = hmacTool . digest ( "hex" ) ; // Output encrypted components return { mode : "cbc" , auth : hmacHex , iv : ivHex , salt : keyDerivationInfo . salt , rounds , content : encryptedContent } ; } ) ; }


Input: Encrypt text using AES - GCM [CODESPLIT] function encryptGCM ( text , keyDerivationInfo , iv ) { return Promise . resolve ( ) . then ( ( ) => { const ivHex = iv . toString ( "hex" ) ; const { rounds } = keyDerivationInfo ; const encryptTool = crypto . createCipheriv ( ENC_ALGORITHM_GCM , keyDerivationInfo . key , iv ) ; // Add additional auth data encryptTool . setAAD ( new Buffer ( ` ${ ivHex } ${ keyDerivationInfo . salt } ` , "utf8" ) ) ; // Perform encryption let encryptedContent = encryptTool . update ( text , "utf8" , "base64" ) ; encryptedContent += encryptTool . final ( "base64" ) ; // Handle authentication const tag = encryptTool . getAuthTag ( ) ; // Output encrypted components return { mode : "gcm" , iv : ivHex , salt : keyDerivationInfo . salt , rounds , content : encryptedContent , auth : tag . toString ( "hex" ) } ; } ) ; }


Input: Salt generator [CODESPLIT] function generateSalt ( length ) { if ( length <= 0 ) { return Promise . reject ( new Error ( ` ${ length } ` ) ) ; } let output = "" ; while ( output . length < length ) { output += crypto . randomBytes ( 3 ) . toString ( "base64" ) ; if ( output . length > length ) { output = output . substr ( 0 , length ) ; } } return Promise . resolve ( output ) ; }


Input: Encrypted content components [CODESPLIT] function packEncryptedContent ( encryptedContent , iv , salt , auth , rounds , method ) { return [ encryptedContent , iv , salt , auth , rounds , method ] . join ( "$" ) ; }


Input: Unpack encrypted content components from an encrypted string [CODESPLIT] function unpackEncryptedContent ( encryptedContent ) { const [ content , iv , salt , auth , roundsRaw , methodRaw ] = encryptedContent . split ( "$" ) ; // iocane was originally part of Buttercup's core package and used defaults from that originally. // There will be 4 components for pre 0.15.0 archives, and 5 in newer archives. The 5th component // is the pbkdf2 round count, which is optional: const rounds = roundsRaw ? parseInt ( roundsRaw , 10 ) : PBKDF2_ROUND_DEFAULT ; // Originally only "cbc" was supported, but GCM was added in version 1 const method = methodRaw || "cbc" ; return { content , iv , salt , auth , rounds , method } ; }


Input: Derived key info [CODESPLIT] function deriveFromPassword ( pbkdf2Gen , password , salt , rounds , generateHMAC = true ) { if ( ! password ) { return Promise . reject ( new Error ( "Failed deriving key: Password must be provided" ) ) ; } if ( ! salt ) { return Promise . reject ( new Error ( "Failed deriving key: Salt must be provided" ) ) ; } if ( ! rounds || rounds <= 0 ) { return Promise . reject ( new Error ( "Failed deriving key: Rounds must be greater than 0" ) ) ; } const bits = generateHMAC ? ( PASSWORD_KEY_SIZE + HMAC_KEY_SIZE ) * 8 : PASSWORD_KEY_SIZE * 8 ; return pbkdf2Gen ( password , salt , rounds , bits ) . then ( derivedKeyData => derivedKeyData . toString ( "hex" ) ) . then ( function ( derivedKeyHex ) { const dkhLength = derivedKeyHex . length ; const keyBuffer = generateHMAC ? new Buffer ( derivedKeyHex . substr ( 0 , dkhLength / 2 ) , "hex" ) : new Buffer ( derivedKeyHex , "hex" ) ; const output = { salt : salt , key : keyBuffer , rounds : rounds } ; if ( generateHMAC ) { output . hmac = new Buffer ( derivedKeyHex . substr ( dkhLength / 2 , dkhLength / 2 ) , "hex" ) ; } return output ; } ) ; }


Input: The default PBKDF2 function [CODESPLIT] function pbkdf2 ( password , salt , rounds , bits ) { return new Promise ( ( resolve , reject ) => { deriveKey ( password , salt , rounds , bits / 8 , DERIVED_KEY_ALGORITHM , ( err , key ) => { if ( err ) { return reject ( err ) ; } return resolve ( key ) ; } ) ; } ) ; }


Input: Node Constructor [CODESPLIT] function Node ( id , opts ) { var me = this this . id = id Object . defineProperty ( me , 'inner' , { value : opts . inner , enumerable : false , writable : true } ) Object . defineProperty ( me , 'outer' , { value : opts . outer , enumerable : false , writable : true } ) Object . defineProperty ( me , this . inner , { value : new Edge ( { inner : this . inner , outer : this . outer , id : id } ) , enumerable : false , writable : true } ) Object . defineProperty ( me , this . outer , { value : new Edge ( { inner : this . outer , outer : this . inner , id : id } ) , enumerable : false , writable : true } ) }


Input: Initialize a new Edge with inner / outer edge names [CODESPLIT] function Edge ( opts ) { this . id = opts . id this . innerformat = opts . inner + '_%s' this . outerformat = opts . outer + '_%s' this . innerkey = format ( this . innerformat , this . id ) this . outerkey = format ( this . outerformat , this . id ) this [ opts . inner ] = function ( cb ) { this . all ( function ( error , array ) { if ( error ) return cb ( error ) if ( ! array || ! array . length ) return cb ( null , array || [ ] ) array = array . map ( function ( gid ) { return format ( this . innerformat , String ( gid ) ) } , this ) db . sunion ( array , cb ) } . bind ( this ) ) } this [ opts . outer ] = function ( cb ) { this . all ( function ( error , array ) { if ( error ) return cb ( error ) if ( ! array || ! array . length ) return cb ( null , array || [ ] ) array = array . map ( function ( gid ) { return format ( this . outerformat , gid ) } , this ) db . sunion ( array , cb ) } . bind ( this ) ) } }


Input: - type and value are in Ember > v2 . 8 - name is in Ember === 2 . 8 [CODESPLIT] function getDynamicSegments ( segments ) { return segments . filter ( item => item . type === 1 || ! ! item . name ) . map ( item => item . value || item . name ) ; }


Input: Create transform stream to encode objects into Buffer . [CODESPLIT] function createEncodeStream ( schema ) { const stream = new BinaryStream ( { readableObjectMode : false , writableObjectMode : true , transform : transformEncode , } ) ; stream [ kschema ] = schema ; return stream ; }


Input: Create transform stream to decode binary data into object . [CODESPLIT] function createDecodeStream ( bufOrSchema ) { let schema = null ; const isBuffer = Buffer . isBuffer ( bufOrSchema ) ; if ( ! isBuffer ) { schema = bufOrSchema ; } const stream = new BinaryStream ( { transform : transformDecode , readableObjectMode : true , writableObjectMode : false , } ) ; stream [ kschema ] = schema ; if ( isBuffer ) { stream . append ( bufOrSchema ) ; } return stream ; }


Input: The transform function for transform stream . [CODESPLIT] function transformEncode ( chunk , encoding , cb ) { try { encode ( chunk , this [ kschema ] , this ) ; const buf = this . slice ( ) ; this . consume ( buf . length ) ; cb ( null , buf ) ; } catch ( error ) { cb ( error ) ; } }


Input: The transform function for transform stream . [CODESPLIT] function transformDecode ( chunk , encoding , cb ) { this . append ( chunk ) ; try { while ( this . length > 0 ) { const transaction = new Transaction ( this ) ; const data = decode ( transaction , this [ kschema ] ) ; transaction . commit ( ) ; this . push ( data ) ; } cb ( ) ; } catch ( error ) { if ( error instanceof NotEnoughDataError ) { cb ( ) ; } else { cb ( error ) ; } } }


Input: Generates a binomial graph graph with n nodes . [CODESPLIT] function erdosRenyi ( GraphClass , options ) { if ( ! isGraphConstructor ( GraphClass ) ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid Graph constructor.' ) ; var order = options . order , probability = options . probability , rng = options . rng || Math . random ; var graph = new GraphClass ( ) ; // If user gave a size, we need to compute probability if ( typeof options . approximateSize === 'number' ) { var densityFunction = density [ graph . type + 'Density' ] ; probability = densityFunction ( order , options . approximateSize ) ; } if ( typeof order !== 'number' || order <= 0 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.' ) ; if ( typeof probability !== 'number' || probability < 0 || probability > 1 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\'s density.' ) ; if ( typeof rng !== 'function' ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.' ) ; for ( var i = 0 ; i < order ; i ++ ) graph . addNode ( i ) ; if ( probability <= 0 ) return graph ; if ( order > 1 ) { var iterator = combinations ( range ( order ) , 2 ) , path , step ; while ( ( step = iterator . next ( ) , ! step . done ) ) { path = step . value ; if ( graph . type !== 'directed' ) { if ( rng ( ) < probability ) graph . addUndirectedEdge ( path [ 0 ] , path [ 1 ] ) ; } if ( graph . type !== 'undirected' ) { if ( rng ( ) < probability ) graph . addDirectedEdge ( path [ 0 ] , path [ 1 ] ) ; if ( rng ( ) < probability ) graph . addDirectedEdge ( path [ 1 ] , path [ 0 ] ) ; } } } return graph ; }


Input: Generates a binomial graph graph with n nodes using a faster algorithm for sparse graphs . [CODESPLIT] function erdosRenyiSparse ( GraphClass , options ) { if ( ! isGraphConstructor ( GraphClass ) ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid Graph constructor.' ) ; var order = options . order , probability = options . probability , rng = options . rng || Math . random ; var graph = new GraphClass ( ) ; // If user gave a size, we need to compute probability if ( typeof options . approximateSize === 'number' ) { var densityFunction = density [ graph . type + 'Density' ] ; probability = densityFunction ( order , options . approximateSize ) ; } if ( typeof order !== 'number' || order <= 0 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.' ) ; if ( typeof probability !== 'number' || probability < 0 || probability > 1 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\'s density.' ) ; if ( typeof rng !== 'function' ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.' ) ; for ( var i = 0 ; i < order ; i ++ ) graph . addNode ( i ) ; if ( probability <= 0 ) return graph ; var w = - 1 , lp = Math . log ( 1 - probability ) , lr , v ; if ( graph . type !== 'undirected' ) { v = 0 ; while ( v < order ) { lr = Math . log ( 1 - rng ( ) ) ; w += 1 + ( ( lr / lp ) | 0 ) ; // Avoiding self loops if ( v === w ) { w ++ ; } while ( v < order && order <= w ) { w -= order ; v ++ ; // Avoiding self loops if ( v === w ) w ++ ; } if ( v < order ) graph . addDirectedEdge ( v , w ) ; } } w = - 1 ; if ( graph . type !== 'directed' ) { v = 1 ; while ( v < order ) { lr = Math . log ( 1 - rng ( ) ) ; w += 1 + ( ( lr / lp ) | 0 ) ; while ( w >= v && v < order ) { w -= v ; v ++ ; } if ( v < order ) graph . addUndirectedEdge ( v , w ) ; } } return graph ; }


Input: /////////////// source generators /////////////////////////////////////////// [CODESPLIT] function generateBLEPayloadParser ( profileData ) { var outputSrc = "" ; log ( " ***************************************************************************" ) ; log ( "    Generating JavaScript source file for BLE Payload parser " ) ; log ( " ***************************************************************************" ) ; outputSrc = outputSrc + addLicenseText ( ) ; outputSrc = outputSrc + "//" + "\r\n" + "//  PayloadParser.js" + "\r\n" + "//" + "\r\n" + "//  Autogenerated source" + "\r\n" + "//" + "\r\n" + "// ---------------------------------" + "\r\n" + "//  BLE Payload parser " + "\r\n" + "// ---------------------------------" + "\r\n" + "\r\n" + " 'use strict'" + "\r\n" + " var Int64LE = require('int64-buffer').Int64LE; " + "\r\n" + " import DLog from '../common/DLog'; " + "\r\n" + " const dp =require('./PayloadDefs'); " + "\r\n" + "\r\n" ; for ( var x = 0 ; x < profileData . Services . length ; x ++ ) { var service = profileData . Services [ x ] ; var serviceNameStr = prepareSrcString ( service . Name ) ; var svcNameSnakeStr = prepareSrcStringAsSnakeCase ( service . Name ) ; for ( var y = 0 ; y < service . Characteristics . length ; y ++ ) { var characteristic = service . Characteristics [ y ] ; var characteristicNameStr = prepareSrcString ( characteristic . Name ) ; var characteristicNameSnakeStr = prepareSrcStringAsSnakeCase ( characteristic . Name ) ; var chr_json_filename = "chr_" + characteristicNameSnakeStr ; outputSrc = outputSrc + "  var " + chr_json_filename + "_JSON = require('../device_services/profile/chr/" + chr_json_filename + "'); " + "\r\n" + "  var " + chr_json_filename + "_uuid = " + chr_json_filename + "_JSON.Characteristic.uuid; " + "\r\n" + "  if(" + chr_json_filename + "_JSON.Characteristic.Value != undefined ){  " + "\r\n" + "  		var " + chr_json_filename + "_format = " + chr_json_filename + "_JSON.Characteristic.Value.Field.Format; " + "\r\n" + "  } " + "\r\n" ; } } outputSrc = outputSrc + "\r\n" + " var nPayloadParserObjCnt = 0; " + "\r\n" + " var instancePayloadParser = null; " + "\r\n" + " const BLE_CHARC_VALUE_MAX_LEN = 20; " + "\r\n" + "\r\n" + " export function getPayloadParserInstance() " + "\r\n" + " { " + "\r\n" + "     if(nPayloadParserObjCnt > 0 ) " + "\r\n" + "     { " + "\r\n" + "          DLog.printDebugMsg('Its a singleton class, returning existing instance of PayloadParser class '); " + "\r\n" + "         return instancePayloadParser; " + "\r\n" + "     } " + "\r\n" + "      nPayloadParserObjCnt++; " + "\r\n" + "      DLog.printDebugMsg('PayloadParser Object Count is ' + nPayloadParserObjCnt); " + "\r\n" + "     instancePayloadParser = new PayloadParser(); " + "\r\n" + "     return instancePayloadParser; " + "\r\n" + " } " + "\r\n" + "\r\n" + " class PayloadParser  { " + "\r\n" + "     constructor(props){ " + "\r\n" + "     } " + "\r\n" + "\r\n" + "     parse(svc_class_name,args) " + "\r\n" + "     { " + "\r\n" + "         switch(args.characteristic) " + "\r\n" + "         {  " + "\r\n" ; for ( var x = 0 ; x < profileData . Services . length ; x ++ ) { var service = profileData . Services [ x ] ; var serviceNameStr = prepareSrcString ( service . Name ) ; var svcNameSnakeStr = prepareSrcStringAsSnakeCase ( service . Name ) ; for ( var y = 0 ; y < service . Characteristics . length ; y ++ ) { var characteristic = service . Characteristics [ y ] ; var characteristicNameStr = prepareSrcString ( characteristic . Name ) ; var characteristicNameSnakeStr = prepareSrcStringAsSnakeCase ( characteristic . Name ) ; var chr_json_filename = "chr_" + characteristicNameSnakeStr ; var pkt_chr_name = "pkt_" + characteristicNameSnakeStr ; outputSrc = outputSrc + "			  case " + chr_json_filename + "_uuid.toUpperCase() : " + "\r\n" + "                 DLog.printDebug(this,' Characteristics format is = '+ " + chr_json_filename + "_format );" + "\r\n" + "                 if( " + chr_json_filename + "_format == 'uint8' || " + "\r\n" + "                    " + chr_json_filename + "_format == 'uint16' || " + "\r\n" + "                    " + chr_json_filename + "_format == 'uint32' || " + "\r\n" + "                    " + chr_json_filename + "_format == 'uint64') " + "\r\n" + "                 {" + "\r\n" + "                     let " + pkt_chr_name + " = {" + "\r\n" + "                         " + characteristicNameStr + " : {" + "\r\n" + "                             'FMT':' '," + "\r\n" + "                         }" + "\r\n" + "                     }" + "\r\n" + "                     " + pkt_chr_name + "." + characteristicNameStr + ".FMT = " + chr_json_filename + "_format;" + "\r\n" + "                     return this.parseDatapayloadPkt(args.value, " + pkt_chr_name + ");" + "\r\n" + "                 }" + "\r\n" + "                 else" + "\r\n" + "                 {" + "\r\n" + "                     if(dp." + pkt_chr_name + " != undefined) {" + "\r\n" + "                         return this.parseDatapayloadPkt(args.value,dp." + pkt_chr_name + ");" + "\r\n" + "                     }" + "\r\n" + "                     break;" + "\r\n" + "                 } " + "\r\n" ; } } outputSrc = outputSrc + "             default : " + "\r\n" + "                 return null; " + "\r\n" + "         } " + "\r\n" + "         return null; " + "\r\n" + "     } " + "\r\n" + "\r\n" + "     parseDatapayloadPkt(packetArr, datapayloadDef)" + "\r\n" + "     { " + "\r\n" + "         var packetBytBuf  = this.byteArray2DVByteBuffer(packetArr); " + "\r\n" + "         if(packetBytBuf === null) " + "\r\n" + "         { " + "\r\n" + "             DLog.printDebug(this,'packetBytBuf is NUll '); " + "\r\n" + "             return 'parse_error'; " + "\r\n" + "         } " + "\r\n" + "\r\n" + "         var datapayloadStruct =  {}; " + "\r\n" + "         var totaldatapayloadStructKeys =  Object.keys(datapayloadStruct).length; " + "\r\n" + "         var totaldatapayloadStructValues =  Object.values(datapayloadStruct).length; " + "\r\n" + "         var totalFields = Object.keys(datapayloadDef).length; " + "\r\n" + "\r\n" + "         DLog.printDebug(this,'total datapayload Fields =  ' + totalFields + " + "\r\n" + "                         ' /totaldatapayloadStructKeys =  ' + totaldatapayloadStructKeys  + " + "\r\n" + "                         ' /totaldatapayloadStructValues =  ' + totaldatapayloadStructValues ); " + "\r\n" + "\r\n" + "         for (var [keyFieldName, valueFieldDef] of Object.entries(datapayloadDef)) { " + "\r\n" + "             datapayloadStruct[keyFieldName] = this.extractData(packetBytBuf, valueFieldDef); " + "\r\n" + "         } " + "\r\n" + "\r\n" + "         totaldatapayloadStructKeys =  Object.keys(datapayloadStruct).length " + "\r\n" + "         totaldatapayloadStructValues =  Object.values(datapayloadStruct).length; " + "\r\n" + "\r\n" + "         DLog.printDebug(this,'/totaldatapayloadStructKeys =  ' + totaldatapayloadStructKeys  +  " + "\r\n" + "                         ' /totaldatapayloadStructValues =  ' + totaldatapayloadStructValues );  " + "\r\n" + "         DLog.printDebug(this,datapayloadStruct);  " + "\r\n" + "\r\n" + "         return datapayloadStruct;  " + "\r\n" + "     } " + "\r\n" + "\r\n" + "     extractData(payloadDataBytBuf, payloadDataFieldDef) " + "\r\n" + "     { " + "\r\n" + "         let dataPos = payloadDataFieldDef.POS || 0; " + "\r\n" + "         let dataType = payloadDataFieldDef.FMT || 'uint8'; " + "\r\n" + "         let dataLenInBytes = payloadDataFieldDef.LEN || 1; " + "\r\n" + "\r\n" + "         DLog.printDebug(this,' payloadDataFieldDef =  ' + dataPos + '/' + dataType + '/' + dataLenInBytes); " + "\r\n" + "\r\n" + "         switch (dataType) { " + "\r\n" + "             case 'uint8': " + "\r\n" + "                 return payloadDataBytBuf.getUint8(dataPos, true); // LITTLE_ENDIAN  " + "\r\n" + "             case 'uint16': " + "\r\n" + "                 return payloadDataBytBuf.getUint16(dataPos, true); " + "\r\n" + "             case 'uint32': " + "\r\n" + "                 return payloadDataBytBuf.getUint32(dataPos, true); " + "\r\n" + "             case 'uint64': " + "\r\n" + "                 return null; " + "\r\n" + "             case 'string_ascii': " + "\r\n" + "                 return this.extractStringData(payloadDataBytBuf, dataPos, dataLenInBytes) " + "\r\n" + "             default: " + "\r\n" + "                 return null; " + "\r\n" + "         } " + "\r\n" + "     } " + "\r\n" + "\r\n" + "     extractStringData(payloadDataBytBuf, keyvalueSeekPos, keyvalueLen) { " + "\r\n" + "         var keyvalueStr = ''; " + "\r\n" + "         if(keyvalueLen > BLE_CHARC_VALUE_MAX_LEN) " + "\r\n" + "         { " + "\r\n" + "             keyvalueLen = BLE_CHARC_VALUE_MAX_LEN; " + "\r\n" + "         } " + "\r\n" + "\r\n" + "         var keyvalueSeekPos = 0; " + "\r\n" + "         for(var m=0;m<keyvalueLen;m++) " + "\r\n" + "         { " + "\r\n" + "              var keyvaluebyte     = payloadDataBytBuf.getUint8(keyvalueSeekPos, true); " + "\r\n" + "              keyvalueStr = keyvalueStr + String.fromCharCode(keyvaluebyte); " + "\r\n" + "              DLog.printDebug(this, 'keyvalueStr= ' + keyvalueStr); " + "\r\n" + "              keyvalueSeekPos++; " + "\r\n" + "         } " + "\r\n" + "         DLog.printDebug(this, 'keyvalueStr= ' + keyvalueStr); " + "\r\n" + "         return keyvalueStr; " + "\r\n" + "      }" + "\r\n" + "\r\n" + "     byteArray2DVByteBuffer(byteArray) " + "\r\n" + "     { " + "\r\n" + "         var byteArrayLen = byteArray.length; " + "\r\n" + "\r\n" + "         if(byteArrayLen < 1) " + "\r\n" + "         { " + "\r\n" + "             DLog.printDebug(this,'packet byte arr size is zero = ' + byteArrayLen); " + "\r\n" + "             return null; " + "\r\n" + "         } " + "\r\n" + "\r\n" + "         DLog.printDebug(this,'packet byte arr size = ' + byteArrayLen); " + "\r\n" + "\r\n" + "         var objUint8Array   = new Uint8Array(new ArrayBuffer(byteArrayLen)); " + "\r\n" + "         objUint8Array.set(byteArray); " + "\r\n" + "\r\n" + "         var dvByteBuf  = new DataView(objUint8Array.buffer); " + "\r\n" + "         for(var m=0;m<byteArrayLen;m++) " + "\r\n" + "         { " + "\r\n" + "             DLog.printDebug(this,'DVByteBuf = ' + dvByteBuf.getUint8(m)); " + "\r\n" + "         } " + "\r\n" + "         return dvByteBuf; " + "\r\n" + "     } " + "\r\n" + "   } " + "\r\n" ; FileManager . CreateFile ( ".\\protocols\\PayloadParser.js" , outputSrc ) ; log ( "PayloadParser.js generated sucessfully	" ) ; log ( " ---------------------------------------------------------------------" ) ; }


Input: class Cli / //////////////////////// [CODESPLIT] function validateFiles ( files , stateLint ) { let ok = true for ( const file of files ) { try { ok = validate ( file , stateLint ) && ok } catch ( err ) { console . log ( ` ${ file } \n \t ${ err . message } ` ) ok = false } } // for ... return ok }


Input: validateFiles [CODESPLIT] function validate ( file , stateLint ) { const json = readAndParse ( file ) const problems = stateLint . validate ( json ) if ( problems . length ) { console . log ( ` ${ file } ` ) problems . forEach ( p => console . log ( ` \t ${ p } ` ) ) } return ( problems . length === 0 ) }


Input: readlines [CODESPLIT] function showIfHelp ( args , description ) { const name = path . basename ( args [ 1 ] ) const opts = args . slice ( 2 ) if ( ! ( opts . length === 1 && [ '--help' , '-h' , '-?' ] . includes ( opts [ 0 ] ) ) ) { return false } console . log ( ` ${ name } ` ) console . log ( '' ) console . log ( description ) return true }


Input: adjusts an axis default range [ h () + 1 1 ] if a NullValueSeparator is set [CODESPLIT] function getRange ( ) { if ( __ . nullValueSeparator == "bottom" ) { return [ h ( ) + 1 - __ . nullValueSeparatorPadding . bottom - __ . nullValueSeparatorPadding . top , 1 ] ; } else if ( __ . nullValueSeparator == "top" ) { return [ h ( ) + 1 , 1 + __ . nullValueSeparatorPadding . bottom + __ . nullValueSeparatorPadding . top ] ; } return [ h ( ) + 1 , 1 ] ; }


Input: draw single cubic bezier curve [CODESPLIT] function single_curve ( d , ctx ) { var centroids = compute_centroids ( d ) ; var cps = compute_control_points ( centroids ) ; ctx . moveTo ( cps [ 0 ] . e ( 1 ) , cps [ 0 ] . e ( 2 ) ) ; for ( var i = 1 ; i < cps . length ; i += 3 ) { if ( __ . showControlPoints ) { for ( var j = 0 ; j < 3 ; j ++ ) { ctx . fillRect ( cps [ i + j ] . e ( 1 ) , cps [ i + j ] . e ( 2 ) , 2 , 2 ) ; } } ctx . bezierCurveTo ( cps [ i ] . e ( 1 ) , cps [ i ] . e ( 2 ) , cps [ i + 1 ] . e ( 1 ) , cps [ i + 1 ] . e ( 2 ) , cps [ i + 2 ] . e ( 1 ) , cps [ i + 2 ] . e ( 2 ) ) ; } }


Input: draw single polyline [CODESPLIT] function color_path ( d , ctx ) { ctx . beginPath ( ) ; if ( ( __ . bundleDimension !== null && __ . bundlingStrength > 0 ) || __ . smoothness > 0 ) { single_curve ( d , ctx ) ; } else { single_path ( d , ctx ) ; } ctx . stroke ( ) ; }


Input: draw many polylines of the same color [CODESPLIT] function paths ( data , ctx ) { ctx . clearRect ( - 1 , - 1 , w ( ) + 2 , h ( ) + 2 ) ; ctx . beginPath ( ) ; data . forEach ( function ( d ) { if ( ( __ . bundleDimension !== null && __ . bundlingStrength > 0 ) || __ . smoothness > 0 ) { single_curve ( d , ctx ) ; } else { single_path ( d , ctx ) ; } } ) ; ctx . stroke ( ) ; }


Input: This function can be used for live updates of brushes . That is during the specification of a brush this method can be called to update the view . [CODESPLIT] function brushUpdated ( newSelection ) { __ . brushed = newSelection ; events . brush . call ( pc , __ . brushed ) ; pc . renderBrushed ( ) ; }


Input: data within extents [CODESPLIT] function selected ( ) { var actives = d3 . keys ( __ . dimensions ) . filter ( is_brushed ) , extents = actives . map ( function ( p ) { return brushes [ p ] . extent ( ) ; } ) ; // We don't want to return the full data set when there are no axes brushed. // Actually, when there are no axes brushed, by definition, no items are // selected. So, let's avoid the filtering and just return false. //if (actives.length === 0) return false; // Resolves broken examples for now. They expect to get the full dataset back from empty brushes if ( actives . length === 0 ) return __ . data ; // test if within range var within = { "date" : function ( d , p , dimension ) { if ( typeof __ . dimensions [ p ] . yscale . rangePoints === "function" ) { // if it is ordinal return extents [ dimension ] [ 0 ] <= __ . dimensions [ p ] . yscale ( d [ p ] ) && __ . dimensions [ p ] . yscale ( d [ p ] ) <= extents [ dimension ] [ 1 ] } else { return extents [ dimension ] [ 0 ] <= d [ p ] && d [ p ] <= extents [ dimension ] [ 1 ] } } , "number" : function ( d , p , dimension ) { if ( typeof __ . dimensions [ p ] . yscale . rangePoints === "function" ) { // if it is ordinal return extents [ dimension ] [ 0 ] <= __ . dimensions [ p ] . yscale ( d [ p ] ) && __ . dimensions [ p ] . yscale ( d [ p ] ) <= extents [ dimension ] [ 1 ] } else { return extents [ dimension ] [ 0 ] <= d [ p ] && d [ p ] <= extents [ dimension ] [ 1 ] } } , "string" : function ( d , p , dimension ) { return extents [ dimension ] [ 0 ] <= __ . dimensions [ p ] . yscale ( d [ p ] ) && __ . dimensions [ p ] . yscale ( d [ p ] ) <= extents [ dimension ] [ 1 ] } } ; return __ . data . filter ( function ( d ) { switch ( brush . predicate ) { case "AND" : return actives . every ( function ( p , dimension ) { return within [ __ . dimensions [ p ] . type ] ( d , p , dimension ) ; } ) ; case "OR" : return actives . some ( function ( p , dimension ) { return within [ __ . dimensions [ p ] . type ] ( d , p , dimension ) ; } ) ; default : throw new Error ( "Unknown brush predicate " + __ . brushPredicate ) ; } } ) ; }


Input: Checks if the first dimension is directly left of the second dimension . [CODESPLIT] function consecutive ( first , second ) { var length = d3 . keys ( __ . dimensions ) . length ; return d3 . keys ( __ . dimensions ) . some ( function ( d , i ) { return ( d === first ) ? i + i < length && __ . dimensions [ i + 1 ] === second : false ; } ) ; }