Input: Adapts the associative - array of parameters and hints for simple statements into Arrays based on the ( arbitrary ) position of the keys . [CODESPLIT] function adaptNamedParamsWithHints ( params , execOptions ) { if ( ! params || util . isArray ( params ) ) { //The parameters is an Array or there isn't parameter return { params : params , namedParameters : false , keyIndexes : null } ; } const keys = Object . keys ( params ) ; const paramsArray = new Array ( keys . length ) ; const hints = new Array ( keys . length ) ; const userHints = execOptions . getHints ( ) || emptyObject ; const keyIndexes = { } ; for ( let i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; // As lower cased identifiers paramsArray [ i ] = { name : key . toLowerCase ( ) , value : params [ key ] } ; hints [ i ] = userHints [ key ] ; keyIndexes [ key ] = i ; } execOptions . setHints ( hints ) ; return { params : paramsArray , namedParameters : true , keyIndexes } ; }


Input: Returns a string with a value repeated n times [CODESPLIT] function stringRepeat ( val , times ) { if ( ! times || times < 0 ) { return null ; } if ( times === 1 ) { return val ; } return new Array ( times + 1 ) . join ( val ) ; }


Input: Returns an array containing the values of the Object similar to Object . values () . If obj is null or undefined it will return an empty array . [CODESPLIT] function objectValues ( obj ) { if ( ! obj ) { return exports . emptyArray ; } const keys = Object . keys ( obj ) ; const values = new Array ( keys . length ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { values [ i ] = obj [ keys [ i ] ] ; } return values ; }


Input: Wraps the callback - based method . When no originalCallback is not defined it returns a Promise . [CODESPLIT] function promiseWrapper ( options , originalCallback , handler ) { if ( typeof originalCallback === 'function' ) { // Callback-based invocation handler . call ( this , originalCallback ) ; return undefined ; } const factory = options . promiseFactory || defaultPromiseFactory ; const self = this ; return factory ( function handlerWrapper ( callback ) { handler . call ( self , callback ) ; } ) ; }


Input: Similar to async . series () but instead accumulating the result in an Array it callbacks with the result of the last function in the array . [CODESPLIT] function series ( arr , callback ) { if ( ! Array . isArray ( arr ) ) { throw new TypeError ( 'First parameter must be an Array' ) ; } callback = callback || noop ; let index = 0 ; let sync ; next ( ) ; function next ( err , result ) { if ( err ) { return callback ( err ) ; } if ( index === arr . length ) { return callback ( null , result ) ; } if ( sync ) { return process . nextTick ( function ( ) { sync = true ; arr [ index ++ ] ( next ) ; sync = false ; } ) ; } sync = true ; arr [ index ++ ] ( next ) ; sync = false ; } }


Input: An iterator that holds the context for the subsequent next () calls [CODESPLIT] function TokenAwareIterator ( keyspace , execOptions , replicas , childPolicy ) { this . keyspace = keyspace ; this . childPolicy = childPolicy ; this . options = execOptions ; this . localReplicas = [ ] ; this . replicaIndex = 0 ; this . replicaMap = { } ; this . childIterator = null ; // Memoize the local replicas // The amount of local replicas should be defined before start iterating, in order to select an // appropriate (pseudo random) startIndex for ( let i = 0 ; i < replicas . length ; i ++ ) { const host = replicas [ i ] ; if ( this . childPolicy . getDistance ( host ) !== types . distance . local ) { continue ; } this . replicaMap [ host . address ] = true ; this . localReplicas . push ( host ) ; } // We use a PRNG to set the replica index // We only care about proportional fair scheduling between replicas of a given token // Math.random() has an extremely short permutation cycle length but we don't care about collisions this . startIndex = Math . floor ( Math . random ( ) * this . localReplicas . length ) ; }


Input: Create a new policy that wraps the provided child policy but only allow hosts from the provided while list . [CODESPLIT] function WhiteListPolicy ( childPolicy , whiteList ) { if ( ! childPolicy ) { throw new Error ( "You must specify a child load balancing policy" ) ; } if ( ! util . isArray ( whiteList ) ) { throw new Error ( "You must provide the white list of host addresses" ) ; } this . childPolicy = childPolicy ; const map = { } ; whiteList . forEach ( function ( address ) { map [ address ] = true ; } ) ; this . whiteList = map ; }


Input: A timestamp generator that guarantees monotonically increasing timestamps and logs warnings when timestamps drift in the future . <p > { [CODESPLIT] function MonotonicTimestampGenerator ( warningThreshold , minLogInterval ) { if ( warningThreshold < 0 ) { throw new errors . ArgumentError ( 'warningThreshold can not be lower than 0' ) ; } this . _warningThreshold = warningThreshold || 1000 ; this . _minLogInterval = 1000 ; if ( typeof minLogInterval === 'number' ) { // A value under 1 will disable logging this . _minLogInterval = minLogInterval ; } this . _micros = - 1 ; this . _lastDate = 0 ; this . _lastLogDate = 0 ; }


Input: A reconnection policy that waits exponentially longer between each reconnection attempt ( but keeps a constant delay once a maximum delay is reached ) . <p > A random amount of jitter ( + / - 15% ) will be added to the pure exponential delay value to avoid situations where many clients are in the reconnection process at exactly the same time . The jitter will never cause the delay to be less than the base delay or more than the max delay . < / p > [CODESPLIT] function ExponentialReconnectionPolicy ( baseDelay , maxDelay , startWithNoDelay ) { this . baseDelay = baseDelay ; this . maxDelay = maxDelay ; this . startWithNoDelay = startWithNoDelay ; }


Input:
Creates a new instance of <code > ControlConnection< / code > . [CODESPLIT] function ControlConnection ( options , profileManager , context ) { this . protocolVersion = null ; this . hosts = new HostMap ( ) ; this . setMaxListeners ( 0 ) ; Object . defineProperty ( this , "options" , { value : options , enumerable : false , writable : false } ) ; /**
   * Cluster metadata that is going to be shared between the Client and ControlConnection
   */ this . metadata = new Metadata ( this . options , this ) ; this . addressTranslator = this . options . policies . addressResolution ; this . reconnectionPolicy = this . options . policies . reconnection ; this . reconnectionSchedule = this . reconnectionPolicy . newSchedule ( ) ; this . initialized = false ; this . isShuttingDown = false ; /**
   * Host used by the control connection
   * @type {Host|null}
   */ this . host = null ; /**
   * Connection used to retrieve metadata and subscribed to events
   * @type {Connection|null}
   */ this . connection = null ; /**
   * Reference to the encoder of the last valid connection
   * @type {Encoder|null}
   */ this . encoder = null ; this . debouncer = new EventDebouncer ( options . refreshSchemaDelay , this . log . bind ( this ) ) ; this . profileManager = profileManager ; /** Timeout used for delayed handling of topology changes */ this . topologyChangeTimeout = null ; /** Timeout used for delayed handling of node status changes */ this . nodeStatusChangeTimeout = null ; this . reconnectionTimeout = null ; this . hostIterator = null ; this . triedHosts = null ; this . _resolvedContactPoints = new Map ( ) ; this . _contactPoints = new Set ( ) ; if ( context && context . borrowHostConnection ) { this . borrowHostConnection = context . borrowHostConnection ; } if ( context && context . createConnection ) { this . createConnection = context . createConnection ; } }


Input: Uses the DNS protocol to resolve a IPv4 and IPv6 addresses ( A and AAAA records ) for the hostname [CODESPLIT] function resolveAll ( name , callback ) { const addresses = [ ] ; utils . parallel ( [ function resolve4 ( next ) { dns . resolve4 ( name , function resolve4Callback ( err , arr ) { if ( arr ) { arr . forEach ( address => addresses . push ( { address , isIPv6 : false } ) ) ; } // Ignore error next ( ) ; } ) ; } , function resolve6 ( next ) { dns . resolve6 ( name , function resolve6Callback ( err , arr ) { if ( arr ) { arr . forEach ( address => addresses . push ( { address , isIPv6 : true } ) ) ; } // Ignore error next ( ) ; } ) ; } ] , function resolveAllCallback ( ) { if ( addresses . length === 0 ) { // In case dns.resolve*() methods don't yield a valid address for the host name // Use system call getaddrinfo() that might resolve according to host system definitions return dns . lookup ( name , function ( err , address , family ) { if ( err ) { return callback ( err ) ; } addresses . push ( { address , isIPv6 : family === 6 } ) ; callback ( null , addresses ) ; } ) ; } callback ( null , addresses ) ; } ) ; }


Input: Creates a new instance of <code > ClientState< / code > . [CODESPLIT] function ClientState ( hosts , openConnections , inFlightQueries ) { this . _hosts = hosts ; this . _openConnections = openConnections ; this . _inFlightQueries = inFlightQueries ; }


Input: Debounce protocol events by acting on those events with a sliding delay . [CODESPLIT] function EventDebouncer ( delay , logger ) { this . _delay = delay ; this . _logger = logger ; this . _queue = null ; this . _timeout = null ; }


Input: Buffer forward reader of CQL binary frames [CODESPLIT] function FrameReader ( header , body , offset ) { this . header = header ; this . opcode = header . opcode ; this . offset = offset || 0 ; this . buf = body ; }


Input:
Represents a connection to a Cassandra node [CODESPLIT] function Connection ( endpoint , protocolVersion , options ) { events . EventEmitter . call ( this ) ; this . setMaxListeners ( 0 ) ; if ( ! options ) { throw new Error ( 'options is not defined' ) ; } /**
   * Gets the ip and port of the server endpoint.
   * @type {String}
   */ this . endpoint = endpoint ; /**
   * Gets the friendly name of the host, used to identify the connection in log messages.
   * With direct connect, this is the address and port.
   * @type {String}
   */ this . endpointFriendlyName = endpoint ; if ( ! this . endpoint || this . endpoint . indexOf ( ':' ) < 0 ) { throw new Error ( 'EndPoint must contain the ip address and port separated by : symbol' ) ; } const portSeparatorIndex = this . endpoint . lastIndexOf ( ':' ) ; this . address = this . endpoint . substr ( 0 , portSeparatorIndex ) ; this . port = this . endpoint . substr ( portSeparatorIndex + 1 ) ; Object . defineProperty ( this , "options" , { value : options , enumerable : false , writable : false } ) ; if ( protocolVersion === null ) { // Set initial protocol version protocolVersion = types . protocolVersion . maxSupported ; if ( options . protocolOptions . maxVersion ) { // User provided the protocol version protocolVersion = options . protocolOptions . maxVersion ; } // Allow to check version using this connection instance this . _checkingVersion = true ; } this . protocolVersion = protocolVersion ; /** @type {Object.<String, OperationState>} */ this . _operations = { } ; this . _pendingWrites = [ ] ; this . _preparing = { } ; /**
   * The timeout state for the idle request (heartbeat)
   */ this . _idleTimeout = null ; this . timedOutOperations = 0 ; this . _streamIds = new StreamIdStack ( this . protocolVersion ) ; this . _metrics = options . metrics ; this . encoder = new Encoder ( protocolVersion , options ) ; this . keyspace = null ; this . emitDrain = false ; /**
   * Determines if the socket is open and startup succeeded, whether the connection can be used to send requests /
   * receive events
   */ this . connected = false ; /**
   * Determines if the socket can be considered as open
   */ this . isSocketOpen = false ; }


Input: Creates a new instance of Uuid based on the parameters provided according to rfc4122 . If any of the arguments is not provided it will be randomly generated except for the date that will use the current date . <p > Note that when nodeId and / or clockId portions are not provided the constructor will generate them using <code > crypto . randomBytes () < / code > . As it s possible that <code > crypto . randomBytes () < / code > might block it s recommended that you use the callback - based version of the static methods <code > fromDate () < / code > or <code > now () < / code > in that case . < / p > [CODESPLIT] function TimeUuid ( value , ticks , nodeId , clockId ) { let buffer ; if ( value instanceof Buffer ) { if ( value . length !== 16 ) { throw new Error ( 'Buffer for v1 uuid not valid' ) ; } buffer = value ; } else { buffer = generateBuffer ( value , ticks , nodeId , clockId ) ; } Uuid . call ( this , buffer ) ; }


Input: Returns a buffer of length 2 representing the clock identifier [CODESPLIT] function getClockId ( clockId ) { let buffer = clockId ; if ( typeof clockId === 'string' ) { buffer = utils . allocBufferFromString ( clockId , 'ascii' ) ; } if ( ! ( buffer instanceof Buffer ) ) { //Generate buffer = getRandomBytes ( 2 ) ; } else if ( buffer . length !== 2 ) { throw new Error ( 'Clock identifier must have 2 bytes' ) ; } return buffer ; }


Input: Returns a buffer of length 6 representing the clock identifier [CODESPLIT] function getNodeId ( nodeId ) { let buffer = nodeId ; if ( typeof nodeId === 'string' ) { buffer = utils . allocBufferFromString ( nodeId , 'ascii' ) ; } if ( ! ( buffer instanceof Buffer ) ) { //Generate buffer = getRandomBytes ( 6 ) ; } else if ( buffer . length !== 6 ) { throw new Error ( 'Node identifier must have 6 bytes' ) ; } return buffer ; }


Input: Returns the ticks portion of a timestamp . If the ticks are not provided an internal counter is used that gets reset at 10000 . [CODESPLIT] function getTicks ( ticks ) { if ( typeof ticks !== 'number' || ticks >= _ticksInMs ) { _ticks ++ ; if ( _ticks >= _ticksInMs ) { _ticks = 0 ; } ticks = _ticks ; } return ticks ; }


Input: Returns an object with the time representation of the date expressed in milliseconds since unix epoch and a ticks property for the 100 - nanoseconds precision . [CODESPLIT] function getTimeWithTicks ( date , ticks ) { if ( ! ( date instanceof Date ) || isNaN ( date . getTime ( ) ) ) { // time with ticks for the current time date = new Date ( ) ; const time = date . getTime ( ) ; _ticksForCurrentTime ++ ; if ( _ticksForCurrentTime > _ticksInMs || time > _lastTimestamp ) { _ticksForCurrentTime = 0 ; _lastTimestamp = time ; } ticks = _ticksForCurrentTime ; } return { time : date . getTime ( ) , ticks : getTicks ( ticks ) } ; }


Input: Generates a 16 - length Buffer instance [CODESPLIT] function generateBuffer ( date , ticks , nodeId , clockId ) { const timeWithTicks = getTimeWithTicks ( date , ticks ) ; nodeId = getNodeId ( nodeId ) ; clockId = getClockId ( clockId ) ; const buffer = utils . allocBufferUnsafe ( 16 ) ; //Positions 0-7 Timestamp writeTime ( buffer , timeWithTicks . time , timeWithTicks . ticks ) ; //Position 8-9 Clock clockId . copy ( buffer , 8 , 0 ) ; //Positions 10-15 Node nodeId . copy ( buffer , 10 , 0 ) ; //Version Byte: Time based //0001xxxx //turn off first 4 bits buffer [ 6 ] = buffer [ 6 ] & 0x0f ; //turn on fifth bit buffer [ 6 ] = buffer [ 6 ] | 0x10 ; //IETF Variant Byte: 1.0.x //10xxxxxx //turn off first 2 bits buffer [ 8 ] = buffer [ 8 ] & 0x3f ; //turn on first bit buffer [ 8 ] = buffer [ 8 ] | 0x80 ; return buffer ; }


Input: Serializes and deserializes to and from a CQL type and a Javascript Type . [CODESPLIT] function Encoder ( protocolVersion , options ) { this . encodingOptions = options . encoding || utils . emptyObject ; defineInstanceMembers . call ( this ) ; this . setProtocolVersion ( protocolVersion ) ; setEncoders . call ( this ) ; if ( this . encodingOptions . copyBuffer ) { this . handleBuffer = handleBufferCopy ; } else { this . handleBuffer = handleBufferRef ; } }


Input:
Declares the privileged instance members . [CODESPLIT] function defineInstanceMembers ( ) { /**
   * Sets the protocol version and the encoding/decoding methods depending on the protocol version
   * @param {Number} value
   * @ignore
   * @internal
   */ this . setProtocolVersion = function ( value ) { this . protocolVersion = value ; //Set the collection serialization based on the protocol version this . decodeCollectionLength = decodeCollectionLengthV3 ; this . getLengthBuffer = getLengthBufferV3 ; this . collectionLengthSize = 4 ; if ( ! types . protocolVersion . uses4BytesCollectionLength ( this . protocolVersion ) ) { this . decodeCollectionLength = decodeCollectionLengthV2 ; this . getLengthBuffer = getLengthBufferV2 ; this . collectionLengthSize = 2 ; } } ; const customDecoders = { } ; const customEncoders = { } ; // Decoding methods this . decodeBlob = function ( bytes ) { return this . handleBuffer ( bytes ) ; } ; this . decodeCustom = function ( bytes , typeName ) { const handler = customDecoders [ typeName ] ; if ( handler ) { return handler . call ( this , bytes ) ; } return this . handleBuffer ( bytes ) ; } ; this . decodeDuration = function ( bytes ) { return types . Duration . fromBuffer ( bytes ) ; } ; this . decodeUtf8String = function ( bytes ) { return bytes . toString ( 'utf8' ) ; } ; this . decodeAsciiString = function ( bytes ) { return bytes . toString ( 'ascii' ) ; } ; this . decodeBoolean = function ( bytes ) { return ! ! bytes . readUInt8 ( 0 ) ; } ; this . decodeDouble = function ( bytes ) { return bytes . readDoubleBE ( 0 ) ; } ; this . decodeFloat = function ( bytes ) { return bytes . readFloatBE ( 0 ) ; } ; this . decodeInt = function ( bytes ) { return bytes . readInt32BE ( 0 ) ; } ; this . decodeSmallint = function ( bytes ) { return bytes . readInt16BE ( 0 ) ; } ; this . decodeTinyint = function ( bytes ) { return bytes . readInt8 ( 0 ) ; } ; this . _decodeCqlLongAsLong = function ( bytes ) { return Long . fromBuffer ( bytes ) ; } ; this . _decodeCqlLongAsBigInt = function ( bytes ) { return BigInt . asIntN ( 64 , ( BigInt ( bytes . readUInt32BE ( 0 ) ) << bigInt32 ) | BigInt ( bytes . readUInt32BE ( 4 ) ) ) ; } ; this . decodeLong = this . encodingOptions . useBigIntAsLong ? this . _decodeCqlLongAsBigInt : this . _decodeCqlLongAsLong ; this . _decodeVarintAsInteger = function ( bytes ) { return Integer . fromBuffer ( bytes ) ; } ; this . _decodeVarintAsBigInt = function decodeVarintAsBigInt ( bytes ) { let result = bigInt0 ; if ( bytes [ 0 ] <= 0x7f ) { for ( let i = 0 ; i < bytes . length ; i ++ ) { const b = BigInt ( bytes [ bytes . length - 1 - i ] ) ; result = result | ( b << BigInt ( i * 8 ) ) ; } } else { for ( let i = 0 ; i < bytes . length ; i ++ ) { const b = BigInt ( bytes [ bytes . length - 1 - i ] ) ; result = result | ( ( ~ b & bigInt8BitsOn ) << BigInt ( i * 8 ) ) ; } result = ~ result ; } return result ; } ; this . decodeVarint = this . encodingOptions . useBigIntAsVarint ? this . _decodeVarintAsBigInt : this . _decodeVarintAsInteger ; this . decodeDecimal = function ( bytes ) { return BigDecimal . fromBuffer ( bytes ) ; } ; this . decodeTimestamp = function ( bytes ) { return new Date ( this . _decodeCqlLongAsLong ( bytes ) . toNumber ( ) ) ; } ; this . decodeDate = function ( bytes ) { return types . LocalDate . fromBuffer ( bytes ) ; } ; this . decodeTime = function ( bytes ) { return types . LocalTime . fromBuffer ( bytes ) ; } ; /*
   * Reads a list from bytes
   */ this . decodeList = function ( bytes , subtype ) { const totalItems = this . decodeCollectionLength ( bytes , 0 ) ; let offset = this . collectionLengthSize ; const list = new Array ( totalItems ) ; for ( let i = 0 ; i < totalItems ; i ++ ) { //bytes length of the item const length = this . decodeCollectionLength ( bytes , offset ) ; offset += this . collectionLengthSize ; //slice it list [ i ] = this . decode ( bytes . slice ( offset , offset + length ) , subtype ) ; offset += length ; } return list ; } ; /*
   * Reads a Set from bytes
   */ this . decodeSet = function ( bytes , subtype ) { const arr = this . decodeList ( bytes , subtype ) ; if ( this . encodingOptions . set ) { const setConstructor = this . encodingOptions . set ; return new setConstructor ( arr ) ; } return arr ; } ; /*
   * Reads a map (key / value) from bytes
   */ this . decodeMap = function ( bytes , subtypes ) { let map ; const totalItems = this . decodeCollectionLength ( bytes , 0 ) ; let offset = this . collectionLengthSize ; const self = this ; function readValues ( callback , thisArg ) { for ( let i = 0 ; i < totalItems ; i ++ ) { const keyLength = self . decodeCollectionLength ( bytes , offset ) ; offset += self . collectionLengthSize ; const key = self . decode ( bytes . slice ( offset , offset + keyLength ) , subtypes [ 0 ] ) ; offset += keyLength ; const valueLength = self . decodeCollectionLength ( bytes , offset ) ; offset += self . collectionLengthSize ; if ( valueLength < 0 ) { callback . call ( thisArg , key , null ) ; continue ; } const value = self . decode ( bytes . slice ( offset , offset + valueLength ) , subtypes [ 1 ] ) ; offset += valueLength ; callback . call ( thisArg , key , value ) ; } } if ( this . encodingOptions . map ) { const mapConstructor = this . encodingOptions . map ; map = new mapConstructor ( ) ; readValues ( map . set , map ) ; } else { map = { } ; readValues ( function ( key , value ) { map [ key ] = value ; } ) ; } return map ; } ; this . decodeUuid = function ( bytes ) { return new types . Uuid ( this . handleBuffer ( bytes ) ) ; } ; this . decodeTimeUuid = function ( bytes ) { return new types . TimeUuid ( this . handleBuffer ( bytes ) ) ; } ; this . decodeInet = function ( bytes ) { return new types . InetAddress ( this . handleBuffer ( bytes ) ) ; } ; /**
   * Decodes a user defined type into an object
   * @param {Buffer} bytes
   * @param {{fields: Array}} udtInfo
   * @private
   */ this . decodeUdt = function ( bytes , udtInfo ) { const result = { } ; let offset = 0 ; for ( let i = 0 ; i < udtInfo . fields . length && offset < bytes . length ; i ++ ) { //bytes length of the field value const length = bytes . readInt32BE ( offset ) ; offset += 4 ; //slice it const field = udtInfo . fields [ i ] ; if ( length < 0 ) { result [ field . name ] = null ; continue ; } result [ field . name ] = this . decode ( bytes . slice ( offset , offset + length ) , field . type ) ; offset += length ; } return result ; } ; this . decodeTuple = function ( bytes , tupleInfo ) { const elements = new Array ( tupleInfo . length ) ; let offset = 0 ; for ( let i = 0 ; i < tupleInfo . length ; i ++ ) { const length = bytes . readInt32BE ( offset ) ; offset += 4 ; if ( length < 0 ) { elements [ i ] = null ; continue ; } elements [ i ] = this . decode ( bytes . slice ( offset , offset + length ) , tupleInfo [ i ] ) ; offset += length ; } return new types . Tuple ( elements ) ; } ; //Encoding methods this . encodeFloat = function ( value ) { if ( typeof value !== 'number' ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 4 ) ; buf . writeFloatBE ( value , 0 ) ; return buf ; } ; this . encodeDouble = function ( value ) { if ( typeof value !== 'number' ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 8 ) ; buf . writeDoubleBE ( value , 0 ) ; return buf ; } ; /**
   * @param {Date|String|Long|Number} value
   * @private
   */ this . encodeTimestamp = function ( value ) { const originalValue = value ; if ( typeof value === 'string' ) { value = new Date ( value ) ; } if ( value instanceof Date ) { //milliseconds since epoch value = value . getTime ( ) ; if ( isNaN ( value ) ) { throw new TypeError ( 'Invalid date: ' + originalValue ) ; } } return this . encodeLong ( value ) ; } ; /**
   * @param {Date|String|LocalDate} value
   * @returns {Buffer}
   * @throws {TypeError}
   * @private
   */ this . encodeDate = function ( value ) { const originalValue = value ; try { if ( typeof value === 'string' ) { value = types . LocalDate . fromString ( value ) ; } if ( value instanceof Date ) { value = types . LocalDate . fromDate ( value ) ; } } catch ( err ) { //Wrap into a TypeError throw new TypeError ( 'LocalDate could not be parsed ' + err ) ; } if ( ! ( value instanceof types . LocalDate ) ) { throw new TypeError ( 'Expected Date/String/LocalDate, obtained ' + util . inspect ( originalValue ) ) ; } return value . toBuffer ( ) ; } ; /**
   * @param {String|LocalDate} value
   * @returns {Buffer}
   * @throws {TypeError}
   * @private
   */ this . encodeTime = function ( value ) { const originalValue = value ; try { if ( typeof value === 'string' ) { value = types . LocalTime . fromString ( value ) ; } } catch ( err ) { //Wrap into a TypeError throw new TypeError ( 'LocalTime could not be parsed ' + err ) ; } if ( ! ( value instanceof types . LocalTime ) ) { throw new TypeError ( 'Expected String/LocalTime, obtained ' + util . inspect ( originalValue ) ) ; } return value . toBuffer ( ) ; } ; /**
   * @param {Uuid|String|Buffer} value
   * @private
   */ this . encodeUuid = function ( value ) { if ( typeof value === 'string' ) { try { value = types . Uuid . fromString ( value ) . getBuffer ( ) ; } catch ( err ) { throw new TypeError ( err . message ) ; } } else if ( value instanceof types . Uuid ) { value = value . getBuffer ( ) ; } else { throw new TypeError ( 'Not a valid Uuid, expected Uuid/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return value ; } ; /**
   * @param {String|InetAddress|Buffer} value
   * @returns {Buffer}
   * @private
   */ this . encodeInet = function ( value ) { if ( typeof value === 'string' ) { value = types . InetAddress . fromString ( value ) ; } if ( value instanceof types . InetAddress ) { value = value . getBuffer ( ) ; } if ( ! ( value instanceof Buffer ) ) { throw new TypeError ( 'Not a valid Inet, expected InetAddress/Buffer, obtained ' + util . inspect ( value ) ) ; } return value ; } ; /**
   * @param {Long|Buffer|String|Number} value
   * @private
   */ this . _encodeBigIntFromLong = function ( value ) { if ( typeof value === 'number' ) { value = Long . fromNumber ( value ) ; } else if ( typeof value === 'string' ) { value = Long . fromString ( value ) ; } let buf = null ; if ( value instanceof Long ) { buf = Long . toBuffer ( value ) ; } else if ( value instanceof MutableLong ) { buf = Long . toBuffer ( value . toImmutable ( ) ) ; } if ( buf === null ) { throw new TypeError ( 'Not a valid bigint, expected Long/Number/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return buf ; } ; this . _encodeBigIntFromBigInt = function ( value ) { // eslint-disable-next-line valid-typeof if ( typeof value !== 'bigint' ) { // Only BigInt values are supported throw new TypeError ( 'Not a valid BigInt value, obtained ' + util . inspect ( value ) ) ; } const buffer = utils . allocBufferUnsafe ( 8 ) ; buffer . writeUInt32BE ( Number ( value >> bigInt32 ) >>> 0 , 0 ) ; buffer . writeUInt32BE ( Number ( value & bigInt32BitsOn ) , 4 ) ; return buffer ; } ; this . encodeLong = this . encodingOptions . useBigIntAsLong ? this . _encodeBigIntFromBigInt : this . _encodeBigIntFromLong ; /**
   * @param {Integer|Buffer|String|Number} value
   * @returns {Buffer}
   * @private
   */ this . _encodeVarintFromInteger = function ( value ) { if ( typeof value === 'number' ) { value = Integer . fromNumber ( value ) ; } if ( typeof value === 'string' ) { value = Integer . fromString ( value ) ; } let buf = null ; if ( value instanceof Buffer ) { buf = value ; } if ( value instanceof Integer ) { buf = Integer . toBuffer ( value ) ; } if ( buf === null ) { throw new TypeError ( 'Not a valid varint, expected Integer/Number/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return buf ; } ; this . _encodeVarintFromBigInt = function ( value ) { // eslint-disable-next-line valid-typeof if ( typeof value !== 'bigint' ) { throw new TypeError ( 'Not a valid varint, expected BigInt, obtained ' + util . inspect ( value ) ) ; } if ( value === bigInt0 ) { return buffers . int8Zero ; } else if ( value === bigIntMinus1 ) { return buffers . int8MaxValue ; } const parts = [ ] ; if ( value > bigInt0 ) { while ( value !== bigInt0 ) { parts . unshift ( Number ( value & bigInt8BitsOn ) ) ; value = value >> bigInt8 ; } if ( parts [ 0 ] > 0x7f ) { // Positive value needs a padding parts . unshift ( 0 ) ; } } else { while ( value !== bigIntMinus1 ) { parts . unshift ( Number ( value & bigInt8BitsOn ) ) ; value = value >> bigInt8 ; } if ( parts [ 0 ] <= 0x7f ) { // Negative value needs a padding parts . unshift ( 0xff ) ; } } return utils . allocBufferFromArray ( parts ) ; } ; this . encodeVarint = this . encodingOptions . useBigIntAsVarint ? this . _encodeVarintFromBigInt : this . _encodeVarintFromInteger ; /**
   * @param {BigDecimal|Buffer|String|Number} value
   * @returns {Buffer}
   * @private
   */ this . encodeDecimal = function ( value ) { if ( typeof value === 'number' ) { value = BigDecimal . fromNumber ( value ) ; } else if ( typeof value === 'string' ) { value = BigDecimal . fromString ( value ) ; } let buf = null ; if ( value instanceof BigDecimal ) { buf = BigDecimal . toBuffer ( value ) ; } else { throw new TypeError ( 'Not a valid varint, expected BigDecimal/Number/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return buf ; } ; this . encodeString = function ( value , encoding ) { if ( typeof value !== 'string' ) { throw new TypeError ( 'Not a valid text value, expected String obtained ' + util . inspect ( value ) ) ; } return utils . allocBufferFromString ( value , encoding ) ; } ; this . encodeUtf8String = function ( value ) { return this . encodeString ( value , 'utf8' ) ; } ; this . encodeAsciiString = function ( value ) { return this . encodeString ( value , 'ascii' ) ; } ; this . encodeBlob = function ( value ) { if ( ! ( value instanceof Buffer ) ) { throw new TypeError ( 'Not a valid blob, expected Buffer obtained ' + util . inspect ( value ) ) ; } return value ; } ; this . encodeCustom = function ( value , name ) { const handler = customEncoders [ name ] ; if ( handler ) { return handler . call ( this , value ) ; } throw new TypeError ( 'No encoding handler found for type ' + name ) ; } ; this . encodeDuration = function ( value ) { if ( ! ( value instanceof types . Duration ) ) { throw new TypeError ( 'Not a valid duration, expected Duration/Buffer obtained ' + util . inspect ( value ) ) ; } return value . toBuffer ( ) ; } ; /**
   * @param {Boolean} value
   * @returns {Buffer}
   * @private
   */ this . encodeBoolean = function ( value ) { return value ? buffers . int8One : buffers . int8Zero ; } ; /**
   * @param {Number|String} value
   * @private
   */ this . encodeInt = function ( value ) { if ( isNaN ( value ) ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 4 ) ; buf . writeInt32BE ( value , 0 ) ; return buf ; } ; /**
   * @param {Number|String} value
   * @private
   */ this . encodeSmallint = function ( value ) { if ( isNaN ( value ) ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 2 ) ; buf . writeInt16BE ( value , 0 ) ; return buf ; } ; /**
   * @param {Number|String} value
   * @private
   */ this . encodeTinyint = function ( value ) { if ( isNaN ( value ) ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 1 ) ; buf . writeInt8 ( value , 0 ) ; return buf ; } ; this . encodeList = function ( value , subtype ) { if ( ! util . isArray ( value ) ) { throw new TypeError ( 'Not a valid list value, expected Array obtained ' + util . inspect ( value ) ) ; } if ( value . length === 0 ) { return null ; } const parts = [ ] ; parts . push ( this . getLengthBuffer ( value ) ) ; for ( let i = 0 ; i < value . length ; i ++ ) { const val = value [ i ] ; if ( val === null || typeof val === 'undefined' || val === types . unset ) { throw new TypeError ( 'A collection can\'t contain null or unset values' ) ; } const bytes = this . encode ( val , subtype ) ; //include item byte length parts . push ( this . getLengthBuffer ( bytes ) ) ; //include item parts . push ( bytes ) ; } return Buffer . concat ( parts ) ; } ; this . encodeSet = function ( value , subtype ) { if ( this . encodingOptions . set && value instanceof this . encodingOptions . set ) { const arr = [ ] ; value . forEach ( function ( x ) { arr . push ( x ) ; } ) ; return this . encodeList ( arr , subtype ) ; } return this . encodeList ( value , subtype ) ; } ; /**
   * Serializes a map into a Buffer
   * @param value
   * @param {Array} [subtypes]
   * @returns {Buffer}
   * @private
   */ this . encodeMap = function ( value , subtypes ) { const parts = [ ] ; let propCounter = 0 ; let keySubtype = null ; let valueSubtype = null ; const self = this ; if ( subtypes ) { keySubtype = subtypes [ 0 ] ; valueSubtype = subtypes [ 1 ] ; } function addItem ( val , key ) { if ( key === null || typeof key === 'undefined' || key === types . unset ) { throw new TypeError ( 'A map can\'t contain null or unset keys' ) ; } if ( val === null || typeof val === 'undefined' || val === types . unset ) { throw new TypeError ( 'A map can\'t contain null or unset values' ) ; } const keyBuffer = self . encode ( key , keySubtype ) ; //include item byte length parts . push ( self . getLengthBuffer ( keyBuffer ) ) ; //include item parts . push ( keyBuffer ) ; //value const valueBuffer = self . encode ( val , valueSubtype ) ; //include item byte length parts . push ( self . getLengthBuffer ( valueBuffer ) ) ; //include item if ( valueBuffer !== null ) { parts . push ( valueBuffer ) ; } propCounter ++ ; } if ( this . encodingOptions . map && value instanceof this . encodingOptions . map ) { //Use Map#forEach() method to iterate value . forEach ( addItem ) ; } else { //Use object for ( const key in value ) { if ( ! value . hasOwnProperty ( key ) ) { continue ; } const val = value [ key ] ; addItem ( val , key ) ; } } parts . unshift ( this . getLengthBuffer ( propCounter ) ) ; return Buffer . concat ( parts ) ; } ; this . encodeUdt = function ( value , udtInfo ) { const parts = [ ] ; let totalLength = 0 ; for ( let i = 0 ; i < udtInfo . fields . length ; i ++ ) { const field = udtInfo . fields [ i ] ; const item = this . encode ( value [ field . name ] , field . type ) ; if ( ! item ) { parts . push ( nullValueBuffer ) ; totalLength += 4 ; continue ; } if ( item === types . unset ) { parts . push ( unsetValueBuffer ) ; totalLength += 4 ; continue ; } const lengthBuffer = utils . allocBufferUnsafe ( 4 ) ; lengthBuffer . writeInt32BE ( item . length , 0 ) ; parts . push ( lengthBuffer ) ; parts . push ( item ) ; totalLength += item . length + 4 ; } return Buffer . concat ( parts , totalLength ) ; } ; this . encodeTuple = function ( value , tupleInfo ) { const parts = [ ] ; let totalLength = 0 ; for ( let i = 0 ; i < tupleInfo . length ; i ++ ) { const type = tupleInfo [ i ] ; const item = this . encode ( value . get ( i ) , type ) ; if ( ! item ) { parts . push ( nullValueBuffer ) ; totalLength += 4 ; continue ; } if ( item === types . unset ) { parts . push ( unsetValueBuffer ) ; totalLength += 4 ; continue ; } const lengthBuffer = utils . allocBufferUnsafe ( 4 ) ; lengthBuffer . writeInt32BE ( item . length , 0 ) ; parts . push ( lengthBuffer ) ; parts . push ( item ) ; totalLength += item . length + 4 ; } return Buffer . concat ( parts , totalLength ) ; } ; /**
   * If not provided, it uses the array of buffers or the parameters and hints to build the routingKey
   * @param {Array} params
   * @param {ExecutionOptions} execOptions
   * @param [keys] parameter keys and positions in the params array
   * @throws TypeError
   * @internal
   * @ignore
   */ this . setRoutingKeyFromUser = function ( params , execOptions , keys ) { let totalLength = 0 ; const userRoutingKey = execOptions . getRoutingKey ( ) ; if ( util . isArray ( userRoutingKey ) ) { if ( userRoutingKey . length === 1 ) { execOptions . setRoutingKey ( userRoutingKey [ 0 ] ) ; return ; } // Its a composite routing key totalLength = 0 ; for ( let i = 0 ; i < userRoutingKey . length ; i ++ ) { const item = userRoutingKey [ i ] ; if ( ! item ) { // Invalid routing key part provided by the user, clear the value execOptions . setRoutingKey ( null ) ; return ; } totalLength += item . length + 3 ; } execOptions . setRoutingKey ( concatRoutingKey ( userRoutingKey , totalLength ) ) ; return ; } // If routingKey is present, ensure it is a Buffer, Token, or TokenRange.  Otherwise throw an error. if ( userRoutingKey ) { if ( userRoutingKey instanceof Buffer || userRoutingKey instanceof token . Token || userRoutingKey instanceof token . TokenRange ) { return ; } throw new TypeError ( ` ${ util . inspect ( userRoutingKey ) } ` + ` ` ) ; } // If no params are present, return as routing key cannot be determined. if ( ! params || params . length === 0 ) { return ; } let routingIndexes = execOptions . getRoutingIndexes ( ) ; if ( execOptions . getRoutingNames ( ) ) { routingIndexes = execOptions . getRoutingNames ( ) . map ( k => keys [ k ] ) ; } if ( ! routingIndexes ) { return ; } const parts = [ ] ; const hints = execOptions . getHints ( ) || utils . emptyArray ; const encodeParam = ! keys ? ( i => this . encode ( params [ i ] , hints [ i ] ) ) : ( i => this . encode ( params [ i ] . value , hints [ i ] ) ) ; try { totalLength = this . _encodeRoutingKeyParts ( parts , routingIndexes , encodeParam ) ; } catch ( e ) { // There was an error encoding a parameter that is part of the routing key, // ignore now to fail afterwards } if ( totalLength === 0 ) { return ; } execOptions . setRoutingKey ( concatRoutingKey ( parts , totalLength ) ) ; } ; /**
   * Sets the routing key in the options based on the prepared statement metadata.
   * @param {Object} meta Prepared metadata
   * @param {Array} params Array of parameters
   * @param {ExecutionOptions} execOptions
   * @throws TypeError
   * @internal
   * @ignore
   */ this . setRoutingKeyFromMeta = function ( meta , params , execOptions ) { const routingIndexes = execOptions . getRoutingIndexes ( ) ; if ( ! routingIndexes ) { return ; } const parts = new Array ( routingIndexes . length ) ; const encodeParam = i => { const columnInfo = meta . columns [ i ] ; return this . encode ( params [ i ] , columnInfo ? columnInfo . type : null ) ; } ; let totalLength = 0 ; try { totalLength = this . _encodeRoutingKeyParts ( parts , routingIndexes , encodeParam ) ; } catch ( e ) { // There was an error encoding a parameter that is part of the routing key, // ignore now to fail afterwards } if ( totalLength === 0 ) { return ; } execOptions . setRoutingKey ( concatRoutingKey ( parts , totalLength ) ) ; } ; /**
   * @param {Array} parts
   * @param {Array} routingIndexes
   * @param {Function} encodeParam
   * @returns {Number} The total length
   * @private
   */ this . _encodeRoutingKeyParts = function ( parts , routingIndexes , encodeParam ) { let totalLength = 0 ; for ( let i = 0 ; i < routingIndexes . length ; i ++ ) { const paramIndex = routingIndexes [ i ] ; if ( paramIndex === undefined ) { // Bad input from the user, ignore return 0 ; } const item = encodeParam ( paramIndex ) ; if ( item === null || item === undefined || item === types . unset ) { // The encoded partition key should an instance of Buffer // Let it fail later in the pipeline for null/undefined parameter values return 0 ; } // Per each part of the routing key, 3 extra bytes are needed totalLength += item . length + 3 ; parts [ i ] = item ; } return totalLength ; } ; /**
   * Parses a CQL name string into data type information
   * @param {String} keyspace
   * @param {String} typeName
   * @param {Number} startIndex
   * @param {Number|null} length
   * @param {Function} udtResolver
   * @param {Function} callback Callback invoked with err and  {{code: number, info: Object|Array|null, options: {frozen: Boolean}}}
   * @internal
   * @ignore
   */ this . parseTypeName = function ( keyspace , typeName , startIndex , length , udtResolver , callback ) { startIndex = startIndex || 0 ; if ( ! length ) { length = typeName . length ; } const dataType = { code : 0 , info : null , options : { frozen : false } } ; let innerTypes ; if ( typeName . indexOf ( "'" , startIndex ) === startIndex ) { //If quoted, this is a custom type. dataType . info = typeName . substr ( startIndex + 1 , length - 2 ) ; return callback ( null , dataType ) ; } if ( ! length ) { length = typeName . length ; } if ( typeName . indexOf ( cqlNames . frozen , startIndex ) === startIndex ) { //Remove the frozen token startIndex += cqlNames . frozen . length + 1 ; length -= cqlNames . frozen . length + 2 ; dataType . options . frozen = true ; } if ( typeName . indexOf ( cqlNames . list , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . list . length + 1 ; length -= cqlNames . list . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; if ( innerTypes . length !== 1 ) { return callback ( new TypeError ( 'Not a valid type ' + typeName ) ) ; } dataType . code = dataTypes . list ; return this . parseTypeName ( keyspace , innerTypes [ 0 ] , 0 , null , udtResolver , function ( err , childType ) { if ( err ) { return callback ( err ) ; } dataType . info = childType ; callback ( null , dataType ) ; } ) ; } if ( typeName . indexOf ( cqlNames . set , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . set . length + 1 ; length -= cqlNames . set . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; if ( innerTypes . length !== 1 ) { return callback ( new TypeError ( 'Not a valid type ' + typeName ) ) ; } dataType . code = dataTypes . set ; return this . parseTypeName ( keyspace , innerTypes [ 0 ] , 0 , null , udtResolver , function ( err , childType ) { if ( err ) { return callback ( err ) ; } dataType . info = childType ; callback ( null , dataType ) ; } ) ; } if ( typeName . indexOf ( cqlNames . map , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . map . length + 1 ; length -= cqlNames . map . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; //It should contain the key and value types if ( innerTypes . length !== 2 ) { return callback ( new TypeError ( 'Not a valid type ' + typeName ) ) ; } dataType . code = dataTypes . map ; return this . _parseChildTypes ( keyspace , dataType , innerTypes , udtResolver , callback ) ; } if ( typeName . indexOf ( cqlNames . tuple , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . tuple . length + 1 ; length -= cqlNames . tuple . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; if ( innerTypes . length < 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . tuple ; return this . _parseChildTypes ( keyspace , dataType , innerTypes , udtResolver , callback ) ; } const quoted = typeName . indexOf ( '"' , startIndex ) === startIndex ; if ( quoted ) { //Remove quotes startIndex ++ ; length -= 2 ; } //Quick check if its a single type if ( startIndex > 0 ) { typeName = typeName . substr ( startIndex , length ) ; } // Un-escape double quotes if quoted. if ( quoted ) { typeName = typeName . replace ( '""' , '"' ) ; } const typeCode = dataTypes [ typeName ] ; if ( typeof typeCode === 'number' ) { dataType . code = typeCode ; return callback ( null , dataType ) ; } if ( typeName === cqlNames . duration ) { dataType . info = durationTypeName ; return callback ( null , dataType ) ; } if ( typeName === cqlNames . empty ) { //set as custom dataType . info = 'empty' ; return callback ( null , dataType ) ; } udtResolver ( keyspace , typeName , function ( err , udtInfo ) { if ( err ) { return callback ( err ) ; } if ( udtInfo ) { dataType . code = dataTypes . udt ; dataType . info = udtInfo ; return callback ( null , dataType ) ; } callback ( new TypeError ( 'Not a valid type "' + typeName + '"' ) ) ; } ) ; } ; /**
   * @param {String} keyspace
   * @param dataType
   * @param {Array} typeNames
   * @param {Function} udtResolver
   * @param {Function} callback
   * @private
   */ this . _parseChildTypes = function ( keyspace , dataType , typeNames , udtResolver , callback ) { const self = this ; utils . mapSeries ( typeNames , function ( name , next ) { self . parseTypeName ( keyspace , name . trim ( ) , 0 , null , udtResolver , next ) ; } , function ( err , childTypes ) { if ( err ) { return callback ( err ) ; } dataType . info = childTypes ; callback ( null , dataType ) ; } ) ; } ; /**
   * Parses a Cassandra fully-qualified class name string into data type information
   * @param {String} typeName
   * @param {Number} [startIndex]
   * @param {Number} [length]
   * @throws TypeError
   * @returns {{code: number, info: Object|Array|null, options: {frozen: Boolean, reversed: Boolean}}}
   * @internal
   * @ignore
   */ this . parseFqTypeName = function ( typeName , startIndex , length ) { const dataType = { code : 0 , info : null , options : { reversed : false , frozen : false } } ; startIndex = startIndex || 0 ; let innerTypes ; if ( ! length ) { length = typeName . length ; } if ( length > complexTypeNames . reversed . length && typeName . indexOf ( complexTypeNames . reversed ) === startIndex ) { //Remove the reversed token startIndex += complexTypeNames . reversed . length + 1 ; length -= complexTypeNames . reversed . length + 2 ; dataType . options . reversed = true ; } if ( length > complexTypeNames . frozen . length && typeName . indexOf ( complexTypeNames . frozen , startIndex ) === startIndex ) { //Remove the frozen token startIndex += complexTypeNames . frozen . length + 1 ; length -= complexTypeNames . frozen . length + 2 ; dataType . options . frozen = true ; } if ( typeName === complexTypeNames . empty ) { //set as custom dataType . info = 'empty' ; return dataType ; } //Quick check if its a single type if ( length <= singleFqTypeNamesLength ) { if ( startIndex > 0 ) { typeName = typeName . substr ( startIndex , length ) ; } const typeCode = singleTypeNames [ typeName ] ; if ( typeof typeCode === 'number' ) { dataType . code = typeCode ; return dataType ; } throw new TypeError ( 'Not a valid type "' + typeName + '"' ) ; } if ( typeName . indexOf ( complexTypeNames . list , startIndex ) === startIndex ) { //Its a list //org.apache.cassandra.db.marshal.ListType(innerType) //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . list . length + 1 ; length -= complexTypeNames . list . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; if ( innerTypes . length !== 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . list ; dataType . info = this . parseFqTypeName ( innerTypes [ 0 ] ) ; return dataType ; } if ( typeName . indexOf ( complexTypeNames . set , startIndex ) === startIndex ) { //Its a set //org.apache.cassandra.db.marshal.SetType(innerType) //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . set . length + 1 ; length -= complexTypeNames . set . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; if ( innerTypes . length !== 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . set ; dataType . info = this . parseFqTypeName ( innerTypes [ 0 ] ) ; return dataType ; } if ( typeName . indexOf ( complexTypeNames . map , startIndex ) === startIndex ) { //org.apache.cassandra.db.marshal.MapType(keyType,valueType) //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . map . length + 1 ; length -= complexTypeNames . map . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; //It should contain the key and value types if ( innerTypes . length !== 2 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . map ; dataType . info = [ this . parseFqTypeName ( innerTypes [ 0 ] ) , this . parseFqTypeName ( innerTypes [ 1 ] ) ] ; return dataType ; } if ( typeName . indexOf ( complexTypeNames . udt , startIndex ) === startIndex ) { //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . udt . length + 1 ; length -= complexTypeNames . udt . length + 2 ; return this . _parseUdtName ( typeName , startIndex , length ) ; } if ( typeName . indexOf ( complexTypeNames . tuple , startIndex ) === startIndex ) { //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . tuple . length + 1 ; length -= complexTypeNames . tuple . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; if ( innerTypes . length < 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . tuple ; dataType . info = innerTypes . map ( x => this . parseFqTypeName ( x ) ) ; return dataType ; } // Assume custom type if cannot be parsed up to this point. dataType . info = typeName . substr ( startIndex , length ) ; return dataType ; } ; /**
   * Parses type names with composites
   * @param {String} typesString
   * @returns {{types: Array, isComposite: Boolean, hasCollections: Boolean}}
   * @internal
   * @ignore
   */ this . parseKeyTypes = function ( typesString ) { let i = 0 ; let length = typesString . length ; const isComposite = typesString . indexOf ( complexTypeNames . composite ) === 0 ; if ( isComposite ) { i = complexTypeNames . composite . length + 1 ; length -- ; } const types = [ ] ; let startIndex = i ; let nested = 0 ; let inCollectionType = false ; let hasCollections = false ; //as collection types are not allowed, it is safe to split by , while ( ++ i < length ) { switch ( typesString [ i ] ) { case ',' : if ( nested > 0 ) { break ; } if ( inCollectionType ) { //remove type id startIndex = typesString . indexOf ( ':' , startIndex ) + 1 ; } types . push ( typesString . substring ( startIndex , i ) ) ; startIndex = i + 1 ; break ; case '(' : if ( nested === 0 && typesString . indexOf ( complexTypeNames . collection , startIndex ) === startIndex ) { inCollectionType = true ; hasCollections = true ; //skip collection type i ++ ; startIndex = i ; break ; } nested ++ ; break ; case ')' : if ( inCollectionType && nested === 0 ) { types . push ( typesString . substring ( typesString . indexOf ( ':' , startIndex ) + 1 , i ) ) ; startIndex = i + 1 ; break ; } nested -- ; break ; } } if ( startIndex < length ) { types . push ( typesString . substring ( startIndex , length ) ) ; } return { types : types . map ( name => this . parseFqTypeName ( name ) ) , hasCollections : hasCollections , isComposite : isComposite } ; } ; this . _parseUdtName = function ( typeName , startIndex , length ) { const udtParams = parseParams ( typeName , startIndex , length ) ; if ( udtParams . length < 2 ) { //It should contain at least the keyspace, name of the udt and a type throw new TypeError ( 'Not a valid type ' + typeName ) ; } const dataType = { code : dataTypes . udt , info : null } ; const udtInfo = { keyspace : udtParams [ 0 ] , name : utils . allocBufferFromString ( udtParams [ 1 ] , 'hex' ) . toString ( ) , fields : [ ] } ; for ( let i = 2 ; i < udtParams . length ; i ++ ) { const p = udtParams [ i ] ; const separatorIndex = p . indexOf ( ':' ) ; const fieldType = this . parseFqTypeName ( p , separatorIndex + 1 , p . length - ( separatorIndex + 1 ) ) ; udtInfo . fields . push ( { name : utils . allocBufferFromString ( p . substr ( 0 , separatorIndex ) , 'hex' ) . toString ( ) , type : fieldType } ) ; } dataType . info = udtInfo ; return dataType ; } ; customDecoders [ durationTypeName ] = this . decodeDuration ; customEncoders [ durationTypeName ] = this . encodeDuration ; }


Input: Sets the encoder and decoder methods for this instance [CODESPLIT] function setEncoders ( ) { this . decoders = { [ dataTypes . custom ] : this . decodeCustom , [ dataTypes . ascii ] : this . decodeAsciiString , [ dataTypes . bigint ] : this . decodeLong , [ dataTypes . blob ] : this . decodeBlob , [ dataTypes . boolean ] : this . decodeBoolean , [ dataTypes . counter ] : this . decodeLong , [ dataTypes . decimal ] : this . decodeDecimal , [ dataTypes . double ] : this . decodeDouble , [ dataTypes . float ] : this . decodeFloat , [ dataTypes . int ] : this . decodeInt , [ dataTypes . text ] : this . decodeUtf8String , [ dataTypes . timestamp ] : this . decodeTimestamp , [ dataTypes . uuid ] : this . decodeUuid , [ dataTypes . varchar ] : this . decodeUtf8String , [ dataTypes . varint ] : this . decodeVarint , [ dataTypes . timeuuid ] : this . decodeTimeUuid , [ dataTypes . inet ] : this . decodeInet , [ dataTypes . date ] : this . decodeDate , [ dataTypes . time ] : this . decodeTime , [ dataTypes . smallint ] : this . decodeSmallint , [ dataTypes . tinyint ] : this . decodeTinyint , [ dataTypes . list ] : this . decodeList , [ dataTypes . map ] : this . decodeMap , [ dataTypes . set ] : this . decodeSet , [ dataTypes . udt ] : this . decodeUdt , [ dataTypes . tuple ] : this . decodeTuple } ; this . encoders = { [ dataTypes . custom ] : this . encodeCustom , [ dataTypes . ascii ] : this . encodeAsciiString , [ dataTypes . bigint ] : this . encodeLong , [ dataTypes . blob ] : this . encodeBlob , [ dataTypes . boolean ] : this . encodeBoolean , [ dataTypes . counter ] : this . encodeLong , [ dataTypes . decimal ] : this . encodeDecimal , [ dataTypes . double ] : this . encodeDouble , [ dataTypes . float ] : this . encodeFloat , [ dataTypes . int ] : this . encodeInt , [ dataTypes . text ] : this . encodeUtf8String , [ dataTypes . timestamp ] : this . encodeTimestamp , [ dataTypes . uuid ] : this . encodeUuid , [ dataTypes . varchar ] : this . encodeUtf8String , [ dataTypes . varint ] : this . encodeVarint , [ dataTypes . timeuuid ] : this . encodeUuid , [ dataTypes . inet ] : this . encodeInet , [ dataTypes . date ] : this . encodeDate , [ dataTypes . time ] : this . encodeTime , [ dataTypes . smallint ] : this . encodeSmallint , [ dataTypes . tinyint ] : this . encodeTinyint , [ dataTypes . list ] : this . encodeList , [ dataTypes . map ] : this . encodeMap , [ dataTypes . set ] : this . encodeSet , [ dataTypes . udt ] : this . encodeUdt , [ dataTypes . tuple ] : this . encodeTuple } ; }


Input: Gets a buffer containing with the bytes ( BE ) representing the collection length for protocol v2 and below [CODESPLIT] function getLengthBufferV2 ( value ) { if ( ! value ) { return buffers . int16Zero ; } const lengthBuffer = utils . allocBufferUnsafe ( 2 ) ; if ( typeof value === 'number' ) { lengthBuffer . writeUInt16BE ( value , 0 ) ; } else { lengthBuffer . writeUInt16BE ( value . length , 0 ) ; } return lengthBuffer ; }


Input: Gets a buffer containing with the bytes ( BE ) representing the collection length for protocol v3 and above [CODESPLIT] function getLengthBufferV3 ( value ) { if ( ! value ) { return buffers . int32Zero ; } const lengthBuffer = utils . allocBufferUnsafe ( 4 ) ; if ( typeof value === 'number' ) { lengthBuffer . writeInt32BE ( value , 0 ) ; } else { lengthBuffer . writeInt32BE ( value . length , 0 ) ; } return lengthBuffer ; }


Input:
Creates a new instance of { [CODESPLIT] function Duration ( months , days , nanoseconds ) { /**
   * Gets the number of months.
   * @type {Number}
   */ this . months = months ; /**
   * Gets the number of days.
   * @type {Number}
   */ this . days = days ; /**
   * Gets the number of nanoseconds represented as a int64.
   * @type {Long}
   */ this . nanoseconds = typeof nanoseconds === 'number' ? Long . fromNumber ( nanoseconds ) : nanoseconds ; }


Input: Returns the number of zero bits preceding the highest - order one - bit in the binary representation of the value . [CODESPLIT] function numberOfLeadingZeros ( value ) { if ( value . equals ( Long . ZERO ) ) { return 64 ; } let n = 1 ; let x = value . getHighBits ( ) ; if ( x === 0 ) { n += 32 ; x = value . getLowBits ( ) ; } if ( x >>> 16 === 0 ) { n += 16 ; x <<= 16 ; } if ( x >>> 24 === 0 ) { n += 8 ; x <<= 8 ; } if ( x >>> 28 === 0 ) { n += 4 ; x <<= 4 ; } if ( x >>> 30 === 0 ) { n += 2 ; x <<= 2 ; } n -= x >>> 31 ; return n ; }


Input:
Creates a new Index instance . [CODESPLIT] function Index ( name , target , kind , options ) { /**
   * Name of the index.
   * @type {String}
   */ this . name = name ; /**
   * Target of the index.
   * @type {String}
   */ this . target = target ; /**
   * A numeric value representing index kind (0: custom, 1: keys, 2: composite);
   * @type {Number}
   */ this . kind = typeof kind === 'string' ? getKindByName ( kind ) : kind ; /**
   * An associative array containing the index options
   * @type {Object}
   */ this . options = options ; }


Input: work - horse [CODESPLIT] function ( key ) { return _ . sortBy ( files , function ( el ) { return Number ( $ ( el ) . find ( 'span[data-lint]' ) . attr ( key ) ) * - 1 ; } ) ; }


Input: Resizer () resizes items based on the object width divided by the compressor * 10 [CODESPLIT] function ( ) { $this . css ( 'font-size' , Math . max ( Math . min ( $this . width ( ) / ( compressor * 10 ) , parseFloat ( settings . maxFontSize ) ) , parseFloat ( settings . minFontSize ) ) ) ; }


Input: CONSTRUCTOR [CODESPLIT] function CodeMirror ( place , options ) { if ( ! ( this instanceof CodeMirror ) ) return new CodeMirror ( place , options ) ; this . options = options = options || { } ; // Determine effective options based on given values and defaults. for ( var opt in defaults ) if ( ! options . hasOwnProperty ( opt ) && defaults . hasOwnProperty ( opt ) ) options [ opt ] = defaults [ opt ] ; setGuttersForLineNumbers ( options ) ; var display = this . display = makeDisplay ( place ) ; display . wrapper . CodeMirror = this ; updateGutters ( this ) ; if ( options . autofocus && ! mobile ) focusInput ( this ) ; this . view = makeView ( new BranchChunk ( [ new LeafChunk ( [ makeLine ( "" , null , textHeight ( display ) ) ] ) ] ) ) ; this . nextOpId = 0 ; loadMode ( this ) ; themeChanged ( this ) ; if ( options . lineWrapping ) this . display . wrapper . className += " CodeMirror-wrap" ; // Initialize the content. this . setValue ( options . value || "" ) ; // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if ( ie ) setTimeout ( bind ( resetInput , this , true ) , 20 ) ; this . view . history = makeHistory ( ) ; registerEventHandlers ( this ) ; // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus ; try { hasFocus = ( document . activeElement == display . input ) ; } catch ( e ) { } if ( hasFocus || ( options . autofocus && ! mobile ) ) setTimeout ( bind ( onFocus , this ) , 20 ) ; else onBlur ( this ) ; operation ( this , function ( ) { for ( var opt in optionHandlers ) if ( optionHandlers . propertyIsEnumerable ( opt ) ) optionHandlers [ opt ] ( this , options [ opt ] , Init ) ; for ( var i = 0 ; i < initHooks . length ; ++ i ) initHooks [ i ] ( this ) ; } ) ( ) ; }


Input: DISPLAY CONSTRUCTOR [CODESPLIT] function makeDisplay ( place ) { var d = { } ; var input = d . input = elt ( "textarea" , null , null , "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;" ) ; input . setAttribute ( "wrap" , "off" ) ; input . setAttribute ( "autocorrect" , "off" ) ; input . setAttribute ( "autocapitalize" , "off" ) ; // Wraps and hides input textarea d . inputDiv = elt ( "div" , [ input ] , null , "overflow: hidden; position: relative; width: 3px; height: 0px;" ) ; // The actual fake scrollbars. d . scrollbarH = elt ( "div" , [ elt ( "div" , null , null , "height: 1px" ) ] , "CodeMirror-hscrollbar" ) ; d . scrollbarV = elt ( "div" , [ elt ( "div" , null , null , "width: 1px" ) ] , "CodeMirror-vscrollbar" ) ; d . scrollbarFiller = elt ( "div" , null , "CodeMirror-scrollbar-filler" ) ; // DIVs containing the selection and the actual code d . lineDiv = elt ( "div" ) ; d . selectionDiv = elt ( "div" , null , null , "position: relative; z-index: 1" ) ; // Blinky cursor, and element used to ensure cursor fits at the end of a line d . cursor = elt ( "pre" , "\u00a0" , "CodeMirror-cursor" ) ; // Secondary cursor, shown when on a 'jump' in bi-directional text d . otherCursor = elt ( "pre" , "\u00a0" , "CodeMirror-cursor CodeMirror-secondarycursor" ) ; // Used to measure text size d . measure = elt ( "div" , null , "CodeMirror-measure" ) ; // Wraps everything that needs to exist inside the vertically-padded coordinate system d . lineSpace = elt ( "div" , [ d . measure , d . selectionDiv , d . lineDiv , d . cursor , d . otherCursor ] , null , "position: relative; outline: none" ) ; // Moved around its parent to cover visible view d . mover = elt ( "div" , [ elt ( "div" , [ d . lineSpace ] , "CodeMirror-lines" ) ] , null , "position: relative" ) ; // Set to the height of the text, causes scrolling d . sizer = elt ( "div" , [ d . mover ] , "CodeMirror-sizer" ) ; // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers d . heightForcer = elt ( "div" , "\u00a0" , null , "position: absolute; height: " + scrollerCutOff + "px" ) ; // Will contain the gutters, if any d . gutters = elt ( "div" , null , "CodeMirror-gutters" ) ; d . lineGutter = null ; // Helper element to properly size the gutter backgrounds var scrollerInner = elt ( "div" , [ d . sizer , d . heightForcer , d . gutters ] , null , "position: relative; min-height: 100%" ) ; // Provides scrolling d . scroller = elt ( "div" , [ scrollerInner ] , "CodeMirror-scroll" ) ; d . scroller . setAttribute ( "tabIndex" , "-1" ) ; // The element in which the editor lives. d . wrapper = elt ( "div" , [ d . inputDiv , d . scrollbarH , d . scrollbarV , d . scrollbarFiller , d . scroller ] , "CodeMirror" ) ; // Work around IE7 z-index bug if ( ie_lt8 ) { d . gutters . style . zIndex = - 1 ; d . scroller . style . paddingRight = 0 ; } if ( place . appendChild ) place . appendChild ( d . wrapper ) ; else place ( d . wrapper ) ; // Needed to hide big blue blinking cursor on Mobile Safari if ( ios ) input . style . width = "0px" ; if ( ! webkit ) d . scroller . draggable = true ; // Needed to handle Tab key in KHTML if ( khtml ) { d . inputDiv . style . height = "1px" ; d . inputDiv . style . position = "absolute" ; } // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). else if ( ie_lt8 ) d . scrollbarH . style . minWidth = d . scrollbarV . style . minWidth = "18px" ; // Current visible range (may be bigger than the view window). d . viewOffset = d . showingFrom = d . showingTo = d . lastSizeC = 0 ; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d . lineNumWidth = d . lineNumInnerWidth = d . lineNumChars = null ; // See readInput and resetInput d . prevInput = "" ; // Set to true when a non-horizontal-scrolling widget is added. As // an optimization, widget aligning is skipped when d is false. d . alignWidgets = false ; // Flag that indicates whether we currently expect input to appear // (after some event like 'keypress' or 'input') and are polling // intensively. d . pollingFast = false ; // Self-resetting timeout for the poller d . poll = new Delayed ( ) ; // True when a drag from the editor is active d . draggingText = false ; d . cachedCharWidth = d . cachedTextHeight = null ; d . measureLineCache = [ ] ; d . measureLineCachePos = 0 ; // Tracks when resetInput has punted to just putting a short // string instead of the (large) selection. d . inaccurateSelection = false ; // Used to adjust overwrite behaviour when a paste has been // detected d . pasteIncoming = false ; return d ; }


Input: VIEW CONSTRUCTOR [CODESPLIT] function makeView ( doc ) { var selPos = { line : 0 , ch : 0 } ; return { doc : doc , // frontier is the point up to which the content has been parsed, frontier : 0 , highlight : new Delayed ( ) , sel : { from : selPos , to : selPos , head : selPos , anchor : selPos , shift : false , extend : false } , scrollTop : 0 , scrollLeft : 0 , overwrite : false , focused : false , // Tracks the maximum line length so that // the horizontal scrollbar can be kept // static when scrolling. maxLine : getLine ( doc , 0 ) , maxLineLength : 0 , maxLineChanged : false , suppressEdits : false , goalColumn : null , cantEdit : false , keyMaps : [ ] } ; }


Input: STATE UPDATES Used to get the editor into a consistent state again when options change . [CODESPLIT] function loadMode ( cm ) { var doc = cm . view . doc ; cm . view . mode = CodeMirror . getMode ( cm . options , cm . options . mode ) ; doc . iter ( 0 , doc . size , function ( line ) { line . stateAfter = null ; } ) ; cm . view . frontier = 0 ; startWorker ( cm , 100 ) ; }


Input: Re - synchronize the fake scrollbars with the actual size of the content . Optionally force a scrollTop . [CODESPLIT] function updateScrollbars ( d /* display */ , docHeight ) { var totalHeight = docHeight + 2 * paddingTop ( d ) ; d . sizer . style . minHeight = d . heightForcer . style . top = totalHeight + "px" ; var scrollHeight = Math . max ( totalHeight , d . scroller . scrollHeight ) ; var needsH = d . scroller . scrollWidth > d . scroller . clientWidth ; var needsV = scrollHeight > d . scroller . clientHeight ; if ( needsV ) { d . scrollbarV . style . display = "block" ; d . scrollbarV . style . bottom = needsH ? scrollbarWidth ( d . measure ) + "px" : "0" ; d . scrollbarV . firstChild . style . height = ( scrollHeight - d . scroller . clientHeight + d . scrollbarV . clientHeight ) + "px" ; } else d . scrollbarV . style . display = "" ; if ( needsH ) { d . scrollbarH . style . display = "block" ; d . scrollbarH . style . right = needsV ? scrollbarWidth ( d . measure ) + "px" : "0" ; d . scrollbarH . firstChild . style . width = ( d . scroller . scrollWidth - d . scroller . clientWidth + d . scrollbarH . clientWidth ) + "px" ; } else d . scrollbarH . style . display = "" ; if ( needsH && needsV ) { d . scrollbarFiller . style . display = "block" ; d . scrollbarFiller . style . height = d . scrollbarFiller . style . width = scrollbarWidth ( d . measure ) + "px" ; } else d . scrollbarFiller . style . display = "" ; if ( mac_geLion && scrollbarWidth ( d . measure ) === 0 ) d . scrollbarV . style . minWidth = d . scrollbarH . style . minHeight = mac_geMountainLion ? "18px" : "12px" ; }


Input: DISPLAY DRAWING [CODESPLIT] function updateDisplay ( cm , changes , viewPort ) { var oldFrom = cm . display . showingFrom , oldTo = cm . display . showingTo ; var updated = updateDisplayInner ( cm , changes , viewPort ) ; if ( updated ) { signalLater ( cm , cm , "update" , cm ) ; if ( cm . display . showingFrom != oldFrom || cm . display . showingTo != oldTo ) signalLater ( cm , cm , "viewportChange" , cm , cm . display . showingFrom , cm . display . showingTo ) ; } updateSelection ( cm ) ; updateScrollbars ( cm . display , cm . view . doc . height ) ; return updated ; }


Input: Uses a set of changes plus the current scroll position to determine which DOM updates have to be made and makes the updates . [CODESPLIT] function updateDisplayInner ( cm , changes , viewPort ) { var display = cm . display , doc = cm . view . doc ; if ( ! display . wrapper . clientWidth ) { display . showingFrom = display . showingTo = display . viewOffset = 0 ; return ; } // Compute the new visible window // If scrollTop is specified, use that to determine which lines // to render instead of the current scrollbar position. var visible = visibleLines ( display , doc , viewPort ) ; // Bail out if the visible area is already rendered and nothing changed. if ( changes !== true && changes . length == 0 && visible . from > display . showingFrom && visible . to < display . showingTo ) return ; if ( changes && maybeUpdateLineNumberWidth ( cm ) ) changes = true ; display . sizer . style . marginLeft = display . scrollbarH . style . left = display . gutters . offsetWidth + "px" ; // When merged lines are present, the line that needs to be // redrawn might not be the one that was changed. if ( changes !== true && sawCollapsedSpans ) for ( var i = 0 ; i < changes . length ; ++ i ) { var ch = changes [ i ] , merged ; while ( merged = collapsedSpanAtStart ( getLine ( doc , ch . from ) ) ) { var from = merged . find ( ) . from . line ; if ( ch . diff ) ch . diff -= ch . from - from ; ch . from = from ; } } // Used to determine which lines need their line numbers updated var positionsChangedFrom = changes === true ? 0 : Infinity ; if ( cm . options . lineNumbers && changes && changes !== true ) for ( var i = 0 ; i < changes . length ; ++ i ) if ( changes [ i ] . diff ) { positionsChangedFrom = changes [ i ] . from ; break ; } var from = Math . max ( visible . from - cm . options . viewportMargin , 0 ) ; var to = Math . min ( doc . size , visible . to + cm . options . viewportMargin ) ; if ( display . showingFrom < from && from - display . showingFrom < 20 ) from = display . showingFrom ; if ( display . showingTo > to && display . showingTo - to < 20 ) to = Math . min ( doc . size , display . showingTo ) ; if ( sawCollapsedSpans ) { from = lineNo ( visualLine ( doc , getLine ( doc , from ) ) ) ; while ( to < doc . size && lineIsHidden ( getLine ( doc , to ) ) ) ++ to ; } // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = changes === true ? [ ] : computeIntact ( [ { from : display . showingFrom , to : display . showingTo } ] , changes ) ; // Clip off the parts that won't be visible var intactLines = 0 ; for ( var i = 0 ; i < intact . length ; ++ i ) { var range = intact [ i ] ; if ( range . from < from ) range . from = from ; if ( range . to > to ) range . to = to ; if ( range . from >= range . to ) intact . splice ( i -- , 1 ) ; else intactLines += range . to - range . from ; } if ( intactLines == to - from && from == display . showingFrom && to == display . showingTo ) return ; intact . sort ( function ( a , b ) { return a . from - b . from ; } ) ; if ( intactLines < ( to - from ) * .7 ) display . lineDiv . style . display = "none" ; patchDisplay ( cm , from , to , intact , positionsChangedFrom ) ; display . lineDiv . style . display = "" ; var different = from != display . showingFrom || to != display . showingTo || display . lastSizeC != display . wrapper . clientHeight ; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if ( different ) display . lastSizeC = display . wrapper . clientHeight ; display . showingFrom = from ; display . showingTo = to ; startWorker ( cm , 100 ) ; var prevBottom = display . lineDiv . offsetTop ; for ( var node = display . lineDiv . firstChild , height ; node ; node = node . nextSibling ) if ( node . lineObj ) { if ( ie_lt8 ) { var bot = node . offsetTop + node . offsetHeight ; height = bot - prevBottom ; prevBottom = bot ; } else { var box = node . getBoundingClientRect ( ) ; height = box . bottom - box . top ; } var diff = node . lineObj . height - height ; if ( height < 2 ) height = textHeight ( display ) ; if ( diff > .001 || diff < - .001 ) updateLineHeight ( node . lineObj , height ) ; } display . viewOffset = heightAtLine ( cm , getLine ( doc , from ) ) ; // Position the mover div to align with the current virtual scroll position display . mover . style . top = display . viewOffset + "px" ; return true ; }


Input: Highlight selection [CODESPLIT] function updateSelectionRange ( cm ) { var display = cm . display , doc = cm . view . doc , sel = cm . view . sel ; var fragment = document . createDocumentFragment ( ) ; var clientWidth = display . lineSpace . offsetWidth , pl = paddingLeft ( cm . display ) ; function add ( left , top , width , bottom ) { if ( top < 0 ) top = 0 ; fragment . appendChild ( elt ( "div" , null , "CodeMirror-selected" , "position: absolute; left: " + left + "px; top: " + top + "px; width: " + ( width == null ? clientWidth - left : width ) + "px; height: " + ( bottom - top ) + "px" ) ) ; } function drawForLine ( line , fromArg , toArg , retTop ) { var lineObj = getLine ( doc , line ) ; var lineLen = lineObj . text . length , rVal = retTop ? Infinity : - Infinity ; function coords ( ch ) { return charCoords ( cm , { line : line , ch : ch } , "div" , lineObj ) ; } iterateBidiSections ( getOrder ( lineObj ) , fromArg || 0 , toArg == null ? lineLen : toArg , function ( from , to , dir ) { var leftPos = coords ( dir == "rtl" ? to - 1 : from ) ; var rightPos = coords ( dir == "rtl" ? from : to - 1 ) ; var left = leftPos . left , right = rightPos . right ; if ( rightPos . top - leftPos . top > 3 ) { // Different lines, draw top part add ( left , leftPos . top , null , leftPos . bottom ) ; left = pl ; if ( leftPos . bottom < rightPos . top ) add ( left , leftPos . bottom , null , rightPos . top ) ; } if ( toArg == null && to == lineLen ) right = clientWidth ; if ( fromArg == null && from == 0 ) left = pl ; rVal = retTop ? Math . min ( rightPos . top , rVal ) : Math . max ( rightPos . bottom , rVal ) ; if ( left < pl + 1 ) left = pl ; add ( left , rightPos . top , right - left , rightPos . bottom ) ; } ) ; return rVal ; } if ( sel . from . line == sel . to . line ) { drawForLine ( sel . from . line , sel . from . ch , sel . to . ch ) ; } else { var fromObj = getLine ( doc , sel . from . line ) ; var cur = fromObj , merged , path = [ sel . from . line , sel . from . ch ] , singleLine ; while ( merged = collapsedSpanAtEnd ( cur ) ) { var found = merged . find ( ) ; path . push ( found . from . ch , found . to . line , found . to . ch ) ; if ( found . to . line == sel . to . line ) { path . push ( sel . to . ch ) ; singleLine = true ; break ; } cur = getLine ( doc , found . to . line ) ; } // This is a single, merged line if ( singleLine ) { for ( var i = 0 ; i < path . length ; i += 3 ) drawForLine ( path [ i ] , path [ i + 1 ] , path [ i + 2 ] ) ; } else { var middleTop , middleBot , toObj = getLine ( doc , sel . to . line ) ; if ( sel . from . ch ) // Draw the first line of selection. middleTop = drawForLine ( sel . from . line , sel . from . ch , null , false ) ; else // Simply include it in the middle block. middleTop = heightAtLine ( cm , fromObj ) - display . viewOffset ; if ( ! sel . to . ch ) middleBot = heightAtLine ( cm , toObj ) - display . viewOffset ; else middleBot = drawForLine ( sel . to . line , collapsedSpanAtStart ( toObj ) ? null : 0 , sel . to . ch , true ) ; if ( middleTop < middleBot ) add ( pl , middleTop , null , middleBot ) ; } } removeChildrenAndAdd ( display . selectionDiv , fragment ) ; display . selectionDiv . style . display = "" ; }


Input: Cursor - blinking [CODESPLIT] function restartBlink ( cm ) { var display = cm . display ; clearInterval ( display . blinker ) ; var on = true ; display . cursor . style . visibility = display . otherCursor . style . visibility = "" ; display . blinker = setInterval ( function ( ) { if ( ! display . cursor . offsetHeight ) return ; display . cursor . style . visibility = display . otherCursor . style . visibility = ( on = ! on ) ? "" : "hidden" ; } , cm . options . cursorBlinkRate ) ; }


Input: HIGHLIGHT WORKER [CODESPLIT] function startWorker ( cm , time ) { if ( cm . view . frontier < cm . display . showingTo ) cm . view . highlight . set ( time , bind ( highlightWorker , cm ) ) ; }


Input: Context is one of line div ( display . lineDiv ) local / null ( editor ) or page [CODESPLIT] function intoCoordSystem ( cm , lineObj , rect , context ) { if ( lineObj . widgets ) for ( var i = 0 ; i < lineObj . widgets . length ; ++ i ) if ( lineObj . widgets [ i ] . above ) { var size = lineObj . widgets [ i ] . node . offsetHeight ; rect . top += size ; rect . bottom += size ; } if ( context == "line" ) return rect ; if ( ! context ) context = "local" ; var yOff = heightAtLine ( cm , lineObj ) ; if ( context != "local" ) yOff -= cm . display . viewOffset ; if ( context == "page" ) { var lOff = cm . display . lineSpace . getBoundingClientRect ( ) ; yOff += lOff . top + ( window . pageYOffset || ( document . documentElement || document . body ) . scrollTop ) ; var xOff = lOff . left + ( window . pageXOffset || ( document . documentElement || document . body ) . scrollLeft ) ; rect . left += xOff ; rect . right += xOff ; } rect . top += yOff ; rect . bottom += yOff ; return rect ; }


Input: Coords must be lineSpace - local [CODESPLIT] function coordsChar ( cm , x , y ) { var doc = cm . view . doc ; y += cm . display . viewOffset ; if ( y < 0 ) return { line : 0 , ch : 0 , outside : true } ; var lineNo = lineAtHeight ( doc , y ) ; if ( lineNo >= doc . size ) return { line : doc . size - 1 , ch : getLine ( doc , doc . size - 1 ) . text . length } ; if ( x < 0 ) x = 0 ; for ( ; ; ) { var lineObj = getLine ( doc , lineNo ) ; var found = coordsCharInner ( cm , lineObj , lineNo , x , y ) ; var merged = collapsedSpanAtEnd ( lineObj ) ; if ( merged && found . ch == lineRight ( lineObj ) ) lineNo = merged . find ( ) . to . line ; else return found ; } }


Input: Operations are used to wrap changes in such a way that each change won t have to update the cursor and display ( which would be awkward slow and error - prone ) but instead updates are batched and then all combined and executed at once . [CODESPLIT] function startOperation ( cm ) { if ( cm . curOp ) ++ cm . curOp . depth ; else cm . curOp = { // Nested operations delay update until the outermost one // finishes. depth : 1 , // An array of ranges of lines that have to be updated. See // updateDisplay. changes : [ ] , delayedCallbacks : [ ] , updateInput : null , userSelChange : null , textChanged : null , selectionChanged : false , updateMaxLine : false , id : ++ cm . nextOpId } ; }


Input: prevInput is a hack to work with IME . If we reset the textarea on every change that breaks IME . So we look for changes compared to the previous content instead . ( Modern browsers have events that indicate IME taking place but these are not widely supported or compatible enough yet to rely on . ) [CODESPLIT] function readInput ( cm ) { var input = cm . display . input , prevInput = cm . display . prevInput , view = cm . view , sel = view . sel ; if ( ! view . focused || hasSelection ( input ) || isReadOnly ( cm ) ) return false ; var text = input . value ; if ( text == prevInput && posEq ( sel . from , sel . to ) ) return false ; startOperation ( cm ) ; view . sel . shift = false ; var same = 0 , l = Math . min ( prevInput . length , text . length ) ; while ( same < l && prevInput [ same ] == text [ same ] ) ++ same ; var from = sel . from , to = sel . to ; if ( same < prevInput . length ) from = { line : from . line , ch : from . ch - ( prevInput . length - same ) } ; else if ( view . overwrite && posEq ( from , to ) && ! cm . display . pasteIncoming ) to = { line : to . line , ch : Math . min ( getLine ( cm . view . doc , to . line ) . text . length , to . ch + ( text . length - same ) ) } ; var updateInput = cm . curOp . updateInput ; updateDoc ( cm , from , to , splitLines ( text . slice ( same ) ) , "end" , cm . display . pasteIncoming ? "paste" : "input" , { from : from , to : to } ) ; cm . curOp . updateInput = updateInput ; if ( text . length > 1000 ) input . value = cm . display . prevInput = "" ; else cm . display . prevInput = text ; endOperation ( cm ) ; cm . display . pasteIncoming = false ; return true ; }


Input: EVENT HANDLERS [CODESPLIT] function registerEventHandlers ( cm ) { var d = cm . display ; on ( d . scroller , "mousedown" , operation ( cm , onMouseDown ) ) ; on ( d . scroller , "dblclick" , operation ( cm , e_preventDefault ) ) ; on ( d . lineSpace , "selectstart" , function ( e ) { if ( ! mouseEventInWidget ( d , e ) ) e_preventDefault ( e ) ; } ) ; // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if ( ! gecko ) on ( d . scroller , "contextmenu" , function ( e ) { onContextMenu ( cm , e ) ; } ) ; on ( d . scroller , "scroll" , function ( ) { setScrollTop ( cm , d . scroller . scrollTop ) ; setScrollLeft ( cm , d . scroller . scrollLeft , true ) ; signal ( cm , "scroll" , cm ) ; } ) ; on ( d . scrollbarV , "scroll" , function ( ) { setScrollTop ( cm , d . scrollbarV . scrollTop ) ; } ) ; on ( d . scrollbarH , "scroll" , function ( ) { setScrollLeft ( cm , d . scrollbarH . scrollLeft ) ; } ) ; on ( d . scroller , "mousewheel" , function ( e ) { onScrollWheel ( cm , e ) ; } ) ; on ( d . scroller , "DOMMouseScroll" , function ( e ) { onScrollWheel ( cm , e ) ; } ) ; function reFocus ( ) { if ( cm . view . focused ) setTimeout ( bind ( focusInput , cm ) , 0 ) ; } on ( d . scrollbarH , "mousedown" , reFocus ) ; on ( d . scrollbarV , "mousedown" , reFocus ) ; // Prevent wrapper from ever scrolling on ( d . wrapper , "scroll" , function ( ) { d . wrapper . scrollTop = d . wrapper . scrollLeft = 0 ; } ) ; on ( window , "resize" , function resizeHandler ( ) { // Might be a text scaling operation, clear size caches. d . cachedCharWidth = d . cachedTextHeight = null ; clearCaches ( cm ) ; if ( d . wrapper . parentNode ) updateDisplay ( cm , true ) ; else off ( window , "resize" , resizeHandler ) ; } ) ; on ( d . input , "keyup" , operation ( cm , function ( e ) { if ( cm . options . onKeyEvent && cm . options . onKeyEvent ( cm , addStop ( e ) ) ) return ; if ( e_prop ( e , "keyCode" ) == 16 ) cm . view . sel . shift = false ; } ) ) ; on ( d . input , "input" , bind ( fastPoll , cm ) ) ; on ( d . input , "keydown" , operation ( cm , onKeyDown ) ) ; on ( d . input , "keypress" , operation ( cm , onKeyPress ) ) ; on ( d . input , "focus" , bind ( onFocus , cm ) ) ; on ( d . input , "blur" , bind ( onBlur , cm ) ) ; function drag_ ( e ) { if ( cm . options . onDragEvent && cm . options . onDragEvent ( cm , addStop ( e ) ) ) return ; e_stop ( e ) ; } if ( cm . options . dragDrop ) { on ( d . scroller , "dragstart" , function ( e ) { onDragStart ( cm , e ) ; } ) ; on ( d . scroller , "dragenter" , drag_ ) ; on ( d . scroller , "dragover" , drag_ ) ; on ( d . scroller , "drop" , operation ( cm , onDrop ) ) ; } on ( d . scroller , "paste" , function ( ) { focusInput ( cm ) ; fastPoll ( cm ) ; } ) ; on ( d . input , "paste" , function ( ) { d . pasteIncoming = true ; fastPoll ( cm ) ; } ) ; function prepareCopy ( ) { if ( d . inaccurateSelection ) { d . prevInput = "" ; d . inaccurateSelection = false ; d . input . value = cm . getSelection ( ) ; selectInput ( d . input ) ; } } on ( d . input , "cut" , prepareCopy ) ; on ( d . input , "copy" , prepareCopy ) ; // Needed to handle Tab key in KHTML if ( khtml ) on ( d . sizer , "mouseup" , function ( ) { if ( document . activeElement == d . input ) d . input . blur ( ) ; focusInput ( cm ) ; } ) ; }


Input: Replace the range from from to to by the strings in newText . Afterwards set the selection to selFrom selTo . [CODESPLIT] function updateDoc ( cm , from , to , newText , selUpdate , origin ) { // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && removeReadOnlyRanges ( cm . view . doc , from , to ) ; if ( split ) { for ( var i = split . length - 1 ; i >= 1 ; -- i ) updateDocInner ( cm , split [ i ] . from , split [ i ] . to , [ "" ] , origin ) ; if ( split . length ) return updateDocInner ( cm , split [ 0 ] . from , split [ 0 ] . to , newText , selUpdate , origin ) ; } else { return updateDocInner ( cm , from , to , newText , selUpdate , origin ) ; } }


Input: Update the selection . Last two args are only used by updateDoc since they have to be expressed in the line numbers before the update . [CODESPLIT] function setSelection ( cm , anchor , head , bias , checkAtomic ) { cm . view . goalColumn = null ; var sel = cm . view . sel ; // Skip over atomic spans. if ( checkAtomic || ! posEq ( anchor , sel . anchor ) ) anchor = skipAtomic ( cm , anchor , bias , checkAtomic != "push" ) ; if ( checkAtomic || ! posEq ( head , sel . head ) ) head = skipAtomic ( cm , head , bias , checkAtomic != "push" ) ; if ( posEq ( sel . anchor , anchor ) && posEq ( sel . head , head ) ) return ; sel . anchor = anchor ; sel . head = head ; var inv = posLess ( head , anchor ) ; sel . from = inv ? head : anchor ; sel . to = inv ? anchor : head ; cm . curOp . updateInput = true ; cm . curOp . selectionChanged = true ; }


Input: Fetch the parser token for a given character . Useful for hacks that want to inspect the mode state ( say for completion ) . [CODESPLIT] function ( pos ) { var doc = this . view . doc ; pos = clipPos ( doc , pos ) ; var state = getStateBefore ( this , pos . line ) , mode = this . view . mode ; var line = getLine ( doc , pos . line ) ; var stream = new StringStream ( line . text , this . options . tabSize ) ; while ( stream . pos < pos . ch && ! stream . eol ( ) ) { stream . start = stream . pos ; var style = mode . token ( stream , state ) ; } return { start : stream . start , end : stream . pos , string : stream . current ( ) , className : style || null , // Deprecated, use 'type' instead type : style || null , state : state } ; }


Input: Line objects . These hold state related to a line including highlighting info ( the styles array ) . [CODESPLIT] function makeLine ( text , markedSpans , height ) { var line = { text : text , height : height } ; attachMarkedSpans ( line , markedSpans ) ; if ( lineIsHidden ( line ) ) line . height = 0 ; return line ; }


Input: Run the given mode s parser over a line update the styles array which contains alternating fragments of text and CSS classes . [CODESPLIT] function highlightLine ( cm , line , state ) { var mode = cm . view . mode , flattenSpans = cm . options . flattenSpans ; var changed = ! line . styles , pos = 0 , curText = "" , curStyle = null ; var stream = new StringStream ( line . text , cm . options . tabSize ) , st = line . styles || ( line . styles = [ ] ) ; if ( line . text == "" && mode . blankLine ) mode . blankLine ( state ) ; while ( ! stream . eol ( ) ) { var style = mode . token ( stream , state ) , substr = stream . current ( ) ; stream . start = stream . pos ; if ( ! flattenSpans || curStyle != style ) { if ( curText ) { changed = changed || pos >= st . length || curText != st [ pos ] || curStyle != st [ pos + 1 ] ; st [ pos ++ ] = curText ; st [ pos ++ ] = curStyle ; } curText = substr ; curStyle = style ; } else curText = curText + substr ; // Give up when line is ridiculously long if ( stream . pos > 5000 ) break ; } if ( curText ) { changed = changed || pos >= st . length || curText != st [ pos ] || curStyle != st [ pos + 1 ] ; st [ pos ++ ] = curText ; st [ pos ++ ] = curStyle ; } if ( stream . pos > 5000 ) { st [ pos ++ ] = line . text . slice ( stream . pos ) ; st [ pos ++ ] = null ; } if ( pos != st . length ) { st . length = pos ; changed = true ; } return changed ; }


Input: Allow 3rd - party code to override event properties by adding an override object to an event object . [CODESPLIT] function e_prop ( e , prop ) { var overridden = e . override && e . override . hasOwnProperty ( prop ) ; return overridden ? e . override [ prop ] : e [ prop ] ; }


Input: This is somewhat involved . It is needed in order to move visually through bi - directional text -- i . e . pressing left should make the cursor go left even when in RTL text . The tricky part is the jumps where RTL and LTR text touch each other . This often requires the cursor offset to move more than one unit in order to visually move one unit . [CODESPLIT] function moveVisually ( line , start , dir , byUnit ) { var bidi = getOrder ( line ) ; if ( ! bidi ) return moveLogically ( line , start , dir , byUnit ) ; var moveOneUnit = byUnit ? function ( pos , dir ) { do pos += dir ; while ( pos > 0 && isExtendingChar . test ( line . text . charAt ( pos ) ) ) ; return pos ; } : function ( pos , dir ) { return pos + dir ; } ; var linedir = bidi [ 0 ] . level ; for ( var i = 0 ; i < bidi . length ; ++ i ) { var part = bidi [ i ] , sticky = part . level % 2 == linedir ; if ( ( part . from < start && part . to > start ) || ( sticky && ( part . from == start || part . to == start ) ) ) break ; } var target = moveOneUnit ( start , part . level % 2 ? - dir : dir ) ; while ( target != null ) { if ( part . level % 2 == linedir ) { if ( target < part . from || target > part . to ) { part = bidi [ i += dir ] ; target = part && ( dir > 0 == part . level % 2 ? moveOneUnit ( part . to , - 1 ) : moveOneUnit ( part . from , 1 ) ) ; } else break ; } else { if ( target == bidiLeft ( part ) ) { part = bidi [ -- i ] ; target = part && bidiRight ( part ) ; } else if ( target == bidiRight ( part ) ) { part = bidi [ ++ i ] ; target = part && bidiLeft ( part ) ; } else break ; } } return target < 0 || target > line . text . length ? null : target ; }


Input:
Flow . js is a library providing multiple simultaneous stable and resumable uploads via the HTML5 File API . [CODESPLIT] function Flow ( opts ) { /**
     * Supported by browser?
     * @type {boolean}
     */ this . support = ( typeof File !== 'undefined' && typeof Blob !== 'undefined' && typeof FileList !== 'undefined' && ( ! ! Blob . prototype . slice || ! ! Blob . prototype . webkitSlice || ! ! Blob . prototype . mozSlice || false ) // slicing files support ) ; if ( ! this . support ) { return ; } /**
     * Check if directory upload is supported
     * @type {boolean}
     */ this . supportDirectory = ( / Chrome / . test ( window . navigator . userAgent ) || / Firefox / . test ( window . navigator . userAgent ) || / Edge / . test ( window . navigator . userAgent ) ) ; /**
     * List of FlowFile objects
     * @type {Array.<FlowFile>}
     */ this . files = [ ] ; /**
     * Default options for flow.js
     * @type {Object}
     */ this . defaults = { chunkSize : 1024 * 1024 , forceChunkSize : false , simultaneousUploads : 3 , singleFile : false , fileParameterName : 'file' , progressCallbacksInterval : 500 , speedSmoothingFactor : 0.1 , query : { } , headers : { } , withCredentials : false , preprocess : null , method : 'multipart' , testMethod : 'GET' , uploadMethod : 'POST' , prioritizeFirstAndLastChunk : false , allowDuplicateUploads : false , target : '/' , testChunks : true , generateUniqueIdentifier : null , maxChunkRetries : 0 , chunkRetryInterval : null , permanentErrors : [ 404 , 413 , 415 , 500 , 501 ] , successStatuses : [ 200 , 201 , 202 ] , onDropStopPropagation : false , initFileFn : null , readFileFn : webAPIFileRead } ; /**
     * Current options
     * @type {Object}
     */ this . opts = { } ; /**
     * List of events:
     *  key stands for event name
     *  value array list of callbacks
     * @type {}
     */ this . events = { } ; var $ = this ; /**
     * On drop event
     * @function
     * @param {MouseEvent} event
     */ this . onDrop = function ( event ) { if ( $ . opts . onDropStopPropagation ) { event . stopPropagation ( ) ; } event . preventDefault ( ) ; var dataTransfer = event . dataTransfer ; if ( dataTransfer . items && dataTransfer . items [ 0 ] && dataTransfer . items [ 0 ] . webkitGetAsEntry ) { $ . webkitReadDataTransfer ( event ) ; } else { $ . addFiles ( dataTransfer . files , event ) ; } } ; /**
     * Prevent default
     * @function
     * @param {MouseEvent} event
     */ this . preventEvent = function ( event ) { event . preventDefault ( ) ; } ; /**
     * Current options
     * @type {Object}
     */ this . opts = Flow . extend ( { } , this . defaults , opts || { } ) ; }


Input: Set a callback for an event possible events : fileSuccess ( file ) fileProgress ( file ) fileAdded ( file event ) fileRemoved ( file ) fileRetry ( file ) fileError ( file message ) complete () progress () error ( message file ) pause () [CODESPLIT] function ( event , callback ) { event = event . toLowerCase ( ) ; if ( ! this . events . hasOwnProperty ( event ) ) { this . events [ event ] = [ ] ; } this . events [ event ] . push ( callback ) ; }


Input: Remove event callback [CODESPLIT] function ( event , fn ) { if ( event !== undefined ) { event = event . toLowerCase ( ) ; if ( fn !== undefined ) { if ( this . events . hasOwnProperty ( event ) ) { arrayRemove ( this . events [ event ] , fn ) ; } } else { delete this . events [ event ] ; } } else { this . events = { } ; } }


Input: Fire an event [CODESPLIT] function ( event , args ) { // `arguments` is an object, not array, in FF, so: args = Array . prototype . slice . call ( arguments ) ; event = event . toLowerCase ( ) ; var preventDefault = false ; if ( this . events . hasOwnProperty ( event ) ) { each ( this . events [ event ] , function ( callback ) { preventDefault = callback . apply ( this , args . slice ( 1 ) ) === false || preventDefault ; } , this ) ; } if ( event != 'catchall' ) { args . unshift ( 'catchAll' ) ; preventDefault = this . fire . apply ( this , args ) === false || preventDefault ; } return ! preventDefault ; }


Input: Read webkit dataTransfer object [CODESPLIT] function ( event ) { var $ = this ; var queue = event . dataTransfer . items . length ; var files = [ ] ; each ( event . dataTransfer . items , function ( item ) { var entry = item . webkitGetAsEntry ( ) ; if ( ! entry ) { decrement ( ) ; return ; } if ( entry . isFile ) { // due to a bug in Chrome's File System API impl - #149735 fileReadSuccess ( item . getAsFile ( ) , entry . fullPath ) ; } else { readDirectory ( entry . createReader ( ) ) ; } } ) ; function readDirectory ( reader ) { reader . readEntries ( function ( entries ) { if ( entries . length ) { queue += entries . length ; each ( entries , function ( entry ) { if ( entry . isFile ) { var fullPath = entry . fullPath ; entry . file ( function ( file ) { fileReadSuccess ( file , fullPath ) ; } , readError ) ; } else if ( entry . isDirectory ) { readDirectory ( entry . createReader ( ) ) ; } } ) ; readDirectory ( reader ) ; } else { decrement ( ) ; } } , readError ) ; } function fileReadSuccess ( file , fullPath ) { // relative path should not start with "/" file . relativePath = fullPath . substring ( 1 ) ; files . push ( file ) ; decrement ( ) ; } function readError ( fileError ) { throw fileError ; } function decrement ( ) { if ( -- queue == 0 ) { $ . addFiles ( files , event ) ; } } }


Input: Generate unique identifier for a file [CODESPLIT] function ( file ) { var custom = this . opts . generateUniqueIdentifier ; if ( typeof custom === 'function' ) { return custom ( file ) ; } // Some confusion in different versions of Firefox var relativePath = file . relativePath || file . webkitRelativePath || file . fileName || file . name ; return file . size + '-' + relativePath . replace ( / [^0-9a-zA-Z_-] / img , '' ) ; }


Input: Upload next chunk from the queue [CODESPLIT] function ( preventEvents ) { // In some cases (such as videos) it's really handy to upload the first // and last chunk of a file quickly; this let's the server check the file's // metadata and determine if there's even a point in continuing. var found = false ; if ( this . opts . prioritizeFirstAndLastChunk ) { each ( this . files , function ( file ) { if ( ! file . paused && file . chunks . length && file . chunks [ 0 ] . status ( ) === 'pending' ) { file . chunks [ 0 ] . send ( ) ; found = true ; return false ; } if ( ! file . paused && file . chunks . length > 1 && file . chunks [ file . chunks . length - 1 ] . status ( ) === 'pending' ) { file . chunks [ file . chunks . length - 1 ] . send ( ) ; found = true ; return false ; } } ) ; if ( found ) { return found ; } } // Now, simply look for the next, best thing to upload each ( this . files , function ( file ) { if ( ! file . paused ) { each ( file . chunks , function ( chunk ) { if ( chunk . status ( ) === 'pending' ) { chunk . send ( ) ; found = true ; return false ; } } ) ; } if ( found ) { return false ; } } ) ; if ( found ) { return true ; } // The are no more outstanding chunks to upload, check is everything is done var outstanding = false ; each ( this . files , function ( file ) { if ( ! file . isComplete ( ) ) { outstanding = true ; return false ; } } ) ; if ( ! outstanding && ! preventEvents ) { // All chunks have been uploaded, complete async ( function ( ) { this . fire ( 'complete' ) ; } , this ) ; } return false ; }


Input: Assign a browse action to one or more DOM nodes . [CODESPLIT] function ( domNodes , isDirectory , singleFile , attributes ) { if ( domNodes instanceof Element ) { domNodes = [ domNodes ] ; } each ( domNodes , function ( domNode ) { var input ; if ( domNode . tagName === 'INPUT' && domNode . type === 'file' ) { input = domNode ; } else { input = document . createElement ( 'input' ) ; input . setAttribute ( 'type' , 'file' ) ; // display:none - not working in opera 12 extend ( input . style , { visibility : 'hidden' , position : 'absolute' , width : '1px' , height : '1px' } ) ; // for opera 12 browser, input must be assigned to a document domNode . appendChild ( input ) ; // https://developer.mozilla.org/en/using_files_from_web_applications) // event listener is executed two times // first one - original mouse click event // second - input.click(), input is inside domNode domNode . addEventListener ( 'click' , function ( ) { input . click ( ) ; } , false ) ; } if ( ! this . opts . singleFile && ! singleFile ) { input . setAttribute ( 'multiple' , 'multiple' ) ; } if ( isDirectory ) { input . setAttribute ( 'webkitdirectory' , 'webkitdirectory' ) ; } each ( attributes , function ( value , key ) { input . setAttribute ( key , value ) ; } ) ; // When new files are added, simply append them to the overall list var $ = this ; input . addEventListener ( 'change' , function ( e ) { if ( e . target . value ) { $ . addFiles ( e . target . files , e ) ; e . target . value = '' ; } } , false ) ; } , this ) ; }


Input: Assign one or more DOM nodes as a drop target . [CODESPLIT] function ( domNodes ) { if ( typeof domNodes . length === 'undefined' ) { domNodes = [ domNodes ] ; } each ( domNodes , function ( domNode ) { domNode . addEventListener ( 'dragover' , this . preventEvent , false ) ; domNode . addEventListener ( 'dragenter' , this . preventEvent , false ) ; domNode . addEventListener ( 'drop' , this . onDrop , false ) ; } , this ) ; }


Input: Un - assign drop event from DOM nodes [CODESPLIT] function ( domNodes ) { if ( typeof domNodes . length === 'undefined' ) { domNodes = [ domNodes ] ; } each ( domNodes , function ( domNode ) { domNode . removeEventListener ( 'dragover' , this . preventEvent ) ; domNode . removeEventListener ( 'dragenter' , this . preventEvent ) ; domNode . removeEventListener ( 'drop' , this . onDrop ) ; } , this ) ; }


Input: Returns a boolean indicating whether or not the instance is currently uploading anything . [CODESPLIT] function ( ) { var uploading = false ; each ( this . files , function ( file ) { if ( file . isUploading ( ) ) { uploading = true ; return false ; } } ) ; return uploading ; }


Input: should upload next chunk [CODESPLIT] function ( ) { var num = 0 ; var should = true ; var simultaneousUploads = this . opts . simultaneousUploads ; each ( this . files , function ( file ) { each ( file . chunks , function ( chunk ) { if ( chunk . status ( ) === 'uploading' ) { num ++ ; if ( num >= simultaneousUploads ) { should = false ; return false ; } } } ) ; } ) ; // if should is true then return uploading chunks's length return should && num ; }