All files / ext.wikilambda.edit/mixins schemata.js

91.12% Statements 113/124
88.18% Branches 112/127
95% Functions 19/20
90.98% Lines 111/122

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                      38x 38x       38x 38x     4051x   4051x 933x 933x 119x   814x     3118x 3118x 3083x     35x       331x 765x                                                 7040x   7040x 4x 7036x 563x 6473x 899x 1927x   5574x     4051x 1523x           1523x 331x         1523x 4878x     7036x       60x       131x                       618x     618x 2x 616x 358x 280x         78x         258x 75x 136x     183x 183x 512x   38x 38x   474x 7x       7x   467x 20x 20x   447x 18x 18x   429x     616x                         40x   40x 114x   114x 114x               6x                         205x   76x 198x 198x                       7x   7x 1x     7x 198x 98x       7x                                       36x     1x 1x 1x 1x 1x 1x   1x 35x     10x 10x 10x 10x 10x     10x           38x                                       36x 36x 11x   1x 10x   6x   4x   11x   25x                               38x                                       29x 29x 17x   17x   50x   33x       29x     38x                  
/**
 * WikiLambda Vue editor: schemata mixin
 * Mixin with functions to canonicalize and normalize ZObjects.
 * This is distinct from the function-schemata as the UI
 * relies of slightly different requirements for normalization.
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
'use strict';
 
var Constants = require( '../Constants.js' ),
	typeUtils = require( './typeUtils.js' ).methods;
 
// Note: This is intentionally "wrong" in that it allows for Z0.
// It excludes letters so as not to apply to keys (containing a 'K').
const referenceRe = /^Z0*[1-9]*\d*$/;
const errorTypeReferenceRe = /^Z5\d{2}$/;
 
function canonicalizeZ6OrZ9( zobject ) {
	var objectType = zobject[ Constants.Z_OBJECT_TYPE ];
 
	if ( objectType === Constants.Z_STRING ) {
		var Z6 = zobject[ Constants.Z_STRING_VALUE ];
		if ( Z6 && typeof Z6.match === 'function' && Z6.match( referenceRe ) ) {
			return zobject;
		}
		return Z6 || '';
	}
 
	var Z9 = zobject[ Constants.Z_REFERENCE_ID ];
	if ( Z9 && typeof Z9.match === 'function' && Z9.match( referenceRe ) ) {
		return Z9;
	}
 
	return '';
}
 
function filterUndefinedLabels( allLabels ) {
	return allLabels.filter( function ( label ) {
		return label[ Constants.Z_OBJECT_TYPE ] !== Constants.Z_MONOLINGUALSTRING ||
		!!label[ Constants.Z_MONOLINGUALSTRING_VALUE ];
	} );
}
 
function canonicalize( zobject ) {
	function listifyArray( zlist, arr ) {
		var head = zlist[ Constants.Z_TYPED_OBJECT_ELEMENT_1 ],
			tail = zlist[ Constants.Z_TYPED_OBJECT_ELEMENT_2 ];
 
		if ( typeof arr === 'undefined' ) {
			arr = [];
		}
 
		if ( head ) {
			arr.push( canonicalize( head ) );
		}
 
		if ( tail ) {
			return listifyArray( tail, arr );
		} else {
			return arr;
		}
	}
 
	var canon = {};
 
	if ( typeof zobject === 'undefined' ) {
		return undefined;
	} else if ( typeof zobject === 'string' ) {
		canon = zobject;
	} else if ( Array.isArray( zobject ) ) {
		canon = zobject.map( function ( element ) {
			return canonicalize( element );
		} );
	} else if (
		[ Constants.Z_REFERENCE, Constants.Z_STRING ].indexOf( zobject[ Constants.Z_OBJECT_TYPE ] ) > -1
	) {
		canon = canonicalizeZ6OrZ9( zobject );
	} else Iif ( zobject[ Constants.Z_OBJECT_TYPE ] &&
		zobject[ Constants.Z_OBJECT_TYPE ][ Constants.Z_REFERENCE_ID ] === Constants.Z_TYPED_LIST
	) {
		canon = canonicalize( listifyArray( zobject ) );
	} else {
		// remove any 'undefined' labels
		if ( zobject[ Constants.Z_MULTILINGUALSTRING_VALUE ] ) {
			zobject[ Constants.Z_MULTILINGUALSTRING_VALUE ] = filterUndefinedLabels(
				zobject[ Constants.Z_MULTILINGUALSTRING_VALUE ]
			);
		}
 
		Object.keys( zobject ).forEach( function ( key ) {
			canon[ key ] = canonicalize( zobject[ key ] );
		} );
	}
	return canon;
}
 
function isString( s ) {
	return typeof s === 'string' || s instanceof String;
}
 
function isZid( k ) {
	return k.match( /^Z[1-9]\d*$/ ) !== null;
}
 
/**
 * Return the ZObject in semi-normalized form. This means that the strings
 * and references will be normalized, but a canonical list will still be
 * left as a canonical list. This has also been referred to as Hybrid form
 *
 * @param {Object | Array | string} zobject
 * @return {Object|Array|undefined}
 */
