All files utils.js

97.4% Statements 338/347
90.23% Branches 194/215
100% Functions 76/76
97.39% Lines 336/345

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 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233                      2087x 5x   2082x 4430x 988x     1094x       157x       690x       1050x 266x   784x       190x 55x   135x 135x 132x   3x                     14x 1x   13x 10x   3x                     7x     7x     7x                       383x 296x   87x 79x 79x 35x   44x     8x                     2x     2x     2x                       153x         430x 136x     17x       267197x       74204x       70699x         45x       260135x         811x       26x       9x                     252x 199x   53x 40x   13x 13x               156x       156x                 60x       1x           5x 5x 5x       5x   5x 10x   10x 10x         10x 5x   5x     5x       3x 3x 3x 3x 3x 3x   3x   3x       1x           53x 53x 53x       40x 40x 40x 139x 80x   59x   40x 40x 40x   59x   40x                       23x 23x 23x 25x   23x   23x       1x           13x       13x 13x   26x   13x                   12x 12x 12x 24x   12x   12x       1x                                                                                                                     205x 205x     205x       1x 1x 1x     204x 204x 204x   5x   199x 199x   146x 53x   13x 40x   40x                                       18x 4x     4x 4x 3x     1x   14x 14x 14x   4x 4x 4x     6x 6x 6x 3x                 1x 10x   8x     2x         63x 4x 4x 4x   4x         4x   59x 11x 11x 11x 11x 26x 26x 26x   11x         11x         48x       18x                             26x 36x 36x 13x     26x                         387x 4x   383x                       37x 8x       29x 29x     5x   24x                       24x 10x               14x 14x     1x   13x                 1x                 1x                   297x                   95x                   1x                     190x                   62x 1x 1x     61x 61x 61x   149x 61x   88x 88x   61x                           1908x   1169x 1169x 1169x 739x 739x 739x   1169x                       13x 13x 18x       13x 13x 8x   5x     13x                     6x 6x                       118x 118x                       1169x 1169x                     1175x                     1175x 1048x   127x 119x       8x       1175x                         17x 17x 1x 1x   16x               16x                   16x                       3x                                   72x 72x   72x                       72x                                 21x 1x 1x     20x 20x 20x 21x 17x   4x 4x   3x 3x   1x 1x       17x 17x 17x 17x 17x           17x                     17x 1x     17x 16x   1x   17x                         23x 2x 2x   21x 7x     14x 14x 20x 5x   15x   15x   9x   6x   5x                           7x 7x 8x 8x     4x     3x                             375x 9x 9x 9x 9x   366x     375x 2x   373x         375x                           55x 55x   7x 1x 1x   6x 6x   7x 7x 2x   7x   48x                                 3x 3x 1x   3x 3x 3x     1x         1x     1x       94x       29x       1193x 5x 1x   4x   1188x 1x   1187x       73542x             1506461x             73441x             129152x           1x                                                                                                          
'use strict';
 
// NOTE: This file is used in a MediaWiki context as well, and so MUST parse as a
// stand-alone JS file without use of require().
//
// DO NOT modify javascript/src/utils.js directly. Modify this file, then
// regenerate javascript/src/utils.js with
//
//      $ npm run run-rollup
 
function checkTypeShallowly( ZObject, keys ) {
	if ( ZObject === null || ZObject === undefined ) {
		return false;
	}
	for ( const key of keys ) {
		if ( ZObject[ key ] === undefined ) {
			return false;
		}
	}
	return true;
}
 
function isZArgumentReference( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z18K1' ] );
}
 
function isZFunctionCall( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z7K1' ] );
}
 
function isZReference( ZObject ) {
	if ( !checkTypeShallowly( ZObject, [ 'Z1K1', 'Z9K1' ] ) ) {
		return false;
	}
	return ZObject.Z9K1.match( /^Z[1-9]\d*$/ ) !== null;
}
 
function isZType( ZObject ) {
	if ( !checkTypeShallowly( ZObject, [ 'Z1K1', 'Z4K1', 'Z4K2', 'Z4K3' ] ) ) {
		return false;
	}
	const identity = ZObject.Z4K1;
	if ( isMemberOfDangerTrio( identity ) || isZType( identity ) ) {
		return true;
	}
	return false;
}
 
/**
 * Finds the Z9/Reference identity of a Z46/Type converter to code. If the identity is
 * not eventually given as a Z9/Reference, returns null.
 *
 * @param {Object} Z46 a Type converter from code
 * @return {Object|null} the Z46's Z9/Reference identity
 */
function findTypeConverterToCodeIdentity( Z46 ) {
	if ( Z46 === undefined ) {
		return null;
	}
	if ( isZReference( Z46 ) ) {
		return Z46;
	}
	return findTypeConverterToCodeIdentity( Z46.Z46K1 );
}
 
/**
 * Finds the Z9/Reference identity of a Z8/Function. If the identity is
 * not eventually given as a Z9/Reference, returns null.
 *
 * @param {Object} Z8 a Function
 * @return {Object|null} the Z8's Z9/Reference identity
 */
function findFunctionIdentity( Z8 ) {
	Iif ( Z8 === undefined ) {
		return null;
	}
	Iif ( isZReference( Z8 ) ) {
		return Z8;
	}
	return findTypeConverterToCodeIdentity( Z8.Z8K5 );
}
 
