All files errorFormatter.js

96.66% Statements 116/120
95.65% Branches 66/69
100% Functions 16/16
96.63% Lines 115/119

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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415    1x 1x 1x                   134025x 1x 1x     134025x                       129723x   129723x   129723x 134025x   134025x 8728x     134025x 129336x   129336x             129723x   129723x     129723x                           129723x           129723x   129336x     129336x 129116x     220x 287x 164x             287x     220x       129723x                       129887x   129887x 129887x 164x   129887x   129887x       129887x                         164x                               129723x                               1042x                                     1x           1x                                   134025x   134025x 132054x 465461x   457265x     66x       8130x         1971x                         8130x   4906x     3224x 1671x     1671x 363x 1308x 42x   1266x     1671x     1553x                       260271x               260271x 463480x 463479x       260271x                             260274x   260274x 3x     260271x   1x 1x     129724x 129724x 129724x     1x 1x 1x     1042x 1042x     73322x 73322x 73322x     4x 4x     13x 13x     16x 16x     12x 12x     65x 65x     164x 164x 164x               25549x 25549x     9x 9x     30299x 30299x     1x 1x     34x 34x     10x 10x       5x 19x 3x     5x       260271x     260271x                 1x  
'use strict';
 
const { convertArrayToKnownTypedList, isString, isKey, isZid, wrapInZ6, wrapInZ9, wrapInKeyReference, wrapInQuote } = require( './utils.js' );
const { dataDir, readYaml } = require( './fileUtils.js' );
const errorTypes = require( './error.js' );
 
class ErrorFormatter {
 
	/**
	 * Read and parse the yaml file with the error type descriptors
	 *
	 * @return {Array}
	 */
	static get errorDescriptors() {
		if ( !this._errorDescriptors ) {
			const descriptorPath = dataDir( 'errors', 'error_types.yaml' );
			this._errorDescriptors = readYaml( descriptorPath ).patterns.keywords;
		}
 
		return this._errorDescriptors;
	}
 
	/**
	 * Root function to transform an array of Ajv error objects to a root Z5
	 * object with all the nested errors identified by the builtin
	 * ZErrorTypes (Z50).
	 *
	 * @param {Array} errors
	 * @return {Object}
	 */
	static createRootZError( errors ) {
		const Z5s = [];
		// descriptors found for parser errors
		const descriptors = [];
 
		for ( const error of errors ) {
			const descriptor = this.matchDescriptor( error );
			// Ajv returns duplicates, so we need to check for them and ignore
			const isDuplicate = descriptors.find(
				( d ) => d.path === error.instancePath && d.descriptor === descriptor
			);
 
			if ( descriptor && !isDuplicate ) {
				descriptors.push( { path: error.instancePath, descriptor } );
 
				Z5s.push( [
					error,
					this.createZErrorInstance( descriptor.errorType, error )
				] );
			}
		}
 
		const errorTree = this.buildErrorTree( Z5s );
 
		Iif ( errorTree.children.length === 0 && errorTree.errors.length === 0 ) {
			return null;
		} else {
			return this.getZObjectFromErrorTree( errorTree );
		}
	}
 
	/**
	 * Builds a tree of errors from a list of Z5s. Each node indicates where the
	 * errors ocurred in the data object. Each Z5 is associated with one of the
	 * nodes. Z5s can be associated to nodes that are not leaves. The function
	 * returns the root object of the tree.
	 *
	 * @param {Array} Z5s
	 * @return {Object}
	 */
	static buildErrorTree( Z5s ) {
		const root = {
			key: 'root',
			children: {},
			errors: []
		};
 
		for ( const [ parserError, Z5 ] of Z5s ) {
			// only ZnKn are considered as part of the path
			const path = parserError.instancePath.match( /\bZ\d+K\d+\b/g );
 
			// no path means it's a root error
			if ( !path || path.length === 0 ) {
				root.errors.push( Z5 );
			} else {
				// find the leaf node based on the path creating intermediary nodes if required
				const leaf = path.reduce( ( node, key ) => {
					if ( !node.children[ key ] ) {
						node.children[ key ] = {
							key,
							children: {},
							errors: []
						};
					}
 
					return node.children[ key ];
				}, root );
 
				leaf.errors.push( Z5 );
			}
		}
 
		return root;
	}
 
