All files utils.js

96.03% Statements 145/151
93% Branches 93/100
100% Functions 21/21
96.03% Lines 145/151

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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486    1x           1x                             1x 1x   1x 1x 1x                     6x                         730x                       1983x   1983x 4x   1983x             1977x 1977x 1977x     1977x 2x   1975x 1899x     1899x   76x 76x 76x                     239x 239x   15x                       24414x 24414x 24414x   24414x 24412x 24412x   2x   24414x 22196x   2218x 2218x 6598x 2218x   4380x       2218x             5765x 5765x 5765x 38x   5727x 5727x 4292x   1435x                   81534x 81534x 73262x 67664x       5598x   8272x 4039x     4233x 4233x   4206x 27x 27x 27x                                 218x 218x             56x 56x 2x   54x           56x 20x 1x   19x           36x 1x   35x             56x         3x                                                                         7497x 7497x 1845x   5652x 5652x 7246x 7246x   5652x                                     1198x 1198x 1915x       22x   1893x 1x   1893x 1893x 1893x 904x   1893x 3559x   1893x   1198x       732x 732x                             51268x 51268x                 10x 10x 10x   10x 10x   7x 7x                 7x               7x             7x                 10x 10x       10x 10x 10x 10x 1x 9x 8x   10x 9x 9x 9x   10x       2175x 2003x   172x 91x   81x                   2094x 2094x 2003x   91x       272x 272x 47x   272x       242x 242x     242x     1x                                            
'use strict';
 
const normalize = require( '../function-schemata/javascript/src/normalize.js' );
const {
	SchemaFactory,
	validatesAsZObject,
	validatesAsFunctionCall,
	validatesAsReference
} = require( '../function-schemata/javascript/src/schema.js' );
const {
	createZObjectKey,
	findFunctionIdentity,
	findTypeIdentity,
	isUserDefined,
	getHead,
	getTail,
	makeMappedResultEnvelope,
	isString,
	isVoid,
	isZMap,
	isZReference,
	makeTrue,
	getZMapValue
} = require( '../function-schemata/javascript/src/utils.js' );
const { EmptyFrame } = require( './frame.js' );
 
const normalFactory = SchemaFactory.NORMAL();
const Z6Validator = normalFactory.create( 'Z6_literal' );
const Z9Validator = normalFactory.create( 'Z9_literal' );
 
/**
 * Accesses the quoted internals of a Z99/Quote and attempts to normalize them.
 * Returns the envelope intact; thus, if the original object was not a valid
 * ZObject, the envelope will contain an error.
 *
 * @param {Object} someQuote a Z99/Quote
 * @return {Object} Z22 containing either the normalized quote internals or an error
 */
function unquoteVeryCarefully( someQuote ) {
	return normalize( someQuote.Z99K1 );
}
 
/**
 * Accesses the quoted internals of a Z99/Quote directly. This function should
 * only be used on Quotes generated internally to the orchestrator (e.g. by
 * validation functions), when we know that the internal object is already in
 * normal form.
 *
 * @param {Object} someQuote a Z99/Quote
 * @return {Object} the quote internals
 */
function unquoteBrashly( someQuote ) {
	return someQuote.Z99K1;
}
 
/**
 * Determines whether argument is a Z6 or Z9. These two types' Z1K1s are
 * strings instead of Z9s, so some checks below need to special-case their
 * logic.
 *
 * @param {Object} Z1 a ZObject
 * @return {boolean} true if Z1 validates as either Z6 or Z7
 */
function isRefOrString( Z1 ) {
	const { ZWrapper } = require( './ZWrapper.js' );
 
	if ( Z1 instanceof ZWrapper ) {
		Z1 = Z1.asJSON();
	}
	return (
		( Z6Validator.validate( Z1 ) ) ||
		( Z9Validator.validate( Z1 ) )
	);
}
 
function createSchema( Z1 ) {
	let Z1K1 = Z1.Z1K1;
	const { ZWrapper } = require( './ZWrapper.js' );
	Iif ( Z1K1 instanceof ZWrapper ) {
		Z1K1 = Z1K1.asJSONEphemeral();
	}
	if ( isRefOrString( Z1 ) ) {
		return normalFactory.create( Z1K1 );
	}
	if ( validatesAsReference( Z1K1 ).isValid() ) {
		Iif ( isUserDefined( Z1K1.Z9K1 ) ) {
			throw new Error( `Tried to create schema for unrecognized ZID ${ Z1K1.Z9K1 }` );
		}
		return normalFactory.create( Z1K1.Z9K1 );
	}
	const result = normalFactory.createUserDefined( [ Z1K1 ] );
	const key = createZObjectKey( Z1K1 );
	return result.get( key );
}
 