function normalize( zobject ) {
	var normal = {},
		keys;
 
	if ( typeof zobject === 'undefined' ) {
		return undefined;
	} else if ( typeof zobject === 'string' ) {
		if ( typeUtils.getZObjectType( zobject ) === Constants.Z_REFERENCE ) {
			normal = {
				Z1K1: Constants.Z_REFERENCE,
				Z9K1: zobject
			};
		} else {
			normal = {
				Z1K1: Constants.Z_STRING,
				Z6K1: zobject
			};
		}
	} else if ( Array.isArray( zobject ) ) {
		normal = zobject.map( function ( element ) {
			return normalize( element );
		} );
	} else {
		keys = Object.keys( zobject );
		for ( var i = 0; i < keys.length; i++ ) {
			if ( keys[ i ] === Constants.Z_OBJECT_TYPE && (
				zobject.Z1K1 === Constants.Z_STRING || zobject.Z1K1 === Constants.Z_REFERENCE ) ) {
				normal.Z1K1 = zobject.Z1K1;
				continue;
			}
			if ( keys[ i ] === Constants.Z_PERSISTENTOBJECT_ID && isString( zobject.Z2K1 ) ) {
				normal.Z2K1 = {
					Z1K1: Constants.Z_STRING,
					Z6K1: zobject.Z2K1
				};
				continue;
			}
			if ( keys[ i ] === Constants.Z_STRING_VALUE && isString( zobject.Z6K1 ) ) {
				normal.Z6K1 = zobject.Z6K1;
				continue;
			}
			if ( keys[ i ] === Constants.Z_REFERENCE_ID && isString( zobject.Z9K1 ) ) {
				normal.Z9K1 = zobject.Z9K1;
				continue;
			}
			normal[ keys[ i ] ] = normalize( zobject[ keys[ i ] ] );
		}
	}
	return normal;
}
 
/**
 * Return the ZMap value corresponding to the given key, if present.
 * TODO (T302015) When ZMap keys are extended beyond Z6/Z39, update accordingly
 *
 * @param {Object} zMap a Z883/Typed map, in canonical form
 * @param {Object} key a Z6 or Z39 instance, in canonical form
 * @return {Object|undefined} a Z1/Object, the value of the map entry with the given key,
 * or undefined if there is no such entry
 */
function getValueFromCanonicalZMap( zMap, key ) {
	const K1Array = zMap[ Constants.Z_TYPED_OBJECT_ELEMENT_1 ];
	// Ignore first item in the canonical form array; this is a string representing the type
	for ( let i = 1; i < K1Array.length; i++ ) {
		const entry = K1Array[ i ];
		// To accommodate our current programming practices, we need to allow for either key here:
		const currentKey = entry[ Constants.Z_TYPED_OBJECT_ELEMENT_1 ] || entry[ Constants.Z_TYPED_PAIR_TYPE1 ];
		if ( ( currentKey === key ) ||
			( currentKey[ Constants.Z_OBJECT_TYPE ] === Constants.Z_STRING &&
				key[ Constants.Z_OBJECT_TYPE ] === Constants.Z_STRING &&
				currentKey[ Constants.Z_STRING_VALUE ] === key[ Constants.Z_STRING_VALUE ] ) ||
			( currentKey[ Constants.Z_OBJECT_TYPE ] === Constants.Z_KEY_REFERENCE &&
				key[ Constants.Z_OBJECT_TYPE ] === Constants.Z_KEY_REFERENCE &&
				currentKey[ Constants.Z_KEY_REFERENCE_ID ] === key[ Constants.Z_KEY_REFERENCE_ID ] ) ) {
			// To accommodate our current programming practices, we need to allow for either key here:
			return entry[ Constants.Z_TYPED_OBJECT_ELEMENT_2 ] || entry[ Constants.Z_TYPED_PAIR_TYPE2 ];
		}
	}
}
 
