# All files ProtobufMessageStream.js

93.75% Statements 15/16
100% Branches 0/0
100% Functions 2/2
93.75% Lines 15/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    391x

    1x

    1x

    5x
    5x
    5x

    5x
    5x

    5x
    5x
    15x
    15x
    15x

    5x

    1x
     const Stream = require('stream')
    let Reader
    try {
      // If cucumber-messages is `npm link`ed, use this
      Reader = require('cucumber-messages/node_modules/protobufjs').Reader
    } catch (ignore) {
      // Otherwise (when it's not `npm link`ed), use this
      Reader = require('protobufjs').Reader
    }

    /**
     * Transforms a stream of bytes to protobuf messages
     */
    class ProtobufMessageStream extends Stream.Transform {
      constructor(type) {
        super({ objectMode: true })
        this._type = type
        this._buffer = Buffer.alloc(0)
      }

      _transform(chunk, _, cb) {
        this._buffer = Buffer.concat([this._buffer, chunk])
        this._reader = Reader.create(this._buffer)

        try {
          while (this._reader.pos < this._reader.len) {
            const message = this._type.decodeDelimited(this._reader)
            this._buffer = this._buffer.slice(this._reader.pos)
            this.push(message)
          }
        } catch (err) {
          // wait for more
        }
        cb()
      }
    }

    module.exports = ProtobufMessageStream