/**
 * Validates a ZObject against the Error schema.
 *
 * @param {Object} Z1 object to be validated
 * @return {boolean} whether Z1 can validate as an Error
 */
function isError( Z1 ) {
	// TODO (T287921): Assay that Z1 validates as Z5 but not as Z9 or Z18.
	try {
		return Z1.Z1K1 === 'Z5' || Z1.Z1K1.Z9K1 === 'Z5';
	} catch ( error ) {
		return false;
	}
}
 
/**
 * Validates a ZObject against the GENERIC schema.
 *
 * @param {Object} Z1 object to be validated
 * @return {boolean} whether Z1 can validate as a generic type instantiation
 */
function isGenericType( Z1 ) {
	// TODO (T296658): Use the GENERIC schema.
	try {
		let Z1K1 = Z1.Z1K1;
		const { ZWrapper } = require( './ZWrapper.js' );
		let keys;
		if ( Z1 instanceof ZWrapper ) {
			Z1K1 = Z1.asJSONEphemeral().Z1K1;
			keys = Z1.keys();
		} else {
			keys = Object.keys( Z1 );
		}
		if ( !validatesAsFunctionCall( Z1K1 ).isValid() ) {
			return false;
		}
		const localKeyRegex = /K[1-9]\d*$/;
		for ( const key of keys ) {
			if ( key === 'Z1K1' || key === 'Z7K1' ) {
				continue;
			}
			Iif ( key.match( localKeyRegex ) === null ) {
				return false;
			}
		}
		return true;
	} catch ( err ) {
		return false;
	}
}
 
function isGenericListType( Z1K1 ) {
	const typeIdentity = findTypeIdentity( Z1K1 );
	const theFunction = typeIdentity.Z7K1;
	if ( theFunction === undefined ) {
		return false;
	}
	const functionIdentity = findFunctionIdentity( theFunction );
	if ( functionIdentity && functionIdentity.Z9K1 === 'Z881' ) {
		return true;
	}
	return false;
}
 
/**
 * Determines whether a Z22 / Evaluation result contains an error.
 *
 * @param {Object} envelope a Z22
 * @return {boolean} true if Z22K2 contains an error; false otherwise
 */
function responseEnvelopeContainsError( envelope ) {
	const { ZEnvelopeWrapper, ZWrapper } = require( './ZWrapper.js' );
	if ( envelope instanceof ZWrapper ) {
		if ( envelope instanceof ZEnvelopeWrapper ) {
			return envelope.containsError();
		}
		// If we've been called with a non-response envelope,
		// it's not a Z22 with an error in it
		return false;
	}
	if ( !envelope || !envelope.Z1K1 || !( envelope.Z22K1 && envelope.Z22K2 ) ) {
		return false;
	}
 
	const metadata = envelope.Z22K2;
	if ( metadata === undefined || isVoid( metadata ) ) {
		// envelope wasn't a Z22 or Z22 wasn't a ZMap
		return false;
	} else Eif ( isZMap( metadata ) ) {
		const errorValue = getZMapValue( metadata, { Z1K1: 'Z6', Z6K1: 'errors' } );
		return ( errorValue !== undefined && !isVoid( errorValue ) );
	} else {
		throw new Error( `Invalid value for Z22K2: "${ metadata }"` );
	}
}
 
/**
 * Determines whether a responseEnvelope contains a value (i.e., a non-Void first element).
 * The input responseEnvelope should be in normal form.
 *
 * FIXME (T311055): responseEnvelopeContainsValue might require normal form, as validateAsZObject
 * is a normal validator. Check and document.
 *
 * @param {Object} responseEnvelope a Z22
 * @return {boolean} true if Z22K1 is not Z24 / Void; false otherwise
 */
function responseEnvelopeContainsValue( responseEnvelope ) {
	const Z22K1 = responseEnvelope.Z22K1.asJSON();
	return (
		validatesAsZObject( Z22K1 ).isValid() &&
		!( isVoid( Z22K1 ) )
	);
}
 