/**
 * Traverses a ZObject calling the provided callback function for every
 * <key, value> pair. This a depth-first procedure.
 *
 * @param {Object} zobject
 * @param {Function} callback
 */
function traverse( zobject, callback ) {
	if ( zobject !== null && typeof zobject === 'object' ) {
		// eslint-disable-next-line es/no-object-entries
		Object.entries( zobject ).forEach( ( [ key, value ] ) => {
			callback( key, value );
			traverse( value, callback );
		} );
	}
}
 
/**
 * Finds all of the ZIDs appearing in an arbitrary ZObject.
 *
 * @param {Object|string} zobject a Z1/Object
 * @return {Set} Set of (string) ZIDs
 */
function extractZIDs( zobject ) {
	const found = new Set( [] );
	// Handle the case of a lone canonical reference
	if ( typeof zobject === 'string' && isZid( zobject ) ) {
		found.add( zobject );
	}
 
	traverse( zobject, ( _key, value ) => {
		if ( typeof value === 'string' && isZid( value ) ) {
			found.add( value );
		}
	} );
 
	return found;
}
 
/**
 * Checks if a given zobject is a suberror (a zobject whose type is an instance of Z50/'Error type').
 * If so, returns a JS object with keys errorType and (optionally) explanation.  If not, returns null.
 *
 * The 'explanation' is an explanatory string for this suberror.
 * Such strings are expected for Z500, but are also generated in the orchestrator for
 * some other error types. In addition to explanatory strings, a few other useful keys
 * with string values will show up here, e.g. Z503K1/'feature name' and Z504K1/ZID.
 *
 * Allows for the more relaxed Z5/Error format from the orchestrator, in which the suberror's
 * type appears directly as the value of Z1K1/type, and also the stricter format, in which
 * it appears in a function call to Z885/'Errortype to type'.  Z885K1 is the 'errortype' key of Z885.
 *
 * @param {Object} zobject
 * @return {Array} of objects
 */
function checkIfSuberror( zobject ) {
	if ( typeof zobject === 'object' && zobject.Z1K1 && typeof zobject.Z1K1 === 'string' &&
		zobject.Z1K1.match( errorTypeReferenceRe ) ) {
		// Handle the relaxed Z5/Error format from the orchestrator
		const suberror = {};
		suberror.errorType = zobject.Z1K1;
		const stringKey = suberror.errorType + 'K1';
		const k1String = zobject[ stringKey ];
		if ( k1String && isString( k1String ) && !isZid( k1String ) ) {
			suberror.explanation = k1String;
		}
		return suberror;
	} else if ( typeof zobject === 'object' && zobject.Z1K1 && typeof zobject.Z1K1 === 'object' &&
		zobject.Z1K1.Z885K1 && typeof zobject.Z1K1.Z885K1 === 'string' &&
		zobject.Z1K1.Z885K1.match( errorTypeReferenceRe ) ) {
		const suberror = {};
		suberror.errorType = zobject.Z1K1.Z885K1;
		const stringKey = 'K1';
		const k1String = zobject[ stringKey ];
		Iif ( k1String && isString( k1String ) && !isZid( k1String ) ) {
			suberror.explanation = k1String;
		}
		return suberror;
	}
}
 