/**
 * Finds the identity of a type. This might be a Function Call (in the case of
 * a generic type), a Reference (in the case of a builtin), or the Z4 itself
 * (in the case of a user-defined type).
 *
 * @param {Object} Z4 a Type
 * @return {Object|null} the Z4's identity
 */
function findIdentity( Z4 ) {
	if ( isZFunctionCall( Z4 ) || isZReference( Z4 ) ) {
		return Z4;
	}
	if ( isZType( Z4 ) ) {
		const identity = findIdentity( Z4.Z4K1 );
		if ( isZReference( identity ) && !isBuiltInType( identity.Z9K1 ) ) {
			return Z4;
		}
		return identity;
	}
	// I guess this wasn't a type.
	return null;
}
 
/**
 * Finds the Z9/Reference identity of a Z64/Type converter from code. If the identity is
 * not eventually given as a Z9/Reference, returns null.
 *
 * @param {Object} Z64 a Type converter from code
 * @return {Object|null} the Z46's Z9/Reference identity
 */
function findTypeConverterFromCodeIdentity( Z64 ) {
	Iif ( Z64 === undefined ) {
		return null;
	}
	Iif ( isZReference( Z64 ) ) {
		return Z64;
	}
	return findTypeConverterToCodeIdentity( Z64.Z64K1 );
}
 
/**
 * Type-checks Z1 against Function Call, Reference, and Argument Reference.
 * Returns the true if Z1 can plausibly be interpreted as belonging to one of
 * those three types, else false.
 *
 * @param {Object} Z1 object to be validated
 * @return {boolean} whether Z1's type is any of the Danger Trio
 */
function isMemberOfDangerTrio( Z1 ) {
	for ( const typeComparisonFunction of [
		isZArgumentReference,
		isZFunctionCall,
		isZReference
	] ) {
		if ( typeComparisonFunction( Z1 ) ) {
			return true;
		}
	}
	return false;
}
 
function isString( s ) {
	return typeof s === 'string' || s instanceof String;
}
 
function isArray( a ) {
	return Array.isArray( a );
}
 
function isObject( o ) {
	return !isArray( o ) && typeof o === 'object' && o !== null;
}
 
function isKey( k ) {
	// eslint-disable-next-line security/detect-unsafe-regex
	return k.match( /^(Z[1-9]\d*)?K[1-9]\d*$/ ) !== null;
}
 
function isZid( k ) {
	return k.match( /^Z[1-9]\d*$/ ) !== null;
}
 
function isReference( z ) {
	// Note that A1 and Q34 are References but K2 isn't.
	return z.match( /^[A-JL-Z][1-9]\d*$/ ) !== null;
}
 
function isGlobalKey( k ) {
	return k.match( /^Z[1-9]\d*K[1-9]\d*$/ ) !== null;
}
 
function kidFromGlobalKey( k ) {
	return k.match( /^Z[1-9]\d*(K[1-9]\d*)$/ )[ 1 ];
}
 
/**
 * Finds the ZID associated with a type's identity. This might be the ZID of
 * the Function (if identity is a Function Call) or the ZID of a built-in type.
 *
 * @param {Object} Z4 a Type's identity
 * @return {Object|null} the associated ZID
 */
function getZIDForType( Z4 ) {
	if ( isZReference( Z4 ) ) {
		return Z4.Z9K1;
	}
	if ( isZFunctionCall( Z4 ) ) {
		return getZIDForType( Z4.Z7K1 );
	}
	Eif ( isZType( Z4 ) ) {
		return getZIDForType( Z4.Z4K1 );
	}
	// I guess this wasn't a type.
	return null;
}
 
class SimpleTypeKey {
	constructor( ZID ) {
		this.ZID_ = ZID;
	}
 
	static create( ZID ) {
		return new SimpleTypeKey( ZID );
	}
 
	/**
	 * String representation containing the type's ZID.
	 *
	 * @return {string} ZID of builtin type
	 */
	asString() {
		return this.ZID_;
	}
 
	type() {
		return 'SimpleTypeKey';
	}
}
 
class ZObjectKey {
	constructor( typeKey, childKeys ) {
		this.typeKey_ = typeKey;
		this.childKeys_ = childKeys;
		this.string_ = null;
	}
 
	static create( ZObject ) {
		const children = new Map();
		let typeKey;
		for ( const objectKey of Object.keys( ZObject ) ) {
			const value = ZObject[ objectKey ];
			let subKey;
			Eif ( isString( value ) ) {
				subKey = SimpleTypeKey.create( value );
			} else {
				// eslint-disable-next-line no-use-before-define
				subKey = ZObjectKeyFactory.create( ZObject[ objectKey ] );
			}
			if ( objectKey === 'Z1K1' ) {
				typeKey = subKey;
			} else {
				children.set( objectKey, subKey );
			}
		}
		return new ZObjectKey( typeKey, children );
	}
 
	asString() {
		Eif ( this.string_ === null ) {
			const childObject = {};
			for ( const entry of this.childKeys_.entries() ) {
				const key = entry[ 0 ];
				const value = entry[ 1 ].asString();
				childObject[ key ] = value;
			}
			this.string_ = this.typeKey_.asString() + stableStringify( childObject );
		}
		return this.string_;
	}
 
