Input: Return the next available name in the pattern _a ... _z _0 _1 ... TempFlags . _i or TempFlags . _n may be used to express a preference for that dedicated name . Note that names generated by makeTempVariableName and makeUniqueName will never conflict . [CODESPLIT] function makeTempVariableName ( flags ) { if ( flags && ! ( tempFlags & flags ) ) { var name_19 = flags === 268435456 /* _i */ ? "_i" : "_n" ; if ( isUniqueName ( name_19 ) ) { tempFlags |= flags ; return name_19 ; } } while ( true ) { var count = tempFlags & 268435455 /* CountMask */ ; tempFlags ++ ; // Skip over 'i' and 'n' if ( count !== 8 && count !== 13 ) { var name_20 = count < 26 ? "_" + String . fromCharCode ( 97 /* a */ + count ) : "_" + ( count - 26 ) ; if ( isUniqueName ( name_20 ) ) { return name_20 ; } } } }


Input: Generate a name that is unique within the current file and doesn t conflict with any names in global scope . The name is formed by adding an _n suffix to the specified base name where n is a positive integer . Note that names generated by makeTempVariableName and makeUniqueName are guaranteed to never conflict . [CODESPLIT] function makeUniqueName ( baseName ) { // Find the first unique 'name_n', where n is a positive number if ( baseName . charCodeAt ( baseName . length - 1 ) !== 95 /* _ */ ) { baseName += "_" ; } var i = 1 ; while ( true ) { var generatedName = baseName + i ; if ( isUniqueName ( generatedName ) ) { return generatedNameSet [ generatedName ] = generatedName ; } i ++ ; } }


Input: Encoding for sourcemap span [CODESPLIT] function encodeLastRecordedSourceMapSpan ( ) { if ( ! lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan ) { return ; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan . emittedColumn ; // Line/Comma delimiters if ( lastEncodedSourceMapSpan . emittedLine === lastRecordedSourceMapSpan . emittedLine ) { // Emit comma to separate the entry if ( sourceMapData . sourceMapMappings ) { sourceMapData . sourceMapMappings += "," ; } } else { // Emit line delimiters for ( var encodedLine = lastEncodedSourceMapSpan . emittedLine ; encodedLine < lastRecordedSourceMapSpan . emittedLine ; encodedLine ++ ) { sourceMapData . sourceMapMappings += ";" ; } prevEncodedEmittedColumn = 1 ; } // 1. Relative Column 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . emittedColumn - prevEncodedEmittedColumn ) ; // 2. Relative sourceIndex sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceIndex - lastEncodedSourceMapSpan . sourceIndex ) ; // 3. Relative sourceLine 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceLine - lastEncodedSourceMapSpan . sourceLine ) ; // 4. Relative sourceColumn 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceColumn - lastEncodedSourceMapSpan . sourceColumn ) ; // 5. Relative namePosition 0 based if ( lastRecordedSourceMapSpan . nameIndex >= 0 ) { sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . nameIndex - lastEncodedNameIndex ) ; lastEncodedNameIndex = lastRecordedSourceMapSpan . nameIndex ; } lastEncodedSourceMapSpan = lastRecordedSourceMapSpan ; sourceMapData . sourceMapDecodedMappings . push ( lastEncodedSourceMapSpan ) ; function base64VLQFormatEncode ( inValue ) { function base64FormatEncode ( inValue ) { if ( inValue < 64 ) { return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" . charAt ( inValue ) ; } throw TypeError ( inValue + ": not a 64 based value" ) ; } // Add a new least significant bit that has the sign of the value. // if negative number the least significant bit that gets added to the number has value 1 // else least significant bit value that gets added is 0 // eg. -1 changes to binary : 01 [1] => 3 //     +1 changes to binary : 01 [0] => 2 if ( inValue < 0 ) { inValue = ( ( - inValue ) << 1 ) + 1 ; } else { inValue = inValue << 1 ; } // Encode 5 bits at a time starting from least significant bits var encodedStr = "" ; do { var currentDigit = inValue & 31 ; // 11111 inValue = inValue >> 5 ; if ( inValue > 0 ) { // There are still more digits to decode, set the msb (6th bit) currentDigit = currentDigit | 32 ; } encodedStr = encodedStr + base64FormatEncode ( currentDigit ) ; } while ( inValue > 0 ) ; return encodedStr ; } }


Input: Create a temporary variable with a unique unused name . [CODESPLIT] function createTempVariable ( flags ) { var result = ts . createSynthesizedNode ( 69 /* Identifier */ ) ; result . text = makeTempVariableName ( flags ) ; return result ; }


Input: / Emit a tag name which is either div for lower - cased names or / Div for upper - cased or dotted names [CODESPLIT] function emitTagName ( name ) { if ( name . kind === 69 /* Identifier */ && ts . isIntrinsicJsxName ( name . text ) ) { write ( "\"" ) ; emit ( name ) ; write ( "\"" ) ; } else { emit ( name ) ; } }


Input: This function specifically handles numeric / string literals for enum and accessor identifiers . In a sense it does not actually emit identifiers as much as it declares a name for a specific property . For example this is utilized when feeding in a result to Object . defineProperty . [CODESPLIT] function emitExpressionForPropertyName ( node ) { ts . Debug . assert ( node . kind !== 163 /* BindingElement */ ) ; if ( node . kind === 9 /* StringLiteral */ ) { emitLiteral ( node ) ; } else if ( node . kind === 136 /* ComputedPropertyName */ ) { // if this is a decorated computed property, we will need to capture the result // of the property expression so that we can apply decorators later. This is to ensure // we don't introduce unintended side effects: // //   class C { //     [_a = x]() { } //   } // // The emit for the decorated computed property decorator is: // //   __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a)); // if ( ts . nodeIsDecorated ( node . parent ) ) { if ( ! computedPropertyNamesToGeneratedNames ) { computedPropertyNamesToGeneratedNames = [ ] ; } var generatedName = computedPropertyNamesToGeneratedNames [ ts . getNodeId ( node ) ] ; if ( generatedName ) { // we have already generated a variable for this node, write that value instead. write ( generatedName ) ; return ; } generatedName = createAndRecordTempVariable ( 0 /* Auto */ ) . text ; computedPropertyNamesToGeneratedNames [ ts . getNodeId ( node ) ] = generatedName ; write ( generatedName ) ; write ( " = " ) ; } emit ( node . expression ) ; } else { write ( "\"" ) ; if ( node . kind === 8 /* NumericLiteral */ ) { write ( node . text ) ; } else { writeTextOfNode ( currentSourceFile , node ) ; } write ( "\"" ) ; } }


Input: Returns true if the code was actually indented false otherwise . If the code is not indented an optional valueToWriteWhenNotIndenting will be emitted instead . [CODESPLIT] function indentIfOnDifferentLines ( parent , node1 , node2 , valueToWriteWhenNotIndenting ) { var realNodesAreOnDifferentLines = ! ts . nodeIsSynthesized ( parent ) && ! nodeEndIsOnSameLineAsNodeStart ( node1 , node2 ) ; // Always use a newline for synthesized code if the synthesizer desires it. var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine ( node2 ) ; if ( realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine ) { increaseIndent ( ) ; writeLine ( ) ; return true ; } else { if ( valueToWriteWhenNotIndenting ) { write ( valueToWriteWhenNotIndenting ) ; } return false ; } }


Input: / * Checks if given node is a source file level declaration ( not nested in module / function ) . If isExported is true - then declaration must also be exported . This function is used in two cases : - check if node is a exported source file level value to determine if we should also export the value after its it changed - check if node is a source level declaration to emit it differently i . e non - exported variable statement var x = 1 is hoisted so we we emit variable statement var should be dropped . [CODESPLIT] function isSourceFileLevelDeclarationInSystemJsModule ( node , isExported ) { if ( ! node || languageVersion >= 2 /* ES6 */ || ! isCurrentFileSystemExternalModule ( ) ) { return false ; } var current = node ; while ( current ) { if ( current . kind === 248 /* SourceFile */ ) { return ! isExported || ( ( ts . getCombinedNodeFlags ( node ) & 1 /* Export */ ) !== 0 ) ; } else if ( ts . isFunctionLike ( current ) || current . kind === 219 /* ModuleBlock */ ) { return false ; } else { current = current . parent ; } } }


Input: Emit ES7 exponentiation operator downlevel using Math . pow [CODESPLIT] function emitExponentiationOperator ( node ) { var leftHandSideExpression = node . left ; if ( node . operatorToken . kind === 60 /* AsteriskAsteriskEqualsToken */ ) { var synthesizedLHS ; var shouldEmitParentheses = false ; if ( ts . isElementAccessExpression ( leftHandSideExpression ) ) { shouldEmitParentheses = true ; write ( "(" ) ; synthesizedLHS = ts . createSynthesizedNode ( 167 /* ElementAccessExpression */ , /*startsOnNewLine*/ false ) ; var identifier = emitTempVariableAssignment ( leftHandSideExpression . expression , /*canDefinedTempVariablesInPlaces*/ false , /*shouldEmitCommaBeforeAssignment*/ false ) ; synthesizedLHS . expression = identifier ; if ( leftHandSideExpression . argumentExpression . kind !== 8 /* NumericLiteral */ && leftHandSideExpression . argumentExpression . kind !== 9 /* StringLiteral */ ) { var tempArgumentExpression = createAndRecordTempVariable ( 268435456 /* _i */ ) ; synthesizedLHS . argumentExpression = tempArgumentExpression ; emitAssignment ( tempArgumentExpression , leftHandSideExpression . argumentExpression , /*shouldEmitCommaBeforeAssignment*/ true ) ; } else { synthesizedLHS . argumentExpression = leftHandSideExpression . argumentExpression ; } write ( ", " ) ; } else if ( ts . isPropertyAccessExpression ( leftHandSideExpression ) ) { shouldEmitParentheses = true ; write ( "(" ) ; synthesizedLHS = ts . createSynthesizedNode ( 166 /* PropertyAccessExpression */ , /*startsOnNewLine*/ false ) ; var identifier = emitTempVariableAssignment ( leftHandSideExpression . expression , /*canDefinedTempVariablesInPlaces*/ false , /*shouldemitCommaBeforeAssignment*/ false ) ; synthesizedLHS . expression = identifier ; synthesizedLHS . dotToken = leftHandSideExpression . dotToken ; synthesizedLHS . name = leftHandSideExpression . name ; write ( ", " ) ; } emit ( synthesizedLHS || leftHandSideExpression ) ; write ( " = " ) ; write ( "Math.pow(" ) ; emit ( synthesizedLHS || leftHandSideExpression ) ; write ( ", " ) ; emit ( node . right ) ; write ( ")" ) ; if ( shouldEmitParentheses ) { write ( ")" ) ; } } else { write ( "Math.pow(" ) ; emit ( leftHandSideExpression ) ; write ( ", " ) ; emit ( node . right ) ; write ( ")" ) ; } }


Input: Returns true if start of variable declaration list was emitted . Returns false if nothing was written - this can happen for source file level variable declarations in system modules where such variable declarations are hoisted . [CODESPLIT] function tryEmitStartOfVariableDeclarationList ( decl , startPos ) { if ( shouldHoistVariable ( decl , /*checkIfSourceFileLevelDecl*/ true ) ) { // variables in variable declaration list were already hoisted return false ; } var tokenKind = 102 /* VarKeyword */ ; if ( decl && languageVersion >= 2 /* ES6 */ ) { if ( ts . isLet ( decl ) ) { tokenKind = 108 /* LetKeyword */ ; } else if ( ts . isConst ( decl ) ) { tokenKind = 74 /* ConstKeyword */ ; } } if ( startPos !== undefined ) { emitToken ( tokenKind , startPos ) ; write ( " " ) ; } else { switch ( tokenKind ) { case 102 /* VarKeyword */ : write ( "var " ) ; break ; case 108 /* LetKeyword */ : write ( "let " ) ; break ; case 74 /* ConstKeyword */ : write ( "const " ) ; break ; } } return true ; }


Input: Emit an assignment to a given identifier name with a given expression value . [CODESPLIT] function emitAssignment ( name , value , shouldEmitCommaBeforeAssignment ) { if ( shouldEmitCommaBeforeAssignment ) { write ( ", " ) ; } var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( name ) ; if ( exportChanged ) { write ( exportFunctionForFile + "(\"" ) ; emitNodeWithCommentsAndWithoutSourcemap ( name ) ; write ( "\", " ) ; } var isVariableDeclarationOrBindingElement = name . parent && ( name . parent . kind === 211 /* VariableDeclaration */ || name . parent . kind === 163 /* BindingElement */ ) ; if ( isVariableDeclarationOrBindingElement ) { emitModuleMemberName ( name . parent ) ; } else { emit ( name ) ; } write ( " = " ) ; emit ( value ) ; if ( exportChanged ) { write ( ")" ) ; } }


Input: Create temporary variable emit an assignment of the variable the given expression [CODESPLIT] function emitTempVariableAssignment ( expression , canDefineTempVariablesInPlace , shouldEmitCommaBeforeAssignment ) { var identifier = createTempVariable ( 0 /* Auto */ ) ; if ( ! canDefineTempVariablesInPlace ) { recordTempDeclaration ( identifier ) ; } emitAssignment ( identifier , expression , shouldEmitCommaBeforeAssignment ) ; return identifier ; }


Input: Ensures that there exists a declared identifier whose value holds the given expression . This function is useful to ensure that the expression s value can be read from in subsequent expressions . Unless reuseIdentifierExpressions is false expr will be returned if it is just an identifier . [CODESPLIT] function ensureIdentifier ( expr , reuseIdentifierExpressions ) { if ( expr . kind === 69 /* Identifier */ && reuseIdentifierExpressions ) { return expr ; } var identifier = emitTempVariableAssignment ( expr , canDefineTempVariablesInPlace , emitCount > 0 ) ; emitCount ++ ; return identifier ; }


Input: Serializes the type of a declaration to an appropriate JS constructor value . Used by the __metadata decorator for a class member . [CODESPLIT] function emitSerializedTypeOfNode ( node ) { // serialization of the type of a declaration uses the following rules: // // * The serialized type of a ClassDeclaration is "Function" // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation. // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation. // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. // * The serialized type of any other FunctionLikeDeclaration is "Function". // * The serialized type of any other node is "void 0". // // For rules on serializing type annotations, see `serializeTypeNode`. switch ( node . kind ) { case 214 /* ClassDeclaration */ : write ( "Function" ) ; return ; case 141 /* PropertyDeclaration */ : emitSerializedTypeNode ( node . type ) ; return ; case 138 /* Parameter */ : emitSerializedTypeNode ( node . type ) ; return ; case 145 /* GetAccessor */ : emitSerializedTypeNode ( node . type ) ; return ; case 146 /* SetAccessor */ : emitSerializedTypeNode ( ts . getSetAccessorTypeAnnotationNode ( node ) ) ; return ; } if ( ts . isFunctionLike ( node ) ) { write ( "Function" ) ; return ; } write ( "void 0" ) ; }


Input: Serializes the return type of function . Used by the __metadata decorator for a method . [CODESPLIT] function emitSerializedReturnTypeOfNode ( node ) { if ( node && ts . isFunctionLike ( node ) && node . type ) { emitSerializedTypeNode ( node . type ) ; return ; } write ( "void 0" ) ; }


Input: / * Some bundlers ( SystemJS builder ) sometimes want to rename dependencies . Here we check if alternative name was provided for a given moduleName and return it if possible . [CODESPLIT] function tryRenameExternalModule ( moduleName ) { if ( currentSourceFile . renamedDependencies && ts . hasProperty ( currentSourceFile . renamedDependencies , moduleName . text ) ) { return "\"" + currentSourceFile . renamedDependencies [ moduleName . text ] + "\"" ; } return undefined ; }


Input: Emit trailing comments at the position . The term trailing comment is used here to describe following comment : x / comment1 / y ^ = > pos ; the function will emit comment1 in the emitJS [CODESPLIT] function emitTrailingCommentsOfPosition ( pos ) { if ( compilerOptions . removeComments ) { return ; } var trailingComments = ts . getTrailingCommentRanges ( currentSourceFile . text , pos ) ; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ ts . emitComments ( currentSourceFile , writer , trailingComments , /*trailingSeparator*/ true , newLine , writeComment ) ; }


Input: Get source file from normalized fileName [CODESPLIT] function findSourceFile ( fileName , isDefaultLib , refFile , refPos , refEnd ) { if ( filesByName . contains ( fileName ) ) { // We've already looked for this file, use cached result return getSourceFileFromCache ( fileName , /*useAbsolutePath*/ false ) ; } var normalizedAbsolutePath = ts . getNormalizedAbsolutePath ( fileName , host . getCurrentDirectory ( ) ) ; if ( filesByName . contains ( normalizedAbsolutePath ) ) { var file_1 = getSourceFileFromCache ( normalizedAbsolutePath , /*useAbsolutePath*/ true ) ; // we don't have resolution for this relative file name but the match was found by absolute file name // store resolution for relative name as well filesByName . set ( fileName , file_1 ) ; return file_1 ; } // We haven't looked for this file, do so now and cache result var file = host . getSourceFile ( fileName , options . target , function ( hostErrorMessage ) { if ( refFile !== undefined && refPos !== undefined && refEnd !== undefined ) { fileProcessingDiagnostics . add ( ts . createFileDiagnostic ( refFile , refPos , refEnd - refPos , ts . Diagnostics . Cannot_read_file_0_Colon_1 , fileName , hostErrorMessage ) ) ; } else { fileProcessingDiagnostics . add ( ts . createCompilerDiagnostic ( ts . Diagnostics . Cannot_read_file_0_Colon_1 , fileName , hostErrorMessage ) ) ; } } ) ; filesByName . set ( fileName , file ) ; if ( file ) { skipDefaultLib = skipDefaultLib || file . hasNoDefaultLib ; // Set the source file for normalized absolute path filesByName . set ( normalizedAbsolutePath , file ) ; var basePath = ts . getDirectoryPath ( fileName ) ; if ( ! options . noResolve ) { processReferencedFiles ( file , basePath ) ; } // always process imported modules to record module name resolutions processImportedModules ( file , basePath ) ; if ( isDefaultLib ) { file . isDefaultLib = true ; files . unshift ( file ) ; } else { files . push ( file ) ; } } return file ; function getSourceFileFromCache ( fileName , useAbsolutePath ) { var file = filesByName . get ( fileName ) ; if ( file && host . useCaseSensitiveFileNames ( ) ) { var sourceFileName = useAbsolutePath ? ts . getNormalizedAbsolutePath ( file . fileName , host . getCurrentDirectory ( ) ) : file . fileName ; if ( ts . normalizeSlashes ( fileName ) !== ts . normalizeSlashes ( sourceFileName ) ) { if ( refFile !== undefined && refPos !== undefined && refEnd !== undefined ) { fileProcessingDiagnostics . add ( ts . createFileDiagnostic ( refFile , refPos , refEnd - refPos , ts . Diagnostics . File_name_0_differs_from_already_included_file_name_1_only_in_casing , fileName , sourceFileName ) ) ; } else { fileProcessingDiagnostics . add ( ts . createCompilerDiagnostic ( ts . Diagnostics . File_name_0_differs_from_already_included_file_name_1_only_in_casing , fileName , sourceFileName ) ) ; } } } return file ; } }


Input: / * [CODESPLIT] function getOptionNameMap ( ) { if ( optionNameMapCache ) { return optionNameMapCache ; } var optionNameMap = { } ; var shortOptionNames = { } ; ts . forEach ( ts . optionDeclarations , function ( option ) { optionNameMap [ option . name . toLowerCase ( ) ] = option ; if ( option . shortName ) { shortOptionNames [ option . shortName ] = option . name ; } } ) ; optionNameMapCache = { optionNameMap : optionNameMap , shortOptionNames : shortOptionNames } ; return optionNameMapCache ; }


Input: Read tsconfig . json file [CODESPLIT] function readConfigFile ( fileName , readFile ) { var text = "" ; try { text = readFile ( fileName ) ; } catch ( e ) { return { error : ts . createCompilerDiagnostic ( ts . Diagnostics . Cannot_read_file_0_Colon_1 , fileName , e . message ) } ; } return parseConfigFileTextToJson ( fileName , text ) ; }


Input: Parse the text of the tsconfig . json file [CODESPLIT] function parseConfigFileTextToJson ( fileName , jsonText ) { try { return { config : / \S / . test ( jsonText ) ? JSON . parse ( jsonText ) : { } } ; } catch ( e ) { return { error : ts . createCompilerDiagnostic ( ts . Diagnostics . Failed_to_parse_file_0_Colon_1 , fileName , e . message ) } ; } }


Input: Parse the contents of a config file ( tsconfig . json ) . [CODESPLIT] function parseJsonConfigFileContent ( json , host , basePath ) { var errors = [ ] ; return { options : getCompilerOptions ( ) , fileNames : getFileNames ( ) , errors : errors } ; function getCompilerOptions ( ) { var options = { } ; var optionNameMap = { } ; ts . forEach ( ts . optionDeclarations , function ( option ) { optionNameMap [ option . name ] = option ; } ) ; var jsonOptions = json [ "compilerOptions" ] ; if ( jsonOptions ) { for ( var id in jsonOptions ) { if ( ts . hasProperty ( optionNameMap , id ) ) { var opt = optionNameMap [ id ] ; var optType = opt . type ; var value = jsonOptions [ id ] ; var expectedType = typeof optType === "string" ? optType : "string" ; if ( typeof value === expectedType ) { if ( typeof optType !== "string" ) { var key = value . toLowerCase ( ) ; if ( ts . hasProperty ( optType , key ) ) { value = optType [ key ] ; } else { errors . push ( ts . createCompilerDiagnostic ( opt . error ) ) ; value = 0 ; } } if ( opt . isFilePath ) { value = ts . normalizePath ( ts . combinePaths ( basePath , value ) ) ; if ( value === "" ) { value = "." ; } } options [ opt . name ] = value ; } else { errors . push ( ts . createCompilerDiagnostic ( ts . Diagnostics . Compiler_option_0_requires_a_value_of_type_1 , id , expectedType ) ) ; } } else { errors . push ( ts . createCompilerDiagnostic ( ts . Diagnostics . Unknown_compiler_option_0 , id ) ) ; } } } return options ; } function getFileNames ( ) { var fileNames = [ ] ; if ( ts . hasProperty ( json , "files" ) ) { if ( json [ "files" ] instanceof Array ) { fileNames = ts . map ( json [ "files" ] , function ( s ) { return ts . combinePaths ( basePath , s ) ; } ) ; } else { errors . push ( ts . createCompilerDiagnostic ( ts . Diagnostics . Compiler_option_0_requires_a_value_of_type_1 , "files" , "Array" ) ) ; } } else { var exclude = json [ "exclude" ] instanceof Array ? ts . map ( json [ "exclude" ] , ts . normalizeSlashes ) : undefined ; var sysFiles = host . readDirectory ( basePath , ".ts" , exclude ) . concat ( host . readDirectory ( basePath , ".tsx" , exclude ) ) ; for ( var i = 0 ; i < sysFiles . length ; i ++ ) { var name_28 = sysFiles [ i ] ; if ( ts . fileExtensionIs ( name_28 , ".d.ts" ) ) { var baseName = name_28 . substr ( 0 , name_28 . length - ".d.ts" . length ) ; if ( ! ts . contains ( sysFiles , baseName + ".tsx" ) && ! ts . contains ( sysFiles , baseName + ".ts" ) ) { fileNames . push ( name_28 ) ; } } else if ( ts . fileExtensionIs ( name_28 , ".ts" ) ) { if ( ! ts . contains ( sysFiles , name_28 + "x" ) ) { fileNames . push ( name_28 ) ; } } else { fileNames . push ( name_28 ) ; } } } return fileNames ; } }


Input: Like removeComputedProperties but retains the properties with well known symbol names [CODESPLIT] function removeDynamicallyNamedProperties ( node ) { return ts . filter ( node . members , function ( member ) { return ! ts . hasDynamicName ( member ) ; } ) ; }


Input: Helper function to compare two matches to determine which is better . Matches are first ordered by kind ( so all prefix matches always beat all substring matches ) . Then if the match is a camel case match the relative weights of the match are used to determine which is better ( with a greater weight being better ) . Then if the match is of the same type then a case sensitive match is considered better than an insensitive one . [CODESPLIT] function patternMatchCompareTo ( match1 , match2 ) { return compareType ( match1 , match2 ) || compareCamelCase ( match1 , match2 ) || compareCase ( match1 , match2 ) || comparePunctuation ( match1 , match2 ) ; }


Input: Assumes value is already lowercase . [CODESPLIT] function indexOfIgnoringCase ( string , value ) { for ( var i = 0 , n = string . length - value . length ; i <= n ; i ++ ) { if ( startsWithIgnoringCase ( string , value , i ) ) { return i ; } } return - 1 ; }


Input: Assumes value is already lowercase . [CODESPLIT] function startsWithIgnoringCase ( string , value , start ) { for ( var i = 0 , n = value . length ; i < n ; i ++ ) { var ch1 = toLowerCase ( string . charCodeAt ( i + start ) ) ; var ch2 = value . charCodeAt ( i ) ; if ( ch1 !== ch2 ) { return false ; } } return true ; }


Input: Returns relevant information for the argument list and the current argument if we are in the argument of an invocation ; returns undefined otherwise . [CODESPLIT] function getImmediatelyContainingArgumentInfo ( node ) { if ( node . parent . kind === 168 /* CallExpression */ || node . parent . kind === 169 /* NewExpression */ ) { var callExpression = node . parent ; // There are 3 cases to handle: //   1. The token introduces a list, and should begin a sig help session //   2. The token is either not associated with a list, or ends a list, so the session should end //   3. The token is buried inside a list, and should give sig help // // The following are examples of each: // //    Case 1: //          foo<#T, U>(#a, b)    -> The token introduces a list, and should begin a sig help session //    Case 2: //          fo#o<T, U>#(a, b)#   -> The token is either not associated with a list, or ends a list, so the session should end //    Case 3: //          foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give sig help // Find out if 'node' is an argument, a type argument, or neither if ( node . kind === 25 /* LessThanToken */ || node . kind === 17 /* OpenParenToken */ ) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. var list = getChildListThatStartsWithOpenerToken ( callExpression , node , sourceFile ) ; var isTypeArgList = callExpression . typeArguments && callExpression . typeArguments . pos === list . pos ; ts . Debug . assert ( list !== undefined ) ; return { kind : isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */ , invocation : callExpression , argumentsSpan : getApplicableSpanForArguments ( list ) , argumentIndex : 0 , argumentCount : getArgumentCount ( list ) } ; } // findListItemInfo can return undefined if we are not in parent's argument list // or type argument list. This includes cases where the cursor is: //   - To the right of the closing paren, non-substitution template, or template tail. //   - Between the type arguments and the arguments (greater than token) //   - On the target of the call (parent.func) //   - On the 'new' keyword in a 'new' expression var listItemInfo = ts . findListItemInfo ( node ) ; if ( listItemInfo ) { var list = listItemInfo . list ; var isTypeArgList = callExpression . typeArguments && callExpression . typeArguments . pos === list . pos ; var argumentIndex = getArgumentIndex ( list , node ) ; var argumentCount = getArgumentCount ( list ) ; ts . Debug . assert ( argumentIndex === 0 || argumentIndex < argumentCount , "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex ) ; return { kind : isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */ , invocation : callExpression , argumentsSpan : getApplicableSpanForArguments ( list ) , argumentIndex : argumentIndex , argumentCount : argumentCount } ; } } else if ( node . kind === 11 /* NoSubstitutionTemplateLiteral */ && node . parent . kind === 170 /* TaggedTemplateExpression */ ) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if ( ts . isInsideTemplateLiteral ( node , position ) ) { return getArgumentListInfoForTemplate ( node . parent , /*argumentIndex*/ 0 ) ; } } else if ( node . kind === 12 /* TemplateHead */ && node . parent . parent . kind === 170 /* TaggedTemplateExpression */ ) { var templateExpression = node . parent ; var tagExpression = templateExpression . parent ; ts . Debug . assert ( templateExpression . kind === 183 /* TemplateExpression */ ) ; var argumentIndex = ts . isInsideTemplateLiteral ( node , position ) ? 0 : 1 ; return getArgumentListInfoForTemplate ( tagExpression , argumentIndex ) ; } else if ( node . parent . kind === 190 /* TemplateSpan */ && node . parent . parent . parent . kind === 170 /* TaggedTemplateExpression */ ) { var templateSpan = node . parent ; var templateExpression = templateSpan . parent ; var tagExpression = templateExpression . parent ; ts . Debug . assert ( templateExpression . kind === 183 /* TemplateExpression */ ) ; // If we're just after a template tail, don't show signature help. if ( node . kind === 14 /* TemplateTail */ && ! ts . isInsideTemplateLiteral ( node , position ) ) { return undefined ; } var spanIndex = templateExpression . templateSpans . indexOf ( templateSpan ) ; var argumentIndex = getArgumentIndexForTemplatePiece ( spanIndex , node ) ; return getArgumentListInfoForTemplate ( tagExpression , argumentIndex ) ; } return undefined ; }


Input: The selectedItemIndex could be negative for several reasons . 1 . There are too many arguments for all of the overloads 2 . None of the overloads were type compatible The solution here is to try to pick the best overload by picking either the first one that has an appropriate number of parameters or the one with the most parameters . [CODESPLIT] function selectBestInvalidOverloadIndex ( candidates , argumentCount ) { var maxParamsSignatureIndex = - 1 ; var maxParams = - 1 ; for ( var i = 0 ; i < candidates . length ; i ++ ) { var candidate = candidates [ i ] ; if ( candidate . hasRestParameter || candidate . parameters . length >= argumentCount ) { return i ; } if ( candidate . parameters . length > maxParams ) { maxParams = candidate . parameters . length ; maxParamsSignatureIndex = i ; } } return maxParamsSignatureIndex ; }


Input: / * Checks if node ends with expectedLastToken . If child at position length - 1 is SemicolonToken it is skipped and expectedLastToken is compared with child at position length - 2 . [CODESPLIT] function nodeEndsWith ( n , expectedLastToken , sourceFile ) { var children = n . getChildren ( sourceFile ) ; if ( children . length ) { var last = ts . lastOrUndefined ( children ) ; if ( last . kind === expectedLastToken ) { return true ; } else if ( last . kind === 23 /* SemicolonToken */ && children . length !== 1 ) { return children [ children . length - 2 ] . kind === expectedLastToken ; } } return false ; }


Input: / * Gets the token whose text has range [ start end ) and position > = start and ( position < end or ( position === end && token is keyword or identifier )) [CODESPLIT] function getTouchingWord ( sourceFile , position ) { return getTouchingToken ( sourceFile , position , function ( n ) { return isWord ( n . kind ) ; } ) ; }


Input: / * Gets the token whose text has range [ start end ) and position > = start and ( position < end or ( position === end && token is keyword or identifier or numeric \ string litera )) [CODESPLIT] function getTouchingPropertyName ( sourceFile , position ) { return getTouchingToken ( sourceFile , position , function ( n ) { return isPropertyName ( n . kind ) ; } ) ; }


Input: Get the token whose text contains the position [CODESPLIT] function getTokenAtPositionWorker ( sourceFile , position , allowPositionInLeadingTrivia , includeItemAtEndPosition ) { var current = sourceFile ; outer : while ( true ) { if ( isToken ( current ) ) { // exit early return current ; } // find the child that contains 'position' for ( var i = 0 , n = current . getChildCount ( sourceFile ) ; i < n ; i ++ ) { var child = current . getChildAt ( i ) ; var start = allowPositionInLeadingTrivia ? child . getFullStart ( ) : child . getStart ( sourceFile ) ; if ( start <= position ) { var end = child . getEnd ( ) ; if ( position < end || ( position === end && child . kind === 1 /* EndOfFileToken */ ) ) { current = child ; continue outer ; } else if ( includeItemAtEndPosition && end === position ) { var previousToken = findPrecedingToken ( position , sourceFile , child ) ; if ( previousToken && includeItemAtEndPosition ( previousToken ) ) { return previousToken ; } } } } return current ; } }


Input: The token on the left of the position is the token that strictly includes the position or sits to the left of the cursor if it is on a boundary . For example [CODESPLIT] function findTokenOnLeftOfPosition ( file , position ) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. var tokenAtPosition = getTokenAtPosition ( file , position ) ; if ( isToken ( tokenAtPosition ) && position > tokenAtPosition . getStart ( file ) && position < tokenAtPosition . getEnd ( ) ) { return tokenAtPosition ; } return findPrecedingToken ( position , file ) ; }


Input: / finds last node that is considered as candidate for search ( isCandidate ( node ) === true ) starting from exclusiveStartPosition [CODESPLIT] function findRightmostChildNodeWithTokens ( children , exclusiveStartPosition ) { for ( var i = exclusiveStartPosition - 1 ; i >= 0 ; -- i ) { if ( nodeHasTokens ( children [ i ] ) ) { return children [ i ] ; } } }


Input: Get the corresponding JSDocTag node if the position is in a jsDoc comment [CODESPLIT] function getJsDocTagAtPosition ( sourceFile , position ) { var node = ts . getTokenAtPosition ( sourceFile , position ) ; if ( isToken ( node ) ) { switch ( node . kind ) { case 102 /* VarKeyword */ : case 108 /* LetKeyword */ : case 74 /* ConstKeyword */ : // if the current token is var, let or const, skip the VariableDeclarationList node = node . parent === undefined ? undefined : node . parent . parent ; break ; default : node = node . parent ; break ; } } if ( node ) { var jsDocComment = node . jsDocComment ; if ( jsDocComment ) { for ( var _i = 0 , _a = jsDocComment . tags ; _i < _a . length ; _i ++ ) { var tag = _a [ _i ] ; if ( tag . pos <= position && position <= tag . end ) { return tag ; } } } } return undefined ; }


Input: Strip off existed single quotes or double quotes from a given string [CODESPLIT] function stripQuotes ( name ) { var length = name . length ; if ( length >= 2 && name . charCodeAt ( 0 ) === name . charCodeAt ( length - 1 ) && ( name . charCodeAt ( 0 ) === 34 /* doubleQuote */ || name . charCodeAt ( 0 ) === 39 /* singleQuote */ ) ) { return name . substring ( 1 , length - 1 ) ; } ; return name ; }


Input: when containing node in the tree is token but its kind differs from the kind that was returned by the scanner then kind needs to be fixed . This might happen in cases when parser interprets token differently i . e keyword treated as identifier [CODESPLIT] function fixTokenKind ( tokenInfo , container ) { if ( ts . isToken ( container ) && tokenInfo . token . kind !== container . kind ) { tokenInfo . token . kind = container . kind ; } return tokenInfo ; }


Input: Returns true if node is a element in some list in parent i . e . parent is class declaration with the list of members and node is one of members . [CODESPLIT] function isListElement ( parent , node ) { switch ( parent . kind ) { case 214 /* ClassDeclaration */ : case 215 /* InterfaceDeclaration */ : return ts . rangeContainsRange ( parent . members , node ) ; case 218 /* ModuleDeclaration */ : var body = parent . body ; return body && body . kind === 192 /* Block */ && ts . rangeContainsRange ( body . statements , node ) ; case 248 /* SourceFile */ : case 192 /* Block */ : case 219 /* ModuleBlock */ : return ts . rangeContainsRange ( parent . statements , node ) ; case 244 /* CatchClause */ : return ts . rangeContainsRange ( parent . block . statements , node ) ; } return false ; }


Input: find node that fully contains given text range [CODESPLIT] function findEnclosingNode ( range , sourceFile ) { return find ( sourceFile ) ; function find ( n ) { var candidate = ts . forEachChild ( n , function ( c ) { return ts . startEndContainsRange ( c . getStart ( sourceFile ) , c . end , range ) && c ; } ) ; if ( candidate ) { var result = find ( candidate ) ; if ( result ) { return result ; } } return n ; } }


Input: formatting is not applied to ranges that contain parse errors . This function will return a predicate that for a given text range will tell if there are any parse errors that overlap with the range . [CODESPLIT] function prepareRangeContainsErrorFunction ( errors , originalRange ) { if ( ! errors . length ) { return rangeHasNoErrors ; } // pick only errors that fall in range var sorted = errors . filter ( function ( d ) { return ts . rangeOverlapsWithStartEnd ( originalRange , d . start , d . start + d . length ) ; } ) . sort ( function ( e1 , e2 ) { return e1 . start - e2 . start ; } ) ; if ( ! sorted . length ) { return rangeHasNoErrors ; } var index = 0 ; return function ( r ) { // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. // 'index' tracks the index of the most recent error that was checked. while ( true ) { if ( index >= sorted . length ) { // all errors in the range were already checked -> no error in specified range return false ; } var error = sorted [ index ] ; if ( r . end <= error . start ) { // specified range ends before the error refered by 'index' - no error in range return false ; } if ( ts . startEndOverlapsWithStartEnd ( r . pos , r . end , error . start , error . start + error . length ) ) { // specified range overlaps with error range return true ; } index ++ ; } } ; function rangeHasNoErrors ( r ) { return false ; } }


Input: / * For cases like if ( a || b ||$ c ) { ... } If we hit Enter at $ we want line b || to be indented . Formatting will be applied to the last two lines . Node that fully encloses these lines is binary expression a || ... . Initial indentation for this node will be 0 . Binary expressions don t introduce new indentation scopes however it is possible that some parent node on the same line does - like if statement in this case . Note that we are considering parents only from the same line with initial node - if parent is on the different line - its delta was already contributed to the initial indentation . [CODESPLIT] function getOwnOrInheritedDelta ( n , options , sourceFile ) { var previousLine = - 1 /* Unknown */ ; var childKind = 0 /* Unknown */ ; while ( n ) { var line = sourceFile . getLineAndCharacterOfPosition ( n . getStart ( sourceFile ) ) . line ; if ( previousLine !== - 1 /* Unknown */ && line !== previousLine ) { break ; } if ( formatting . SmartIndenter . shouldIndentChildNode ( n . kind , childKind ) ) { return options . IndentSize ; } previousLine = line ; childKind = n . kind ; n = n . parent ; } return 0 ; }


Input: / * Function returns Value . Unknown if indentation cannot be determined [CODESPLIT] function getActualIndentationForListItemBeforeComma ( commaToken , sourceFile , options ) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var commaItemInfo = ts . findListItemInfo ( commaToken ) ; if ( commaItemInfo && commaItemInfo . listItemIndex > 0 ) { return deriveActualIndentationFromList ( commaItemInfo . list . getChildren ( ) , commaItemInfo . listItemIndex - 1 , sourceFile , options ) ; } else { // handle broken code gracefully return - 1 /* Unknown */ ; } }


Input: / * Function returns Value . Unknown if actual indentation for node should not be used ( i . e because node is nested expression ) [CODESPLIT] function getActualIndentationForNode ( current , parent , currentLineAndChar , parentAndChildShareLine , sourceFile , options ) { // actual indentation is used for statements\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = ( ts . isDeclaration ( current ) || ts . isStatement ( current ) ) && ( parent . kind === 248 /* SourceFile */ || ! parentAndChildShareLine ) ; if ( ! useActualIndentation ) { return - 1 /* Unknown */ ; } return findColumnForFirstNonWhitespaceCharacterInLine ( currentLineAndChar , sourceFile , options ) ; }


Input: / * Character is the actual index of the character since the beginning of the line . Column - position of the character after expanding tabs to spaces 0 \ t2$ value of character for $ is 3 value of column for $ is 6 ( assuming that tab size is 4 ) [CODESPLIT] function findFirstNonWhitespaceCharacterAndColumn ( startPos , endPos , sourceFile , options ) { var character = 0 ; var column = 0 ; for ( var pos = startPos ; pos < endPos ; ++ pos ) { var ch = sourceFile . text . charCodeAt ( pos ) ; if ( ! ts . isWhiteSpace ( ch ) ) { break ; } if ( ch === 9 /* tab */ ) { column += options . TabSize + ( column % options . TabSize ) ; } else { column ++ ; } character ++ ; } return { column : column , character : character } ; }


Input: / * This function will compile source text from input argument using specified compiler options . If not options are provided - it will use a set of default compiler options . Extra compiler options that will unconditionally be used by this function are : - isolatedModules = true - allowNonTsExtensions = true - noLib = true - noResolve = true [CODESPLIT] function transpileModule ( input , transpileOptions ) { var options = transpileOptions . compilerOptions ? ts . clone ( transpileOptions . compilerOptions ) : getDefaultCompilerOptions ( ) ; options . isolatedModules = true ; // Filename can be non-ts file. options . allowNonTsExtensions = true ; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. options . noLib = true ; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. options . noResolve = true ; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions . fileName || ( options . jsx ? "module.tsx" : "module.ts" ) ; var sourceFile = ts . createSourceFile ( inputFileName , input , options . target ) ; if ( transpileOptions . moduleName ) { sourceFile . moduleName = transpileOptions . moduleName ; } sourceFile . renamedDependencies = transpileOptions . renamedDependencies ; var newLine = ts . getNewLineCharacter ( options ) ; // Output var outputText ; var sourceMapText ; // Create a compilerHost object to allow the compiler to read and write files var compilerHost = { getSourceFile : function ( fileName , target ) { return fileName === ts . normalizeSlashes ( inputFileName ) ? sourceFile : undefined ; } , writeFile : function ( name , text , writeByteOrderMark ) { if ( ts . fileExtensionIs ( name , ".map" ) ) { ts . Debug . assert ( sourceMapText === undefined , "Unexpected multiple source map outputs for the file '" + name + "'" ) ; sourceMapText = text ; } else { ts . Debug . assert ( outputText === undefined , "Unexpected multiple outputs for the file: " + name ) ; outputText = text ; } } , getDefaultLibFileName : function ( ) { return "lib.d.ts" ; } , useCaseSensitiveFileNames : function ( ) { return false ; } , getCanonicalFileName : function ( fileName ) { return fileName ; } , getCurrentDirectory : function ( ) { return "" ; } , getNewLine : function ( ) { return newLine ; } , fileExists : function ( fileName ) { return fileName === inputFileName ; } , readFile : function ( fileName ) { return "" ; } } ; var program = ts . createProgram ( [ inputFileName ] , options , compilerHost ) ; var diagnostics ; if ( transpileOptions . reportDiagnostics ) { diagnostics = [ ] ; ts . addRange ( /*to*/ diagnostics , /*from*/ program . getSyntacticDiagnostics ( sourceFile ) ) ; ts . addRange ( /*to*/ diagnostics , /*from*/ program . getOptionsDiagnostics ( ) ) ; } // Emit program . emit ( ) ; ts . Debug . assert ( outputText !== undefined , "Output generation failed" ) ; return { outputText : outputText , diagnostics : diagnostics , sourceMapText : sourceMapText } ; }


Input: / * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result . [CODESPLIT] function transpile ( input , compilerOptions , fileName , diagnostics , moduleName ) { var output = transpileModule ( input , { compilerOptions : compilerOptions , fileName : fileName , reportDiagnostics : ! ! diagnostics , moduleName : moduleName } ) ; // addRange correctly handles cases when wither 'from' or 'to' argument is missing ts . addRange ( diagnostics , output . diagnostics ) ; return output . outputText ; }


Input: / Helpers [CODESPLIT] function getTargetLabel ( referenceNode , labelName ) { while ( referenceNode ) { if ( referenceNode . kind === 207 /* LabeledStatement */ && referenceNode . label . text === labelName ) { return referenceNode . label ; } referenceNode = referenceNode . parent ; } return undefined ; }


Input: Returns true if node is a name of an object literal property e . g . a in x = { a : 1 } [CODESPLIT] function isNameOfPropertyAssignment ( node ) { return ( node . kind === 69 /* Identifier */ || node . kind === 9 /* StringLiteral */ || node . kind === 8 /* NumericLiteral */ ) && ( node . parent . kind === 245 /* PropertyAssignment */ || node . parent . kind === 246 /* ShorthandPropertyAssignment */ ) && node . parent . name === node ; }


Input: Returns true if the position is within a comment [CODESPLIT] function isInsideComment ( sourceFile , token , position ) { // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment return position <= token . getStart ( sourceFile ) && ( isInsideCommentRange ( ts . getTrailingCommentRanges ( sourceFile . text , token . getFullStart ( ) ) ) || isInsideCommentRange ( ts . getLeadingCommentRanges ( sourceFile . text , token . getFullStart ( ) ) ) ) ; function isInsideCommentRange ( comments ) { return ts . forEach ( comments , function ( comment ) { // either we are 1. completely inside the comment, or 2. at the end of the comment if ( comment . pos < position && position < comment . end ) { return true ; } else if ( position === comment . end ) { var text = sourceFile . text ; var width = comment . end - comment . pos ; // is single line comment or just /* if ( width <= 2 || text . charCodeAt ( comment . pos + 1 ) === 47 /* slash */ ) { return true ; } else { // is unterminated multi-line comment return ! ( text . charCodeAt ( comment . end - 1 ) === 47 /* slash */ && text . charCodeAt ( comment . end - 2 ) === 42 /* asterisk */ ) ; } } return false ; } ) ; } }


Input: getSemanticDiagnostiscs return array of Diagnostics . If - d is not enabled only report semantic errors If - d enabled report both semantic and emitter errors [CODESPLIT] function getSemanticDiagnostics ( fileName ) { synchronizeHostData ( ) ; var targetSourceFile = getValidSourceFile ( fileName ) ; // For JavaScript files, we don't want to report the normal typescript semantic errors. // Instead, we just report errors for using TypeScript-only constructs from within a // JavaScript file. if ( ts . isJavaScript ( fileName ) ) { return getJavaScriptSemanticDiagnostics ( targetSourceFile ) ; } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program . getSemanticDiagnostics ( targetSourceFile , cancellationToken ) ; if ( ! program . getCompilerOptions ( ) . declaration ) { return semanticDiagnostics ; } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface var declarationDiagnostics = program . getDeclarationDiagnostics ( targetSourceFile , cancellationToken ) ; return ts . concatenate ( semanticDiagnostics , declarationDiagnostics ) ; }


Input: Get a displayName from a given for completion list performing any necessary quotes stripping and checking whether the name is valid identifier name . [CODESPLIT] function getCompletionEntryDisplayName ( name , target , performCharacterChecks ) { if ( ! name ) { return undefined ; } name = ts . stripQuotes ( name ) ; if ( ! name ) { return undefined ; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if ( performCharacterChecks ) { if ( ! ts . isIdentifierStart ( name . charCodeAt ( 0 ) , target ) ) { return undefined ; } for ( var i = 1 , n = name . length ; i < n ; i ++ ) { if ( ! ts . isIdentifierPart ( name . charCodeAt ( i ) , target ) ) { return undefined ; } } } return name ; }


Input: Finds the first node that embraces the position so that one may accurately aggregate locals from the closest containing scope . [CODESPLIT] function getScopeNode ( initialToken , position , sourceFile ) { var scope = initialToken ; while ( scope && ! ts . positionBelongsToNode ( scope , position , sourceFile ) ) { scope = scope . parent ; } return scope ; }


Input: Aggregates relevant symbols for completion in object literals and object binding patterns . Relevant symbols are stored in the captured symbols variable . [CODESPLIT] function tryGetObjectLikeCompletionSymbols ( objectLikeContainer ) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true ; var typeForObject ; var existingMembers ; if ( objectLikeContainer . kind === 165 /* ObjectLiteralExpression */ ) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true ; typeForObject = typeChecker . getContextualType ( objectLikeContainer ) ; existingMembers = objectLikeContainer . properties ; } else if ( objectLikeContainer . kind === 161 /* ObjectBindingPattern */ ) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false ; var rootDeclaration = ts . getRootDeclaration ( objectLikeContainer . parent ) ; if ( ts . isVariableLike ( rootDeclaration ) ) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. if ( rootDeclaration . initializer || rootDeclaration . type ) { typeForObject = typeChecker . getTypeAtLocation ( objectLikeContainer ) ; existingMembers = objectLikeContainer . elements ; } } else { ts . Debug . fail ( "Root declaration is not variable-like." ) ; } } else { ts . Debug . fail ( "Expected object literal or binding pattern, got " + objectLikeContainer . kind ) ; } if ( ! typeForObject ) { return false ; } var typeMembers = typeChecker . getPropertiesOfType ( typeForObject ) ; if ( typeMembers && typeMembers . length > 0 ) { // Add filtered items to the completion list symbols = filterObjectMembersList ( typeMembers , existingMembers ) ; } return true ; }


Input: Aggregates relevant symbols for completion in import clauses and export clauses whose declarations have a module specifier ; for instance symbols will be aggregated for [CODESPLIT] function tryGetImportOrExportClauseCompletionSymbols ( namedImportsOrExports ) { var declarationKind = namedImportsOrExports . kind === 225 /* NamedImports */ ? 222 /* ImportDeclaration */ : 228 /* ExportDeclaration */ ; var importOrExportDeclaration = ts . getAncestor ( namedImportsOrExports , declarationKind ) ; var moduleSpecifier = importOrExportDeclaration . moduleSpecifier ; if ( ! moduleSpecifier ) { return false ; } isMemberCompletion = true ; isNewIdentifierLocation = false ; var exports ; var moduleSpecifierSymbol = typeChecker . getSymbolAtLocation ( importOrExportDeclaration . moduleSpecifier ) ; if ( moduleSpecifierSymbol ) { exports = typeChecker . getExportsOfModule ( moduleSpecifierSymbol ) ; } symbols = exports ? filterNamedImportOrExportCompletionItems ( exports , namedImportsOrExports . elements ) : emptyArray ; return true ; }


Input: Returns the immediate owning object literal or binding pattern of a context token on the condition that one exists and that the context implies completion should be given . [CODESPLIT] function tryGetObjectLikeCompletionContainer ( contextToken ) { if ( contextToken ) { switch ( contextToken . kind ) { case 15 /* OpenBraceToken */ : // let x = { | case 24 /* CommaToken */ : var parent_10 = contextToken . parent ; if ( parent_10 && ( parent_10 . kind === 165 /* ObjectLiteralExpression */ || parent_10 . kind === 161 /* ObjectBindingPattern */ ) ) { return parent_10 ; } break ; } } return undefined ; }


Input: Filters out completion suggestions for named imports or exports . [CODESPLIT] function filterNamedImportOrExportCompletionItems ( exportsOfModule , namedImportsOrExports ) { var exisingImportsOrExports = { } ; for ( var _i = 0 ; _i < namedImportsOrExports . length ; _i ++ ) { var element = namedImportsOrExports [ _i ] ; // If this is the current item we are editing right now, do not filter it out if ( element . getStart ( ) <= position && position <= element . getEnd ( ) ) { continue ; } var name_32 = element . propertyName || element . name ; exisingImportsOrExports [ name_32 . text ] = true ; } if ( ts . isEmpty ( exisingImportsOrExports ) ) { return exportsOfModule ; } return ts . filter ( exportsOfModule , function ( e ) { return ! ts . lookUp ( exisingImportsOrExports , e . name ) ; } ) ; }


Input: Filters out completion suggestions for named imports or exports . [CODESPLIT] function filterObjectMembersList ( contextualMemberSymbols , existingMembers ) { if ( ! existingMembers || existingMembers . length === 0 ) { return contextualMemberSymbols ; } var existingMemberNames = { } ; for ( var _i = 0 ; _i < existingMembers . length ; _i ++ ) { var m = existingMembers [ _i ] ; // Ignore omitted expressions for missing members if ( m . kind !== 245 /* PropertyAssignment */ && m . kind !== 246 /* ShorthandPropertyAssignment */ && m . kind !== 163 /* BindingElement */ ) { continue ; } // If this is the current item we are editing right now, do not filter it out if ( m . getStart ( ) <= position && position <= m . getEnd ( ) ) { continue ; } var existingName = void 0 ; if ( m . kind === 163 /* BindingElement */ && m . propertyName ) { existingName = m . propertyName . text ; } else { // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. existingName = m . name . text ; } existingMemberNames [ existingName ] = true ; } return ts . filter ( contextualMemberSymbols , function ( m ) { return ! ts . lookUp ( existingMemberNames , m . name ) ; } ) ; }


Input: Filters out completion suggestions from symbols according to existing JSX attributes . [CODESPLIT] function filterJsxAttributes ( symbols , attributes ) { var seenNames = { } ; for ( var _i = 0 ; _i < attributes . length ; _i ++ ) { var attr = attributes [ _i ] ; // If this is the current item we are editing right now, do not filter it out if ( attr . getStart ( ) <= position && position <= attr . getEnd ( ) ) { continue ; } if ( attr . kind === 238 /* JsxAttribute */ ) { seenNames [ attr . name . text ] = true ; } } return ts . filter ( symbols , function ( a ) { return ! ts . lookUp ( seenNames , a . name ) ; } ) ; }


Input: TODO ( drosen ) : use contextual SemanticMeaning . [CODESPLIT] function getSymbolKind ( symbol , location ) { var flags = symbol . getFlags ( ) ; if ( flags & 32 /* Class */ ) return ts . getDeclarationOfKind ( symbol , 186 /* ClassExpression */ ) ? ScriptElementKind . localClassElement : ScriptElementKind . classElement ; if ( flags & 384 /* Enum */ ) return ScriptElementKind . enumElement ; if ( flags & 524288 /* TypeAlias */ ) return ScriptElementKind . typeElement ; if ( flags & 64 /* Interface */ ) return ScriptElementKind . interfaceElement ; if ( flags & 262144 /* TypeParameter */ ) return ScriptElementKind . typeParameterElement ; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar ( symbol , flags , location ) ; if ( result === ScriptElementKind . unknown ) { if ( flags & 262144 /* TypeParameter */ ) return ScriptElementKind . typeParameterElement ; if ( flags & 8 /* EnumMember */ ) return ScriptElementKind . variableElement ; if ( flags & 8388608 /* Alias */ ) return ScriptElementKind . alias ; if ( flags & 1536 /* Module */ ) return ScriptElementKind . moduleElement ; } return result ; }


Input: / Goto definition [CODESPLIT] function getDefinitionAtPosition ( fileName , position ) { synchronizeHostData ( ) ; var sourceFile = getValidSourceFile ( fileName ) ; var node = ts . getTouchingPropertyName ( sourceFile , position ) ; if ( ! node ) { return undefined ; } // Labels if ( isJumpStatementTarget ( node ) ) { var labelName = node . text ; var label = getTargetLabel ( node . parent , node . text ) ; return label ? [ createDefinitionInfo ( label , ScriptElementKind . label , labelName , /*containerName*/ undefined ) ] : undefined ; } /// Triple slash reference comments var comment = ts . forEach ( sourceFile . referencedFiles , function ( r ) { return ( r . pos <= position && position < r . end ) ? r : undefined ; } ) ; if ( comment ) { var referenceFile = ts . tryResolveScriptReference ( program , sourceFile , comment ) ; if ( referenceFile ) { return [ { fileName : referenceFile . fileName , textSpan : ts . createTextSpanFromBounds ( 0 , 0 ) , kind : ScriptElementKind . scriptElement , name : comment . fileName , containerName : undefined , containerKind : undefined } ] ; } return undefined ; } var typeChecker = program . getTypeChecker ( ) ; var symbol = typeChecker . getSymbolAtLocation ( node ) ; // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if ( ! symbol ) { return undefined ; } // If this is an alias, and the request came at the declaration location // get the aliased symbol instead. This allows for goto def on an import e.g. //   import {A, B} from "mod"; // to jump to the implementation directly. if ( symbol . flags & 8388608 /* Alias */ ) { var declaration = symbol . declarations [ 0 ] ; if ( node . kind === 69 /* Identifier */ && node . parent === declaration ) { symbol = typeChecker . getAliasedSymbol ( symbol ) ; } } // Because name in short-hand property assignment has two different meanings: property name and property value, // using go-to-definition at such position should go to the variable declaration of the property value rather than // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. if ( node . parent . kind === 246 /* ShorthandPropertyAssignment */ ) { var shorthandSymbol = typeChecker . getShorthandAssignmentValueSymbol ( symbol . valueDeclaration ) ; if ( ! shorthandSymbol ) { return [ ] ; } var shorthandDeclarations = shorthandSymbol . getDeclarations ( ) ; var shorthandSymbolKind = getSymbolKind ( shorthandSymbol , node ) ; var shorthandSymbolName = typeChecker . symbolToString ( shorthandSymbol ) ; var shorthandContainerName = typeChecker . symbolToString ( symbol . parent , node ) ; return ts . map ( shorthandDeclarations , function ( declaration ) { return createDefinitionInfo ( declaration , shorthandSymbolKind , shorthandSymbolName , shorthandContainerName ) ; } ) ; } return getDefinitionFromSymbol ( symbol , node ) ; }


Input: Aggregates all throw - statements within this node * without * crossing into function boundaries and try - blocks with catch - clauses . [CODESPLIT] function aggregateOwnedThrowStatements ( node ) { var statementAccumulator = [ ] ; aggregate ( node ) ; return statementAccumulator ; function aggregate ( node ) { if ( node . kind === 208 /* ThrowStatement */ ) { statementAccumulator . push ( node ) ; } else if ( node . kind === 209 /* TryStatement */ ) { var tryStatement = node ; if ( tryStatement . catchClause ) { aggregate ( tryStatement . catchClause ) ; } else { // Exceptions thrown within a try block lacking a catch clause // are "owned" in the current context. aggregate ( tryStatement . tryBlock ) ; } if ( tryStatement . finallyBlock ) { aggregate ( tryStatement . finallyBlock ) ; } } else if ( ! ts . isFunctionLike ( node ) ) { ts . forEachChild ( node , aggregate ) ; } } ; }


Input: For lack of a better name this function takes a throw statement and returns the nearest ancestor that is a try - block ( whose try statement has a catch clause ) function - block or source file . [CODESPLIT] function getThrowStatementOwner ( throwStatement ) { var child = throwStatement ; while ( child . parent ) { var parent_12 = child . parent ; if ( ts . isFunctionBlock ( parent_12 ) || parent_12 . kind === 248 /* SourceFile */ ) { return parent_12 ; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. if ( parent_12 . kind === 209 /* TryStatement */ ) { var tryStatement = parent_12 ; if ( tryStatement . tryBlock === child && tryStatement . catchClause ) { return child ; } } child = parent_12 ; } return undefined ; }


Input: Search within node container for references for a search value where the search value is defined as a tuple of ( searchSymbol searchText searchLocation and searchMeaning ) . searchLocation : a node where the search value [CODESPLIT] function getReferencesInNode ( container , searchSymbol , searchText , searchLocation , searchMeaning , findInStrings , findInComments , result , symbolToIndex ) { var sourceFile = container . getSourceFile ( ) ; var tripleSlashDirectivePrefixRegex = / ^\/\/\/\s*< / ; var possiblePositions = getPossibleSymbolReferencePositions ( sourceFile , searchText , container . getStart ( ) , container . getEnd ( ) ) ; if ( possiblePositions . length ) { // Build the set of symbols to search for, initially it has only the current symbol var searchSymbols = populateSearchSymbolSet ( searchSymbol , searchLocation ) ; ts . forEach ( possiblePositions , function ( position ) { cancellationToken . throwIfCancellationRequested ( ) ; var referenceLocation = ts . getTouchingPropertyName ( sourceFile , position ) ; if ( ! isValidReferencePosition ( referenceLocation , searchText ) ) { // This wasn't the start of a token.  Check to see if it might be a // match in a comment or string if that's what the caller is asking // for. if ( ( findInStrings && ts . isInString ( sourceFile , position ) ) || ( findInComments && isInNonReferenceComment ( sourceFile , position ) ) ) { // In the case where we're looking inside comments/strings, we don't have // an actual definition.  So just use 'undefined' here.  Features like // 'Rename' won't care (as they ignore the definitions), and features like // 'FindReferences' will just filter out these results. result . push ( { definition : undefined , references : [ { fileName : sourceFile . fileName , textSpan : ts . createTextSpan ( position , searchText . length ) , isWriteAccess : false } ] } ) ; } return ; } if ( ! ( getMeaningFromLocation ( referenceLocation ) & searchMeaning ) ) { return ; } var referenceSymbol = typeChecker . getSymbolAtLocation ( referenceLocation ) ; if ( referenceSymbol ) { var referenceSymbolDeclaration = referenceSymbol . valueDeclaration ; var shorthandValueSymbol = typeChecker . getShorthandAssignmentValueSymbol ( referenceSymbolDeclaration ) ; var relatedSymbol = getRelatedSymbol ( searchSymbols , referenceSymbol , referenceLocation ) ; if ( relatedSymbol ) { var referencedSymbol = getReferencedSymbol ( relatedSymbol ) ; referencedSymbol . references . push ( getReferenceEntryFromNode ( referenceLocation ) ) ; } else if ( ! ( referenceSymbol . flags & 67108864 /* Transient */ ) && searchSymbols . indexOf ( shorthandValueSymbol ) >= 0 ) { var referencedSymbol = getReferencedSymbol ( shorthandValueSymbol ) ; referencedSymbol . references . push ( getReferenceEntryFromNode ( referenceSymbolDeclaration . name ) ) ; } } } ) ; } return ; function getReferencedSymbol ( symbol ) { var symbolId = ts . getSymbolId ( symbol ) ; var index = symbolToIndex [ symbolId ] ; if ( index === undefined ) { index = result . length ; symbolToIndex [ symbolId ] = index ; result . push ( { definition : getDefinition ( symbol ) , references : [ ] } ) ; } return result [ index ] ; } function isInNonReferenceComment ( sourceFile , position ) { return ts . isInCommentHelper ( sourceFile , position , isNonReferenceComment ) ; function isNonReferenceComment ( c ) { var commentText = sourceFile . text . substring ( c . pos , c . end ) ; return ! tripleSlashDirectivePrefixRegex . test ( commentText ) ; } } }


Input: Given an initial searchMeaning extracted from a location widen the search scope based on the declarations of the corresponding symbol . e . g . if we are searching for Foo in value position but Foo references a class then we need to widen the search to include type positions as well . On the contrary if we are searching for Bar in type position and we trace bar to an interface and an uninstantiated module we want to keep the search limited to only types as the two declarations ( interface and uninstantiated module ) do not intersect in any of the three spaces . [CODESPLIT] function getIntersectingMeaningFromDeclarations ( meaning , declarations ) { if ( declarations ) { var lastIterationMeaning ; do { // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module // intersects with the class in the value space. // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning ; for ( var _i = 0 ; _i < declarations . length ; _i ++ ) { var declaration = declarations [ _i ] ; var declarationMeaning = getMeaningFromDeclaration ( declaration ) ; if ( declarationMeaning & meaning ) { meaning |= declarationMeaning ; } } } while ( meaning !== lastIterationMeaning ) ; } return meaning ; }


Input: A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment [CODESPLIT] function isWriteAccess ( node ) { if ( node . kind === 69 /* Identifier */ && ts . isDeclarationName ( node ) ) { return true ; } var parent = node . parent ; if ( parent ) { if ( parent . kind === 180 /* PostfixUnaryExpression */ || parent . kind === 179 /* PrefixUnaryExpression */ ) { return true ; } else if ( parent . kind === 181 /* BinaryExpression */ && parent . left === node ) { var operator = parent . operatorToken . kind ; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */ ; } } return false ; }


Input: / NavigateTo [CODESPLIT] function getNavigateToItems ( searchValue , maxResultCount ) { synchronizeHostData ( ) ; return ts . NavigateTo . getNavigateToItems ( program , cancellationToken , searchValue , maxResultCount ) ; }


Input: Signature help This is a semantic operation . [CODESPLIT] function getSignatureHelpItems ( fileName , position ) { synchronizeHostData ( ) ; var sourceFile = getValidSourceFile ( fileName ) ; return ts . SignatureHelp . getSignatureHelpItems ( program , sourceFile , position , cancellationToken ) ; }


Input: Returns true if there exists a module that introduces entities on the value side . [CODESPLIT] function hasValueSideModule ( symbol ) { return ts . forEach ( symbol . declarations , function ( declaration ) { return declaration . kind === 218 /* ModuleDeclaration */ && ts . getModuleInstanceState ( declaration ) === 1 /* Instantiated */ ; } ) ; }


Input: for accurate classification the actual token should be passed in . however for cases like disabled merge code classification we just get the token kind and classify based on that instead . [CODESPLIT] function classifyTokenType ( tokenKind , token ) { if ( ts . isKeyword ( tokenKind ) ) { return 3 /* keyword */ ; } // Special case < and >  If they appear in a generic context they are punctuation, // not operators. if ( tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */ ) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if ( token && ts . getTypeArgumentOrTypeParameterList ( token . parent ) ) { return 10 /* punctuation */ ; } } if ( ts . isPunctuation ( tokenKind ) ) { if ( token ) { if ( tokenKind === 56 /* EqualsToken */ ) { // the '=' in a variable declaration is special cased here. if ( token . parent . kind === 211 /* VariableDeclaration */ || token . parent . kind === 141 /* PropertyDeclaration */ || token . parent . kind === 138 /* Parameter */ ) { return 5 /* operator */ ; } } if ( token . parent . kind === 181 /* BinaryExpression */ || token . parent . kind === 179 /* PrefixUnaryExpression */ || token . parent . kind === 180 /* PostfixUnaryExpression */ || token . parent . kind === 182 /* ConditionalExpression */ ) { return 5 /* operator */ ; } } return 10 /* punctuation */ ; } else if ( tokenKind === 8 /* NumericLiteral */ ) { return 4 /* numericLiteral */ ; } else if ( tokenKind === 9 /* StringLiteral */ ) { return 6 /* stringLiteral */ ; } else if ( tokenKind === 10 /* RegularExpressionLiteral */ ) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */ ; } else if ( ts . isTemplateLiteralKind ( tokenKind ) ) { // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */ ; } else if ( tokenKind === 69 /* Identifier */ ) { if ( token ) { switch ( token . parent . kind ) { case 214 /* ClassDeclaration */ : if ( token . parent . name === token ) { return 11 /* className */ ; } return ; case 137 /* TypeParameter */ : if ( token . parent . name === token ) { return 15 /* typeParameterName */ ; } return ; case 215 /* InterfaceDeclaration */ : if ( token . parent . name === token ) { return 13 /* interfaceName */ ; } return ; case 217 /* EnumDeclaration */ : if ( token . parent . name === token ) { return 12 /* enumName */ ; } return ; case 218 /* ModuleDeclaration */ : if ( token . parent . name === token ) { return 14 /* moduleName */ ; } return ; case 138 /* Parameter */ : if ( token . parent . name === token ) { return 17 /* parameterName */ ; } return ; } } return 2 /* identifier */ ; } }


Input: Digs into an an initializer or RHS operand of an assignment operation to get the parameters of an apt signature corresponding to a function expression or a class expression . [CODESPLIT] function getParametersFromRightHandSideOfAssignment ( rightHandSide ) { while ( rightHandSide . kind === 172 /* ParenthesizedExpression */ ) { rightHandSide = rightHandSide . expression ; } switch ( rightHandSide . kind ) { case 173 /* FunctionExpression */ : case 174 /* ArrowFunction */ : return rightHandSide . parameters ; case 186 /* ClassExpression */ : for ( var _i = 0 , _a = rightHandSide . members ; _i < _a . length ; _i ++ ) { var member = _a [ _i ] ; if ( member . kind === 144 /* Constructor */ ) { return member . parameters ; } } break ; } return emptyArray ; }


Input: Get the path of the default library files ( lib . d . ts ) as distributed with the typescript node package . The functionality is not supported if the ts module is consumed outside of a node module . [CODESPLIT] function getDefaultLibFilePath ( options ) { // Check __dirname is defined and that we are on a node.js system. if ( typeof __dirname !== "undefined" ) { return __dirname + ts . directorySeparator + ts . getDefaultLibFileName ( options ) ; } throw new Error ( "getDefaultLibFilePath is only supported when consumed as a node module. " ) ; }


Input: Tokens : [CODESPLIT] function spanInOpenBraceToken ( node ) { switch ( node . parent . kind ) { case 217 /* EnumDeclaration */ : var enumDeclaration = node . parent ; return spanInNodeIfStartsOnSameLine ( ts . findPrecedingToken ( node . pos , sourceFile , node . parent ) , enumDeclaration . members . length ? enumDeclaration . members [ 0 ] : enumDeclaration . getLastToken ( sourceFile ) ) ; case 214 /* ClassDeclaration */ : var classDeclaration = node . parent ; return spanInNodeIfStartsOnSameLine ( ts . findPrecedingToken ( node . pos , sourceFile , node . parent ) , classDeclaration . members . length ? classDeclaration . members [ 0 ] : classDeclaration . getLastToken ( sourceFile ) ) ; case 220 /* CaseBlock */ : return spanInNodeIfStartsOnSameLine ( node . parent . parent , node . parent . clauses [ 0 ] ) ; } // Default to parent node return spanInNode ( node . parent ) ; }


Input:
** send html css and js for gui [CODESPLIT] async function serveGUI ( url ) { let res , fileType ; const headerContentTypes = { 'html' : 'text/html' , 'js' : 'application/javascript' , 'css' : 'text/css' } const pathname = ( url . pathname === '/' ) ? '/index.html' : url . pathname ; res = await fetch ( 'file://build' + pathname ) ; fileType = pathname . split ( '.' ) . pop ( ) ; if ( res . status === 200 && Object . keys ( headerContentTypes ) . includes ( fileType ) ) { let fileText = await res . text ( ) ; return { data : fileText , status : 200 , contentType : headerContentTypes [ fileType ] } ; } return { data : "
Not found.
" , status : 404 , contentType : "text/html" } ; }


Input: ** serve api data ; we only validate fields if query is not coming from the gui [CODESPLIT] async function getGitHubData ( req , url ) { let cacheKey = "" , queryString = "" ; let reqString = await req . text ( ) ; const client = new GraphQLClient ( 'https://api.github.com/graphql' , { headers : { 'User-Agent' : req . headers . get ( 'User-Agent' ) || app . config . userAgent , 'Authorization' : req . headers . get ( 'Authorization' ) || 'Bearer ' + app . config . userToken } } ) ; //only requests from gui are json; non-gui requests use graphql syntax if ( url . pathname === '/standard' ) { let reqStringJSON = await JSON . parse ( reqString ) ; cacheKey = reqStringJSON . org + "-" + reqStringJSON . repo ; queryString = reqStringJSON . query ; } else { queryString = addRequiredQueryFields ( reqString ) ; } const { dataString , status } = await getIssues ( queryString , client , cacheKey ) ; return { data : dataString , status : status , contentType : "application/json" } ; }


Input: ** add missing query fields ( if any ) for custom queries ; we need id number title and bodyText to deliver sentiment [CODESPLIT] function addRequiredQueryFields ( query ) { let stringCondensed = query . replace ( / \s+ / g , " " ) ; let starti = stringCondensed . indexOf ( 'node {' ) + 6 ; let endi = stringCondensed . indexOf ( '}' , starti ) ; let currentParams = ( stringCondensed . substring ( starti , endi ) ) . split ( " " ) ; const requiredParams = [ "id" , "number" , "title" , "bodyText" ] ; requiredParams . forEach ( function ( p ) { if ( ! currentParams . includes ( p ) ) { currentParams . push ( p ) } } ) ; currentParams = currentParams . join ( " " ) ; return stringCondensed . substr ( 0 , starti ) + currentParams + stringCondensed . substr ( endi ) ; }


Input: ** send user s request to github OR retrieve from cache if possible [CODESPLIT] async function getIssues ( query , client , cacheKey ) { let data , dataString , dataJson , status , cachedResponse = null ; if ( cacheKey ) { cachedResponse = await cache . getString ( cacheKey ) ; } if ( cachedResponse !== null ) { status = 200 ; dataString = cachedResponse ; return { dataString , status } ; } else { //get issue details try { data = await client . request ( query ) ; //query github dataString = await JSON . stringify ( data ) ; dataJson = await JSON . parse ( dataString ) ; dataJson = getSentiment ( dataJson ) ; status = 200 ; } catch ( err ) { //remove github status before returning because it seems to return 200 no matter what dataString = await JSON . stringify ( err ) ; dataJson = await JSON . parse ( dataString ) ; delete dataJson . response . status ; status = 500 ; } dataString = await JSON . stringify ( dataJson ) ; if ( cacheKey && ( status !== 500 ) ) { cache . set ( cacheKey , dataString , 172800 ) ; //cache for 2 days (only non-custom requests) } return { dataString , status } ; } }


Input: ** analyze issue ( s ) and stitch sentiment into github response ; return updated response [CODESPLIT] function getSentiment ( response ) { const issuesToEvaluate = response . repository . issues . edges ; for ( let i = issuesToEvaluate . length - 1 ; i >= 0 ; i -- ) { let sent = polarity ( ( issuesToEvaluate [ i ] . node . title + " " + issuesToEvaluate [ i ] . node . bodyText ) . split ( " " ) ) ; issuesToEvaluate [ i ] . node . sentiment = sent ; } ; return response ; }


Input: A fetch function load balancer . Distributes requests to a set of backends ; attempts to send requests to most recently healthy backends using a 2 random ( pick two healthiest randomize which gets requests ) . [CODESPLIT] function balancer ( backends ) { const tracked = backends . map ( ( h ) => { if ( typeof h !== "function" ) { throw Error ( "Backend must be a fetch like function" ) ; } return { proxy : h , requestCount : 0 , scoredRequestCount : 0 , statuses : Array ( 10 ) , lastError : 0 , healthScore : 1 , errorCount : 0 } ; } ) ; const fn = async function fetchBalancer ( req , init ) { if ( typeof req === "string" ) { req = new Request ( req ) ; } const attempted = new Set ( ) ; while ( attempted . size < tracked . length ) { let backend = null ; const [ backendA , backendB ] = chooseBackends ( tracked , attempted ) ; if ( ! backendA ) { return new Response ( "No backend available" , { status : 502 } ) ; } if ( ! backendB ) { backend = backendA ; } else { // randomize between 2 good candidates backend = ( Math . floor ( Math . random ( ) * 2 ) == 0 ) ? backendA : backendB ; } const promise = backend . proxy ( req , init ) ; if ( backend . scoredRequestCount != backend . requestCount ) { // fixup score // this should be relatively concurrent with the fetch promise score ( backend ) ; } backend . requestCount += 1 ; attempted . add ( backend ) ; let resp ; try { resp = await promise ; } catch ( e ) { resp = proxyError ; } if ( backend . statuses . length < 10 ) { backend . statuses . push ( resp . status ) ; } else { backend . statuses [ ( backend . requestCount - 1 ) % backend . statuses . length ] = resp . status ; } if ( resp . status >= 500 && resp . status < 600 ) { backend . lastError = Date . now ( ) ; // always recompute score on errors score ( backend ) ; // clear out response to trigger retry if ( canRetry ( req , resp ) ) { continue ; } } return resp ; } return proxyError ; } ; return Object . assign ( fn , { backends : tracked } ) ; }


Input: compute a backend health score with time + status codes [CODESPLIT] function score ( backend , errorBasis ) { if ( typeof errorBasis !== "number" && ! errorBasis ) errorBasis = Date . now ( ) ; const timeSinceError = ( errorBasis - backend . lastError ) ; const statuses = backend . statuses ; const timeWeight = ( backend . lastError === 0 && 0 ) || ( ( timeSinceError < 1000 ) && 1 ) || ( ( timeSinceError < 3000 ) && 0.8 ) || ( ( timeSinceError < 5000 ) && 0.3 ) || ( ( timeSinceError < 10000 ) && 0.1 ) || 0 ; if ( statuses . length == 0 ) return 0 ; let requests = 0 ; let errors = 0 ; for ( let i = 0 ; i < statuses . length ; i ++ ) { const status = statuses [ i ] ; if ( status && ! isNaN ( status ) ) { requests += 1 ; if ( status >= 500 && status < 600 ) { errors += 1 ; } } } const score = ( 1 - ( timeWeight * ( errors / requests ) ) ) ; backend . healthScore = score ; backend . scoredRequestCount = backend . requestCount ; return score ; }


Input: This is just a basic origin http server that lets us control status codes . [CODESPLIT] async function origin ( req , init ) { const url = new URL ( req . url ) const status = parseInt ( url . searchParams . get ( 'status' ) || '200' ) if ( status === 200 ) { return new Response ( ` ${ req . url } ${ new Date ( ) } ` ) } else { return new Response ( ` ${ status } ` , { status : status } ) } }


Input: This is just a basic origin http server that response to two paths : [CODESPLIT] async function origin ( req , init ) { const url = new URL ( req . url ) switch ( url . pathname ) { case "/" : return new Response ( ` ${ new Date ( ) } ` , { headers : { "Cache-Control" : "max-age=600" } } ) case "/never-cache" : return new Response ( ` ${ new Date ( ) } ` ) } return new Response ( "not found" , { status : 404 } ) }


Input: / * ==================================================================== = Compile and minify js generating source maps = ==================================================================== [CODESPLIT] function ( dest , src ) { return gulp . src ( src ) . pipe ( sourcemaps . init ( ) ) . pipe ( concat ( dest ) ) . pipe ( gulp . dest ( path . join ( 'dist' , 'js' ) ) ) . pipe ( uglify ( ) ) . pipe ( rename ( { suffix : '.min' } ) ) . pipe ( sourcemaps . write ( '.' ) ) . pipe ( gulp . dest ( path . join ( 'dist' , 'js' ) ) ) ; }


Input: This is an example of custom transform function [CODESPLIT] function ( element , transform , touch ) { // // use translate both as basis for the new transform: // var t = $drag . TRANSLATE_BOTH ( element , transform , touch ) ; // // Add rotation: // var Dx = touch . distanceX ; var t0 = touch . startTransform ; var sign = Dx < 0 ? - 1 : 1 ; var angle = sign * Math . min ( ( Math . abs ( Dx ) / 700 ) * 30 , 30 ) ; t . rotateZ = angle + ( Math . round ( t0 . rotateZ ) ) ; return t ; }


Input: @function initialize @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( scope , id , options ) { options = options || { } ; var isNewScope = scopes [ scope ] === undefined ; var defaultValue = options . defaultValue ; var exclusionGroup = options . exclusionGroup ; scopes [ scope . $id ] = scopes [ scope . $id ] || [ ] ; scopes [ scope . $id ] . push ( id ) ; if ( ! statusesMeta [ id ] ) { // is a brand new state // not referenced by any // scope currently statusesMeta [ id ] = angular . extend ( { } , options , { references : 1 } ) ; $rootScope . $broadcast ( 'mobile-angular-ui.state.initialized.' + id , defaultValue ) ; if ( defaultValue !== undefined ) { this . setOne ( id , defaultValue ) ; } if ( exclusionGroup ) { // Exclusion groups are sets of statuses references exclusionGroups [ exclusionGroup ] = exclusionGroups [ exclusionGroup ] || { } ; exclusionGroups [ exclusionGroup ] [ id ] = true ; } } else if ( isNewScope ) { // is a new reference from // a different scope statusesMeta [ id ] . references ++ ; } scope . $on ( '$destroy' , function ( ) { var ids = scopes [ scope . $id ] || [ ] ; for ( var i = 0 ; i < ids . length ; i ++ ) { var status = statusesMeta [ ids [ i ] ] ; if ( status . exclusionGroup ) { delete exclusionGroups [ status . exclusionGroup ] [ ids [ i ] ] ; if ( Object . keys ( exclusionGroups [ status . exclusionGroup ] ) . length === 0 ) { delete exclusionGroups [ status . exclusionGroup ] ; } } status . references -- ; if ( status . references <= 0 ) { delete statusesMeta [ ids [ i ] ] ; delete values [ ids [ i ] ] ; $rootScope . $broadcast ( 'mobile-angular-ui.state.destroyed.' + id ) ; } } delete scopes [ scope . $id ] ; } ) ; }


Input: @function setOne @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( id , value ) { if ( statusesMeta [ id ] !== undefined ) { var prev = values [ id ] ; values [ id ] = value ; if ( prev !== value ) { $rootScope . $broadcast ( 'mobile-angular-ui.state.changed.' + id , value , prev ) ; } return value ; } $log . warn ( 'Warning: Attempt to set uninitialized shared state: ' + id ) ; }


Input: @function set @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( idOrMap , value ) { if ( ! idOrMap ) { return ; } else if ( angular . isObject ( idOrMap ) ) { this . setMany ( idOrMap ) ; } else { this . setOne ( idOrMap , value ) ; } }


Input: @function turnOn @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( id ) { // Turns off other statuses belonging to the same exclusion group. var eg = statusesMeta [ id ] && statusesMeta [ id ] . exclusionGroup ; if ( eg ) { var egStatuses = Object . keys ( exclusionGroups [ eg ] ) ; for ( var i = 0 ; i < egStatuses . length ; i ++ ) { var item = egStatuses [ i ] ; if ( item !== id ) { this . turnOff ( item ) ; } } } return this . setOne ( id , true ) ; }


Input: This would make postLink calls happen after ngClick ( and similar ) ones thus intercepting events after them . This will prevent eventual ng - if to detach elements before ng - click fires . [CODESPLIT] function ( elem , attrs ) { var attr = attrs [ directiveName ] ; var needsInterpolation = attr . match ( / \{\{ / ) ; var exprFn = function ( $scope ) { var res = attr ; if ( needsInterpolation ) { var interpolateFn = $interpolate ( res ) ; res = interpolateFn ( $scope ) ; } if ( methodName === 'set' ) { res = ( $parse ( res ) ) ( $scope ) ; } return res ; } ; return function ( scope , elem , attrs ) { var callback = function ( ) { var arg = exprFn ( scope ) ; return method . call ( SharedState , arg ) ; } ; uiBindEvent ( scope , elem , attrs . uiTriggers , callback ) ; } ; }


Input: @name uiScopeContext @inner @description [CODESPLIT] function ( attr ) { if ( ! attr || attr === '' ) { return [ ] ; } var vars = attr ? attr . trim ( ) . split ( /  *, * / ) : [ ] ; var res = [ ] ; for ( var i = 0 ; i < vars . length ; i ++ ) { var item = vars [ i ] . split ( /  *as * / ) ; if ( item . length > 2 || item . length < 1 ) { throw new Error ( 'Error parsing uiScopeContext="' + attr + '"' ) ; } res . push ( item ) ; } return res ; }


Input: Fill er up! From here down all logic is associated with touch scroll handling elem references the overthrow element in use [CODESPLIT] function ( val ) { inputs = elem . querySelectorAll ( "textarea, input" ) ; for ( var i = 0 , il = inputs . length ; i < il ; i ++ ) { inputs [ i ] . style . pointerEvents = val ; } }


Input: Fill er up! From here down all logic is associated with touch scroll handling elem references the overthrow element in use [CODESPLIT] function ( startEvent , ascend ) { if ( doc . createEvent ) { var newTarget = ( ! ascend || ascend === undefined ) && elem . parentNode || elem . touchchild || elem , tEnd ; if ( newTarget !== elem ) { tEnd = doc . createEvent ( "HTMLEvents" ) ; tEnd . initEvent ( "touchend" , true , true ) ; elem . dispatchEvent ( tEnd ) ; newTarget . touchchild = elem ; elem = newTarget ; newTarget . dispatchEvent ( startEvent ) ; } } }


Input: Fill er up! From here down all logic is associated with touch scroll handling elem references the overthrow element in use [CODESPLIT] function ( e ) { // Stop any throw in progress if ( o . intercept ) { o . intercept ( ) ; } // Reset the distance and direction tracking resetVertTracking ( ) ; resetHorTracking ( ) ; elem = o . closest ( e . target ) ; if ( ! elem || elem === docElem || e . touches . length > 1 ) { return ; } setPointers ( "none" ) ; var touchStartE = e , scrollT = elem . scrollTop , scrollL = elem . scrollLeft , height = elem . offsetHeight , width = elem . offsetWidth , startY = e . touches [ 0 ] . pageY , startX = e . touches [ 0 ] . pageX , scrollHeight = elem . scrollHeight , scrollWidth = elem . scrollWidth , // Touchmove handler move = function ( e ) { var ty = scrollT + startY - e . touches [ 0 ] . pageY , tx = scrollL + startX - e . touches [ 0 ] . pageX , down = ty >= ( lastTops . length ? lastTops [ 0 ] : 0 ) , right = tx >= ( lastLefts . length ? lastLefts [ 0 ] : 0 ) ; // If there's room to scroll the current container, prevent the default window scroll if ( ( ty > 0 && ty < scrollHeight - height ) || ( tx > 0 && tx < scrollWidth - width ) ) { e . preventDefault ( ) ; } // This bubbling is dumb. Needs a rethink. else { changeScrollTarget ( touchStartE ) ; } // If down and lastDown are inequal, the y scroll has changed direction. Reset tracking. if ( lastDown && down !== lastDown ) { resetVertTracking ( ) ; } // If right and lastRight are inequal, the x scroll has changed direction. Reset tracking. if ( lastRight && right !== lastRight ) { resetHorTracking ( ) ; } // remember the last direction in which we were headed lastDown = down ; lastRight = right ; // set the container's scroll elem . scrollTop = ty ; elem . scrollLeft = tx ; lastTops . unshift ( ty ) ; lastLefts . unshift ( tx ) ; if ( lastTops . length > 3 ) { lastTops . pop ( ) ; } if ( lastLefts . length > 3 ) { lastLefts . pop ( ) ; } } , // Touchend handler end = function ( e ) { // Bring the pointers back setPointers ( "auto" ) ; setTimeout ( function ( ) { setPointers ( "none" ) ; } , 450 ) ; elem . removeEventListener ( "touchmove" , move , false ) ; elem . removeEventListener ( "touchend" , end , false ) ; } ; elem . addEventListener ( "touchmove" , move , false ) ; elem . addEventListener ( "touchend" , end , false ) ; }


Input: bind function [CODESPLIT] function ( $element , dragOptions , touchOptions ) { $element = angular . element ( $element ) ; dragOptions = dragOptions || { } ; touchOptions = touchOptions || { } ; var startEventHandler = dragOptions . start ; var endEventHandler = dragOptions . end ; var moveEventHandler = dragOptions . move ; var cancelEventHandler = dragOptions . cancel ; var transformEventHandler = dragOptions . transform || this . TRANSLATE_BOTH ; var domElement = $element [ 0 ] ; var tO = $transform . get ( $element ) ; // original transform var rO = domElement . getBoundingClientRect ( ) ; // original bounding rect var tS ; // transform at start var rS ; var moving = false ; var isMoving = function ( ) { return moving ; } ; var cleanup = function ( ) { moving = false ; tS = rS = null ; $element . removeClass ( 'ui-drag-move' ) ; } ; var reset = function ( ) { $transform . set ( domElement , tO ) ; } ; var undo = function ( ) { $transform . set ( domElement , tS || tO ) ; } ; var setup = function ( ) { moving = true ; rS = domElement . getBoundingClientRect ( ) ; tS = $transform . get ( domElement ) ; $element . addClass ( 'ui-drag-move' ) ; } ; var createDragInfo = function ( touch ) { touch = angular . extend ( { } , touch ) ; touch . originalTransform = tO ; touch . originalRect = rO ; touch . startRect = rS ; touch . rect = domElement . getBoundingClientRect ( ) ; touch . startTransform = tS ; touch . transform = $transform . get ( domElement ) ; touch . reset = reset ; touch . undo = undo ; return touch ; } ; var onTouchMove = function ( touch , event ) { // preventDefault no matter what // it is (ie. maybe html5 drag for images or scroll) event . preventDefault ( ) ; // $touch calls start on the first touch // to ensure $drag.start is called only while actually // dragging and not for touches we will bind $drag.start // to the first time move is called if ( isMoving ( ) ) { // drag move touch = createDragInfo ( touch ) ; var transform = transformEventHandler ( $element , angular . extend ( { } , touch . transform ) , touch , event ) ; $transform . set ( domElement , transform ) ; if ( moveEventHandler ) { moveEventHandler ( touch , event ) ; } } else { // drag start setup ( ) ; if ( startEventHandler ) { startEventHandler ( createDragInfo ( touch ) , event ) ; } } } ; var onTouchEnd = function ( touch , event ) { if ( ! isMoving ( ) ) { return ; } // prevents outer swipes event . __UiSwipeHandled__ = true ; touch = createDragInfo ( touch ) ; cleanup ( ) ; if ( endEventHandler ) { endEventHandler ( touch , event ) ; } } ; var onTouchCancel = function ( touch , event ) { if ( ! isMoving ( ) ) { return ; } touch = createDragInfo ( touch ) ; undo ( ) ; // on cancel movement is undoed automatically; cleanup ( ) ; if ( cancelEventHandler ) { cancelEventHandler ( touch , event ) ; } } ; return $touch . bind ( $element , { move : onTouchMove , end : onTouchEnd , cancel : onTouchCancel } , touchOptions ) ; }


Input: start to consider only if movement exceeded MOVEMENT_THRESHOLD [CODESPLIT] function ( t ) { var absAngle = abs ( t . angle ) ; absAngle = absAngle >= 90 ? absAngle - 90 : absAngle ; var validDistance = t . total - t . distance <= TURNAROUND_MAX ; var validAngle = absAngle <= ANGLE_THRESHOLD || absAngle >= 90 - ANGLE_THRESHOLD ; var validVelocity = t . averageVelocity >= VELOCITY_THRESHOLD ; return validDistance && validAngle && validVelocity ; }


Input: Bind swipe gesture handlers for an element . [CODESPLIT] function ( element , eventHandlers , options ) { options = angular . extend ( { } , defaultOptions , options || { } ) ; return $touch . bind ( element , eventHandlers , options ) ; }


Input: TouchInfo is an object containing the following extended informations about any touch event . [CODESPLIT] function ( type , c , t0 , tl ) { // Compute values for new TouchInfo based on coordinates and previus touches. // - c is coords of new touch // - t0 is first touch: useful to compute duration and distance (how far pointer //                    got from first touch) // - tl is last touch: useful to compute velocity and length (total length of the movement) t0 = t0 || { } ; tl = tl || { } ; // timestamps var ts = now ( ) ; var ts0 = t0 . timestamp || ts ; var tsl = tl . timestamp || ts0 ; // coords var x = c . x ; var y = c . y ; var x0 = t0 . x || x ; var y0 = t0 . y || y ; var xl = tl . x || x0 ; var yl = tl . y || y0 ; // total movement var totalXl = tl . totalX || 0 ; var totalYl = tl . totalY || 0 ; var totalX = totalXl + abs ( x - xl ) ; var totalY = totalYl + abs ( y - yl ) ; var total = len ( totalX , totalY ) ; // duration var duration = timediff ( ts , ts0 ) ; var durationl = timediff ( ts , tsl ) ; // distance var dxl = x - xl ; var dyl = y - yl ; var dl = len ( dxl , dyl ) ; var dx = x - x0 ; var dy = y - y0 ; var d = len ( dx , dy ) ; // velocity (px per second) var v = durationl > 0 ? abs ( dl / ( durationl / 1000 ) ) : 0 ; var tv = duration > 0 ? abs ( total / ( duration / 1000 ) ) : 0 ; // main direction: 'LEFT', 'RIGHT', 'TOP', 'BOTTOM' var dir = abs ( dx ) > abs ( dy ) ? ( dx < 0 ? 'LEFT' : 'RIGHT' ) : ( dy < 0 ? 'TOP' : 'BOTTOM' ) ; // angle (angle between distance vector and x axis) // angle will be: //   0 for x > 0 and y = 0 //   90 for y < 0 and x = 0 //   180 for x < 0 and y = 0 //   -90 for y > 0 and x = 0 // //               -90° //                | //                | //                | //   180° --------|-------- 0° //                | //                | //                | //               90° // var angle = dx !== 0 || dy !== 0 ? atan2 ( dy , dx ) * ( 180 / Math . PI ) : null ; angle = angle === - 180 ? 180 : angle ; return { type : type , timestamp : ts , duration : duration , startX : x0 , startY : y0 , prevX : xl , prevY : yl , x : c . x , y : c . y , step : dl , // distance from prev stepX : dxl , stepY : dyl , velocity : v , averageVelocity : tv , distance : d , // distance from start distanceX : dx , distanceY : dy , total : total , // total length of momement, // considering turnaround totalX : totalX , totalY : totalY , direction : dir , angle : angle } ; }


Input: Callbacks on touchstart [CODESPLIT] function ( event ) { // don't handle multi-touch if ( event . touches && event . touches . length > 1 ) { return ; } tl = t0 = buildTouchInfo ( 'touchstart' , getCoordinates ( event ) ) ; $movementTarget . on ( moveEvents , onTouchMove ) ; $movementTarget . on ( endEvents , onTouchEnd ) ; if ( cancelEvents ) { $movementTarget . on ( cancelEvents , onTouchCancel ) ; } if ( startEventHandler ) { startEventHandler ( t0 , event ) ; } }


Input: return current element transform matrix in a cross - browser way [CODESPLIT] function ( e ) { e = e . length ? e [ 0 ] : e ; var tr = window . getComputedStyle ( e , null ) . getPropertyValue ( transformProperty ) ; return tr ; }


Input: set current element transform matrix in a cross - browser way [CODESPLIT] function ( elem , value ) { elem = elem . length ? elem [ 0 ] : elem ; elem . style [ styleProperty ] = value ; }


Input: Recompose a transform from decomposition t and apply it to element e [CODESPLIT] function ( e , t ) { var str = ( typeof t === 'string' ) ? t : this . toCss ( t ) ; setElementTransformProperty ( e , str ) ; }


Input: loader . vue = > module . loaders . vue [CODESPLIT] function ( _path ) { if ( / ^((pre|post)?loader)s? / ig . test ( _path ) ) { return _path . replace ( / ^((pre|post)?loader)s? / ig , 'module.$1s' ) } if ( / ^(plugin)s? / g . test ( _path ) ) { return _path . replace ( / ^(plugin)s? / g , '$1s' ) } return _path }


Input: / * istanbul ignore next [CODESPLIT] function ( extend , cooking , options ) { require ( ` ${ extend } ` ) ( cooking , options ) logger . success ( ` ${ extend } ` ) }


Input: Retrieves the payload from a JWT [CODESPLIT] function getPayload ( token ) { const payloadBase64 = token . split ( "." ) [ 1 ] . replace ( "-" , "+" ) . replace ( "_" , "/" ) ; const payloadDecoded = base64 . decode ( payloadBase64 ) ; const payloadObject = JSON . parse ( payloadDecoded ) ; if ( AV . isNumber ( payloadObject . exp ) ) { payloadObject . exp = new Date ( payloadObject . exp * 1000 ) ; } return payloadObject ; }