All files generate.ts

100% Statements 104/104
100% Branches 85/85
100% Functions 15/15
100% Lines 90/90

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 1791x         1x 1x                             1x 4956x 4956x 257x     1x 1x 4108x 4108x 4108x 38618x   4108x   1x 4731x 32x 263x 34x 219x 39x 4105x   38x 1x       1x 341x 42x   319x 3x   317x     1x 604x                         604x     1x           15994x 1x         15993x 15993x 15993x 8x 8x 8x     15993x 15390x   15993x 7931x 3435x     4496x     8062x 365x 24x   341x 341x 341x       7697x 3386x 3386x 110x 110x 110x 3737x     4311x   4308x 3982x 7683x 7650x 7650x 7650x       326x 67x 67x 67x 67x 37x 37x   189x 189x 189x       259x 6x           253x   249x 246x   3x     3x 2x 2x 1x     1x     1x    
import {
  Validation, isSimpleType, isArray, isEnum,
  isObj, isMap, isNumber, isMeta, isAnd,
  isString, SimpleTypes, isTypeDefValidation, ValueTypes
} from './validationTypes.js'
import { combineValidationObjects } from './validate.js'
import randexp from 'randexp'
type Options = {
  arrayMin: number
  arrayMax: number
  mapMin: number
  mapMax: number
  minNumber: number
  maxNumber: number
  minStringLength: number
  maxStringLength: number
  maxDepthSoft: number
  maxDepthHard: number
  prefer: 'defined' | 'undefined' | 'none'
}
 
export const randomNumber = (isInteger:boolean, min: number, max: number): number => {
  const num = Math.random() * (max - min) + min
  if (isInteger) return Math.round(num)
  return num
}
 
const simpleTypes: SimpleTypes[] = ['number', 'integer', '?', 'string', 'boolean']
const randomString = (length: number) => {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const charactersLength = characters.length
  for (let i = 0; i < length; i += 1) { result += characters.charAt(Math.floor(Math.random() * charactersLength)) }
 
  return result
}
const simpleGeneration = (type: SimpleTypes, options:Options): any => {
  switch (type) {
    case 'any': return simpleGeneration(simpleTypes[randomNumber(true, 0, simpleTypes.length - 1)], options)
    case '?': return undefined
    case 'null': return null
    case 'number': return randomNumber(false, options.minNumber, options.maxNumber)
    case 'integer': return randomNumber(true, options.minNumber, options.maxNumber)
    case 'string': return randomString(
      randomNumber(true, options.minStringLength, options.maxStringLength))
    case 'boolean': return Math.random() > 0.5
    default: throw new Error(`Unknown validator:${JSON.stringify(type)}`)
  }
}
 
const applyPreference = (input: Validation[], options:Options) => {
  if (options.prefer === 'defined') {
    return input.length > 1 ? input.filter(x => x !== '?') : input
  }
  if (options.prefer === 'undefined') {
    return input.find(x => x === '?') ? ['?'] : input
  }
  return input
}
 
export const generate = (type: Validation, options: Partial<Options> = {}) :any => {
  const defaultOptions : Options = {
    arrayMin: 1,
    arrayMax: 90,
    mapMin: 1,
    mapMax: 33,
    minNumber: -Number.MAX_SAFE_INTEGER,
    maxNumber: Number.MAX_SAFE_INTEGER,
    minStringLength: 3,
    maxStringLength: 16,
    maxDepthSoft: 4,
    maxDepthHard: 32,
    prefer: 'none'
  }
  return generateInternal(type, { ...defaultOptions, ...options }, {}, 0)
}
 
const generateInternal = (
  typeIn: Validation,
  options: Options,
  typesIn: {[key:string] : Validation },
  depth :number
): any => {
  if (depth >= options.maxDepthHard) {
    throw new Error(`Maximum depth reached: ${depth} --
  Most likely a circular type with no possible way to terminate.
  Consider making the recursion optional.`)
  }
 
  let customTypes = typesIn
  let type:ValueTypes = typeIn
  if (isTypeDefValidation(typeIn)) {
    customTypes = typeIn.$types
    type = { ...typeIn }
    delete type.$types
  }
 
  const gen = (type:Validation, increaseDepth:boolean = false) =>
    generateInternal(type, options, customTypes, increaseDepth ? depth + 1 : depth)
 
  if (isSimpleType(type)) {
    if (customTypes[type]) {
      return gen(customTypes[type])
    }
 
    return simpleGeneration(type, options)
  }
 
  if (Array.isArray(type)) {
    if (depth > options.maxDepthSoft && type.find(x => x === '?')) {
      return simpleGeneration('?', options)
    } else {
      const typeArray = applyPreference(type, options)
      const randomIndex = randomNumber(true, 0, typeArray.length - 1)
      return gen(typeArray[randomIndex])
    }
  }
 
  if (isArray(type)) {
    const arrayType = type
    if (depth > options.maxDepthSoft) return []
    const min = typeof arrayType.minLength === 'number' ? arrayType.minLength : options.arrayMin
    const max = typeof arrayType.maxLength === 'number' ? arrayType.maxLength : options.arrayMax
    return Array.from(Array(randomNumber(true, min, max)))
      .map(() => gen(arrayType.$array, true)).filter(x => typeof x !== 'undefined')
  }
 
  if (isEnum(type)) { return type.$enum[randomNumber(true, 0, type.$enum.length - 1)] }
 
  if (isObj(type)) {
    return Object.entries(type).reduce((prev: any, [key, value]) => {
      const generated = gen(value, true)
      const keyC = key.startsWith('\\$') ? key.slice(1) : key
      if (typeof generated !== 'undefined') prev[keyC] = generated
      return prev
    }, {})
  }
 
  if (isMap(type)) {
    const mapType = type
    const min = typeof mapType.minLength === 'number' ? mapType.minLength : options.mapMin
    const max = typeof mapType.maxLength === 'number' ? mapType.maxLength : options.mapMax
    if (depth >= options.maxDepthSoft && (mapType.minLength || 0) <= 0) return {}
    const count = randomNumber(true, min, max)
    return Array.from(Array(count))
      .reduce((prev: any) => {
        const str = mapType.regex ? randexp.randexp(mapType.regex) : simpleGeneration('string', options)
        prev[str] = gen(mapType.$map, true)
        return prev
      }, {})
  }
 
  if (isNumber(type)) {
    return randomNumber(
      false,
      type.$number.min == null ? options.minNumber : type.$number.min,
      type.$number.max == null ? options.maxNumber : type.$number.max)
  }
 
  if (isMeta(type)) { return gen(type.$type) }
 
  if (isString(type)) {
    if (type.$string.regex) { return randexp.randexp(type.$string.regex) }
 
    return randomString(type.$string.minLength || type.$string.maxLength || 6)
  }
 
  if (isAnd(type)) {
    const combined = combineValidationObjects(type, customTypes, (x) => x)
    if (combined.result === 'error') {
      throw new Error('Schema error, $and types must be objects: ' + JSON.stringify(combined.error, null, 2))
    }
 
    return gen(combined.pass)
  }
 
  throw new Error('Unknown type')
}