	type() {
		return 'ZObjectKey';
	}
}
 
class GenericTypeKey {
	constructor( ZID, children ) {
		this.ZID_ = ZID;
		this.children_ = children;
		this.string_ = null;
	}
 
	static create( ZID, identity ) {
		const argumentKeys = [];
		const skipTheseKeys = new Set( [ 'Z1K1', 'Z7K1' ] );
		for ( const argumentKey of Object.keys( identity ) ) {
			if ( skipTheseKeys.has( argumentKey ) ) {
				continue;
			}
			argumentKeys.push( argumentKey );
		}
		argumentKeys.sort();
		const children = [];
		for ( const argumentKey of argumentKeys ) {
			// eslint-disable-next-line no-use-before-define
			children.push( ZObjectKeyFactory.create( identity[ argumentKey ] ) );
		}
		return new GenericTypeKey( ZID, children );
	}
 
	/**
	 * String representation containing the identity of the original Z7K1 and
	 * the keys of all of the type arguments.
	 *
	 * TODO (T295373): This assumes that generics will only be parameterized by types.
	 *
	 * @return {string} contains identity of Function and of its arguments
	 */
	asString() {
		Eif ( this.string_ === null ) {
			const subKeys = [];
			for ( const child of this.children_ ) {
				subKeys.push( child.asString() );
			}
			this.string_ = this.ZID_ + '(' + subKeys.join( ',' ) + ')';
		}
		return this.string_;
	}
 
	type() {
		return 'GenericTypeKey';
	}
}
 
class UserDefinedTypeKey extends GenericTypeKey {
	constructor( children ) {
		super( '', children );
	}
 
	static create( identity ) {
		const children = {};
		for ( const Z3 of convertZListToItemArray( identity.Z4K2 ) ) {
			// eslint-disable-next-line no-use-before-define
			children[ Z3.Z3K2.Z6K1 ] = ZObjectKeyFactory.create( Z3.Z3K1 );
		}
		return new UserDefinedTypeKey( children );
	}
 
	/**
	 * String representation containing the keys of all of the members of the
	 * Z4.
	 *
	 * @return {string} containing identity of type's members
	 */
	asString() {
		Eif ( this.string_ === null ) {
			const subKeys = [];
			for ( const child of Object.entries( this.children_ ) ) {
				subKeys.push( child[ 0 ] + ':' + child[ 1 ].asString() );
			}
			this.string_ = '<' + subKeys.join( ',' ) + '>';
		}
		return this.string_;
	}
 
	type() {
		return 'UserDefinedTypeKey';
	}
}
 
class ZObjectKeyFactory {
 
	/**
	 * Generate a unique identifier for a Z4/Type (or any ZObject).
	 *
	 * If the type is built-in, its unique identifier will simply be its ZID.
	 *
	 * If the type is ultimately defined by a generic Z8/Function, the unique
	 * identifier will consist of the ZID of the Function, followed by the unique
	 * idenifiers of its arguments (enclosed in parentheses, comma-separated), e.g.
	 *
	 *  {
	 *      Z1K1: Z7,
	 *      Z7K1: Z831,
	 *      Z831K1: Z6,
	 *      Z831K2: Z40
	 *  }
	 *  ( a.k.a. Pair( String, Boolean ) )
	 *
	 * produces a key like
	 *
	 *  "Z831(Z6,Z40)"
	 *
	 * If the type is user-defined, the unique identifier will be the keys IDs and unique
	 * identifiers of the type's attributes (enclosed in angle brackets, comma-
	 * separated), e.g.
	 *
	 *  {
	 *      ...
	 *      Z4K2: [
	 *          { Z3K1: Z40, Z3K2: Z123K1 },
	 *          { Z3K1: Z6,  Z3K2: Z123K2 },
	 *          { Z3K1: Z86, Z3K2: Z123K3 }
	 *      ]
	 * }
	 *
	 * produces a key like
	 *
	 *  "<Z123K1:Z40,Z123K2:Z6,Z123K3:Z86>"
	 *
	 * Otherwise, if the object is not a type, the unique identifier will be
	 * the unique identifier of the object's type specification (Z1K1), then
	 * a stable string representation of JSON corresponding to the remaining
	 * key-value pairs in the object (enclosed by braces). So the unique
	 * identifier of a ZString (Z6) corresponding to "vittles" will look like
	 *
	 *  "Z6{Z6K1:vittles}"
	 *
	 * @param {Object} ZObject a ZObject
	 * @return {Object} (Simple|Generic|UserDefined)TypeKey or ZObjectKey
	 * @throws {Error} If input is not a valid ZObject.
	 */
	static create( ZObject ) {
		// FIXME: Give normalize the same treatment--should have an ES6 part
		// and a CommonJS wrapper.
		const normalize = require( '../src/normalize.js' );
		const normalizedEnvelope = normalize( ZObject );
 
		// (T304144): If validation failed with an error; return it.
		if (
			normalizedEnvelope.Z22K1.Z1K1 === 'Z9' &&
			normalizedEnvelope.Z22K1.Z9K1 === 'Z24'
		) {
			const responseError = new Error( 'Invalid ZObject input for type' );
			responseError.errorZObjectPayload = normalizedEnvelope.Z22K2;
			throw responseError;
		}
 
		const normalized = normalizedEnvelope.Z22K1;
		const identity = findIdentity( normalized );
		if ( identity === null ) {
			// ZObject isn't a type, so create a ZObjectKey.
			return ZObjectKey.create( normalized );
		}
		const ZID = getZIDForType( identity );
		if ( isZReference( identity ) ) {
			// Built-in type.
			return SimpleTypeKey.create( ZID );
		} else if ( isZType( identity ) ) {
			// User-defined type.
			return UserDefinedTypeKey.create( identity );
		} else Eif ( isZFunctionCall( identity ) ) {
			// Generic type.
			return GenericTypeKey.create( ZID, identity );
		} else {
			throw new Error( `Invalid identity for type: ${ identity }` );
		}
	}
 
}
 