	/**
	 * Transforms a tree of errors in a single Z5 object. Z5s are aggregated
	 * into multiple errors/Z509 and non-leaf nodes wrap those errors in not
	 * wellformed/Z526.
	 *
	 * @param {Object} root
	 * @return {Object}
	 */
	static getZObjectFromErrorTree( root ) {
		const children = Object.values( root.children );
 
		const childrenErrors = [];
		for ( const child of children ) {
			childrenErrors.push( this.getZObjectFromErrorTree( child ) );
		}
		childrenErrors.push( ...root.errors );
 
		const aggregatedZ5 = childrenErrors.length === 1 ?
			childrenErrors[ 0 ] :
			this.createZErrorList( childrenErrors );
 
		return root.key === 'root' ?
			this.createValidationZError( aggregatedZ5 ) :
			this.createZKeyError( root.key, aggregatedZ5 );
	}
 
	/**
	 * Create a ZError (Z5) of the type "Key not wellformed" (Z526)
	 *
	 * @param {string} key
	 * @param {Object} Z5
	 * @return {Object}
	 */
	static createZKeyError( key, Z5 ) {
		return this.createZErrorInstance(
			errorTypes.error.not_wellformed_value,
			{
				key: key,
				value: Z5
			}
		);
	}
 
	/**
	 * Create a ZError (Z5) of the type "Not wellformed" (Z502)
	 *
	 * @param {Object} Z5
	 * @return {Object}
	 */
	static createValidationZError( Z5 ) {
		return this.createZErrorInstance(
			errorTypes.error.not_wellformed,
			{
				subtype: Z5.Z5K1,
				value: Z5
			}
		);
	}
 
	/**
	 * Create a ZError (Z5) of the type "Multiple errors" (Z509)
	 *
	 * @param {*} array
	 * @return {Object|null}
	 */
	static createZErrorList( array ) {
		return this.createZErrorInstance(
			errorTypes.error.list_of_errors,
			{
				list: convertArrayToKnownTypedList( array, 'Z5' )
			}
		);
	}
 
	/**
	 * Wrap an error message in a Z5/Error of type Z507/'Error in evaluation'.
	 * Typically, the message will come from a caught error (an ordinary error,
	 * not a ZError).
	 *
	 * @param {string} message
	 * @param {Object} call the Z7/'Function call' being evaluated when the error arose,
	 * quoted as Z99
	 * @return {Object} a Z5/Error object
	 */
	static wrapMessageInEvaluationError( message, call ) {
		const wrappedError = this.createZErrorInstance(
			errorTypes.error.unknown_error,
			{
				errorInformation: message
			}
		);
		return this.createZErrorInstance(
			errorTypes.error.error_in_evaluation,
			{
				functionCall: call,
				propagatedError: wrappedError
			}
		);
	}
 
	/**
	 * Matches an Ajv parser error to one of the error descriptors in
	 * Wikifunctions. When no descriptor is found for an error, the
	 * function returns null.
	 *
	 * @param {Object} err
	 * @return {Object|null}
	 */
	static matchDescriptor( err ) {
		const candidates = this.errorDescriptors[ err.keyword ];
 
		if ( candidates ) {
			return candidates.find( ( descriptor ) => {
				switch ( err.keyword ) {
					case 'required':
						return !descriptor.keywordArgs.missing ||
							descriptor.keywordArgs.missing === err.params.missingProperty;
					case 'additionalProperties':
						return true;
					case 'type':
					case 'pattern':
					default:
						return this.matchTypeDescriptor( descriptor, err );
				}
			} );
		}
 
		return null;
	}
 