function makeBoolean( truthy = false, canonical = false ) {
	const zobject = {};
	if ( canonical ) {
		zobject.Z1K1 = 'Z40';
	} else {
		zobject.Z1K1 = {
			Z1K1: 'Z9',
			Z9K1: 'Z40'
		};
	}
 
	if ( truthy ) {
		if ( canonical ) {
			zobject.Z40K1 = 'Z41';
		} else {
			zobject.Z40K1 = {
				Z1K1: 'Z9',
				Z9K1: 'Z41'
			};
		}
	} else {
		if ( canonical ) {
			zobject.Z40K1 = 'Z42';
		} else {
			zobject.Z40K1 = {
				Z1K1: 'Z9',
				Z9K1: 'Z42'
			};
		}
	}
 
	return zobject;
}
 
// TODO (T292650): This needs to generate an actual error instead of Z6s.
function generateError( errorString = 'An unknown error occurred' ) {
	return {
		Z1K1: {
			Z1K1: 'Z9',
			Z9K1: 'Z5'
		},
		Z5K2: {
			Z1K1: {
				Z1K1: 'Z7',
				Z7K1: 'Z881',
				Z881K1: 'Z6'
			},
			K1: {
				Z1K1: 'Z6',
				Z6K1: errorString
			},
			K2: {
				Z1K1: {
					Z1K1: 'Z7',
					Z7K1: 'Z881',
					Z881K1: 'Z6'
				}
			}
		}
	};
}
 
/**
 * Convenience function for running a callback over every element of a ZList.
 *
 * Note that the callbacks are run using Promise.all, so do not make assumptions
 * about the order in which they are called.
 *
 * @param {Object} ZList a Typed List (instance of Z881)
 * @param {Function} callback a function to be called over every element of the list
 * @return {Promise<Array[Object]>} the results of running the callback on all list elements
 */
async function traverseZList( ZList, callback ) {
	let tail = ZList;
	if ( tail === undefined ) {
		return;
	}
	const callbacks = [];
	while ( getHead( tail ) !== undefined ) {
		callbacks.push( callback( tail ) );
		tail = getTail( tail );
	}
	return await Promise.all( callbacks );
}
 
/**
 * Runs several functions in sequence; returns first one whose Z22K2 is an error.
 *
 * @param {Object} Z22 a Z22/ResultEnvelope
 * @param {Array} callTuples an array whose elements are also arrays of the form
 *  [ function, argument list, name ]
 *  every function accepts Z22 as its first argument and will be called with the
 *  result of the previous function (starting with input Z22). If the resulting Z22
 *  contains an error (Z22K2), this function returns immediately; otherwise, it
 *  calls the next function with the output of the previous.
 * @param {?Function} callback optional callback to be called on every element of
 *  callTuples; arguments are of the form ( current Z22, current call tuple)
 * @param {boolean} addZ22 whether to inject Z22.Z22K1 as first argument to callables
 * @return {Promise<Object>} a Z22
 */
async function returnOnFirstError( Z22, callTuples, callback = null, addZ22 = true ) {
	let currentResponseEnvelope = Z22;
	for ( const callTuple of callTuples ) {
		if (
			responseEnvelopeContainsError( currentResponseEnvelope ) ||
			isVoid( currentResponseEnvelope.Z22K1 )
		) {
			break;
		}
		if ( callback !== null ) {
			await callback( currentResponseEnvelope, callTuple );
		}
		const callable = callTuple[ 0 ];
		const args = [];
		if ( addZ22 ) {
			args.push( currentResponseEnvelope.Z22K1 );
		}
		for ( const arg of callTuple[ 1 ] ) {
			args.push( arg );
		}
		currentResponseEnvelope = await callable( ...args );
	}
	return currentResponseEnvelope;
}
 
function quoteZObject( ZObject ) {
	const { ZWrapper } = require( './ZWrapper.js' );
	return ZWrapper.create(
		{
			Z1K1: {
				Z1K1: 'Z9',
				Z9K1: 'Z99'
			},
			Z99K1: ZObject
		},
		// Use an empty scope for the outer object, the nested object should already have its own
		// scope, if any.
		new EmptyFrame()
	);
}
 
function makeWrappedResultEnvelope( ...args ) {
	const { ZWrapper } = require( './ZWrapper.js' );
	return ZWrapper.create(
		makeMappedResultEnvelope( ...args ),
		// Use an empty scope for the outer object, the nested object should already have its own
		// scope, if any.
		new EmptyFrame()
	);
}
 
