Input: Converts JSON schema to SQL schema [CODESPLIT] function generateSqlSchema ( dbDialect , metadata , prefix = undefined ) { check . assert . nonEmptyString ( dbDialect ) check . assert . object ( metadata ) check . assert . maybe . string ( prefix ) if ( ! Dialects . isSupported ( dbDialect ) ) { throw new Error ( ` ${ dbDialect } ` ) } prefix = prefix || '' const sqlSerializer = new SqlSerializer ( dbDialect ) const orderedEntities = getEntitiesOrderedByRelations ( metadata ) let queries = [ ] _ . forEach ( orderedEntities , ( entityName ) => { const entity = metadata [ entityName ] const tableName = pgEscape . ident ( ` ${ prefix } ${ entityName } ` ) let createQueries = [ ] _ . forOwn ( entity . fields , ( field , fieldName ) => { const columnName = pgEscape . ident ( fieldName ) let columnQuery = '' columnQuery += columnName let columnConstraints = [ ] const columnType = SqlSerializer . resolveType ( field . type ) columnQuery += ` ${ columnType } ` if ( field . enum ) { const enumValues = field . enum . map ( ( value ) => sqlSerializer . serializeValue ( field . type , value ) ) . join ( ', ' ) const expression = columnType . match ( / (\[\d*\])+ / g ) ? ` ${ enumValues } ` : ` ${ enumValues } ` columnConstraints . push ( ` ${ columnName } ${ expression } ` ) } // SQL doesn't have an "undefined" value, thus no-default would result a nullable column columnConstraints . push ( ( field . nullable || ( field . default === undefined && ! field . identity ) ) ? 'NULL' : 'NOT NULL' ) if ( field . default !== undefined ) { const value = sqlSerializer . serializeValue ( field . type , field . default ) columnConstraints . push ( ` ${ value } ` ) } if ( columnConstraints . length > 0 ) { columnQuery += ` ${ columnConstraints . join ( ' ' ) } ` } createQueries . push ( ` \n \t ${ columnQuery } ` ) } ) const identity = _ . chain ( entity . fields ) . pickBy ( ( field ) => field . identity ) . map ( ( field , fieldName ) => pgEscape . ident ( fieldName ) ) . value ( ) if ( identity . length > 0 ) { const primaryKeyName = pgEscape . ident ( ` ${ prefix } ${ entityName } ` ) const uniqueName = pgEscape . ident ( ` ${ prefix } ${ entityName } ` ) const columns = identity . join ( ', ' ) createQueries . push ( ` \n \t ${ primaryKeyName } ${ columns } ` ) createQueries . push ( ` \n \t ${ uniqueName } ${ columns } ` ) } let referencesCount = 0 const references = _ . chain ( entity . fields ) . pickBy ( ( field ) => field . relation ) . toPairs ( ) . groupBy ( ( pair ) => pair [ 1 ] . relation . entity ) . value ( ) _ . forOwn ( references , ( pairs , otherEntityName ) => { const otherTableName = pgEscape . ident ( ` ${ prefix } ${ otherEntityName } ` ) const constraintName = pgEscape . ident ( ` ${ prefix } ${ entityName } ${ referencesCount ++ } ` ) pairs = _ . zip ( ... pairs ) const fieldsList = pairs [ 0 ] . map ( ( fieldName ) => pgEscape . ident ( fieldName ) ) . join ( ', ' ) const otherEntityFieldsList = pairs [ 1 ] . map ( ( field ) => pgEscape . ident ( field . relation . field ) ) . join ( ', ' ) let foreignConstraint = '' foreignConstraint += ` \n \t ${ constraintName } ${ fieldsList } ` foreignConstraint += ` \n \t \t ${ otherTableName } ${ otherEntityFieldsList } ` foreignConstraint += '\n\t\tON DELETE CASCADE' foreignConstraint += '\n\t\tON UPDATE CASCADE' createQueries . push ( foreignConstraint ) } ) let createQuery = '' createQuery += ` ${ tableName } ` createQuery += createQueries . join ( ',' ) createQuery += createQueries . length > 0 ? '\n)' : ')' queries . push ( createQuery ) } ) return queries }


Input: 根据名字获取全局对象 [CODESPLIT] function getGlobalObj ( str , root ) { for ( var i = 0 ; i < root . length ; ++ i ) { if ( root [ i ] . name == str ) { return root [ i ] ; } } return undefined ; }


Input: callback ( structname obj root ) [CODESPLIT] function forEachStruct ( structname , obj , root , callback , noexline ) { if ( noexline == undefined ) { noexline = false ; } for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( noexline && obj . val [ i ] . name . name . indexOf ( '_' ) == 0 ) { continue ; } if ( obj . val [ i ] . hasOwnProperty ( 'type2' ) && obj . val [ i ] . type2 == 'expand' ) { if ( ! obj . val [ i ] . hasOwnProperty ( 'expand' ) ) { forEachStruct ( structname , getGlobalObj ( obj . val [ i ] . type , root ) , root , callback ) ; } else { var expandobj = getGlobalObj ( obj . val [ i ] . expand , root ) ; for ( var eoi = 0 ; eoi < expandobj . val . length ; ++ eoi ) { callback ( structname , { name : { name : getEnumMemberRealName ( expandobj . val [ eoi ] . name , expandobj . name ) } , type : obj . val [ i ] . type , comment : expandobj . val [ eoi ] . comment } , root ) ; } } } else { if ( obj . name != structname && obj . val [ i ] . hasOwnProperty ( 'type2' ) && obj . val [ i ] . type2 == 'primary' ) { callback ( structname , { name : obj . val [ i ] . name , val : obj . val [ i ] . val , type : obj . val [ i ] . type , type2 : 'unique' } , root ) ; } else { callback ( structname , obj . val [ i ] , root ) ; } } } }


Input: function isStaticStruct ( name root ) { var obj = getGlobalObj ( name root ) ; if ( obj ! = undefined ) { if ( obj . type == static ) { return true ; } if ( obj . type == struct ) { for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( isBaseType ( obj . val [ i ] . type )) { if ( ! ( obj . val [ i ] . hasOwnProperty ( type2 ) && obj . val [ i ] . type2 == primary )) { return false ; } } else { if ( !isStaticStruct ( obj . val [ i ] . type root )) { return false ; } } } return true ; } } return false ; } [CODESPLIT] function getStructMemberType ( membername , structname , root ) { var obj = getGlobalObj ( structname , root ) ; if ( obj != undefined ) { if ( obj . type == 'message' || obj . type == 'struct' || obj . type == 'static' ) { for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( obj . val [ i ] . name . name == membername ) { return obj . val [ i ] . type ; } } } } return undefined ; }


Input: 根据名字取到成员 [CODESPLIT] function getMember ( obj , name , root ) { var ii = str . indexOf ( '.' ) ; if ( ii < 0 ) { var curobj = undefined ; forEachStruct ( obj . name , obj , root , function ( structname , cobj , root ) { if ( name == cobj . name . name ) { curobj = cobj ; } } ) ; return curobj ; } if ( ii == 0 ) { return ; } var curtype = undefined ; var cur = str . slice ( 0 , ii ) ; forEachStruct ( obj . name , obj , root , function ( structname , cobj , root ) { if ( cur == cobj . name . name ) { curtype = cobj . type ; } } ) ; if ( curtype != undefined ) { return getMember ( getGlobalObj ( curtype , root ) , str . slice ( ii + 1 ) , root ) ; } return ; }


Input: 为结构增加标识 [CODESPLIT] function setInMessage ( obj , root ) { obj . inmessage = true ; if ( obj . type == 'static' || obj . type == 'struct' || obj . type == 'message' ) { for ( var i = 0 ; i < obj . val . length ; ++ i ) { var cval = obj . val [ i ] ; if ( cval . hasOwnProperty ( 'type2' ) && 'expand' == cval . type2 ) { continue ; } var mytype = getRealType ( cval . type , root ) ; if ( isBaseType ( mytype ) ) { continue ; } setInMessage ( getGlobalObj ( mytype , root ) , root ) ; } } }


Input: 为所有消息内结构增加标识 [CODESPLIT] function procInMessage ( root ) { for ( var i = 0 ; i < root . length ; ++ i ) { if ( 'message' == root [ i ] . type ) { setInMessage ( root [ i ] , root ) ; } } return root ; }


Input: 获取版本号 [CODESPLIT] function getVer ( root ) { let cur = getGlobalObj ( 'VER' , root ) ; if ( cur == undefined ) { return '' ; } return cur . val . val ; }


Input: Represents an RPC interface [CODESPLIT] function RPC ( contact , options ) { assert ( this instanceof RPC , 'Invalid instance supplied' ) assert ( contact instanceof Contact , 'Invalid contact was supplied' ) events . EventEmitter . call ( this ) options = options || { } if ( options . replyto ) { assert ( options . replyto instanceof Contact , 'Invalid contact was supplied' ) } this . _hooks = { before : { } , after : { } } this . _pendingCalls = { } this . _contact = options . replyto || contact this . _log = options && options . logger this . readyState = 0 this . open ( ) }


Input: Returns true if the passed element ( s ) match the passed simple selector ( e . g . div . some - class or span : first - child ) [CODESPLIT] function ( el , q ) { var root , is , i , ln ; if ( typeof el == "string" ) { el = document . getElementById ( el ) ; } if ( Ext . isArray ( el ) ) { is = true ; ln = el . length ; for ( i = 0 ; i < ln ; i ++ ) { if ( ! this . is ( el [ i ] , q ) ) { is = false ; break ; } } } else { root = el . parentNode ; if ( ! root ) { root = document . createDocumentFragment ( ) ; root . appendChild ( el ) ; is = this . select ( q , root ) . indexOf ( el ) !== - 1 ; root . removeChild ( el ) ; root = null ; } else { is = this . select ( q , root ) . indexOf ( el ) !== - 1 ; } } return is ; }


Input: An Channel is where messages are sent to and receive [CODESPLIT] function Channel ( id , exchange ) { var self = this ; events . EventEmitter . call ( this ) ; this . id = id ; this . exchange = exchange ; this . exchange . on ( this . id , function ( message ) { self . emit ( 'message' , message ) ; } ) ; this . setMaxListeners ( 0 ) ; }


Input: Defines a metric that measures availability by number of requests / responses [CODESPLIT] function AvailabilityMetric ( ) { if ( ! ( this instanceof AvailabilityMetric ) ) { return new AvailabilityMetric ( ) } Metric . call ( this ) this . key = 'availability' this . default = [ 0 , 0 ] // [requests,responses] this . hooks = [ { trigger : 'before' , event : 'send' , handler : this . _start } , { trigger : 'before' , event : 'receive' , handler : this . _stop } ] }


Input: # HELPERS Additional functions that adds to the original jam function . [CODESPLIT] function includeHelpers ( func ) { // ## jam.identity() // Simple function that passes the values it receives to the next function. // Useful if you need a `process.nextTick` inserted in-between your call chain. func . identity = function ( next ) { function _identity ( next ) { var args = arguments ; tick ( function ( ) { next . apply ( this , replaceHead ( args , null ) ) ; } ) ; } // This function can also be passed to jam verbatim. return ( typeof next === 'function' ) ? _identity . apply ( this , arguments ) : _identity ; } ; // ## jam.nextTick() // Alias for `.identity`. Use when you need a `process.nextTick` inserted in-between // your call chain. func . nextTick = func . identity // ## jam.return( [args...] ) // Returns a set of values to the next function in the chain. Useful when you want to // pass in the next function verbatim without wrapping it in a `function() { }` just // to pass values into it. func . return = function ( ) { var args = toArgs ( arguments ) ; return function ( next ) { args . unshift ( null ) ; next . apply ( this , args ) ; } ; } ; // ## jam.null() // Similar to `.identity` but absorbs all arguments that has been passed to it and // forward nothing to the next function. Effectively nullifying any arguments passed // from previous jam call. //  // Like `jam.identity`, this function can be passed to the jam chain verbatim. func . null = function ( next ) { function _null ( next ) { next ( ) ; } return ( typeof next === 'function' ) ? _null . call ( this , next ) : _null ; } ; // ## jam.call( function, [args...] ) // Convenience for calling functions that accepts arguments in standard node.js // convention. Since jam insert `next` as first argument, most functions cannot be // passed directly into the jam chain, thus this helper function. //  // If no `args` is given, this function passes arguments given to `next()` call from // previous function directly to the function (with proper callback) placement). //  // Use this in combination with `jam.return` or `jam.null` if you want to control the // arguments that are passed to the function. func . call = function ( func ) { ensureFunc ( func , 'function' ) ; var args = toArgs ( arguments ) ; args . shift ( ) ; // func if ( args . length ) { // use provided arguments return function ( next ) { args . push ( next ) ; func . apply ( this , args ) ; } ; } else { // use passed-in arguments during chain resolution return function ( next ) { args = toArgs ( arguments ) ; args . shift ( ) ; // move next to last position args . push ( next ) ; func . apply ( this , args ) ; } ; } } ; // ## jam.each( array, iterator( next, element, index ) ) // Execute the given `iterator` function for each element given in the `array`. The // iterator is given a `next` function and the element to act on. The next step in the // chain will receive the original array passed verbatim so you can chain multiple // `.each` calls to act on the same array. //  // You can also pass `arguments` and `"strings"` as an array or you can omit the array // entirely, in which case this method will assume that the previous chain step // returns something that looks like an array as its first result. //  // Under the hood, a JAM step is added for each element. So the iterator will be // called serially, one after another finish. A parallel version maybe added in the // future. func . each = function ( array , iterator ) { if ( typeof array === 'function' ) { iterator = array ; array = null } else { ensureArray ( array , 'array' ) ; } ensureFunc ( iterator , 'iterator' ) ; return function ( next , array_ ) { var arr = array || array_ ; // Builds another JAM chain internally var chain = jam ( jam . identity ) , count = arr . length ; for ( var i = 0 ; i < count ; i ++ ) ( function ( element , i ) { chain = chain ( function ( next ) { iterator ( next , element , i ) ; } ) ; } ) ( arr [ i ] , i ) ; chain = chain ( function ( next ) { next ( null , arr ) ; } ) ; return chain ( next ) ; } ; } ; // ## jam.map( array, iterator( next, element, index ) ) // Works exactly like the `each` helper but if a value is passed to the iterator's // `next` function, it is collected into a new array which will be passed to the next // function in the JAM chain after `map`. //  // Like with `each`, you can omit the `array` input, in which case this method will // assume that the previous chain step returns something that looks like an array as // its first result. func . map = function ( array , iterator ) { if ( typeof array === 'function' ) { iterator = array ; array = null ; } else { ensureArray ( array , 'array' ) ; } ensureFunc ( iterator , 'iterator' ) ; return function ( next , array_ ) { var arr = array || array_ ; // Builds another JAM chain internally and collect results. // TODO: Dry with .each? var chain = jam ( jam . identity ) , count = arr . length , result = [ ] ; for ( var i = 0 ; i < count ; i ++ ) ( function ( element , i ) { chain = chain ( function ( next , previous ) { result . push ( previous ) ; iterator ( next , element , i ) ; } ) ; } ) ( arr [ i ] , i ) ; chain = chain ( function ( next , last ) { result . push ( last ) ; result . shift ( ) ; // discard first undefined element next ( null , result ) ; } ) ; return chain ( next ) ; } ; } ; // ## jam.timeout( timeout ) // Pauses the chain for the specified `timeout` using `setTimeout`. Useful for // inserting a delay in-between a long jam chain. func . timeout = function ( timeout ) { ensureNum ( timeout , 'timeout' ) ; return function ( next ) { var args = replaceHead ( arguments , null ) ; setTimeout ( function ( ) { next . apply ( this , args ) ; } , timeout ) ; } ; } ; // ## jam.promise( [chain] ) // Returns a JAM promise, useful when you are starting an asynchronous call outside of // the JAM chain itself but wants the callback to call into the chain. In other words, // this allow you to put a 'waiting point' (aka promise?) into existing JAM chain that // waits for the initial call to finish and also pass any arguments passed to the // callback to the next step in the JAM chain as well. // // This function will returns a callback that automatically bridges into the JAM // chain. You can pass the returned callback to any asynchronous function and the JAM // chain (at the point of calling .promise()) will wait for that asynchronous function // to finish effectively creating a 'waiting point'. // // Additionally, any arguments passed to the callback are forwarded to the next call // in the JAM chain as well. If errors are passed, then it is fast-forwarded to the // last handler normally like normal JAM steps. func . promise = function ( chain ) { chain = typeof chain === 'function' ? chain : // chain is supplied typeof this === 'function' ? this : // called from the chain variable ensureFunc ( chain , 'chain' ) ; // fails if ( typeof chain === 'undefined' && typeof this === 'function' ) { chain = this ; } var args = null , next = null ; chain ( function ( next_ ) { if ( args ) return next_ . apply ( this , args ) ; // callback already called next = next_ ; // wait for callback } ) ; return function ( ) { if ( next ) return next . apply ( this , arguments ) ; // chain promise already called args = arguments ; // wait for chain to call the promise } ; } ; // TODO: noError() ? or absorbError() return func ; }


Input: # JAM function Exported function starts the asynchronous call chain . [CODESPLIT] function jam ( func , context ) { ensureFunc ( func , 'function' ) ; var steps = [ ] ; // ##### Chain resolver. // The resolver will execute all functions passed to the chain as soon as `nextTick`. // Thus jam will not works across async context where the chain is not built all at // once in a single event loop, which is not really a problem from my personal // experience. tick ( function resolve ( e ) { var args = Array . prototype . slice . call ( arguments ) ; // Any errors passed to next() are (fast-)forwarded to the last function in the // chain skipping any functions that's left to be executed. if ( e ) return steps [ steps . length - 1 ] . apply ( this , args ) ; // Any parameters given to next() are passed as arguments to the next function in // the chain (except for errors, of course.) var next = steps . shift ( ) , args = Array . prototype . slice . call ( arguments ) if ( steps . length ) { args . shift ( ) ; // error arg args . unshift ( resolve ) ; // next() function } return next . apply ( this , args ) ; } ) ; // ##### Chain context continuation. // Subsequent invocation of the function returned from the `jam` function simply adds // the given function to the chain. function continuable ( func , context ) { ensureFunc ( func , 'function' ) ; if ( context ) { // TODO: Handle falsy things? func = bind ( func , context ) ; } steps . push ( func ) ; return continuable ; } ; return includeHelpers ( continuable ( func , context ) ) ; }


Input: Subsequent invocation of the function returned from the jam function simply adds the given function to the chain . [CODESPLIT] function continuable ( func , context ) { ensureFunc ( func , 'function' ) ; if ( context ) { // TODO: Handle falsy things? func = bind ( func , context ) ; } steps . push ( func ) ; return continuable ; }


Input: Extracts description from contents of a readme file in markdown format [CODESPLIT] function extractDescription ( d ) { if ( ! d ) return ; if ( d === "ERROR: No README data found!" ) return ; // the first block of text before the first heading // that isn't the first line heading d = d . trim ( ) . split ( '\n' ) for ( var s = 0 ; d [ s ] && d [ s ] . trim ( ) . match ( / ^(#|$) / ) ; s ++ ) ; var l = d . length for ( var e = s + 1 ; e < l && d [ e ] . trim ( ) ; e ++ ) ; return d . slice ( s , e ) . join ( ' ' ) . trim ( ) }


Input: 7 . 4 Comments [CODESPLIT] function addComment ( type , value , start , end , loc ) { var comment ; assert ( typeof start === 'number' , 'Comment must have valid position' ) ; // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if ( state . lastCommentStart >= start ) { return ; } state . lastCommentStart = start ; comment = { type : type , value : value } ; if ( extra . range ) { comment . range = [ start , end ] ; } if ( extra . loc ) { comment . loc = loc ; } extra . comments . push ( comment ) ; if ( extra . attachComment ) { extra . leadingComments . push ( comment ) ; extra . trailingComments . push ( comment ) ; } }


Input: 7 . 7 Punctuators [CODESPLIT] function scanPunctuator ( ) { var start = index , code = source . charCodeAt ( index ) , code2 , ch1 = source [ index ] , ch2 , ch3 , ch4 ; if ( state . inJSXTag || state . inJSXChild ) { // Don't need to check for '{' and '}' as it's already handled // correctly by default. switch ( code ) { case 60 : // < case 62 : // > ++ index ; return { type : Token . Punctuator , value : String . fromCharCode ( code ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } } switch ( code ) { // Check for most common single-character punctuators. case 40 : // ( open bracket case 41 : // ) close bracket case 59 : // ; semicolon case 44 : // , comma case 91 : // [ case 93 : // ] case 58 : // : case 63 : // ? case 126 : // ~ ++ index ; if ( extra . tokenize && code === 40 ) { extra . openParenToken = extra . tokens . length ; } return { type : Token . Punctuator , value : String . fromCharCode ( code ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; case 123 : // { open curly brace case 125 : // } close curly brace ++ index ; if ( extra . tokenize && code === 123 ) { extra . openCurlyToken = extra . tokens . length ; } // lookahead2 function can cause tokens to be scanned twice and in doing so // would wreck the curly stack by pushing the same token onto the stack twice. // curlyLastIndex ensures each token is pushed or popped exactly once if ( index > state . curlyLastIndex ) { state . curlyLastIndex = index ; if ( code === 123 ) { state . curlyStack . push ( '{' ) ; } else { state . curlyStack . pop ( ) ; } } return { type : Token . Punctuator , value : String . fromCharCode ( code ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; default : code2 = source . charCodeAt ( index + 1 ) ; // '=' (char #61) marks an assignment or comparison operator. if ( code2 === 61 ) { switch ( code ) { case 37 : // % case 38 : // & case 42 : // *: case 43 : // + case 45 : // - case 47 : // / case 60 : // < case 62 : // > case 94 : // ^ case 124 : // | index += 2 ; return { type : Token . Punctuator , value : String . fromCharCode ( code ) + String . fromCharCode ( code2 ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; case 33 : // ! case 61 : // = index += 2 ; // !== and === if ( source . charCodeAt ( index ) === 61 ) { ++ index ; } return { type : Token . Punctuator , value : source . slice ( start , index ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; default : break ; } } break ; } // Peek more characters. ch2 = source [ index + 1 ] ; ch3 = source [ index + 2 ] ; ch4 = source [ index + 3 ] ; // 4-character punctuator: >>>= if ( ch1 === '>' && ch2 === '>' && ch3 === '>' ) { if ( ch4 === '=' ) { index += 4 ; return { type : Token . Punctuator , value : '>>>=' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } } // 3-character punctuators: === !== >>> <<= >>= if ( ch1 === '>' && ch2 === '>' && ch3 === '>' && ! state . inType ) { index += 3 ; return { type : Token . Punctuator , value : '>>>' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '<' && ch2 === '<' && ch3 === '=' ) { index += 3 ; return { type : Token . Punctuator , value : '<<=' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '>' && ch2 === '>' && ch3 === '=' ) { index += 3 ; return { type : Token . Punctuator , value : '>>=' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '.' && ch2 === '.' && ch3 === '.' ) { index += 3 ; return { type : Token . Punctuator , value : '...' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map<string, Array<string>> if ( ch1 === ch2 && ( '+-<>&|' . indexOf ( ch1 ) >= 0 ) && ! state . inType ) { index += 2 ; return { type : Token . Punctuator , value : ch1 + ch2 , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '=' && ch2 === '>' ) { index += 2 ; return { type : Token . Punctuator , value : '=>' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( '<>=!+-*%&|^/' . indexOf ( ch1 ) >= 0 ) { ++ index ; return { type : Token . Punctuator , value : ch1 , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '.' ) { ++ index ; return { type : Token . Punctuator , value : ch1 , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } throwError ( { } , Messages . UnexpectedToken , 'ILLEGAL' ) ; }


Input: Expect the next token to match the specified keyword . If not an exception will be thrown . [CODESPLIT] function expectKeyword ( keyword , contextual ) { var token = lex ( ) ; if ( token . type !== ( contextual ? Token . Identifier : Token . Keyword ) || token . value !== keyword ) { throwUnexpected ( token ) ; } }


Input: 11 . 1 . 4 Array Initialiser [CODESPLIT] function parseArrayInitialiser ( ) { var elements = [ ] , blocks = [ ] , filter = null , tmp , possiblecomprehension = true , marker = markerCreate ( ) ; expect ( '[' ) ; while ( ! match ( ']' ) ) { if ( lookahead . value === 'for' && lookahead . type === Token . Keyword ) { if ( ! possiblecomprehension ) { throwError ( { } , Messages . ComprehensionError ) ; } matchKeyword ( 'for' ) ; tmp = parseForStatement ( { ignoreBody : true } ) ; tmp . of = tmp . type === Syntax . ForOfStatement ; tmp . type = Syntax . ComprehensionBlock ; if ( tmp . left . kind ) { // can't be let or const throwError ( { } , Messages . ComprehensionError ) ; } blocks . push ( tmp ) ; } else if ( lookahead . value === 'if' && lookahead . type === Token . Keyword ) { if ( ! possiblecomprehension ) { throwError ( { } , Messages . ComprehensionError ) ; } expectKeyword ( 'if' ) ; expect ( '(' ) ; filter = parseExpression ( ) ; expect ( ')' ) ; } else if ( lookahead . value === ',' && lookahead . type === Token . Punctuator ) { possiblecomprehension = false ; // no longer allowed. lex ( ) ; elements . push ( null ) ; } else { tmp = parseSpreadOrAssignmentExpression ( ) ; elements . push ( tmp ) ; if ( tmp && tmp . type === Syntax . SpreadElement ) { if ( ! match ( ']' ) ) { throwError ( { } , Messages . ElementAfterSpreadElement ) ; } } else if ( ! ( match ( ']' ) || matchKeyword ( 'for' ) || matchKeyword ( 'if' ) ) ) { expect ( ',' ) ; // this lexes. possiblecomprehension = false ; } } } expect ( ']' ) ; if ( filter && ! blocks . length ) { throwError ( { } , Messages . ComprehensionRequiresBlock ) ; } if ( blocks . length ) { if ( elements . length !== 1 ) { throwError ( { } , Messages . ComprehensionError ) ; } return markerApply ( marker , delegate . createComprehensionExpression ( filter , blocks , elements [ 0 ] ) ) ; } return markerApply ( marker , delegate . createArrayExpression ( elements ) ) ; }


Input: 11 . 1 . 5 Object Initialiser [CODESPLIT] function parsePropertyFunction ( options ) { var previousStrict , previousYieldAllowed , previousAwaitAllowed , params , defaults , body , marker = markerCreate ( ) ; previousStrict = strict ; previousYieldAllowed = state . yieldAllowed ; state . yieldAllowed = options . generator ; previousAwaitAllowed = state . awaitAllowed ; state . awaitAllowed = options . async ; params = options . params || [ ] ; defaults = options . defaults || [ ] ; body = parseConciseBody ( ) ; if ( options . name && strict && isRestrictedWord ( params [ 0 ] . name ) ) { throwErrorTolerant ( options . name , Messages . StrictParamName ) ; } strict = previousStrict ; state . yieldAllowed = previousYieldAllowed ; state . awaitAllowed = previousAwaitAllowed ; return markerApply ( marker , delegate . createFunctionExpression ( null , params , defaults , body , options . rest || null , options . generator , body . type !== Syntax . BlockStatement , options . async , options . returnType , options . typeParameters ) ) ; }


Input: 11 . 3 Postfix Expressions [CODESPLIT] function parsePostfixExpression ( ) { var marker = markerCreate ( ) , expr = parseLeftHandSideExpressionAllowCall ( ) , token ; if ( lookahead . type !== Token . Punctuator ) { return expr ; } if ( ( match ( '++' ) || match ( '--' ) ) && ! peekLineTerminator ( ) ) { // 11.3.1, 11.3.2 if ( strict && expr . type === Syntax . Identifier && isRestrictedWord ( expr . name ) ) { throwErrorTolerant ( { } , Messages . StrictLHSPostfix ) ; } if ( ! isLeftHandSide ( expr ) ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } token = lex ( ) ; expr = markerApply ( marker , delegate . createPostfixExpression ( token . value , expr ) ) ; } return expr ; }


Input: 11 . 4 Unary Operators [CODESPLIT] function parseUnaryExpression ( ) { var marker , token , expr ; if ( lookahead . type !== Token . Punctuator && lookahead . type !== Token . Keyword ) { return parsePostfixExpression ( ) ; } if ( match ( '++' ) || match ( '--' ) ) { marker = markerCreate ( ) ; token = lex ( ) ; expr = parseUnaryExpression ( ) ; // 11.4.4, 11.4.5 if ( strict && expr . type === Syntax . Identifier && isRestrictedWord ( expr . name ) ) { throwErrorTolerant ( { } , Messages . StrictLHSPrefix ) ; } if ( ! isLeftHandSide ( expr ) ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } return markerApply ( marker , delegate . createUnaryExpression ( token . value , expr ) ) ; } if ( match ( '+' ) || match ( '-' ) || match ( '~' ) || match ( '!' ) ) { marker = markerCreate ( ) ; token = lex ( ) ; expr = parseUnaryExpression ( ) ; return markerApply ( marker , delegate . createUnaryExpression ( token . value , expr ) ) ; } if ( matchKeyword ( 'delete' ) || matchKeyword ( 'void' ) || matchKeyword ( 'typeof' ) ) { marker = markerCreate ( ) ; token = lex ( ) ; expr = parseUnaryExpression ( ) ; expr = markerApply ( marker , delegate . createUnaryExpression ( token . value , expr ) ) ; if ( strict && expr . operator === 'delete' && expr . argument . type === Syntax . Identifier ) { throwErrorTolerant ( { } , Messages . StrictDelete ) ; } return expr ; } return parsePostfixExpression ( ) ; }


Input: 11 . 13 Assignment Operators 12 . 14 . 5 AssignmentPattern [CODESPLIT] function reinterpretAsAssignmentBindingPattern ( expr ) { var i , len , property , element ; if ( expr . type === Syntax . ObjectExpression ) { expr . type = Syntax . ObjectPattern ; for ( i = 0 , len = expr . properties . length ; i < len ; i += 1 ) { property = expr . properties [ i ] ; if ( property . type === Syntax . SpreadProperty ) { if ( i < len - 1 ) { throwError ( { } , Messages . PropertyAfterSpreadProperty ) ; } reinterpretAsAssignmentBindingPattern ( property . argument ) ; } else { if ( property . kind !== 'init' ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } reinterpretAsAssignmentBindingPattern ( property . value ) ; } } } else if ( expr . type === Syntax . ArrayExpression ) { expr . type = Syntax . ArrayPattern ; for ( i = 0 , len = expr . elements . length ; i < len ; i += 1 ) { element = expr . elements [ i ] ; /* istanbul ignore else */ if ( element ) { reinterpretAsAssignmentBindingPattern ( element ) ; } } } else if ( expr . type === Syntax . Identifier ) { if ( isRestrictedWord ( expr . name ) ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } } else if ( expr . type === Syntax . SpreadElement ) { reinterpretAsAssignmentBindingPattern ( expr . argument ) ; if ( expr . argument . type === Syntax . ObjectPattern ) { throwError ( { } , Messages . ObjectPatternAsSpread ) ; } } else { /* istanbul ignore else */ if ( expr . type !== Syntax . MemberExpression && expr . type !== Syntax . CallExpression && expr . type !== Syntax . NewExpression ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } } }


Input: 12 . 4 Expression Statement [CODESPLIT] function parseExpressionStatement ( ) { var marker = markerCreate ( ) , expr = parseExpression ( ) ; consumeSemicolon ( ) ; return markerApply ( marker , delegate . createExpressionStatement ( expr ) ) ; }


Input: 12 . 9 The return statement [CODESPLIT] function parseReturnStatement ( ) { var argument = null , marker = markerCreate ( ) ; expectKeyword ( 'return' ) ; if ( ! state . inFunctionBody ) { throwErrorTolerant ( { } , Messages . IllegalReturn ) ; } // 'return' followed by a space and an identifier is very common. if ( source . charCodeAt ( index ) === 32 ) { if ( isIdentifierStart ( source . charCodeAt ( index + 1 ) ) ) { argument = parseExpression ( ) ; consumeSemicolon ( ) ; return markerApply ( marker , delegate . createReturnStatement ( argument ) ) ; } } if ( peekLineTerminator ( ) ) { return markerApply ( marker , delegate . createReturnStatement ( null ) ) ; } if ( ! match ( ';' ) ) { if ( ! match ( '}' ) && lookahead . type !== Token . EOF ) { argument = parseExpression ( ) ; } } consumeSemicolon ( ) ; return markerApply ( marker , delegate . createReturnStatement ( argument ) ) ; }


Input: 12 Statements [CODESPLIT] function parseStatement ( ) { var type = lookahead . type , marker , expr , labeledBody ; if ( type === Token . EOF ) { throwUnexpected ( lookahead ) ; } if ( type === Token . Punctuator ) { switch ( lookahead . value ) { case ';' : return parseEmptyStatement ( ) ; case '{' : return parseBlock ( ) ; case '(' : return parseExpressionStatement ( ) ; default : break ; } } if ( type === Token . Keyword ) { switch ( lookahead . value ) { case 'break' : return parseBreakStatement ( ) ; case 'continue' : return parseContinueStatement ( ) ; case 'debugger' : return parseDebuggerStatement ( ) ; case 'do' : return parseDoWhileStatement ( ) ; case 'for' : return parseForStatement ( ) ; case 'function' : return parseFunctionDeclaration ( ) ; case 'class' : return parseClassDeclaration ( ) ; case 'if' : return parseIfStatement ( ) ; case 'return' : return parseReturnStatement ( ) ; case 'switch' : return parseSwitchStatement ( ) ; case 'throw' : return parseThrowStatement ( ) ; case 'try' : return parseTryStatement ( ) ; case 'var' : return parseVariableStatement ( ) ; case 'while' : return parseWhileStatement ( ) ; case 'with' : return parseWithStatement ( ) ; default : break ; } } if ( matchAsyncFuncExprOrDecl ( ) ) { return parseFunctionDeclaration ( ) ; } marker = markerCreate ( ) ; expr = parseExpression ( ) ; // 12.12 Labelled Statements if ( ( expr . type === Syntax . Identifier ) && match ( ':' ) ) { lex ( ) ; if ( state . labelSet . has ( expr . name ) ) { throwError ( { } , Messages . Redeclaration , 'Label' , expr . name ) ; } state . labelSet . set ( expr . name , true ) ; labeledBody = parseStatement ( ) ; state . labelSet . delete ( expr . name ) ; return markerApply ( marker , delegate . createLabeledStatement ( expr , labeledBody ) ) ; } consumeSemicolon ( ) ; return markerApply ( marker , delegate . createExpressionStatement ( expr ) ) ; }


Input: 15 Program [CODESPLIT] function parseSourceElement ( ) { var token ; if ( lookahead . type === Token . Keyword ) { switch ( lookahead . value ) { case 'const' : case 'let' : return parseConstLetDeclaration ( lookahead . value ) ; case 'function' : return parseFunctionDeclaration ( ) ; case 'export' : throwErrorTolerant ( { } , Messages . IllegalExportDeclaration ) ; return parseExportDeclaration ( ) ; case 'import' : throwErrorTolerant ( { } , Messages . IllegalImportDeclaration ) ; return parseImportDeclaration ( ) ; case 'interface' : if ( lookahead2 ( ) . type === Token . Identifier ) { return parseInterface ( ) ; } return parseStatement ( ) ; default : return parseStatement ( ) ; } } if ( matchContextualKeyword ( 'type' ) && lookahead2 ( ) . type === Token . Identifier ) { return parseTypeAlias ( ) ; } if ( matchContextualKeyword ( 'interface' ) && lookahead2 ( ) . type === Token . Identifier ) { return parseInterface ( ) ; } if ( matchContextualKeyword ( 'declare' ) ) { token = lookahead2 ( ) ; if ( token . type === Token . Keyword ) { switch ( token . value ) { case 'class' : return parseDeclareClass ( ) ; case 'function' : return parseDeclareFunction ( ) ; case 'var' : return parseDeclareVariable ( ) ; } } else if ( token . type === Token . Identifier && token . value === 'module' ) { return parseDeclareModule ( ) ; } } if ( lookahead . type !== Token . EOF ) { return parseStatement ( ) ; } }


Input: Between JSX opening and closing tags ( e . g . <foo > HERE< / foo > ) anything that is not another JSX tag and is not an expression wrapped by {} is text . [CODESPLIT] function advanceJSXChild ( ) { var ch = source . charCodeAt ( index ) ; // '<' 60, '>' 62, '{' 123, '}' 125 if ( ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125 ) { return scanJSXText ( [ '<' , '>' , '{' , '}' ] ) ; } return scanPunctuator ( ) ; }


Input: This is used to modify the delegate . [CODESPLIT] function extend ( object , properties ) { var entry , result = { } ; for ( entry in object ) { /* istanbul ignore else */ if ( object . hasOwnProperty ( entry ) ) { result [ entry ] = object [ entry ] ; } } for ( entry in properties ) { /* istanbul ignore else */ if ( properties . hasOwnProperty ( entry ) ) { result [ entry ] = properties [ entry ] ; } } return result ; }


Input: Converts bef : aft to { _before : bef _after : aft } and resolves undefined before / after from parent or root [CODESPLIT] function resolve ( value , key ) { // resolve before/after from root or parent if it isn't present on the current node if ( ! value . _parent ) return undefined ; // Immediate parent if ( value . _parent . _default && value . _parent . _default [ key ] ) return value . _parent . _default [ key ] ; // Root var root = value . _parent . _parent ; if ( ! root ) return undefined ; return root . _default ? root . _default [ key ] : undefined ; }


Input: Clones ( copies ) an Object using deep copying . [CODESPLIT] function clone ( parent , circular , depth , prototype ) { var filter ; if ( typeof circular === 'object' ) { depth = circular . depth ; prototype = circular . prototype ; filter = circular . filter ; circular = circular . circular } // maintain two arrays for circular references, where corresponding parents // and children have the same index var allParents = [ ] ; var allChildren = [ ] ; var useBuffer = typeof Buffer != 'undefined' ; if ( typeof circular == 'undefined' ) circular = true ; if ( typeof depth == 'undefined' ) depth = Infinity ; // recurse this function so we don't reset allParents and allChildren function _clone ( parent , depth ) { // cloning null always returns null if ( parent === null ) return null ; if ( depth == 0 ) return parent ; var child ; var proto ; if ( typeof parent != 'object' ) { return parent ; } if ( clone . __isArray ( parent ) ) { child = [ ] ; } else if ( clone . __isRegExp ( parent ) ) { child = new RegExp ( parent . source , __getRegExpFlags ( parent ) ) ; if ( parent . lastIndex ) child . lastIndex = parent . lastIndex ; } else if ( clone . __isDate ( parent ) ) { child = new Date ( parent . getTime ( ) ) ; } else if ( useBuffer && Buffer . isBuffer ( parent ) ) { child = new Buffer ( parent . length ) ; parent . copy ( child ) ; return child ; } else { if ( typeof prototype == 'undefined' ) { proto = Object . getPrototypeOf ( parent ) ; child = Object . create ( proto ) ; } else { child = Object . create ( prototype ) ; proto = prototype ; } } if ( circular ) { var index = allParents . indexOf ( parent ) ; if ( index != - 1 ) { return allChildren [ index ] ; } allParents . push ( parent ) ; allChildren . push ( child ) ; } for ( var i in parent ) { var attrs ; if ( proto ) { attrs = Object . getOwnPropertyDescriptor ( proto , i ) ; } if ( attrs && attrs . set == null ) { continue ; } child [ i ] = _clone ( parent [ i ] , depth - 1 ) ; } return child ; } return _clone ( parent , depth ) ; }


Input: lotta situps ... [CODESPLIT] function makeAbs ( self , f ) { var abs = f if ( f . charAt ( 0 ) === '/' ) { abs = path . join ( self . root , f ) } else if ( isAbsolute ( f ) || f === '' ) { abs = f } else if ( self . changedCwd ) { abs = path . resolve ( self . cwd , f ) } else { abs = path . resolve ( f ) } return abs }


Input: Checks if value is a plain object that is an object created by the Object constructor or one with a [[ Prototype ]] of null . [CODESPLIT] function isPlainObject ( value ) { var Ctor ; // Exit early for non `Object` objects. if ( ! ( isObjectLike ( value ) && objToString . call ( value ) == objectTag && ! isArguments ( value ) ) || ( ! hasOwnProperty . call ( value , 'constructor' ) && ( Ctor = value . constructor , typeof Ctor == 'function' && ! ( Ctor instanceof Ctor ) ) ) ) { return false ; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result ; // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn ( value , function ( subValue , key ) { result = key ; } ) ; return result === undefined || hasOwnProperty . call ( value , result ) ; }


Input: Munge \ n s and spaces in text so that the number of characters between \ n s is less than or equal to width . [CODESPLIT] function reflowText ( text , width , gfm ) { // Hard break was inserted by Renderer.prototype.br or is // <br /> when gfm is true var splitRe = gfm ? HARD_RETURN_GFM_RE : HARD_RETURN_RE , sections = text . split ( splitRe ) , reflowed = [ ] ; sections . forEach ( function ( section ) { var words = section . split ( / [ \t\n]+ / ) , column = 0 , nextText = '' ; words . forEach ( function ( word ) { var addOne = column != 0 ; if ( ( column + textLength ( word ) + addOne ) > width ) { nextText += '\n' ; column = 0 ; } else if ( addOne ) { nextText += " " ; column += 1 ; } nextText += word ; column += textLength ( word ) ; } ) ; reflowed . push ( nextText ) ; } ) ; return reflowed . join ( '\n' ) ; }


Input: Returns true if a file path is absolute . [CODESPLIT] function isAbsolute ( fp ) { if ( typeof fp !== 'string' ) { throw new TypeError ( 'isAbsolute expects a string.' ) ; } if ( ! isWindows ( ) && isAbsolute . posix ( fp ) ) { return true ; } return isAbsolute . win32 ( fp ) ; }


Input: Repeat the given string the specified number of times . [CODESPLIT] function repeat ( str , num ) { if ( typeof str !== 'string' ) { throw new TypeError ( 'repeat-string expects a string.' ) ; } if ( num === 1 ) return str ; if ( num === 2 ) return str + str ; var max = str . length * num ; if ( cache !== str || typeof cache === 'undefined' ) { cache = str ; res = '' ; } while ( max > res . length && num > 0 ) { if ( num & 1 ) { res += str ; } num >>= 1 ; if ( ! num ) break ; str += str ; } return res . substr ( 0 , max ) ; }


Input: 2 - a simple Set type is defined [CODESPLIT] function uniqSet ( arr ) { var seen = new Set ( ) ; return arr . filter ( function ( el ) { if ( ! seen . has ( el ) ) { seen . add ( el ) ; return true ; } } ) ; }


Input: helper methods [CODESPLIT] function ( data , options ) { var handler = new DomHandler ( options ) ; new Parser ( handler , options ) . end ( data ) ; return handler . dom ; }


Input: Shows error message . Throws unless _continue or config . fatal are true [CODESPLIT] function error ( msg , _continue ) { if ( state . error === null ) state . error = '' ; state . error += state . currentCmd + ': ' + msg + '\n' ; if ( msg . length > 0 ) log ( state . error ) ; if ( config . fatal ) process . exit ( 1 ) ; if ( ! _continue ) throw '' ; }


Input: Returns { alice : true bob : false } when passed a dictionary e . g . : parseOptions ( - a { a : alice b : bob } ) ; [CODESPLIT] function parseOptions ( str , map ) { if ( ! map ) error ( 'parseOptions() internal error: no map given' ) ; // All options are false by default var options = { } ; for ( var letter in map ) options [ map [ letter ] ] = false ; if ( ! str ) return options ; // defaults if ( typeof str !== 'string' ) error ( 'parseOptions() internal error: wrong str' ) ; // e.g. match[1] = 'Rf' for str = '-Rf' var match = str . match ( / ^\-(.+) / ) ; if ( ! match ) return options ; // e.g. chars = ['R', 'f'] var chars = match [ 1 ] . split ( '' ) ; chars . forEach ( function ( c ) { if ( c in map ) options [ map [ c ] ] = true ; else error ( 'option not recognized: ' + c ) ; } ) ; return options ; }


Input: Expands wildcards with matching ( ie . existing ) file names . For example : expand ( [ file * . js ] ) = [ file1 . js file2 . js ... ] ( if the files file1 . js file2 . js etc exist in the current dir ) [CODESPLIT] function expand ( list ) { var expanded = [ ] ; list . forEach ( function ( listEl ) { // Wildcard present on directory names ? if ( listEl . search ( / \*[^\/]*\/ / ) > - 1 || listEl . search ( / \*\*[^\/]*\/ / ) > - 1 ) { var match = listEl . match ( / ^([^*]+\/|)(.*) / ) ; var root = match [ 1 ] ; var rest = match [ 2 ] ; var restRegex = rest . replace ( / \*\* / g , ".*" ) . replace ( / \* / g , "[^\\/]*" ) ; restRegex = new RegExp ( restRegex ) ; _ls ( '-R' , root ) . filter ( function ( e ) { return restRegex . test ( e ) ; } ) . forEach ( function ( file ) { expanded . push ( file ) ; } ) ; } // Wildcard present on file names ? else if ( listEl . search ( / \* / ) > - 1 ) { _ls ( '' , listEl ) . forEach ( function ( file ) { expanded . push ( file ) ; } ) ; } else { expanded . push ( listEl ) ; } } ) ; return expanded ; }


Input: Normalizes _unlinkSync () across platforms to match Unix behavior i . e . file can be unlinked even if it s read - only see https : // github . com / joyent / node / issues / 3006 [CODESPLIT] function unlinkSync ( file ) { try { fs . unlinkSync ( file ) ; } catch ( e ) { // Try to override file permission if ( e . code === 'EPERM' ) { fs . chmodSync ( file , '0666' ) ; fs . unlinkSync ( file ) ; } else { throw e ; } } }


Input: e . g . shelljs_a5f185d0443ca ... [CODESPLIT] function randomFileName ( ) { function randomHash ( count ) { if ( count === 1 ) return parseInt ( 16 * Math . random ( ) , 10 ) . toString ( 16 ) ; else { var hash = '' ; for ( var i = 0 ; i < count ; i ++ ) hash += randomHash ( 1 ) ; return hash ; } } return 'shelljs_' + randomHash ( 20 ) ; }


Input: extend ( target_obj source_obj1 [ source_obj2 ... ] ) Shallow extend e . g . : extend ( { A : 1 } { b : 2 } { c : 3 } ) returns { A : 1 b : 2 c : 3 } [CODESPLIT] function extend ( target ) { var sources = [ ] . slice . call ( arguments , 1 ) ; sources . forEach ( function ( source ) { for ( var key in source ) target [ key ] = source [ key ] ; } ) ; return target ; }


Input: Common wrapper for all Unix - like commands [CODESPLIT] function wrap ( cmd , fn , options ) { return function ( ) { var retValue = null ; state . currentCmd = cmd ; state . error = null ; try { var args = [ ] . slice . call ( arguments , 0 ) ; if ( options && options . notUnix ) { retValue = fn . apply ( this , args ) ; } else { if ( args . length === 0 || typeof args [ 0 ] !== 'string' || args [ 0 ] [ 0 ] !== '-' ) args . unshift ( '' ) ; // only add dummy option if '-option' not already present retValue = fn . apply ( this , args ) ; } } catch ( e ) { if ( ! state . error ) { // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... console . log ( 'shell.js: internal error' ) ; console . log ( e . stack || e ) ; process . exit ( 1 ) ; } if ( config . fatal ) throw e ; } state . currentCmd = 'shell.js' ; return retValue ; } ; }


Input: Conditionally pushes file to list - returns true if pushed false otherwise ( e . g . prevents hidden files to be included unless explicitly told so ) [CODESPLIT] function pushFile ( file , query ) { // hidden file? if ( path . basename ( file ) [ 0 ] === '.' ) { // not explicitly asking for hidden files? if ( ! options . all && ! ( path . basename ( query ) [ 0 ] === '.' && path . basename ( query ) . length > 1 ) ) return false ; } if ( common . platform === 'win' ) file = file . replace ( / \\ / g , '/' ) ; list . push ( file ) ; return true ; }


Input: Returns false if dir is not a writeable directory dir otherwise [CODESPLIT] function writeableDir ( dir ) { if ( ! dir || ! fs . existsSync ( dir ) ) return false ; if ( ! fs . statSync ( dir ) . isDirectory ( ) ) return false ; var testFile = dir + '/' + common . randomFileName ( ) ; try { fs . writeFileSync ( testFile , ' ' ) ; common . unlinkSync ( testFile ) ; return dir ; } catch ( e ) { return false ; } }


Input: Buffered file copy synchronous ( Using readFileSync () + writeFileSync () could easily cause a memory overflow with large files ) [CODESPLIT] function copyFileSync ( srcFile , destFile ) { if ( ! fs . existsSync ( srcFile ) ) common . error ( 'copyFileSync: no such file or directory: ' + srcFile ) ; var BUF_LENGTH = 64 * 1024 , buf = new Buffer ( BUF_LENGTH ) , bytesRead = BUF_LENGTH , pos = 0 , fdr = null , fdw = null ; try { fdr = fs . openSync ( srcFile , 'r' ) ; } catch ( e ) { common . error ( 'copyFileSync: could not read src file (' + srcFile + ')' ) ; } try { fdw = fs . openSync ( destFile , 'w' ) ; } catch ( e ) { common . error ( 'copyFileSync: could not write to dest file (code=' + e . code + '):' + destFile ) ; } while ( bytesRead === BUF_LENGTH ) { bytesRead = fs . readSync ( fdr , buf , 0 , BUF_LENGTH , pos ) ; fs . writeSync ( fdw , buf , 0 , bytesRead ) ; pos += bytesRead ; } fs . closeSync ( fdr ) ; fs . closeSync ( fdw ) ; fs . chmodSync ( destFile , fs . statSync ( srcFile ) . mode ) ; }


Input: Recursively copies sourceDir into destDir Adapted from https : // github . com / ryanmcgrath / wrench - js Copyright ( c ) 2010 Ryan McGrath Copyright ( c ) 2012 Artur Adib Licensed under the MIT License http : // www . opensource . org / licenses / mit - license . php [CODESPLIT] function cpdirSyncRecursive ( sourceDir , destDir , opts ) { if ( ! opts ) opts = { } ; /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs . statSync ( sourceDir ) ; try { fs . mkdirSync ( destDir , checkDir . mode ) ; } catch ( e ) { //if the directory already exists, that's okay if ( e . code !== 'EEXIST' ) throw e ; } var files = fs . readdirSync ( sourceDir ) ; for ( var i = 0 ; i < files . length ; i ++ ) { var srcFile = sourceDir + "/" + files [ i ] ; var destFile = destDir + "/" + files [ i ] ; var srcFileStat = fs . lstatSync ( srcFile ) ; if ( srcFileStat . isDirectory ( ) ) { /* recursion this thing right on back. */ cpdirSyncRecursive ( srcFile , destFile , opts ) ; } else if ( srcFileStat . isSymbolicLink ( ) ) { var symlinkFull = fs . readlinkSync ( srcFile ) ; fs . symlinkSync ( symlinkFull , destFile , os . platform ( ) === "win32" ? "junction" : null ) ; } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ if ( fs . existsSync ( destFile ) && ! opts . force ) { common . log ( 'skipping existing file: ' + files [ i ] ) ; } else { copyFileSync ( srcFile , destFile ) ; } } } // for files }


Input: Recursively creates dir [CODESPLIT] function mkdirSyncRecursive ( dir ) { var baseDir = path . dirname ( dir ) ; // Base dir exists, no recursion necessary if ( fs . existsSync ( baseDir ) ) { fs . mkdirSync ( dir , parseInt ( '0777' , 8 ) ) ; return ; } // Base dir does not exist, go recursive mkdirSyncRecursive ( baseDir ) ; // Base dir created, can create dir fs . mkdirSync ( dir , parseInt ( '0777' , 8 ) ) ; }


Input: Cross - platform method for splitting environment PATH variables [CODESPLIT] function splitPath ( p ) { for ( i = 1 ; i < 2 ; i ++ ) { } if ( ! p ) return [ ] ; if ( common . platform === 'win' ) return p . split ( ';' ) ; else return p . split ( ':' ) ; }


Input: Hack to run child_process . exec () synchronously ( sync avoids callback hell ) Uses a custom wait loop that checks for a flag file created when the child process is done . ( Can t do a wait loop that checks for internal Node variables / messages as Node is single - threaded ; callbacks and other internal state changes are done in the event loop ) . [CODESPLIT] function execSync ( cmd , opts ) { var tempDir = _tempDir ( ) ; var stdoutFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) , codeFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) , scriptFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) , sleepFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) ; var options = common . extend ( { silent : common . config . silent } , opts ) ; var previousStdoutContent = '' ; // Echoes stdout changes from running process, if not silent function updateStdout ( ) { if ( options . silent || ! fs . existsSync ( stdoutFile ) ) return ; var stdoutContent = fs . readFileSync ( stdoutFile , 'utf8' ) ; // No changes since last time? if ( stdoutContent . length <= previousStdoutContent . length ) return ; process . stdout . write ( stdoutContent . substr ( previousStdoutContent . length ) ) ; previousStdoutContent = stdoutContent ; } function escape ( str ) { return ( str + '' ) . replace ( / ([\\"']) / g , "\\$1" ) . replace ( / \0 / g , "\\0" ) ; } if ( fs . existsSync ( scriptFile ) ) common . unlinkSync ( scriptFile ) ; if ( fs . existsSync ( stdoutFile ) ) common . unlinkSync ( stdoutFile ) ; if ( fs . existsSync ( codeFile ) ) common . unlinkSync ( codeFile ) ; var execCommand = '"' + process . execPath + '" ' + scriptFile ; var execOptions = { env : process . env , cwd : _pwd ( ) , maxBuffer : 20 * 1024 * 1024 } ; if ( typeof child . execSync === 'function' ) { var script = [ "var child = require('child_process')" , "  , fs = require('fs');" , "var childProcess = child.exec('" + escape ( cmd ) + "', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {" , "  fs.writeFileSync('" + escape ( codeFile ) + "', err ? err.code.toString() : '0');" , "});" , "var stdoutStream = fs.createWriteStream('" + escape ( stdoutFile ) + "');" , "childProcess.stdout.pipe(stdoutStream, {end: false});" , "childProcess.stderr.pipe(stdoutStream, {end: false});" , "childProcess.stdout.pipe(process.stdout);" , "childProcess.stderr.pipe(process.stderr);" , "var stdoutEnded = false, stderrEnded = false;" , "function tryClosing(){ if(stdoutEnded && stderrEnded){ stdoutStream.end(); } }" , "childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosing(); });" , "childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosing(); });" ] . join ( '\n' ) ; fs . writeFileSync ( scriptFile , script ) ; if ( options . silent ) { execOptions . stdio = 'ignore' ; } else { execOptions . stdio = [ 0 , 1 , 2 ] ; } // Welcome to the future child . execSync ( execCommand , execOptions ) ; } else { cmd += ' > ' + stdoutFile + ' 2>&1' ; // works on both win/unix var script = [ "var child = require('child_process')" , "  , fs = require('fs');" , "var childProcess = child.exec('" + escape ( cmd ) + "', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {" , "  fs.writeFileSync('" + escape ( codeFile ) + "', err ? err.code.toString() : '0');" , "});" ] . join ( '\n' ) ; fs . writeFileSync ( scriptFile , script ) ; child . exec ( execCommand , execOptions ) ; // The wait loop // sleepFile is used as a dummy I/O op to mitigate unnecessary CPU usage // (tried many I/O sync ops, writeFileSync() seems to be only one that is effective in reducing // CPU usage, though apparently not so much on Windows) while ( ! fs . existsSync ( codeFile ) ) { updateStdout ( ) ; fs . writeFileSync ( sleepFile , 'a' ) ; } while ( ! fs . existsSync ( stdoutFile ) ) { updateStdout ( ) ; fs . writeFileSync ( sleepFile , 'a' ) ; } } // At this point codeFile exists, but it's not necessarily flushed yet. // Keep reading it until it is. var code = parseInt ( '' , 10 ) ; while ( isNaN ( code ) ) { code = parseInt ( fs . readFileSync ( codeFile , 'utf8' ) , 10 ) ; } var stdout = fs . readFileSync ( stdoutFile , 'utf8' ) ; // No biggie if we can't erase the files now -- they're in a temp dir anyway try { common . unlinkSync ( scriptFile ) ; } catch ( e ) { } try { common . unlinkSync ( stdoutFile ) ; } catch ( e ) { } try { common . unlinkSync ( codeFile ) ; } catch ( e ) { } try { common . unlinkSync ( sleepFile ) ; } catch ( e ) { } // some shell return codes are defined as errors, per http://tldp.org/LDP/abs/html/exitcodes.html if ( code === 1 || code === 2 || code >= 126 ) { common . error ( '' , true ) ; // unix/shell doesn't really give an error message after non-zero exit codes } // True if successful, false if not var obj = { code : code , output : stdout } ; return obj ; }


Input: Echoes stdout changes from running process if not silent [CODESPLIT] function updateStdout ( ) { if ( options . silent || ! fs . existsSync ( stdoutFile ) ) return ; var stdoutContent = fs . readFileSync ( stdoutFile , 'utf8' ) ; // No changes since last time? if ( stdoutContent . length <= previousStdoutContent . length ) return ; process . stdout . write ( stdoutContent . substr ( previousStdoutContent . length ) ) ; previousStdoutContent = stdoutContent ; }


Input: execSync () Wrapper around exec () to enable echoing output to console in real time [CODESPLIT] function execAsync ( cmd , opts , callback ) { var output = '' ; var options = common . extend ( { silent : common . config . silent } , opts ) ; var c = child . exec ( cmd , { env : process . env , maxBuffer : 20 * 1024 * 1024 } , function ( err ) { if ( callback ) callback ( err ? err . code : 0 , output ) ; } ) ; c . stdout . on ( 'data' , function ( data ) { output += data ; if ( ! options . silent ) process . stdout . write ( data ) ; } ) ; c . stderr . on ( 'data' , function ( data ) { output += data ; if ( ! options . silent ) process . stdout . write ( data ) ; } ) ; return c ; }


Input: Adds ANSI color escape codes if enabled . [CODESPLIT] function formatArgs ( ) { var args = arguments ; var useColors = this . useColors ; var name = this . namespace ; if ( useColors ) { var c = this . color ; args [ 0 ] = '  \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m' + args [ 0 ] + '\u001b[3' + c + 'm' + ' +' + exports . humanize ( this . diff ) + '\u001b[0m' ; } else { args [ 0 ] = new Date ( ) . toUTCString ( ) + ' ' + name + ' ' + args [ 0 ] ; } return args ; }


Input: Create a new GNTP request of the given type . [CODESPLIT] function GNTP ( type , opts ) { opts = opts || { } ; this . type = type ; this . host = opts . host || 'localhost' ; this . port = opts . port || 23053 ; this . request = 'GNTP/1.0 ' + type + ' NONE' + nl ; this . resources = [ ] ; this . attempts = 0 ; this . maxAttempts = 5 ; }


Input: Interface for registering Growl applications and sending Growl notifications . [CODESPLIT] function Growly ( ) { this . appname = 'Growly' ; this . notifications = undefined ; this . labels = undefined ; this . count = 0 ; this . registered = false ; this . host = undefined ; this . port = undefined ; }


Input: Initialize a new Command . [CODESPLIT] function Command ( name ) { this . commands = [ ] ; this . options = [ ] ; this . _execs = [ ] ; this . _allowUnknownOption = false ; this . _args = [ ] ; this . _name = name ; }


Input: Creates a duplicate - free version of an array using [ SameValueZero ] ( http : // ecma - international . org / ecma - 262 / 6 . 0 / #sec - samevaluezero ) for equality comparisons in which only the first occurence of each element is kept . Providing true for isSorted performs a faster search algorithm for sorted arrays . If an iteratee function is provided it is invoked for each element in the array to generate the criterion by which uniqueness is computed . The iteratee is bound to thisArg and invoked with three arguments : ( value index array ) . [CODESPLIT] function uniq ( array , isSorted , iteratee , thisArg ) { var length = array ? array . length : 0 ; if ( ! length ) { return [ ] ; } if ( isSorted != null && typeof isSorted != 'boolean' ) { thisArg = iteratee ; iteratee = isIterateeCall ( array , isSorted , thisArg ) ? undefined : isSorted ; isSorted = false ; } iteratee = iteratee == null ? iteratee : baseCallback ( iteratee , thisArg , 3 ) ; return ( isSorted ) ? sortedUniq ( array , iteratee ) : baseUniq ( array , iteratee ) ; }


Input: The base implementation of _ . difference which accepts a single array of values to exclude . [CODESPLIT] function baseDifference ( array , values ) { var length = array ? array . length : 0 , result = [ ] ; if ( ! length ) { return result ; } var index = - 1 , indexOf = baseIndexOf , isCommon = true , cache = ( isCommon && values . length >= LARGE_ARRAY_SIZE ) ? createCache ( values ) : null , valuesLength = values . length ; if ( cache ) { indexOf = cacheIndexOf ; isCommon = false ; values = cache ; } outer : while ( ++ index < length ) { var value = array [ index ] ; if ( isCommon && value === value ) { var valuesIndex = valuesLength ; while ( valuesIndex -- ) { if ( values [ valuesIndex ] === value ) { continue outer ; } } result . push ( value ) ; } else if ( indexOf ( values , value , 0 ) < 0 ) { result . push ( value ) ; } } return result ; }


Input: ### AssertionError [CODESPLIT] function AssertionError ( message , _props , ssf ) { var extend = exclude ( 'name' , 'message' , 'stack' , 'constructor' , 'toJSON' ) , props = extend ( _props || { } ) ; // default values this . message = message || 'Unspecified AssertionError' ; this . showDiff = false ; // copy from properties for ( var key in props ) { this [ key ] = props [ key ] ; } // capture stack trace ssf = ssf || arguments . callee ; if ( ssf && Error . captureStackTrace ) { Error . captureStackTrace ( this , ssf ) ; } else { this . stack = new Error ( ) . stack ; } }


Input: / * Extract a punctuator out of the next sequence of characters or return null if its not possible . [CODESPLIT] function ( ) { var ch1 = this . peek ( ) ; var ch2 , ch3 , ch4 ; switch ( ch1 ) { // Most common single-character punctuators case "." : if ( ( / ^[0-9]$ / ) . test ( this . peek ( 1 ) ) ) { return null ; } if ( this . peek ( 1 ) === "." && this . peek ( 2 ) === "." ) { return { type : Token . Punctuator , value : "..." } ; } /* falls through */ case "(" : case ")" : case ";" : case "," : case "[" : case "]" : case ":" : case "~" : case "?" : return { type : Token . Punctuator , value : ch1 } ; // A block/object opener case "{" : this . pushContext ( Context . Block ) ; return { type : Token . Punctuator , value : ch1 } ; // A block/object closer case "}" : if ( this . inContext ( Context . Block ) ) { this . popContext ( ) ; } return { type : Token . Punctuator , value : ch1 } ; // A pound sign (for Node shebangs) case "#" : return { type : Token . Punctuator , value : ch1 } ; // We're at the end of input case "" : return null ; } // Peek more characters ch2 = this . peek ( 1 ) ; ch3 = this . peek ( 2 ) ; ch4 = this . peek ( 3 ) ; // 4-character punctuator: >>>= if ( ch1 === ">" && ch2 === ">" && ch3 === ">" && ch4 === "=" ) { return { type : Token . Punctuator , value : ">>>=" } ; } // 3-character punctuators: === !== >>> <<= >>= if ( ch1 === "=" && ch2 === "=" && ch3 === "=" ) { return { type : Token . Punctuator , value : "===" } ; } if ( ch1 === "!" && ch2 === "=" && ch3 === "=" ) { return { type : Token . Punctuator , value : "!==" } ; } if ( ch1 === ">" && ch2 === ">" && ch3 === ">" ) { return { type : Token . Punctuator , value : ">>>" } ; } if ( ch1 === "<" && ch2 === "<" && ch3 === "=" ) { return { type : Token . Punctuator , value : "<<=" } ; } if ( ch1 === ">" && ch2 === ">" && ch3 === "=" ) { return { type : Token . Punctuator , value : ">>=" } ; } // Fat arrow punctuator if ( ch1 === "=" && ch2 === ">" ) { return { type : Token . Punctuator , value : ch1 + ch2 } ; } // 2-character punctuators: <= >= == != ++ -- << >> && || // += -= *= %= &= |= ^= (but not /=, see below) if ( ch1 === ch2 && ( "+-<>&|" . indexOf ( ch1 ) >= 0 ) ) { return { type : Token . Punctuator , value : ch1 + ch2 } ; } if ( "<>=!+-*%&|^" . indexOf ( ch1 ) >= 0 ) { if ( ch2 === "=" ) { return { type : Token . Punctuator , value : ch1 + ch2 } ; } return { type : Token . Punctuator , value : ch1 } ; } // Special case: /=. if ( ch1 === "/" ) { if ( ch2 === "=" ) { return { type : Token . Punctuator , value : "/=" } ; } return { type : Token . Punctuator , value : "/" } ; } return null ; }


Input: / * Extract a numeric literal out of the next sequence of characters or return null if its not possible . This method supports all numeric literals described in section 7 . 8 . 3 of the EcmaScript 5 specification . [CODESPLIT] function ( ) { var index = 0 ; var value = "" ; var length = this . input . length ; var char = this . peek ( index ) ; var bad ; var isAllowedDigit = isDecimalDigit ; var base = 10 ; var isLegacy = false ; function isDecimalDigit ( str ) { return ( / ^[0-9]$ / ) . test ( str ) ; } function isOctalDigit ( str ) { return ( / ^[0-7]$ / ) . test ( str ) ; } function isBinaryDigit ( str ) { return ( / ^[01]$ / ) . test ( str ) ; } function isHexDigit ( str ) { return ( / ^[0-9a-fA-F]$ / ) . test ( str ) ; } function isIdentifierStart ( ch ) { return ( ch === "$" ) || ( ch === "_" ) || ( ch === "\\" ) || ( ch >= "a" && ch <= "z" ) || ( ch >= "A" && ch <= "Z" ) ; } // Numbers must start either with a decimal digit or a point. if ( char !== "." && ! isDecimalDigit ( char ) ) { return null ; } if ( char !== "." ) { value = this . peek ( index ) ; index += 1 ; char = this . peek ( index ) ; if ( value === "0" ) { // Base-16 numbers. if ( char === "x" || char === "X" ) { isAllowedDigit = isHexDigit ; base = 16 ; index += 1 ; value += char ; } // Base-8 numbers. if ( char === "o" || char === "O" ) { isAllowedDigit = isOctalDigit ; base = 8 ; if ( ! state . option . esnext ) { this . trigger ( "warning" , { code : "W119" , line : this . line , character : this . char , data : [ "Octal integer literal" ] } ) ; } index += 1 ; value += char ; } // Base-2 numbers. if ( char === "b" || char === "B" ) { isAllowedDigit = isBinaryDigit ; base = 2 ; if ( ! state . option . esnext ) { this . trigger ( "warning" , { code : "W119" , line : this . line , character : this . char , data : [ "Binary integer literal" ] } ) ; } index += 1 ; value += char ; } // Legacy base-8 numbers. if ( isOctalDigit ( char ) ) { isAllowedDigit = isOctalDigit ; base = 8 ; isLegacy = true ; bad = false ; index += 1 ; value += char ; } // Decimal numbers that start with '0' such as '09' are illegal // but we still parse them and return as malformed. if ( ! isOctalDigit ( char ) && isDecimalDigit ( char ) ) { index += 1 ; value += char ; } } while ( index < length ) { char = this . peek ( index ) ; if ( isLegacy && isDecimalDigit ( char ) ) { // Numbers like '019' (note the 9) are not valid octals // but we still parse them and mark as malformed. bad = true ; } else if ( ! isAllowedDigit ( char ) ) { break ; } value += char ; index += 1 ; } if ( isAllowedDigit !== isDecimalDigit ) { if ( ! isLegacy && value . length <= 2 ) { // 0x return { type : Token . NumericLiteral , value : value , isMalformed : true } ; } if ( index < length ) { char = this . peek ( index ) ; if ( isIdentifierStart ( char ) ) { return null ; } } return { type : Token . NumericLiteral , value : value , base : base , isLegacy : isLegacy , isMalformed : false } ; } } // Decimal digits. if ( char === "." ) { value += char ; index += 1 ; while ( index < length ) { char = this . peek ( index ) ; if ( ! isDecimalDigit ( char ) ) { break ; } value += char ; index += 1 ; } } // Exponent part. if ( char === "e" || char === "E" ) { value += char ; index += 1 ; char = this . peek ( index ) ; if ( char === "+" || char === "-" ) { value += this . peek ( index ) ; index += 1 ; } char = this . peek ( index ) ; if ( isDecimalDigit ( char ) ) { value += char ; index += 1 ; while ( index < length ) { char = this . peek ( index ) ; if ( ! isDecimalDigit ( char ) ) { break ; } value += char ; index += 1 ; } } else { return null ; } } if ( index < length ) { char = this . peek ( index ) ; if ( isIdentifierStart ( char ) ) { return null ; } } return { type : Token . NumericLiteral , value : value , base : base , isMalformed : ! isFinite ( value ) } ; }


Input: Assumes previously parsed character was \ ( === \\ ) and was not skipped . [CODESPLIT] function ( checks ) { var allowNewLine = false ; var jump = 1 ; this . skip ( ) ; var char = this . peek ( ) ; switch ( char ) { case "'" : this . triggerAsync ( "warning" , { code : "W114" , line : this . line , character : this . char , data : [ "\\'" ] } , checks , function ( ) { return state . jsonMode ; } ) ; break ; case "b" : char = "\\b" ; break ; case "f" : char = "\\f" ; break ; case "n" : char = "\\n" ; break ; case "r" : char = "\\r" ; break ; case "t" : char = "\\t" ; break ; case "0" : char = "\\0" ; // Octal literals fail in strict mode. // Check if the number is between 00 and 07. var n = parseInt ( this . peek ( 1 ) , 10 ) ; this . triggerAsync ( "warning" , { code : "W115" , line : this . line , character : this . char } , checks , function ( ) { return n >= 0 && n <= 7 && state . isStrict ( ) ; } ) ; break ; case "u" : var hexCode = this . input . substr ( 1 , 4 ) ; var code = parseInt ( hexCode , 16 ) ; if ( isNaN ( code ) ) { this . trigger ( "warning" , { code : "W052" , line : this . line , character : this . char , data : [ "u" + hexCode ] } ) ; } char = String . fromCharCode ( code ) ; jump = 5 ; break ; case "v" : this . triggerAsync ( "warning" , { code : "W114" , line : this . line , character : this . char , data : [ "\\v" ] } , checks , function ( ) { return state . jsonMode ; } ) ; char = "\v" ; break ; case "x" : var x = parseInt ( this . input . substr ( 1 , 2 ) , 16 ) ; this . triggerAsync ( "warning" , { code : "W114" , line : this . line , character : this . char , data : [ "\\x-" ] } , checks , function ( ) { return state . jsonMode ; } ) ; char = String . fromCharCode ( x ) ; jump = 3 ; break ; case "\\" : char = "\\\\" ; break ; case "\"" : char = "\\\"" ; break ; case "/" : break ; case "" : allowNewLine = true ; char = "" ; break ; } return { char : char , jump : jump , allowNewLine : allowNewLine } ; }


Input: / * Extract a template literal out of the next sequence of characters and / or lines or return null if its not possible . Since template literals can span across multiple lines this method has to move the char pointer . [CODESPLIT] function ( checks ) { var tokenType ; var value = "" ; var ch ; var startLine = this . line ; var startChar = this . char ; var depth = this . templateStarts . length ; if ( ! state . option . esnext ) { // Only lex template strings in ESNext mode. return null ; } else if ( this . peek ( ) === "`" ) { // Template must start with a backtick. tokenType = Token . TemplateHead ; this . templateStarts . push ( { line : this . line , char : this . char } ) ; depth = this . templateStarts . length ; this . skip ( 1 ) ; this . pushContext ( Context . Template ) ; } else if ( this . inContext ( Context . Template ) && this . peek ( ) === "}" ) { // If we're in a template context, and we have a '}', lex a TemplateMiddle. tokenType = Token . TemplateMiddle ; } else { // Go lex something else. return null ; } while ( this . peek ( ) !== "`" ) { while ( ( ch = this . peek ( ) ) === "" ) { value += "\n" ; if ( ! this . nextLine ( ) ) { // Unclosed template literal --- point to the starting "`" var startPos = this . templateStarts . pop ( ) ; this . trigger ( "error" , { code : "E052" , line : startPos . line , character : startPos . char } ) ; return { type : tokenType , value : value , startLine : startLine , startChar : startChar , isUnclosed : true , depth : depth , context : this . popContext ( ) } ; } } if ( ch === '$' && this . peek ( 1 ) === '{' ) { value += '${' ; this . skip ( 2 ) ; return { type : tokenType , value : value , startLine : startLine , startChar : startChar , isUnclosed : false , depth : depth , context : this . currentContext ( ) } ; } else if ( ch === '\\' ) { var escape = this . scanEscapeSequence ( checks ) ; value += escape . char ; this . skip ( escape . jump ) ; } else if ( ch !== '`' ) { // Otherwise, append the value and continue. value += ch ; this . skip ( 1 ) ; } } // Final value is either NoSubstTemplate or TemplateTail tokenType = tokenType === Token . TemplateHead ? Token . NoSubstTemplate : Token . TemplateTail ; this . skip ( 1 ) ; this . templateStarts . pop ( ) ; return { type : tokenType , value : value , startLine : startLine , startChar : startChar , isUnclosed : false , depth : depth , context : this . popContext ( ) } ; }


Input: / * Extract a string out of the next sequence of characters and / or lines or return null if its not possible . Since strings can span across multiple lines this method has to move the char pointer . [CODESPLIT] function ( checks ) { /*jshint loopfunc:true */ var quote = this . peek ( ) ; // String must start with a quote. if ( quote !== "\"" && quote !== "'" ) { return null ; } // In JSON strings must always use double quotes. this . triggerAsync ( "warning" , { code : "W108" , line : this . line , character : this . char // +1? } , checks , function ( ) { return state . jsonMode && quote !== "\"" ; } ) ; var value = "" ; var startLine = this . line ; var startChar = this . char ; var allowNewLine = false ; this . skip ( ) ; while ( this . peek ( ) !== quote ) { if ( this . peek ( ) === "" ) { // End Of Line // If an EOL is not preceded by a backslash, show a warning // and proceed like it was a legit multi-line string where // author simply forgot to escape the newline symbol. // // Another approach is to implicitly close a string on EOL // but it generates too many false positives. if ( ! allowNewLine ) { this . trigger ( "warning" , { code : "W112" , line : this . line , character : this . char } ) ; } else { allowNewLine = false ; // Otherwise show a warning if multistr option was not set. // For JSON, show warning no matter what. this . triggerAsync ( "warning" , { code : "W043" , line : this . line , character : this . char } , checks , function ( ) { return ! state . option . multistr ; } ) ; this . triggerAsync ( "warning" , { code : "W042" , line : this . line , character : this . char } , checks , function ( ) { return state . jsonMode && state . option . multistr ; } ) ; } // If we get an EOF inside of an unclosed string, show an // error and implicitly close it at the EOF point. if ( ! this . nextLine ( ) ) { this . trigger ( "error" , { code : "E029" , line : startLine , character : startChar } ) ; return { type : Token . StringLiteral , value : value , startLine : startLine , startChar : startChar , isUnclosed : true , quote : quote } ; } } else { // Any character other than End Of Line allowNewLine = false ; var char = this . peek ( ) ; var jump = 1 ; // A length of a jump, after we're done // parsing this character. if ( char < " " ) { // Warn about a control character in a string. this . trigger ( "warning" , { code : "W113" , line : this . line , character : this . char , data : [ "<non-printable>" ] } ) ; } // Special treatment for some escaped characters. if ( char === "\\" ) { var parsed = this . scanEscapeSequence ( checks ) ; char = parsed . char ; jump = parsed . jump ; allowNewLine = parsed . allowNewLine ; } value += char ; this . skip ( jump ) ; } } this . skip ( ) ; return { type : Token . StringLiteral , value : value , startLine : startLine , startChar : startChar , isUnclosed : false , quote : quote } ; }


Input: adds an indentifier to the relevant current scope and creates warnings / errors as necessary name : string opts : { type : string token : token isblockscoped : bool } [CODESPLIT] function addlabel ( name , opts ) { var type = opts . type ; var token = opts . token ; var isblockscoped = opts . isblockscoped ; // Define label in the current function in the current scope. if ( type === "exception" ) { if ( _ . has ( funct [ "(context)" ] , name ) ) { if ( funct [ name ] !== true && ! state . option . node ) { warning ( "W002" , state . tokens . next , name ) ; } } } if ( _ . has ( funct , name ) && ! funct [ "(global)" ] ) { if ( funct [ name ] === true ) { if ( state . option . latedef ) { if ( ( state . option . latedef === true && _ . contains ( [ funct [ name ] , type ] , "unction" ) ) || ! _ . contains ( [ funct [ name ] , type ] , "unction" ) ) { warning ( "W003" , state . tokens . next , name ) ; } } } else { if ( ( ! state . option . shadow || _ . contains ( [ "inner" , "outer" ] , state . option . shadow ) ) && type !== "exception" || funct [ "(blockscope)" ] . getlabel ( name ) ) { warning ( "W004" , state . tokens . next , name ) ; } } } if ( funct [ "(context)" ] && _ . has ( funct [ "(context)" ] , name ) && type !== "function" ) { if ( state . option . shadow === "outer" ) { warning ( "W123" , state . tokens . next , name ) ; } } // if the identifier is blockscoped (a let or a const), add it only to the current blockscope if ( isblockscoped ) { funct [ "(blockscope)" ] . current . add ( name , type , state . tokens . curr ) ; if ( funct [ "(blockscope)" ] . atTop ( ) && exported [ name ] ) { state . tokens . curr . exported = true ; } } else { funct [ "(blockscope)" ] . shadow ( name ) ; funct [ name ] = type ; if ( token ) { funct [ "(tokens)" ] [ name ] = token ; } if ( funct [ "(global)" ] ) { global [ name ] = funct ; if ( _ . has ( implied , name ) ) { if ( state . option . latedef ) { if ( ( state . option . latedef === true && _ . contains ( [ funct [ name ] , type ] , "unction" ) ) || ! _ . contains ( [ funct [ name ] , type ] , "unction" ) ) { warning ( "W003" , state . tokens . next , name ) ; } } delete implied [ name ] ; } } else { scope [ name ] = funct ; } } }


Input: We need a peek function . If it has an argument it peeks that much farther ahead . It is used to distinguish for ( var i in ... from for ( var i = ... [CODESPLIT] function peek ( p ) { var i = p || 0 , j = 0 , t ; while ( j <= i ) { t = lookahead [ j ] ; if ( ! t ) { t = lookahead [ j ] = lex . token ( ) ; } j += 1 ; } // Peeking past the end of the program should produce the "(end)" token. if ( ! t && state . tokens . next . id === "(end)" ) { return state . tokens . next ; } return t ; }


Input: Checks whether the typeof operator is used with the correct value . For docs on typeof see : https : // developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Operators / typeof [CODESPLIT] function isTypoTypeof ( left , right , state ) { var values ; if ( state . option . notypeof ) return false ; if ( ! left || ! right ) return false ; values = state . inESNext ( ) ? typeofValues . es6 : typeofValues . es3 ; if ( right . type === "(identifier)" && right . value === "typeof" && left . type === "(string)" ) return ! _ . contains ( values , left . value ) ; return false ; }


Input: fnparam means that this identifier is being defined as a function argument prop means that this identifier is that of an object property [CODESPLIT] function identifier ( fnparam , prop ) { var i = optionalidentifier ( fnparam , prop , false ) ; if ( i ) { return i ; } // parameter destructuring with rest operator if ( state . tokens . next . value === "..." ) { if ( ! state . option . esnext ) { warning ( "W119" , state . tokens . next , "spread/rest operator" ) ; } advance ( ) ; if ( checkPunctuators ( state . tokens . next , [ "..." ] ) ) { warning ( "E024" , state . tokens . next , "..." ) ; while ( checkPunctuators ( state . tokens . next , [ "..." ] ) ) { advance ( ) ; } } if ( ! state . tokens . next . identifier ) { warning ( "E024" , state . tokens . curr , "..." ) ; return ; } return identifier ( fnparam , prop ) ; } else { error ( "E030" , state . tokens . next , state . tokens . next . value ) ; // The token should be consumed after a warning is issued so the parser // can continue as though an identifier were found. The semicolon token // should not be consumed in this way so that the parser interprets it as // a statement delimeter; if ( state . tokens . next . id !== ";" ) { advance ( ) ; } } }


Input: Check whether this function has been reached for a destructuring assign with undeclared values [CODESPLIT] function destructuringAssignOrJsonValue ( ) { // lookup for the assignment (esnext only) // if it has semicolons, it is a block, so go parse it as a block // or it's not a block, but there are assignments, check for undeclared variables var block = lookupBlockType ( ) ; if ( block . notJson ) { if ( ! state . inESNext ( ) && block . isDestAssign ) { warning ( "W104" , state . tokens . curr , "destructuring assignment" ) ; } statements ( ) ; // otherwise parse json value } else { state . option . laxbreak = true ; state . jsonMode = true ; jsonValue ( ) ; } }


Input: array comprehension parsing function parses and defines the three states of the list comprehension in order to avoid defining global variables but keeping them to the list comprehension scope only . The order of the states are as follows : * use which will be the returned iterative part of the list comprehension * define which will define the variables local to the list comprehension * filter which will help filter out values [CODESPLIT] function ( ) { var CompArray = function ( ) { this . mode = "use" ; this . variables = [ ] ; } ; var _carrays = [ ] ; var _current ; function declare ( v ) { var l = _current . variables . filter ( function ( elt ) { // if it has, change its undef state if ( elt . value === v ) { elt . undef = false ; return v ; } } ) . length ; return l !== 0 ; } function use ( v ) { var l = _current . variables . filter ( function ( elt ) { // and if it has been defined if ( elt . value === v && ! elt . undef ) { if ( elt . unused === true ) { elt . unused = false ; } return v ; } } ) . length ; // otherwise we warn about it return ( l === 0 ) ; } return { stack : function ( ) { _current = new CompArray ( ) ; _carrays . push ( _current ) ; } , unstack : function ( ) { _current . variables . filter ( function ( v ) { if ( v . unused ) warning ( "W098" , v . token , v . raw_text || v . value ) ; if ( v . undef ) isundef ( v . funct , "W117" , v . token , v . value ) ; } ) ; _carrays . splice ( - 1 , 1 ) ; _current = _carrays [ _carrays . length - 1 ] ; } , setState : function ( s ) { if ( _ . contains ( [ "use" , "define" , "generate" , "filter" ] , s ) ) _current . mode = s ; } , check : function ( v ) { if ( ! _current ) { return ; } // When we are in "use" state of the list comp, we enqueue that var if ( _current && _current . mode === "use" ) { if ( use ( v ) ) { _current . variables . push ( { funct : funct , token : state . tokens . curr , value : v , undef : true , unused : false } ) ; } return true ; // When we are in "define" state of the list comp, } else if ( _current && _current . mode === "define" ) { // check if the variable has been used previously if ( ! declare ( v ) ) { _current . variables . push ( { funct : funct , token : state . tokens . curr , value : v , undef : false , unused : true } ) ; } return true ; // When we are in the "generate" state of the list comp, } else if ( _current && _current . mode === "generate" ) { isundef ( funct , "W117" , state . tokens . curr , v ) ; return true ; // When we are in "filter" state, } else if ( _current && _current . mode === "filter" ) { // we check whether current variable has been declared if ( use ( v ) ) { // if not we warn about it isundef ( funct , "W117" , state . tokens . curr , v ) ; } return true ; } return false ; } } ; }


Input: The actual JSHINT function itself . [CODESPLIT] function ( s , o , g ) { var i , k , x , reIgnoreStr , reIgnore ; var optionKeys ; var newOptionObj = { } ; var newIgnoredObj = { } ; o = _ . clone ( o ) ; state . reset ( ) ; if ( o && o . scope ) { JSHINT . scope = o . scope ; } else { JSHINT . errors = [ ] ; JSHINT . undefs = [ ] ; JSHINT . internals = [ ] ; JSHINT . blacklist = { } ; JSHINT . scope = "(main)" ; } predefined = Object . create ( null ) ; combine ( predefined , vars . ecmaIdentifiers [ 3 ] ) ; combine ( predefined , vars . reservedVars ) ; combine ( predefined , g || { } ) ; declared = Object . create ( null ) ; exported = Object . create ( null ) ; function each ( obj , cb ) { if ( ! obj ) return ; if ( ! Array . isArray ( obj ) && typeof obj === "object" ) obj = Object . keys ( obj ) ; obj . forEach ( cb ) ; } if ( o ) { each ( o . predef || null , function ( item ) { var slice , prop ; if ( item [ 0 ] === "-" ) { slice = item . slice ( 1 ) ; JSHINT . blacklist [ slice ] = slice ; // remove from predefined if there delete predefined [ slice ] ; } else { prop = Object . getOwnPropertyDescriptor ( o . predef , item ) ; predefined [ item ] = prop ? prop . value : false ; } } ) ; each ( o . exported || null , function ( item ) { exported [ item ] = true ; } ) ; delete o . predef ; delete o . exported ; optionKeys = Object . keys ( o ) ; for ( x = 0 ; x < optionKeys . length ; x ++ ) { if ( / ^-W\d{3}$ / g . test ( optionKeys [ x ] ) ) { newIgnoredObj [ optionKeys [ x ] . slice ( 1 ) ] = true ; } else { var optionKey = optionKeys [ x ] ; newOptionObj [ optionKey ] = o [ optionKey ] ; if ( optionKey === "es5" ) { if ( o [ optionKey ] ) { warning ( "I003" ) ; } } if ( optionKeys [ x ] === "newcap" && o [ optionKey ] === false ) newOptionObj [ "(explicitNewcap)" ] = true ; } } } state . option = newOptionObj ; state . ignored = newIgnoredObj ; state . option . indent = state . option . indent || 4 ; state . option . maxerr = state . option . maxerr || 50 ; indent = 1 ; global = Object . create ( predefined ) ; scope = global ; funct = functor ( "(global)" , null , scope , { "(global)" : true , "(blockscope)" : blockScope ( ) , "(comparray)" : arrayComprehension ( ) , "(metrics)" : createMetrics ( state . tokens . next ) } ) ; functions = [ funct ] ; urls = [ ] ; stack = null ; member = { } ; membersOnly = null ; implied = { } ; inblock = false ; lookahead = [ ] ; unuseds = [ ] ; if ( ! isString ( s ) && ! Array . isArray ( s ) ) { errorAt ( "E004" , 0 ) ; return false ; } api = { get isJSON ( ) { return state . jsonMode ; } , getOption : function ( name ) { return state . option [ name ] || null ; } , getCache : function ( name ) { return state . cache [ name ] ; } , setCache : function ( name , value ) { state . cache [ name ] = value ; } , warn : function ( code , data ) { warningAt . apply ( null , [ code , data . line , data . char ] . concat ( data . data ) ) ; } , on : function ( names , listener ) { names . split ( " " ) . forEach ( function ( name ) { emitter . on ( name , listener ) ; } . bind ( this ) ) ; } } ; emitter . removeAllListeners ( ) ; ( extraModules || [ ] ) . forEach ( function ( func ) { func ( api ) ; } ) ; state . tokens . prev = state . tokens . curr = state . tokens . next = state . syntax [ "(begin)" ] ; if ( o && o . ignoreDelimiters ) { if ( ! Array . isArray ( o . ignoreDelimiters ) ) { o . ignoreDelimiters = [ o . ignoreDelimiters ] ; } o . ignoreDelimiters . forEach ( function ( delimiterPair ) { if ( ! delimiterPair . start || ! delimiterPair . end ) return ; reIgnoreStr = escapeRegex ( delimiterPair . start ) + "[\\s\\S]*?" + escapeRegex ( delimiterPair . end ) ; reIgnore = new RegExp ( reIgnoreStr , "ig" ) ; s = s . replace ( reIgnore , function ( match ) { return match . replace ( / . / g , " " ) ; } ) ; } ) ; } lex = new Lexer ( s ) ; lex . on ( "warning" , function ( ev ) { warningAt . apply ( null , [ ev . code , ev . line , ev . character ] . concat ( ev . data ) ) ; } ) ; lex . on ( "error" , function ( ev ) { errorAt . apply ( null , [ ev . code , ev . line , ev . character ] . concat ( ev . data ) ) ; } ) ; lex . on ( "fatal" , function ( ev ) { quit ( "E041" , ev . line , ev . from ) ; } ) ; lex . on ( "Identifier" , function ( ev ) { emitter . emit ( "Identifier" , ev ) ; } ) ; lex . on ( "String" , function ( ev ) { emitter . emit ( "String" , ev ) ; } ) ; lex . on ( "Number" , function ( ev ) { emitter . emit ( "Number" , ev ) ; } ) ; lex . start ( ) ; // Check options for ( var name in o ) { if ( _ . has ( o , name ) ) { checkOption ( name , state . tokens . curr ) ; } } assume ( ) ; // combine the passed globals after we've assumed all our options combine ( predefined , g || { } ) ; //reset values comma . first = true ; try { advance ( ) ; switch ( state . tokens . next . id ) { case "{" : case "[" : destructuringAssignOrJsonValue ( ) ; break ; default : directives ( ) ; if ( state . isStrict ( ) ) { if ( ! state . option . globalstrict ) { if ( ! ( state . option . module || state . option . node || state . option . phantom || state . option . browserify ) ) { warning ( "W097" , state . tokens . prev ) ; } } } statements ( ) ; } if ( state . tokens . next . id !== "(end)" ) { quit ( "E041" , state . tokens . curr . line ) ; } funct [ "(blockscope)" ] . unstack ( ) ; var markDefined = function ( name , context ) { do { if ( typeof context [ name ] === "string" ) { // JSHINT marks unused variables as 'unused' and // unused function declaration as 'unction'. This // code changes such instances back 'var' and // 'closure' so that the code in JSHINT.data() // doesn't think they're unused. if ( context [ name ] === "unused" ) context [ name ] = "var" ; else if ( context [ name ] === "unction" ) context [ name ] = "closure" ; return true ; } context = context [ "(context)" ] ; } while ( context ) ; return false ; } ; var clearImplied = function ( name , line ) { if ( ! implied [ name ] ) return ; var newImplied = [ ] ; for ( var i = 0 ; i < implied [ name ] . length ; i += 1 ) { if ( implied [ name ] [ i ] !== line ) newImplied . push ( implied [ name ] [ i ] ) ; } if ( newImplied . length === 0 ) delete implied [ name ] ; else implied [ name ] = newImplied ; } ; var checkUnused = function ( func , key ) { var type = func [ key ] ; var tkn = func [ "(tokens)" ] [ key ] ; if ( key . charAt ( 0 ) === "(" ) return ; if ( type !== "unused" && type !== "unction" ) return ; // Params are checked separately from other variables. if ( func [ "(params)" ] && func [ "(params)" ] . indexOf ( key ) !== - 1 ) return ; // Variable is in global scope and defined as exported. if ( func [ "(global)" ] && _ . has ( exported , key ) ) return ; warnUnused ( key , tkn , "var" ) ; } ; // Check queued 'x is not defined' instances to see if they're still undefined. for ( i = 0 ; i < JSHINT . undefs . length ; i += 1 ) { k = JSHINT . undefs [ i ] . slice ( 0 ) ; if ( markDefined ( k [ 2 ] . value , k [ 0 ] ) || k [ 2 ] . forgiveUndef ) { clearImplied ( k [ 2 ] . value , k [ 2 ] . line ) ; } else if ( state . option . undef ) { warning . apply ( warning , k . slice ( 1 ) ) ; } } functions . forEach ( function ( func ) { if ( func [ "(unusedOption)" ] === false ) { return ; } for ( var key in func ) { if ( _ . has ( func , key ) ) { checkUnused ( func , key ) ; } } if ( ! func [ "(params)" ] ) return ; var params = func [ "(params)" ] . slice ( ) ; var param = params . pop ( ) ; var type , unused_opt ; while ( param ) { type = func [ param ] ; unused_opt = func [ "(unusedOption)" ] || state . option . unused ; unused_opt = unused_opt === true ? "last-param" : unused_opt ; // 'undefined' is a special case for (function(window, undefined) { ... })(); // patterns. if ( param === "undefined" ) return ; if ( type === "unused" || type === "unction" ) { warnUnused ( param , func [ "(tokens)" ] [ param ] , "param" , func [ "(unusedOption)" ] ) ; } else if ( unused_opt === "last-param" ) { return ; } param = params . pop ( ) ; } } ) ; for ( var key in declared ) { if ( _ . has ( declared , key ) && ! _ . has ( global , key ) && ! _ . has ( exported , key ) ) { warnUnused ( key , declared [ key ] , "var" ) ; } } } catch ( err ) { if ( err && err . name === "JSHintError" ) { var nt = state . tokens . next || { } ; JSHINT . errors . push ( { scope : "(main)" , raw : err . raw , code : err . code , reason : err . message , line : err . line || nt . line , character : err . character || nt . from } , null ) ; } else { throw err ; } } // Loop over the listed "internals", and check them as well. if ( JSHINT . scope === "(main)" ) { o = o || { } ; for ( i = 0 ; i < JSHINT . internals . length ; i += 1 ) { k = JSHINT . internals [ i ] ; o . scope = k . elem ; itself ( k . value , o , g ) ; } } return JSHINT . errors . length === 0 ; }


Input:
/ * Rename filepath using transformer [CODESPLIT] function rename ( filepath , transformer ) { var result ; /*
        Return a file object

        {
          dirname
          basename
          extname
          origin
        }
      */ var fileObj = parse ( filepath ) ; if ( ! transformer ) { result = stringify ( fileObj ) ; debug ( 'transform to %s with no transformer' , result ) ; return result ; } /*
        transformed object

        {
          dirname
          prefix
          basename
          suffix
          extname
        }
      */ var transformed = util . isFunction ( transformer ) ? transformer ( fileObj ) : transformer ; // rename it when transformer is string as a filepath if ( util . isString ( transformed ) ) { result = transformed || stringify ( fileObj ) ; debug ( 'transform from %j to `%s` with %j' , fileObj , result , transformed ) ; return result ; } if ( ! util . isObject ( transformed ) ) { throw new Error ( 'transformer should be string, function or object.' ) ; } result = transform ( fileObj , transformed ) ; debug ( 'transform from %j to `%s` with %j' , fileObj , result , transformed ) ; return result ; }


Input: / * legacy parse method kept for backwards compatibility [CODESPLIT] function parseLegacy ( ext , content , fileName , customTags , withInlineFiles ) { return parse ( { ext : ext , content : content , fileName : fileName , customTags : customTags , withInlineFiles : withInlineFiles } ) ; }


Input: / * ! ## parsePath ( path ) [CODESPLIT] function parsePath ( path ) { var str = path . replace ( / ([^\\])\[ / g , '$1.[' ) , parts = str . match ( / (\\\.|[^.]+?)+ / g ) ; return parts . map ( function ( value ) { var re = / ^\[(\d+)\]$ / , mArr = re . exec ( value ) ; if ( mArr ) return { i : parseFloat ( mArr [ 1 ] ) } ; else return { p : value . replace ( / \\([.\[\]]) / g , '$1' ) } ; } ) ; }


Input: ### . keys ( key1 [ key2 ] [ ... ] ) [CODESPLIT] function assertKeys ( keys ) { var obj = flag ( this , 'object' ) , str , ok = true , mixedArgsMsg = 'keys must be given single argument of Array|Object|String, or multiple String arguments' ; switch ( _ . type ( keys ) ) { case "array" : if ( arguments . length > 1 ) throw ( new Error ( mixedArgsMsg ) ) ; break ; case "object" : if ( arguments . length > 1 ) throw ( new Error ( mixedArgsMsg ) ) ; keys = Object . keys ( keys ) ; break ; default : keys = Array . prototype . slice . call ( arguments ) ; } if ( ! keys . length ) throw new Error ( 'keys required' ) ; var actual = Object . keys ( obj ) , expected = keys , len = keys . length , any = flag ( this , 'any' ) , all = flag ( this , 'all' ) ; if ( ! any && ! all ) { all = true ; } // Has any if ( any ) { var intersection = expected . filter ( function ( key ) { return ~ actual . indexOf ( key ) ; } ) ; ok = intersection . length > 0 ; } // Has all if ( all ) { ok = keys . every ( function ( key ) { return ~ actual . indexOf ( key ) ; } ) ; if ( ! flag ( this , 'negate' ) && ! flag ( this , 'contains' ) ) { ok = ok && keys . length == actual . length ; } } // Key string if ( len > 1 ) { keys = keys . map ( function ( key ) { return _ . inspect ( key ) ; } ) ; var last = keys . pop ( ) ; if ( all ) { str = keys . join ( ', ' ) + ', and ' + last ; } if ( any ) { str = keys . join ( ', ' ) + ', or ' + last ; } } else { str = _ . inspect ( keys [ 0 ] ) ; } // Form str = ( len > 1 ? 'keys ' : 'key ' ) + str ; // Have / include str = ( flag ( this , 'contains' ) ? 'contain ' : 'have ' ) + str ; // Assertion this . assert ( ok , 'expected #{this} to ' + str , 'expected #{this} to not ' + str , expected . slice ( 0 ) . sort ( ) , actual . sort ( ) , true ) ; }


Input: ### . throw ( constructor ) [CODESPLIT] function assertThrows ( constructor , errMsg , msg ) { if ( msg ) flag ( this , 'message' , msg ) ; var obj = flag ( this , 'object' ) ; new Assertion ( obj , msg ) . is . a ( 'function' ) ; var thrown = false , desiredError = null , name = null , thrownError = null ; if ( arguments . length === 0 ) { errMsg = null ; constructor = null ; } else if ( constructor && ( constructor instanceof RegExp || 'string' === typeof constructor ) ) { errMsg = constructor ; constructor = null ; } else if ( constructor && constructor instanceof Error ) { desiredError = constructor ; constructor = null ; errMsg = null ; } else if ( typeof constructor === 'function' ) { name = constructor . prototype . name || constructor . name ; if ( name === 'Error' && constructor !== Error ) { name = ( new constructor ( ) ) . name ; } } else { constructor = null ; } try { obj ( ) ; } catch ( err ) { // first, check desired error if ( desiredError ) { this . assert ( err === desiredError , 'expected #{this} to throw #{exp} but #{act} was thrown' , 'expected #{this} to not throw #{exp}' , ( desiredError instanceof Error ? desiredError . toString ( ) : desiredError ) , ( err instanceof Error ? err . toString ( ) : err ) ) ; flag ( this , 'object' , err ) ; return this ; } // next, check constructor if ( constructor ) { this . assert ( err instanceof constructor , 'expected #{this} to throw #{exp} but #{act} was thrown' , 'expected #{this} to not throw #{exp} but #{act} was thrown' , name , ( err instanceof Error ? err . toString ( ) : err ) ) ; if ( ! errMsg ) { flag ( this , 'object' , err ) ; return this ; } } // next, check message var message = 'error' === _ . type ( err ) && "message" in err ? err . message : '' + err ; if ( ( message != null ) && errMsg && errMsg instanceof RegExp ) { this . assert ( errMsg . exec ( message ) , 'expected #{this} to throw error matching #{exp} but got #{act}' , 'expected #{this} to throw error not matching #{exp}' , errMsg , message ) ; flag ( this , 'object' , err ) ; return this ; } else if ( ( message != null ) && errMsg && 'string' === typeof errMsg ) { this . assert ( ~ message . indexOf ( errMsg ) , 'expected #{this} to throw error including #{exp} but got #{act}' , 'expected #{this} to throw error not including #{act}' , errMsg , message ) ; flag ( this , 'object' , err ) ; return this ; } else { thrown = true ; thrownError = err ; } } var actuallyGot = '' , expectedThrown = name !== null ? name : desiredError ? '#{exp}' //_.inspect(desiredError) : 'an error' ; if ( thrown ) { actuallyGot = ' but #{act} was thrown' } this . assert ( thrown === true , 'expected #{this} to throw ' + expectedThrown + actuallyGot , 'expected #{this} to not throw ' + expectedThrown + actuallyGot , ( desiredError instanceof Error ? desiredError . toString ( ) : desiredError ) , ( thrownError instanceof Error ? thrownError . toString ( ) : thrownError ) ) ; flag ( this , 'object' , thrownError ) ; }