/**
 * Recursively checks that two objects are equal. This function will work well
 * for anything that can be represented in pure JSON: Objects, Arrays, strings,
 * numbers, null, and even undefined. This function may not work with container
 * types such as Maps or Sets.
 *
 * @param {Object} o1 first object to be compared
 * @param {Object} o2 second object to be compared
 * @return {boolean} whether the two objects are equal
 */
function deepEqual( o1, o2 ) {
	// First, consider the case that both are arrays.
	if ( isArray( o1 ) && isArray( o2 ) ) {
		Iif ( o1.length !== o2.length ) {
			return false;
		}
		for ( let i = 0; i < o1.length; ++i ) {
			if ( !deepEqual( o1[ i ], o2[ i ] ) ) {
				return false;
			}
		}
		return true;
	}
	const isObject1 = isObject( o1 );
	const isObject2 = isObject( o2 );
	if ( isObject1 && isObject2 ) {
		// Both input objects are of type Object; compare recursively.
		const o1Keys = Object.keys( o1 );
		const o2Keys = new Set( Object.keys( o2 ) );
		for ( const key of o1Keys ) {
			// Both objects have the key, so we do recursive comparison and
			// remove the key from the o2Keys set.
			Eif ( o2Keys.has( key ) ) {
				o2Keys.delete( key );
				if ( !deepEqual( o1[ key ], o2[ key ] ) ) {
					return false;
				}
			} else {
				// o1 has a key that o2 lacks, so the objects are not equal.
				return false;
			}
		}
		// If o2Keys.size is not zero, then o2's keys are a superset of o1's,
		// and the objects are not equal.
		return o2Keys.size === 0;
	} else if ( !isObject1 && !isObject2 ) {
		// Neither input object is of type Object; we can use ===.
		return o1 === o2;
	} else {
		// Only one input object is of type Object; they cannot be equal.
		return false;
	}
}
 
function stableStringify( jsonObject ) {
	if ( isArray( jsonObject ) ) {
		const children = [];
		for ( const child of jsonObject ) {
			children.push( stableStringify( child ) );
		}
		const parts = [
			'[',
			children.join( ',' ),
			']'
		];
		return parts.join( '' );
	}
	if ( isObject( jsonObject ) ) {
		const keys = Object.keys( jsonObject );
		keys.sort();
		const children = [];
		for ( const key of keys ) {
			const value = jsonObject[ key ];
			const stringifiedValue = stableStringify( value );
			children.push( stableStringify( key ) + ':' + stringifiedValue );
		}
		const parts = [
			'{',
			children.join( ',' ),
			'}'
		];
		return parts.join( '' );
	}
 
	// If the object is not an array or Object, it is terminal (string, Number,
	// null, etc.), and we can fall back on the normal JSON.stringify.
	return JSON.stringify( jsonObject );
}
 
function deepCopy( o ) {
	return JSON.parse( JSON.stringify( o ) );
}
 
/**
 * Recursively freezes an object and its properties so that it cannot be
 * modified or extended.
 *
 * Use this function with caution. In the context of ZObjects, this
 * function should be safe. But for other use cases, make sure there are no
 * cycles in the object or properites that are not supposed to be frozen (window).
 *
 * @param {*} o any object.
 * @return {*} the same object that was the input, but frozen.
 */
function deepFreeze( o ) {
	Object.keys( o ).forEach( ( property ) => {
		const child = o[ property ];
		if ( child && ( typeof child === 'object' ) && !Object.isFrozen( child ) ) {
			deepFreeze( child );
		}
	} );
	return Object.freeze( o );
}
 
/**
 * Create a Z24 / Void object.  (Z24 is the only possible value of the type
 * Z21 / Unit).
 *
 * @param {boolean} canonical whether output should be in canonical form
 * @return {Object} a reference to Z24
 *
 * TODO (T289301): This should read its outputs from a configuration file.
 */
function makeVoid( canonical = false ) {
	if ( canonical ) {
		return 'Z24';
	}
	return { Z1K1: 'Z9', Z9K1: 'Z24' };
}
 
/**
 * Checks whether the input is a reference to the given ZID.
 *
 * @param {Object | string} ZObject a ZObject
 * @param {string} ZID the ZID to be compared against
 * @return {boolean} true iff ZObject is a reference with the given ZID
 */