	/**
	 * Evaluates whether a error descriptor matches the given Ajv parser error of
	 * the "type" kind.
	 *
	 * @param {Object} descriptor
	 * @param {Object} err
	 * @return {boolean}
	 */
	static matchTypeDescriptor( descriptor, err ) {
		// if dataPointer is specified but not found in the actual data path
		if ( descriptor.dataPointer.length > 0 &&
			!err.instancePath.endsWith( descriptor.dataPointer[ 0 ] ) ) {
			return false;
		}
 
		if ( descriptor.keywordArgs.used ) {
			const dataType = typeof err.data;
			let expandedType;
 
			if ( Array.isArray( err.data ) ) {
				expandedType = 'array';
			} else if ( err.data === null ) {
				expandedType = 'null';
			} else {
				expandedType = dataType;
			}
 
			return descriptor.keywordArgs.used.includes( expandedType );
		}
 
		return descriptor.keywordArgs.expected === err.params.type;
	}
 
	/**
	 * Creates an instance of a typed error given its errorType and an array
	 * with the values of its keys.
	 *
	 * @param {string} errorType
	 * @param {Object} errorKeys
	 * @return {Object}
	 */
	static createTypedError( errorType, errorKeys ) {
		const typedError = {
			Z1K1: {
				Z1K1: wrapInZ9( 'Z7' ),
				Z7K1: wrapInZ9( 'Z885' ),
				Z885K1: wrapInZ9( errorType )
			}
		};
 
		for ( let index = 0; index < errorKeys.length; index++ ) {
			if ( errorKeys[ index ] ) {
				typedError[ `${ errorType }K${ index + 1 }` ] = errorKeys[ index ];
			}
		}
 
		return typedError;
	}
 
	/**
	 * Create a ZError (Z5) of a given ZErrorType
	 *
	 * N.B. Before adding an errorType in the switch statement, check whether that errorType is used
	 * in error_types.yaml, and whether your addition will affect the result of createRootZError.
	 *
	 * @param {string} errorType
	 * @param {Object} err
	 * @return {Object}
	 * @throws Will throw an error if the error type is not valid
	 */
	static createZErrorInstance( errorType, err = {} ) {
		const errorKeys = [];
 
		if ( !isString( errorType ) || !isZid( errorType ) ) {
			throw new Error( `Invalid error type: ${ errorType }` );
		}
 
		switch ( errorType ) {
			case errorTypes.error.unknown_error:
				errorKeys.push( err.errorInformation );
				break;
 
			case errorTypes.error.not_wellformed:
				errorKeys.push( err.subtype );
				errorKeys.push( err.value );
				break;
 
			case errorTypes.error.error_in_evaluation:
				errorKeys.push( wrapInQuote( err.functionCall ) );
				errorKeys.push( err.propagatedError );
				break;
 
			case errorTypes.error.list_of_errors:
				errorKeys.push( err.list );
				break;
 
			case errorTypes.error.key_not_found:
				errorKeys.push( wrapInKeyReference( err.params.missingProperty ) );
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.resolved_object_without_z2k2:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.zobject_must_not_be_number_or_boolean_or_null:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.missing_type:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.z1k1_must_not_be_string_or_array:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.invalid_key:
				errorKeys.push( wrapInZ6( err.params.additionalProperty ) );
				break;
 
			case errorTypes.error.not_wellformed_value:
				errorKeys.push( wrapInKeyReference( err.key ) );
				errorKeys.push( err.value );
				break;
 
			case errorTypes.error.unable_to_canonicalize:
				errorKeys.push( wrapInQuote( err.zobject ) );
				errorKeys.push( err.propagatedError );
				break;
 
			case errorTypes.error.z6_without_z6k1:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.z6k1_must_be_string:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.z9_without_z9k1:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.z9k1_must_be_string:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			case errorTypes.error.invalid_zreference:
				errorKeys.push( wrapInZ6( err.data ) );
				break;
 
			case errorTypes.error.disallowed_root_object:
				errorKeys.push( wrapInQuote( err.data ) );
				break;
 
			default:
				// Unknown error
				Object.keys( err ).forEach( ( key ) => {
					if ( isKey( key ) ) {
						errorKeys.push( err[ key ] );
					}
				} );
				break;
		}
 
		// Create a typed error instance with errorType->error
		const typedError = this.createTypedError( errorType, errorKeys );
 
		// Create error Z5
		return {
			Z1K1: wrapInZ9( 'Z5' ),
			Z5K1: wrapInZ9( errorType ),
			Z5K2: typedError
		};
	}
 
}
 
module.exports = ErrorFormatter;