// These error types have no keys whose values contain nested error content.  If a error type ZID
// appears here, extractErrorStructure will not search through any children of a zobject of that type.
const errorTypesNotToTraverse = new Set( [ 'Z501', 'Z505', 'Z508', 'Z511', 'Z512', 'Z513', 'Z516',
	'Z531', 'Z532', 'Z533', 'Z534', 'Z535', 'Z536', 'Z537', 'Z542', 'Z547', 'Z548', 'Z551', 'Z553' ] );
 
/**
 * Traverses a ZObject to find all the suberrors.  (A suberror is a zobject
 * whose type is an instance of Z50/'Error type'). Example:
 *   { Z1K1: 'Z500', Z500K1: 'Could not find argument Z811K1' }
 * For each suberror found, the result includes a JS object with properties
 * 'errorType', 'children', and (optionally) 'explanation'.  Example:
 *   { errorType: 'Z500', explanation: 'Could not find argument Z811K1', children: [] }
 *
 * The 'children', if any, are additional suberrors found within the nested ZObjects of
 * this suberror.
 *
 * zobject is normally a Z5 in the top level call, but doesn't have to be.
 *
 * @param {Object} zobject
 * @return {Array} of objects
 */
function extractErrorStructure( zobject ) {
	const subError = checkIfSuberror( zobject );
	if ( subError ) {
		if ( subError.explanation ) {
			// In this special case, there won't be any nested suberrors; look no further
			subError.children = [];
		} else if ( errorTypesNotToTraverse.has( subError.errorType ) ) {
			// Also in this case, there won't be any nested suberrors; look no further
			subError.children = [];
		} else {
			subError.children = extractNestedSuberrors( zobject, subError.errorType );
		}
		return [ subError ];
	}
	return extractNestedSuberrors( zobject, null );
}
 
/**
 * For each suberror type, these are its keys whose values should be included
 * in the traversal conducted by extractNestedSuberrors(), because
 * they may contain nested error content.  We include both local and global
 * forms of the keys, to make sure all currently generated errors are covered.
 *
 * If a suberror type isn't listed here, *all* of its keys' values will be traversed.
 * It is not necessary for each suberror type to appear here, but if one does,
 * it should *not* appear in errorTypesNotToTraverse.
 *
 * New error types will be handled without updating this map or errorTypesNotToTraverse
 * (albeit not necessarily optimally).
 */
const errorKeysToTraverse = new Map( [
	[ 'Z502', new Set( [ 'Z502K2', 'K2' ] ) ], // Not wellformed, [value]
	[ 'Z506', new Set( [ 'Z506K4', 'K4' ] ) ], // Argument type mismatch, [propagated error]
	[ 'Z507', new Set( [ 'Z507K2', 'K2' ] ) ], // Error in evaluation, [propagated error]
	[ 'Z517', new Set( [ 'Z517K4', 'K4' ] ) ], // Return type mismatch, [propagated error]
	[ 'Z518', new Set( [ 'Z518K3', 'K3' ] ) ] // Object type mismatch, [propagated error]
] );
 
/**
 * Finds all suberrors in the children objects of the given zobject, as described for
 * extractErrorStructure().  In that function we check whether the top-level
 * object is a suberror; here we look at the children objects.
 *
 * Special-purpose function; only meant to be called from extractErrorStructure().
 *
 * @param {Object} zobject
 * @param {string|null} errorType
 * @return {Array} of objects
 */
function extractNestedSuberrors( zobject, errorType ) {
	var nested = [];
	if ( zobject !== null && typeof zobject === 'object' ) {
		const keysToTraverse = errorKeysToTraverse.get( errorType );
		// eslint-disable-next-line es/no-object-entries
		Object.entries( zobject ).forEach( ( [ key, value ] ) => {
			// We've already looked inside Z1K1/type; no need to look again
			if ( key !== Constants.Z_OBJECT_TYPE &&
				( keysToTraverse === undefined || keysToTraverse.has( key ) ) ) {
				nested.push( ...extractErrorStructure( value ) );
			}
		} );
	}
	return nested;
}
 
module.exports = exports = {
	methods: {
		canonicalizeZObject: canonicalize,
		normalizeZObject: normalize,
		getValueFromCanonicalZMap: getValueFromCanonicalZMap,
		extractErrorStructure: extractErrorStructure,
		extractZIDs: extractZIDs
	}
};