'use strict'; const xml2js = require('xml2js'); const stripNS = xml2js.processors.stripPrefix; const parser = new xml2js.Parser({ tagNameProcessors: [stripNS], // xmlns: true, explicitChildren: true, }); const parseXML = input => parser.parseStringPromise(input); function childAttr(obj, key, errorCode = 452) { const value = obj[key]; if (value === undefined || value.length === 0) { return undefined; } if (value.length !== 1) { const error = new Error(`Invalid attribute: ${key}`); error.errorCode = errorCode; throw error; } if (value[0]['$'] && value[0]['_']) { return value[0]['_']; } return value[0]; } function boolean(input, errorCode = 452) { const trimmed = (input || '').toLowerCase().trim(); if (trimmed === '') { return undefined; } else if (trimmed === 'true' || trimmed === '1') { return true; } else if (trimmed === 'false' || trimmed === '0') { return false; } const error = new Error(`Not a boolean: ${input}`); error.errorCode = errorCode; throw error; } function dateTime(input, key, errorCode = 452) { if (input) { if (input['$$']) { return childAttr(input['$$'], key, errorCode); } throw new Error(`unknown dateTime: ${input}`); } } function duration(input, key, errorCode = 452) { if (input) { if (input['$$']) { return childAttr(input['$$'], key, errorCode); } throw new Error(`unknown duration: ${input}`); } } function number(input, errorCode = 452) { const trimmed = (input || '').toLowerCase().trim(); const parsed = Number(trimmed); if (trimmed === '') { return undefined; } else if (isNaN(parsed)) { const error = new Error(`Not a number: ${input}`); error.errorCode = errorCode; throw error; } else { return parsed; } } function required(input, key, errorCode = 452) { if (input == null) { const error = new Error(`Missing required value: ${key}`); error.errorCode = errorCode; throw error; } return input; } module.exports = { parseXML, childAttr, dateTime, duration, boolean, required, number, };