All files / util linkDetector.js

100% Statements 31/31
100% Branches 2/2
100% Functions 7/7
100% Lines 29/29

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 575x       86x 86x   86x 11x 11x     86x   86x   86x 10x 20x 13x       10x 10x   10x 10x   10x 9x 9x 3x   6x       10x 10x 3x     10x 10x 1x     10x           86x    
module.exports = function(crowi) {
  'use strict'
 
  // const debug = require('debug')('crowi:lib:url')
  const linkDetector = {}
  const { decodeSpace } = require('../util/path')
 
  linkDetector.getLinkRegexp = () => {
    const appUrl = crowi.getBaseUrl()
    return new RegExp(appUrl + '(/[^\\s"?)#]*)?', 'g')
  }
 
  linkDetector.getObjectIdRegexp = () => new RegExp('/([0-9a-fA-F]{24})')
 
  linkDetector.getPathRegexps = () => [new RegExp('<(/[^>]+)>', 'g'), /\[(\/[^\]]+)\](?!\()/g]
 
  linkDetector.search = function(text) {
    var unique = function(array) {
      return array.filter(function(x, i, self) {
        return self.indexOf(x) === i
      })
    }
 
    var objectIds = []
    var paths = []
 
    const linkRegexp = linkDetector.getLinkRegexp()
    const objectIdRegexp = linkDetector.getObjectIdRegexp()
 
    while (linkRegexp.exec(text)) {
      const path = decodeSpace(decodeURIComponent(RegExp.$1))
      if (objectIdRegexp.test(path)) {
        objectIds.push(RegExp.$1)
      } else {
        paths.push(path)
      }
    }
 
    const pathRegexp = linkDetector.getPathRegexps()[0]
    while (pathRegexp.exec(text)) {
      paths.push(RegExp.$1)
    }
 
    const pathRegexp2 = linkDetector.getPathRegexps()[1]
    while (pathRegexp2.exec(text)) {
      paths.push(RegExp.$1)
    }
 
    return {
      objectIds: unique(objectIds),
      paths: unique(paths),
    }
  }
 
  return linkDetector
}