# All files parser.js

100% Statements 116/116
100% Branches 71/71
100% Functions 16/16
100% Lines 115/115

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
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292

    1x

    1x
    1x
    1x

    9x
    9x

    9x
    8x
    16x

    8x

    2x

    112x

    444x
    444x

    6x

    444x
    326x
    326x

    444x

    112x
    112x
    112x
    112x

    112x

    78x
    868x
    100x

    78x

    343x

    78x
    350x

    78x

    78x

    78x

    350x

    350x
    112x

    238x
    238x

    3x
    1x
    2x
    1x

    1x

    3x

    235x

    350x
    8x

    350x

    190x
    190x

    78x

    78x
    1x

    77x
    112x

    112x
    112x

    112x

    6x
    6x

    6x
    9x
    9x

    9x
    2x

    2x

    9x
    9x

    6x
    6x
    6x

    106x

    77x

    71x
    71x
    71x

    71x

    71x
    546x
    546x
    546x

    546x
    78x
    78x

    546x
    350x
    350x

    350x

    350x
    272x
    245x
    245x
    245x
    245x
    27x
    13x

    350x

    350x
    78x
    78x
    78x

    546x
    546x

    1x
    67x
    67x
    67x

    67x
    435x
    435x
    65x

    67x

    1x
    1x

    'use strict'

    const PARSERS = require('./parsers')

    const MARKER_START = '/**'
    const MARKER_START_SKIP = '/***'
    const MARKER_END = '*/'

    /* ------- util functions ------- */

    function find (list, filter) {
      let i = list.length
      let matchs = true

      while (i--) {
        Object.keys(filter).forEach((k) => {
          matchs = (filter[k] === list[i][k]) && matchs
        })
        if (matchs) { return list[i] }
      }
      return null
    }

    /* ------- parsing ------- */

    /**
     * Parses "@tag {type} name description"
     * @param {string} str Raw doc string
     * @param {Array<function>} parsers Array of parsers to be applied to the source
     * @returns {object} parsed tag node
     */
    function parse_tag (str, parsers) {
      // Should not get here as enforcing that string begin with whitespace
      //  and an at-sign
      /* istanbul ignore next */
      if (typeof str !== 'string' || !(/\s*@/).test(str)) { return null }

      const data = parsers.reduce(function (state, parser) {
        let result

        try {
          result = parser(state.source, Object.assign({}, state.data))
        } catch (err) {
          state.data.errors = (state.data.errors || [])
            .concat(parser.name + ': ' + err.message)
        }

        if (result) {
          state.source = state.source.slice(result.source.length)
          state.data = Object.assign(state.data, result.data)
        }

        return state
      }, {
        source: str,
        data: {}
      }).data

      data.optional = !!data.optional
      data.type = data.type === undefined ? '' : data.type
      data.name = data.name === undefined ? '' : data.name
      data.description = data.description === undefined ? '' : data.description

      return data
    }

    /**
     * Parses comment block (array of String lines)
     */
    function parse_block (source, opts) {
      const trim = opts.trim
        ? s => s.trim()
        : s => s

      const toggleFence = (typeof opts.fence === 'function')
        ? opts.fence
        : line => line.split(opts.fence).length % 2 === 0

      let source_str = source
        .map((line) => { return trim(line.source) })
        .join('\n')

      source_str = trim(source_str)

      const start = source[0].number

      // merge source lines into tags
      // we assume tag starts with "@"
      source = source
        .reduce(function (state, line) {
          line.source = trim(line.source)

          // start of a new tag detected
          if (line.source.match(/^\s*@(\S+)/) && !state.isFenced) {
            state.tags.push({
              source: [line.source],
              line: line.number
            })
          // keep appending source to the current tag
          } else {
            const tag = state.tags[state.tags.length - 1]
            if (opts.join !== undefined && opts.join !== false && opts.join !== 0 &&
                !line.startWithStar && tag.source.length > 0) {
              let source
              if (typeof opts.join === 'string') {
                source = opts.join + line.source.replace(/^\s+/, '')
              } else if (typeof opts.join === 'number') {
                source = line.source
              } else {
                source = ' ' + line.source.replace(/^\s+/, '')
              }
              tag.source[tag.source.length - 1] += source
            } else {
              tag.source.push(line.source)
            }
          }

          if (toggleFence(line.source)) {
            state.isFenced = !state.isFenced
          }
          return state
        }, {
          tags: [{ source: [] }],
          isFenced: false
        })
        .tags
        .map((tag) => {
          tag.source = trim(tag.source.join('\n'))
          return tag
        })

      // Block description
      const description = source.shift()

      // skip if no descriptions and no tags
      if (description.source === '' && source.length === 0) {
        return null
      }

      const tags = source.reduce(function (tags, tag) {
        const tag_node = parse_tag(tag.source, opts.parsers)

        // Should not get here as enforcing that string begin with whitespace
        //  and an at-sign and return non-nullish value
        /* istanbul ignore next */
        if (!tag_node) { return tags }

        tag_node.line = tag.line
        tag_node.source = tag.source

        if (opts.dotted_names && tag_node.name.includes('.')) {
          let parent_name
          let parent_tag
          let parent_tags = tags
          const parts = tag_node.name.split('.')

          while (parts.length > 1) {
            parent_name = parts.shift()
            parent_tag = find(parent_tags, {
              tag: tag_node.tag,
              name: parent_name
            })

            if (!parent_tag) {
              parent_tag = {
                tag: tag_node.tag,
                line: Number(tag_node.line),
                name: parent_name,
                type: '',
                description: ''
              }
              parent_tags.push(parent_tag)
            }

            parent_tag.tags = parent_tag.tags || []
            parent_tags = parent_tag.tags
          }

          tag_node.name = parts[0]
          parent_tags.push(tag_node)
          return tags
        }

        return tags.concat(tag_node)
      }, [])

      return {
        tags,
        line: start,
        description: description.source,
        source: source_str
      }
    }

    /**
     * Produces `extract` function with internal state initialized
     */
    function mkextract (opts) {
      let chunk = null
      let indent = 0
      let number = 0

      opts = Object.assign({}, {
        trim: true,
        dotted_names: false,
        fence: '```',
        parsers: [
          PARSERS.parse_tag,
          PARSERS.parse_type,
          PARSERS.parse_name,
          PARSERS.parse_description
        ]
      }, opts || {})

      /**
       * Read lines until they make a block
       * Return parsed block once fullfilled or null otherwise
       */
      return function extract (line) {
        let result = null
        const startPos = line.indexOf(MARKER_START)
        const endPos = line.indexOf(MARKER_END)

        // if open marker detected and it's not, skip one
        if (startPos !== -1 && line.indexOf(MARKER_START_SKIP) !== startPos) {
          chunk = []
          indent = startPos + MARKER_START.length
        }

        // if we are on middle of comment block
        if (chunk) {
          let lineStart = indent
          let startWithStar = false

          // figure out if we slice from opening marker pos
          // or line start is shifted to the left
          const nonSpaceChar = line.match(/\S/)

          // skip for the first line starting with /** (fresh chunk)
          // it always has the right indentation
          if (chunk.length > 0 && nonSpaceChar) {
            if (nonSpaceChar[0] === '*') {
              const afterNonSpaceCharIdx = nonSpaceChar.index + 1
              const extraCharIsSpace = line.charAt(afterNonSpaceCharIdx) === ' '
              lineStart = afterNonSpaceCharIdx + (extraCharIsSpace ? 1 : 0)
              startWithStar = true
            } else if (nonSpaceChar.index < indent) {
              lineStart = nonSpaceChar.index
            }
          }

          // slice the line until end or until closing marker start
          chunk.push({
            number,
            startWithStar,
            source: line.slice(lineStart, endPos === -1 ? line.length : endPos)
          })

          // finalize block if end marker detected
          if (endPos !== -1) {
            result = parse_block(chunk, opts)
            chunk = null
            indent = 0
          }
        }

        number += 1
        return result
      }
    }

    /* ------- Public API ------- */

    module.exports = function parse (source, opts) {
      const blocks = []
      const extract = mkextract(opts)
      const lines = source.split(/\n/)

      lines.forEach((line) => {
        const block = extract(line)
        if (block) {
          blocks.push(block)
        }
      })

      return blocks
    }

    module.exports.PARSERS = PARSERS
    module.exports.mkextract = mkextract