function isThisReference( ZObject, ZID ) {
	// Canonical-form reference.
	if ( isString( ZObject ) ) {
		return ZObject === ZID;
	}
	// Normal-form reference.
	let theReference;
	try {
		theReference = ZObject.Z9K1;
	} catch ( e ) {
		// Z9K1 of ZObject could not be accessed, probably because ZObject was undefined.
		return false;
	}
	return theReference === ZID;
}
 
/**
 * Checks whether the input is a Z24 / Void.  Allows for either canonical
 * or normalized input (corresponding to what makeVoid produces).
 *
 * @param {Object | string} v item to be checked
 * @return {boolean} whether v is a Z24
 */
function isVoid( v ) {
	// Case 1: v is a reference to Z24.
	if ( isThisReference( v, 'Z24' ) ) {
		return true;
	}
 
	// Case 2: v is an object whose type is the reference Z21.
	// FIXME: This is still not correct. If v.Z1K1 is a Z4 whose Z4K1/Identity is
	// Z21, this should (but won't) return true. We can't use findIdentity here
	// because findIdentity is defined only for normal-form objects.
	let maybeVoidType;
	try {
		maybeVoidType = v.Z1K1;
	} catch ( e ) {
		// Z1K1 of v could not be accessed, probably because v was undefined.
		return false;
	}
	return isThisReference( maybeVoidType, 'Z21' );
}
 
/**
 * Z9 Reference to Z41 (true).
 *
 * @return {Object} a reference to Z41 (true)
 */
function makeTrue() {
	return { Z1K1: { Z1K1: 'Z9', Z9K1: 'Z40' }, Z40K1: { Z1K1: 'Z9', Z9K1: 'Z41' } };
}
 
/**
 * Z9 Reference to Z42 (false).
 *
 * @return {Object} a reference to Z42 (false)
 */
function makeFalse() {
	return { Z1K1: { Z1K1: 'Z9', Z9K1: 'Z40' }, Z40K1: { Z1K1: 'Z9', Z9K1: 'Z42' } };
}
 
/**
 * Retrieves the head of a ZList.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {Object} the head list element, K1
 */
function getHead( ZList ) {
	return ZList.K1;
}
 
/**
 * Retrieves the tail of a ZList.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {Array} the tail list element, K2
 */
function getTail( ZList ) {
	return ZList.K2;
}
 
/**
 * Sets the tail of a ZList.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @param {Object} newValue object to be set as new tail
 */
function setTail( ZList, newValue ) {
	ZList.K2 = newValue;
}
 
/**
 * Determines whether an already-validated ZList is empty. Because the list has
 * already been validated, it is sufficient to check for the presence of K1.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {boolean} whether ZList is empty
 */
function isEmptyZList( ZList ) {
	return getHead( ZList ) === undefined;
}
 
/**
 * Turns a ZList into a simple JS array for ease of iteration.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {Array} an array consisting of all elements of ZList
 */
function convertZListToItemArray( ZList ) {
	if ( ZList === undefined ) {
		console.error( 'convertZListToItemArray called with undefined; please fix your caller' );
		return [];
	}
 
	let tail = ZList;
	const result = [];
	while ( true ) {
		// FIXME: This should only be called on "an already-validated ZList", which this isn't?
		if ( isEmptyZList( tail ) ) {
			break;
		}
		result.push( getHead( tail ) );
		tail = getTail( tail );
	}
	return result;
}
 
/**
 * Turns a JS array into a Typed List.
 *
 * @param {Array} array an array of ZObjects
 * @param {string} headKey key to be used for list head (K1)
 * @param {string} tailKey key to be used for list tail (K2)
 * @param {Object} tailType list type
 * @return {Object} a Typed List corresponding to the input array
 */
function convertArrayToZListInternal( array, headKey, tailKey, tailType ) {
	function createTail() {
		return { Z1K1: tailType };
	}
	const result = createTail();
	let tail = result;
	for ( const element of array ) {
		tail[ headKey ] = element;
		tail[ tailKey ] = createTail();
		tail = tail[ tailKey ];
	}
	return result;
}
 
/**
 * Infers the shared type of an array of normal ZObjects
 *
 * @param {Array} array an array of ZObjects
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} type of all the elements of the list or Z1
 */
function inferItemType( array, canonical = false ) {
	let headType;
	const Z1K1s = new Set();
	for ( const element of array ) {
		Z1K1s.add( ( ZObjectKeyFactory.create( element.Z1K1 ) ).asString() );
	}
 
	// If inferred type is a resolver type, return Z1 instead
	const resolverTypes = [ 'Z9', 'Z7', 'Z18' ];
	if ( ( Z1K1s.size === 1 ) && ( !resolverTypes.includes( Z1K1s.values().next().value ) ) ) {
		headType = array[ 0 ].Z1K1;
	} else {
		headType = 'Z1';
	}
 
	return ( isString( headType ) && !canonical ) ? { Z1K1: 'Z9', Z9K1: headType } : headType;
}
 
/**
 * Turns a JS array of items into a Typed List after inferring the element type.
 *
 * @param {Array} array an array of ZObjects
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} a Typed List corresponding to the input array
 */
function convertItemArrayToZList( array, canonical = false ) {
	const headType = inferItemType( array, canonical );
	return convertArrayToKnownTypedList( array, headType, canonical );
}
 