function getEvaluatorAndOrchestratorConfigsForEnvironment( environment, useReentrance ) {
	const evaluatorWs = environment.FUNCTION_EVALUATOR_WS || null;
	const evaluatorUri = environment.FUNCTION_EVALUATOR_URL || null;
	const orchestratorConfig = JSON.parse( environment.ORCHESTRATOR_CONFIG || '{}' );
 
	let evaluatorConfigs = orchestratorConfig.evaluatorConfigs;
	if ( evaluatorConfigs === undefined ) {
		// Legacy request: request does not supply evaluatorConfigs.
		evaluatorConfigs = [];
		evaluatorConfigs.push(
			{
				programmingLanguages: [
					'javascript-es2020', 'javascript-es2019', 'javascript-es2018',
					'javascript-es2017', 'javascript-es2016', 'javascript-es2015',
					'javascript' ],
				evaluatorUri: evaluatorUri,
				evaluatorWs: evaluatorWs,
				useReentrance: useReentrance } );
		evaluatorConfigs.push(
			{
				programmingLanguages: [
					'python-3-9', 'python-3-8', 'python-3-7', 'python-3',
					'python' ],
				evaluatorUri: evaluatorUri,
				evaluatorWs: evaluatorWs,
				useReentrance: useReentrance } );
		evaluatorConfigs.push(
			{
				softwareLanguages: [
					'Z600', 'Z601', 'Z602', 'Z603', 'Z604', 'Z605', 'Z606', 'Z607', 'Z608' ],
				evaluatorUri: evaluatorUri,
				evaluatorWs: evaluatorWs,
				useReentrance: useReentrance } );
		evaluatorConfigs.push(
			{
				softwareLanguages: [
					'Z610', 'Z611', 'Z612', 'Z613', 'Z614', 'Z615', 'Z620' ],
				evaluatorUri: evaluatorUri,
				evaluatorWs: evaluatorWs,
				useReentrance: useReentrance } );
	}
	// Orchestrator config doesn't need evaluator configs.
	delete orchestratorConfig.evaluatorConfigs;
	return { evaluatorConfigs, orchestratorConfig };
}
 
function getTimeoutForEnvironment( environment, defaultTimeout, logger ) {
	const millisecondsString = environment.ORCHESTRATOR_TIMEOUT_MS || '';
	let timeout = Number( millisecondsString );
	let logMessage = null;
	if ( isNaN( timeout ) ) {
		logMessage = `ORCHESTRATOR_TIMEOUT_MS was not a numerical value: ${ millisecondsString }; `;
	} else if ( timeout <= 0 ) {
		logMessage = 'Timeout must be greater than 0 ms; ';
	}
	if ( logMessage !== null ) {
		timeout = defaultTimeout;
		logMessage += `setting to default of ${ defaultTimeout } ms.`;
		logger.log( 'warn', { message: logMessage } );
	}
	return timeout;
}
 
function getBooleanIdentity( ZBoolean ) {
	if ( ZBoolean === undefined ) {
		return null;
	}
	if ( isZReference( ZBoolean ) ) {
		return ZBoolean;
	}
	return getBooleanIdentity( ZBoolean.Z40K1 );
}
 
/**
 * Returns true if the input is equivalent to the builtin true value.
 *
 * @param {Object} ZBoolean A Z40/Boolean
 * @return {boolean} Whether the input corresponds to Z41 (true) or not
 */
function isTrue( ZBoolean ) {
	const identity = getBooleanIdentity( ZBoolean );
	if ( identity === null ) {
		return false;
	}
	return identity.Z9K1 === makeTrue().Z40K1.Z9K1;
}
 
function isZ24( ZObject ) {
	let ZID = ZObject;
	if ( !isString( ZObject ) ) {
		ZID = ZObject.Z9K1;
	}
	return ZID === 'Z24';
}
 
function safeJsonStringify( ZObject ) {
	const { ZWrapper } = require( './ZWrapper.js' );
	Iif ( ZObject instanceof ZWrapper ) {
		ZObject = ZObject.asJSON();
	}
	return JSON.stringify( ZObject );
}
 
module.exports = {
	responseEnvelopeContainsError,
	responseEnvelopeContainsValue,
	createSchema,
	generateError,
	getEvaluatorAndOrchestratorConfigsForEnvironment,
	getTimeoutForEnvironment,
	isError,
	isGenericListType,
	isGenericType,
	isRefOrString,
	isTrue,
	isZ24,
	makeBoolean,
	makeWrappedResultEnvelope,
	quoteZObject,
	returnOnFirstError,
	traverseZList,
	unquoteBrashly,
	unquoteVeryCarefully,
	safeJsonStringify
};