All files / src index.ts

93.75% Statements 60/64
83.33% Branches 30/36
91.66% Functions 11/12
95% Lines 57/60

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                                                                                            5x 5x 5x       32x   32x 32x 32x           32x 32x 32x 32x   32x 32x   32x   32x         32x   32x 32x 2x       32x       32x 32x               32x       32x   32x       32x                 32x         32x   32x   2x   2x 2x     2x       32x         32x   32x   7x   7x 8x     7x       32x         32x   32x   3x   3x 3x     3x       32x 32x 32x     32x     32x   32x     32x     32x     32x   32x        
import { parseStringPromise } from 'xml2js'
import xmllint from 'xmllint'
 
import schema from './schema'
import packageJson from '../package.json'
 
import {
    Template,
    Root,
    Person as PersonElement,
    Location as LocationElement,
} from './elements'
 
import {
    NumberGenerator,
    TextGenerator,
    PersonGenerator,
    LocationGenerator
} from './generators'
 
import { 
    resolveInlineTags,
    resolveTemplateRefs,
    loopExpander,
    textTagSampler,
    resolvePeopleRefs,
    resolveLocationRefs
} from './preprocessor'
 
 
export type LoreMLOptions = {
    seed?: number
    locale?: string
    debug?: boolean
}
 
export type ParseOptions = {
    validate?: boolean
}
 
export default class LoreML {
    private seed: number
    private locale: string
    private debug: boolean
 
    constructor(opts?: LoreMLOptions) {
        this.seed = opts?.seed ?? Date.now() ^ (Math.random() * 0x100000000)
        this.locale = opts?.locale ?? 'en'
        this.debug = opts?.debug ?? false
    }
 
    public async parse(xml: string, opts?: ParseOptions): Promise<string> {
        const validate = opts?.validate ?? true
 
        Eif (validate) {
            const validation = this.validate(xml)
            Iif (!validation.isValid) {
                validation.errors.forEach(err => console.error(err))
                return ''
            }
        }
 
        const rootAttributes = await this.loadRootAttributes(xml)
        const seed = rootAttributes.seed !== undefined ? rootAttributes.seed : this.seed
        const locale = rootAttributes.locale ?? this.locale
        const debug = rootAttributes.debug ?? this.debug
 
        const rng = new NumberGenerator(seed)
        const rtg = new TextGenerator({ seed, locale })
 
        const preProcessedXml = await this.preProcess(rng, rtg, xml)
 
        const parsed = await parseStringPromise(preProcessedXml, {
            explicitArray: false,
            preserveChildrenOrder: true,
        })
 
        const root = new Root(parsed.Root)
 
        let debugHeader = ''
        if (debug) {
            debugHeader = `--------------------- DEBUG INFO ---------------------\nversion: ${packageJson.version} | seed: ${seed} | locale: ${locale}\n-------------------------------------------------------\n\n`
        }
 
 
        return debugHeader + root.toString()
    }
 
    public validate(xml: string): { isValid: boolean, errors: string[] } {
        const errors: string[] = xmllint.validateXML({xml, schema })?.errors ?? []
        return {
            isValid: errors.length === 0,
            errors
        }
    }
 
    // gets the attributes from the Root element
    private async loadRootAttributes(xml: string) {
        const parsed = await parseStringPromise(xml, {
            explicitArray: false,
        })
 
        const root = new Root(parsed.Root) as Root
 
        Iif (!root) {
            throw new Error('Root element not found')
        }
 
        return {
            seed: root?.seed,
            locale: root?.locale,
            debug: root?.debug,
        }
        
    }
 
    private async loadTemplates(xml: string): Promise<Record<string, Template> | undefined> {
        const parsed = await parseStringPromise(xml, {
            explicitArray: false,
            preserveChildrenOrder: true,
        })
 
        const templates = parsed.Root.Template as Template | Template[] | undefined
        
        if (!templates) { return }
 
        const acc: Record<string, Template> = {};
 
        (Array.isArray(templates) ? templates : [templates]).forEach((tmpl) => {
            acc[tmpl.$.name] = new Template(tmpl)
        })
 
        return acc
    }
 
    private async loadPeople(rtg: TextGenerator, xml: string): Promise<Record<string, PersonGenerator> | undefined> {
        const parsed = await parseStringPromise(xml, {
            explicitArray: false,
            preserveChildrenOrder: true,
        })
 
        const people = parsed.Root.Person as PersonElement | PersonElement[] | undefined
 
        if (!people) { return }
 
        const acc: Record<string, PersonGenerator> = {};
 
        (Array.isArray(people) ? people : [people]).forEach((person) => {
            acc[person.$.ref] = new PersonGenerator(rtg.generator, person.$)
        })
 
        return acc
    }
 
    private async loadLocations(rtg: TextGenerator, xml: string): Promise<Record<string, LocationGenerator> | undefined> {
        const parsed = await parseStringPromise(xml, {
            explicitArray: false,
            preserveChildrenOrder: true,
        })
 
        const locations = parsed.Root.Location as LocationElement | LocationElement[] | undefined
 
        if (!locations) { return }
 
        const acc: Record<string, LocationGenerator> = {};
 
        (Array.isArray(locations) ? locations : [locations]).forEach( location => {
            acc[location.$.ref] = new LocationGenerator(rtg.generator)
        })
 
        return acc
    }
 
    private async preProcess(rng: NumberGenerator, rtg: TextGenerator, xml: string): Promise<string> {
        const templates = await this.loadTemplates(xml)
        const people = await this.loadPeople(rtg, xml)
        const locations = await this.loadLocations(rtg, xml)
 
        // 1. expand loops
        const expanded = loopExpander(xml)
        
        // 2. resolve person references
        const resolvedPeople = resolvePeopleRefs(expanded, people)
 
        const resolvedLocations = resolveLocationRefs(resolvedPeople, locations)
 
        // 3. resolve inline expressions
        const inlined = resolveInlineTags(resolvedLocations, rng, rtg)
 
        // 4. resolve template references
        const resolvedTemplates = resolveTemplateRefs(inlined, templates)
 
        // 5. Apply random sampling
        const sampled = textTagSampler(rng, resolvedTemplates)
 
        return sampled
    }
 
}