/**
 * Turns a benjamin array into a Typed List. The benjamin array is an array
 * where the first item describes the types of the following ZObjects.
 *
 * @param {Array} array an array of ZObjects
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} a Typed List corresponding to the input array
 */
function convertBenjaminArrayToZList( array, canonical = false ) {
	const headType = array.length >= 1 ? array[ 0 ] : ( canonical ? 'Z1' : { Z1K1: 'Z9', Z9K1: 'Z1' } );
	return convertArrayToKnownTypedList( array.slice( 1 ), headType, canonical );
}
 
/**
 * Turns a JS array into a Typed List of a known type.
 *
 * @param {Array} array an array of ZObjects
 * @param {string} type the known type of the typed list
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} a Typed List corresponding to the input array
 */
function convertArrayToKnownTypedList( array, type, canonical = false ) {
	const listType = getTypedListType( type, canonical );
	return convertArrayToZListInternal( array, 'K1', 'K2', listType );
}
 
/**
 * Creates the type value of a Typed List given the expected type of its elements.
 *
 * @param {Object|string} elementType for the list, in normal form
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} the type of a typed list where the elements are the given type
 */
function getTypedListType( elementType, canonical = false ) {
	const listType = {
		Z1K1: canonical ? 'Z7' : wrapInZ9( 'Z7' ),
		Z7K1: canonical ? 'Z881' : wrapInZ9( 'Z881' )
	};
 
	// elementType can be a string or an object
	// If it's a string, the type is a canonical reference
	// If it's an object, it may be:
	// 1. a normal reference, e.g. { Z1K1: Z9, Z9K1: Z6 }
	// 2. a canonical function call, e.g. { Z1K1: Z7, Z7K1: Z885, Z885K1: Z500 }
	// 3. a normal function call, e.g. {Z1K1:{ Z1K1: Z9, Z9K1: Z7 }, Z7K1:{ Z1K1: Z9, Z9K1: Z999 }}
	if ( isString( elementType ) ) {
		listType.Z881K1 = canonical ? elementType : wrapInZ9( elementType );
	} else {
		if ( elementType.Z1K1 === 'Z9' ) {
			listType.Z881K1 = canonical ? elementType.Z9K1 : elementType;
		} else {
			// FIXME (T304619): If the type is described by a function call,
			// it could be either normal or canonical
			listType.Z881K1 = elementType;
		}
	}
 
	return listType;
}
 
/**
 * Create a new, empty ZMap with the given valueType.
 * At present, the key type of a ZMap can only be Z6 / String or Z39 / Key reference.
 * TODO (T302015) When ZMap keys are extended beyond Z6/Z39, update accordingly
 *
 * @param {Object} keyType A Z9 instance in normal form
 * @param {Object} valueType A ZObject in normal form
 * @return {Object} a Z883 / ZMap with no entries, in normal form
 */
function makeEmptyZMap( keyType, valueType ) {
	const allowedKeyTypes = [ 'Z6', 'Z39' ];
	if ( !allowedKeyTypes.includes( keyType.Z9K1 ) ) {
		console.error( 'makeEmptyZMap called with invalid keyType' );
		return undefined;
	}
	const mapType = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
		Z7K1: { Z1K1: 'Z9', Z9K1: 'Z883' },
		Z883K1: keyType,
		Z883K2: valueType
	};
	// The map's K1 property is a list of pairs, and it's required to be present
	// even when empty
	const listType = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
		Z7K1: { Z1K1: 'Z9', Z9K1: 'Z881' },
		Z881K1: {
			Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
			Z7K1: { Z1K1: 'Z9', Z9K1: 'Z882' },
			Z882K1: keyType,
			Z882K2: valueType
		}
	};
	return {
		Z1K1: mapType,
		K1: { Z1K1: listType }
	};
}
 
/**
 * Create a new, empty ZMap for responses in a Z22/ResponseEnvelope.
 *
 * @return {Object} a Z883 / ZMap with no entries, in normal form
 */
function makeEmptyZResponseEnvelopeMap() {
	return makeEmptyZMap(
		{ Z1K1: 'Z9', Z9K1: 'Z6' },
		{ Z1K1: 'Z9', Z9K1: 'Z1' }
	);
}
 
/**
 * If an object has an .asJSON() method, calls that method and returns the result;
 * otherwise, returns the original object intact.
 *
 * This is a last resort function, to be called sparingly. If we are calling this
 * function, it means we have received a ZWrapper from function-orchestrator
 * code.
 *
 * @param {Object} ZObject a ZObject which may be a ZWrapper
 * @return {Object} the ZObject intact or converted to bare JSON
 */
function maybeAsJSON( ZObject ) {
	try {
		return ZObject.asJSON();
	} catch ( e ) {
		return ZObject;
	}
}
 
/**
 * Does a quick check to determine if the given ZObject is a Z883 / Map.
 * Does not validate the ZObject (i.e., assumes the ZObject is well-formed).
 *
 * @param {Object} ZObject a Z1/ZObject, in canonical or normal form
 * @return {boolean}
 */
function isZMap( ZObject ) {
	return ZObjectKeyFactory.create( maybeAsJSON( ZObject.Z1K1 ) ).ZID_ === 'Z883';
}
 
/**
 * Ensures there is an entry for the given key / value in the given ZMap.  If there is
 * already an entry for the given key, overwrites the corresponding value.  Otherwise,
 * creates a new entry. N.B.: Modifies the value of the ZMap's K1 in place.
 *
 * TODO (T302015) When ZMap keys are extended beyond Z6/Z39, update accordingly
 *
 * @param {Object} ZMap a Z883/Typed map, in normal form
 * @param {Object} key a Z6 or Z39 instance, in normal form
 * @param {Object} value a Z1/ZObject, in normal form
 * @param {Function} callback a function to call on new entries before returning
 * @return {Object} the updated ZMap, in normal form
 */
function setZMapValue( ZMap, key, value, callback = null ) {
	if ( ZMap === undefined ) {
		console.error( 'setZMapValue called with undefined; please fix your caller' );
		return undefined;
	}
 
	let penultimateTail = null;
	let tail = ZMap.K1;
	while ( true ) {
		if ( isEmptyZList( tail ) ) {
			break;
		}
		const entry = getHead( tail );
		if ( ( entry.K1.Z1K1 === 'Z6' && key.Z1K1 === 'Z6' && entry.K1.Z6K1 === key.Z6K1 ) ||
			( entry.K1.Z1K1 === 'Z39' && key.Z1K1 === 'Z39' && entry.K1.Z39K1.Z9K1 === key.Z39K1.Z9K1 ) ) {
			entry.K2 = value;
			return ZMap;
		}
		penultimateTail = tail;
		tail = getTail( tail );
	}
 
	// The key isn't present in the map, so add an entry for it
	const ZMapType = findIdentity( ZMap.Z1K1 );
	const listType = tail.Z1K1;
	const keyType = ZMapType.Z883K1;
	const valueType = ZMapType.Z883K2;
	const pairType = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
		Z7K1: { Z1K1: 'Z9', Z9K1: 'Z882' },
		Z882K1: keyType,
		Z882K2: valueType
	};
	let newTail = {
		Z1K1: listType,
		K1: {
			Z1K1: pairType,
			K1: key,
			K2: value
		},
		K2: {
			Z1K1: listType
		}
	};
	if ( callback !== null ) {
		newTail = callback( newTail );
	}
 
	if ( penultimateTail === null ) {
		ZMap.K1 = newTail;
	} else {
		setTail( penultimateTail, newTail );
	}
	return ZMap;
}
 
/**
 * 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 normal OR canonical form
 * @param {Object} key a Z6 or Z39 instance, in normal OR canonical form (but same form as ZMap)
 * @return {Object} a Z1/Object, the value of the map entry with the given key,
 * or undefined if there is no such entry
 */
function getZMapValue( ZMap, key ) {
	if ( ZMap === undefined ) {
		console.error( 'getZMapValue called with undefined; please fix your caller' );
		return undefined;
	}
	if ( isArray( ZMap.K1 ) ) {
		return getValueFromCanonicalZMap( ZMap, key );
	}
 
	let tail = ZMap.K1;
	while ( tail !== undefined ) {
		if ( isEmptyZList( tail ) ) {
			break;
		}
		const entry = getHead( tail );
 
		if ( ( entry.K1.Z1K1 === 'Z6' && key.Z1K1 === 'Z6' && entry.K1.Z6K1 === key.Z6K1 ) ||
			( entry.K1.Z1K1 === 'Z39' && key.Z1K1 === 'Z39' && entry.K1.Z39K1.Z9K1 === key.Z39K1.Z9K1 ) ) {
			return entry.K2;
		}
		tail = getTail( tail );
	}
	return undefined;
}
 
/**
 * Return the ZMap value corresponding to the given key, if present.
 * INTERNAL to this file; external callers use getZMapValue.
 * 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} 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.K1;
	for ( let i = 1; i < K1Array.length; i++ ) {
		const entry = K1Array[ i ];
		if ( ( entry.K1 === key ) ||
			( entry.K1.Z1K1 === 'Z6' && key.Z1K1 === 'Z6' && entry.K1.Z6K1 === key.Z6K1 ) ||
			( entry.K1.Z1K1 === 'Z39' && key.Z1K1 === 'Z39' && entry.K1.Z39K1 === key.Z39K1 ) ) {
			return entry.K2;
		}
	}
	return undefined;
}
 
/**
 * Creates a map-based Z22 containing result and metadata.  metadata is normally a Z883 / Map.
 * However, if metadata is a Z5 / Error object, we place it in a new ZMap, as the value of an entry
 * with key "errors", as a programming convenience.
 *
 * @param {Object} result Z22K1 of resulting Z22
 * @param {Object} metadata Z22K2 of resulting Z22 - either a Z883 / Map or a Z5 / Error
 * @param {boolean} canonical whether output should be in canonical form
 * @return {Object} a Z22
 */
function makeMappedResultEnvelope( result = null, metadata = null, canonical = false ) {
	let ZMap;
	if ( metadata && !isZMap( metadata ) && ( metadata.Z1K1 === 'Z5' || metadata.Z1K1.Z9K1 === 'Z5' ) ) {
		const keyType = { Z1K1: 'Z9', Z9K1: 'Z6' };
		const valueType = { Z1K1: 'Z9', Z9K1: 'Z1' };
		ZMap = makeEmptyZMap( keyType, valueType );
		setZMapValue( ZMap, { Z1K1: 'Z6', Z6K1: 'errors' }, metadata );
	} else {
		ZMap = metadata;
	}
	let envelopeType;
	if ( canonical ) {
		envelopeType = 'Z22';
	} else {
		envelopeType = {
			Z1K1: 'Z9',
			Z9K1: 'Z22'
		};
	}
	return {
		Z1K1: envelopeType,
		Z22K1: result === null ? makeVoid( canonical ) : result,
		Z22K2: ZMap === null ? makeVoid( canonical ) : ZMap
	};
}
 
/**
 * Retrieves the Z5/Error, if present, from the given Z22/Evaluation result (envelope).
 *
 * @param {Object} envelope a Z22/Evaluation result (envelope), in normal OR canonical form
 * @return {Object} a Z5/Error if the envelope contains an error; Z24/void otherwise
 */
function getError( envelope ) {
	const metadata = envelope.Z22K2;
	if ( isZMap( metadata ) ) {
		let canonical, key;
		if ( isArray( metadata.K1 ) ) {
			canonical = true;
			key = 'errors';
		} else {
			canonical = false;
			key = { Z1K1: 'Z6', Z6K1: 'errors' };
		}
		let error = getZMapValue( metadata, key );
		if ( error === undefined ) {
			error = makeVoid( canonical );
		}
		return error;
	} else { // metadata is Z24/void
		return metadata;
	}
}
 
/**
 * Ensures there is an entry for the given key / value in the metadata map
 * of the given Z22 / Evaluation result (envelope).  If the envelope has
 * no metadata map, creates one.  If there is already an entry for the given key,
 * overwrites the corresponding value.  Otherwise, creates a new entry.
 * N.B.: May modify the value of Z22K2 and the ZMap's K1 in place.
 *
 * @param {Object} envelope a Z22/Evaluation result, in normal form
 * @param {Object} key a Z6 or Z39 instance, in normal form
 * @param {Object} value a Z1/ZObject, in normal form
 * @return {Object} the updated envelope, in normal form
 */
function setMetadataValue( envelope, key, value ) {
	let zMap = envelope.Z22K2;
	if ( zMap === undefined || isVoid( zMap ) ) {
		zMap = makeEmptyZResponseEnvelopeMap();
	}
	zMap = setZMapValue( zMap, key, value );
	envelope.Z22K2 = zMap;
	return envelope;
}
 
const builtInTypesArray_ = Object.freeze( [
	'Z1', 'Z11', 'Z12', 'Z14', 'Z16', 'Z17', 'Z18', 'Z2', 'Z20', 'Z21',
	'Z22', 'Z23', 'Z3', 'Z31', 'Z32', 'Z39', 'Z4', 'Z40', 'Z5', 'Z50', 'Z6',
	'Z60', 'Z61', 'Z7', 'Z8', 'Z80', 'Z86', 'Z9', 'Z99'
] );
const builtInTypes_ = new Set( builtInTypesArray_ );
 
function builtInTypes() {
	return builtInTypesArray_;
}
 
function isBuiltInType( ZID ) {
	return builtInTypes_.has( ZID );
}
 
function isUserDefined( ZID ) {
	return !builtInTypes_.has( ZID );
}
 
function inferType( object ) {
	if ( isString( object ) ) {
		if ( isReference( object ) ) {
			return 'Z9';
		}
		return 'Z6';
	}
	if ( isArray( object ) ) {
		return 'LIST';
	}
	return object.Z1K1;
}
 
function wrapInZ6( zid ) {
	return {
		Z1K1: 'Z6',
		Z6K1: zid
	};
}
 
function wrapInZ9( zid ) {
	return {
		Z1K1: 'Z9',
		Z9K1: zid
	};
}
 
function wrapInKeyReference( key ) {
	return {
		Z1K1: wrapInZ9( 'Z39' ),
		Z39K1: wrapInZ6( key )
	};
}
 
function wrapInQuote( data ) {
	return {
		Z1K1: wrapInZ9( 'Z99' ),
		Z99K1: data
	};
}
 
module.exports = {
	builtInTypes,
	convertItemArrayToZList,
	convertBenjaminArrayToZList,
	convertArrayToKnownTypedList,
	convertZListToItemArray,
	findTypeConverterToCodeIdentity,
	findFunctionIdentity,
	findIdentity,
	findTypeConverterFromCodeIdentity,
	inferItemType,
	isMemberOfDangerTrio,
	isZArgumentReference,
	isZFunctionCall,
	isZReference,
	isZType,
	isString,
	isArray,
	isObject,
	isKey,
	isZid,
	isReference,
	isGlobalKey,
	deepEqual,
	deepCopy,
	deepFreeze,
	getHead,
	getTail,
	getTypedListType,
	inferType,
	isBuiltInType,
	isEmptyZList,
	isUserDefined,
	kidFromGlobalKey,
	makeFalse,
	makeMappedResultEnvelope,
	makeTrue,
	makeVoid,
	isVoid,
	wrapInKeyReference,
	wrapInQuote,
	wrapInZ6,
	wrapInZ9,
	makeEmptyZMap,
	makeEmptyZResponseEnvelopeMap,
	isZMap,
	setZMapValue,
	getZMapValue,
	getError,
	setMetadataValue,
	stableStringify,
	ZObjectKeyFactory
};