All files jsdoc-tsd-parser.ts

97.35% Statements 478/491
85.92% Branches 293/341
100% Functions 52/52
97.5% Lines 429/440

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 11351x 1x 1x 1x 1x 1x                 1x 131x         131x                                                                       131x 131x 131x             1x 5x   5x 6x 6x 6x                           5x 1x     5x               1x 54x 54x 53x   1x             1x 50x 50x 48x       50x     1x 130x   282x       282x 258x 258x 254x     258x 258x 192x   157x     192x 178x     192x 192x           192x                         1x 55x 3x   52x 117x 117x   117x   3x   3x 3x 3x       117x       51x   51x   48x 48x 48x   4x 4x     15x 15x     10x 10x     8x 8x     11x 11x                 3x       66x 66x                 52x 52x                 410x 205x                               205x 205x 188x 188x 188x       188x 188x 87x       348x 348x 102x   102x 102x       100x 100x 3x     100x   246x 14x       188x 101x         205x                 53x 53x       53x 73x 73x 73x 73x 73x     73x       9x     9x                 9x   64x     14x           14x             14x   14x     9x             9x 9x 9x 9x 9x 9x               9x 9x 4x   5x     9x 1x     9x 9x 1x             50x   49x       1x     73x 59x 8x     59x 59x       53x             1x 282x 20x   262x       1x 3x   3x 3x   3x 3x   3x         3x         3x   3x               1x     51x 51x 48x 48x           3x     1x 3x   3x 12x 12x 12x       3x             1x     84x 40x 39x     1x 1x       44x     84x           1x 264x   264x 264x         264x 264x 264x 264x   264x 264x 2x             1x 192x 1x 1x   1x 1x       1x     191x 182x 182x               1x 147x 169x 169x     147x     1x     179x 179x 1x     178x 3x 1x 1x   2x     3x 3x       178x     31x 31x 21x 21x 21x         21x 21x   10x     10x       178x   152x 152x 2x   150x       178x     1x 169x 169x 169x 2x 167x 1x 166x 2x       164x 164x 1x 1x 1x 1x 1x         164x 1x 1x         164x 164x   2x           169x 166x     169x       169x     1x 37x 35x 35x     37x   36x 36x 4x     32x     36x 36x     37x     1x 3x 1x     2x 2x 2x     2x     1x 7x         7x 7x 12x 12x 12x 12x 12x 6x   6x       12x 12x 12x       7x     1x 83x   83x 2x 2x                   83x 48x     35x     83x     1x 6x                     1x 258x   83x     3x     36x 6x   30x       7x     15x     37x 2x 2x   2x 2x   2x 2x         35x     6x     7x       1x     63x       63x       1x 30x         30x 30x 29x     30x     1x 7x     1x 7x     1x 24x 24x 27x 23x 1x 1x 22x 18x 19x   4x 4x         1x     24x     1x     1x         1x           1x 19x   19x 27x 27x 27x 27x     27x 27x 27x   27x       19x     4x 4x 4x       4x   7x       4x               1x 15x 15x 15x       5x 5x 5x           10x 10x               15x 15x                 1x   10x 14x     10x                   1x 8x 8x       6x 6x     2x 2x               8x 8x                 1x 13x 13x     2x       2x                     11x 11x               13x 11x       11x                 1x 4x 4x                   1x 1x                   3x 3x               4x 4x 4x     4x               1x 11x             11x 11x 11x 11x             1x 2x         2x 2x 2x 2x   1x  
import { parse as jsdocCommentParser } from "comment-parser";
import * as dom from "dts-dom";
import { ParameterFlags } from "dts-dom";
import { writeFileSync } from "fs";
import { Configuration } from "./Configuration";
import { Logger } from "./Logger";
 
export interface IParsedJSDocItem {
	longname: string;
	memberof?: string;
	original: TDoclet;
	parsed: dom.DeclarationBase;
}
 
export class JSDocTsdParser {
	private _parsedClassess: IParsedJSDocItem[] | null = null;
 
	/**
	 * Maps the access flags from JSDoc to declaration flags of dts-dom
	 */
	private accessFlagMap: { [key: string]: dom.DeclarationFlags } = {
		private: dom.DeclarationFlags.Private,
		protected: dom.DeclarationFlags.Protected,
		public: dom.DeclarationFlags.None,
	};
 
	/**
	 * Configuration of of this template.
	 */
	private config: Configuration;
 
	/**
	 * JSDoc items which were parsed from the passed in taffy db
	 */
	private jsdocItems: TDoclet[];
 
	/**
	 * Tranformed JSDoc items (to declaration bases) which can
	 * be passed in to dts-dom for output the d.ts-file.
	 *
	 * The membership is not resolved. JSDoc allows a lot of bullshit.
	 * E. g. items with same name of different types can be added. This
	 * is not valid in typescript, but we will simply ignore this to enforce
	 * the user of this module to correct their JSDoc comments. For that reason
	 * we store all items with same longname (Pattern: <membership>.<name>) in
	 * an array. Once all items are parsed, we can resolve the memberships
	 * (@see resolveMembership).
	 */
	private parsedItems: Map<string, IParsedJSDocItem[]>;
 
	/**
	 * Already resolved items. Will be set by "resolvedItems"
	 */
	private resolvedItems: Map<string, dom.TopLevelDeclaration> | undefined;
 
	constructor(config?: Configuration) {
		this.parsedItems = new Map();
		this.jsdocItems = [];
		this.config = config || new Configuration();
	}
 
	/**
	 * Creates the type definition file as string
	 * @param targetPath If passed, the output will be written to the passed file path
	 */
	public generateTypeDefinition(targetPath?: string): string {
		let output = "";
 
		const results = this.resolveMembershipAndExtends();
		for (const [longname, item] of results.entries()) {
			try {
				output += dom.emit(item);
 
			} catch (err) {
				/* istanbul ignore next */
				Logger.log(`Unexpected error. Please report this error on github!\nCan't emit item ${longname}: ${err}\n\n${JSON.stringify(item, null, "\t")}`, console.error);
				/* istanbul ignore next */
				const jsdocItems = this.jsdocItems.filter((elem) => {
					return (elem.hasOwnProperty("name") && elem.name.endsWith(longname)) || (elem.hasOwnProperty("longname") && elem.longname === longname);
				});
				/* istanbul ignore next */
				Logger.log(`JSDoc items: \n${JSON.stringify(jsdocItems, null, "\t")}`);
			}
		}
 
		if (targetPath) {
			writeFileSync(targetPath, output);
		}
 
		return output;
	}
 
	/**
	 * Returns the parsed Declaration Base of an jsdoc item
	 * @param name The longname of the jsdoc item (name including membership, e.g. "myNamespace.myMember")
	 * @throws {Error} When no item with this name was parsed
	 */
	public getParsedItem(name: string): dom.DeclarationBase[] {
		const item = this.parsedItems.get(name);
		if (item) {
			return item.map((i) => i.parsed);
		} else {
			throw new Error(`Item with name '${name}' not found in result items`);
		}
	}
 
	/**
	 * Returns all parsed Declaration Bases
	 */
	public getParsedItems(): Map<string, dom.DeclarationBase[]> {
		const entries = [...this.parsedItems.entries()];
		const newEntries = entries.map((entry) => {
			return [entry[0], entry[1].map((i) => i.parsed)];
		});
 
		// @ts-ignore
		return new Map(newEntries);
	}
 
	public parse(jsdocItems: TDoclet[]) {
		this.jsdocItems = [];
 
		for (const item of jsdocItems) {
			// Ignore inherited items
			// JDoc will duplicate inherited items. If we don't ignore them,
			// inherited items will also be duplicated in the output
			if (this.evaluateSinceTag(item) && !item.ignore && (!item.undocumented || !this.config.skipUndocumented) && !item.inherited && !this.config.ignoreScope(item.scope) && (!item.comment || !(item.comment.match("@type ") && item.scope === "inner"))) {
				const parsedItems: IParsedJSDocItem[] = this.parsedItems.get(item.longname) || [];
				if (parsedItems.length === 0) {
					this.jsdocItems.push(item);
				}
 
				const parsedItem: dom.DeclarationBase | null = this.parseJSDocItem(item);
				if (parsedItem) {
					if (item.kind !== "class") {
						// @ts-ignore
						parsedItem.jsDocComment = this.cleanJSDocComment(item.comment);
					}
 
					if ("flags" in parsedItem) {
						this.handleFlags(item, parsedItem);
					}
 
					this.handleTags(item, parsedItem);
					parsedItems.push({
						longname: item.longname,
						memberof: item.memberof,
						original: item,
						parsed: parsedItem,
					});
					this.parsedItems.set(item.longname, parsedItems);
				}
			}
		}
	}
 
	/**
	 * Resolves the membership of all parsed items. For example a namspace member will be
	 * added to the member-property of the parsed namespace, if the namespace was parsed.
	 * Otherwise the member will be added to the top level declaration.
	 * @returns Map with the top level declarations and resolved memberships. The key is the
	 *          long name of the item, the value is the @see {dom.TopLevelDeclaration}
	 */
	public resolveMembershipAndExtends(): Map<string, dom.TopLevelDeclaration> {
		if (this.resolvedItems) {
			return this.resolvedItems;
		} else {
			const domTopLevelDeclarations: Map<string, dom.TopLevelDeclaration> = new Map();
			for (const parsedItems of this.parsedItems.values()) {
				for (const parsedItem of parsedItems) {
 
					if (parsedItem.original.kind === "class" && parsedItem.original.augments) {
						const parentItem: dom.ClassDeclaration | undefined =
							this.findClassParent(parsedItem.original as IClassDoclet);
 
						Eif (parentItem) {
							const classItem = parsedItem.parsed as dom.ClassDeclaration;
							classItem.baseType = parentItem;
						}
					}
 
					if (parsedItem.memberof) {
						// @todo Do not pass the domTopLevelDeclarations but the parsedItems map.
						//       Maybe the parent item was not processed yet, then it will not be
						//       found
						const parentItem = this.findParentItem(parsedItem.memberof, domTopLevelDeclarations);
 
						if (parentItem) {
							// add the items we parsed before as a member of the top level declaration
							const dtsItem = parsedItem.parsed;
							const kind = (parentItem as any).kind;
							switch (kind) {
								case "namespace":
									this.resolveNamespaceMembership(dtsItem as dom.NamespaceMember, parentItem as dom.NamespaceDeclaration);
									break;
 
								case "class":
									this.resolveClassMembership(dtsItem as dom.ClassMember, parentItem as dom.ClassDeclaration);
									break;
 
								case "enum":
									this.resolveEnumMembership(dtsItem as dom.EnumMemberDeclaration, parentItem as dom.EnumDeclaration);
									break;
 
								case "interface":
									this.resolveInterfaceMembership(dtsItem as dom.ObjectTypeMember, parentItem as dom.InterfaceDeclaration);
									break;
 
								case "module":
									this.resolveModuleMembership(dtsItem as dom.ModuleMember, parentItem as dom.ModuleDeclaration);
									break;
 
								/* istanbul ignore next */
								default:
									// parent type not supported
									Logger.log(`Can't add member '${parsedItem.longname}' to parent item '${(parentItem as any).name}'. Unsupported parent member type: '${kind}'.`);
									break;
							}
						} else {
							Logger.log("Missing top level declaration '" + parsedItem.memberof + "' for member '" + parsedItem.longname + "'.", console.warn);
						}
					} else {
						// member has no parent, add the item as top-level declaration
						Eif (!domTopLevelDeclarations.has(parsedItem.longname)) {
							domTopLevelDeclarations.set(
								parsedItem.longname,
								parsedItem.parsed as dom.TopLevelDeclaration,
							);
						}
					}
				}
			}
 
			this.resolvedItems = domTopLevelDeclarations;
			return domTopLevelDeclarations;
		}
	}
 
	/**
	 * Creates the comment for the jsdoc item
	 * @param comment The complete comment text of the item
	 * @param addExample Indicates if examples should be omitted or not
	 */
	private cleanJSDocComment(comment: string | undefined, EaddExample = false): string {
		const tagsToPass = new Map([
			["author", true],
			["copyright", true],
			["deprecated", true],
			["example", addExample],
			["returns", true],
			["see", true],
			["throws", true],
			["todo", true],
			["param", true],
			["tutorial", true],
			["variation", true],
			["version", true],
			["license", true],
		]);
 
		let cleanedComment = "";
		if (comment) {
			const parsedComments = jsdocCommentParser(comment);
			Eif (parsedComments.length > 0) { // This should be maximum 1 element (except you pass more than one jsdoc comment, which is here never the case)
				const parsedComment = parsedComments[0];
 
				// First, add the description
				// The comment parser removes the " * " by line breaks, so we have to add these again
				let itemDescription = "";
				if (parsedComment.description.length > 0) {
					itemDescription = parsedComment.description;
				}
 
				// Then add all tags as we receive them
				for (const annotation of parsedComment.tags) {
					if (tagsToPass.has(annotation.tag) && tagsToPass.get(annotation.tag)) {
						cleanedComment += "\n@" + annotation.tag;
 
						const tagValue = (annotation.name + " " + annotation.description).trim();
						if (tagValue.length > 0) {
							// The comment parser removes the " * " by line breaks, so we have to add these again
							// The format everything well, we insert as much spaces as the annotation name + 2, because
							// of the "@" char and a white space
							let spacesToInsert = annotation.tag.length + 2;
							if (annotation.name === "param") {
								spacesToInsert += annotation.name.length;
							}
 
							cleanedComment += " " + tagValue.replace(/\r?\n/g, "\n" + " ".repeat(spacesToInsert));
						}
					} else if (annotation.tag === "description") {
						itemDescription = annotation.name + " " + annotation.description;
					}
				}
 
				if (itemDescription.length > 0) {
					cleanedComment = itemDescription.replace(/\r?\n/g, "\n") + cleanedComment;
				}
			}
		}
 
		return cleanedComment;
	}
 
	/**
	 * Creates parameters for functions, constructors etc.
	 * @todo This function needs to be refactored.
	 * @param params
	 * @param functionName
	 */
	private createDomParams(params: IDocletProp[], functionName: string, jsdocItem: TDoclet): dom.Parameter[] {
		const domParams: dom.Parameter[] = [];
		let typeDef: ITypedefDoclet | undefined;
		let propParam: IDocletProp | undefined;
 
		for (let i = 0; i < params.length; i++) {
			const param = params[i];
			const paramIsProperty = (param.name.indexOf(".") > 0);
			const nextParamIsProperty = (i + 1 < params.length) && (params[i + 1].name.indexOf(".") > 0);
			const lastParam = (i + 1 === params.length);
			let domParam: dom.Parameter | undefined;
 
			// check the type of the parameter
			if (!paramIsProperty && nextParamIsProperty) {
				// the parameter is a parameter with properties
 
				// remember the parameter
				propParam = param;
 
				// create a new typedef
				typeDef = {
					kind: "typedef",
					longname: functionName + "_" + param.name,
					meta: param.meta,
					name: functionName + "_" + param.name,
					properties: [],
					scope: "",
					type: param.type,
				};
				this.jsdocItems.push(typeDef);
 
			} else if (paramIsProperty) {
				// the parameter is a property
 
				Iif (!typeDef || !typeDef.properties) {
					/* istanbul ignore next */
					throw new Error(`Parent of property ${param.name} is missing or incorrect`);
				}
 
				// add the property to the typedef
				const prop: IDocletProp = {
					comment: param.comment,
					description: param.description,
					name: param.name.substr(param.name.indexOf(".") + 1),
					optional: param.optional,
					type: param.type,
				};
				typeDef.properties.push(prop);
 
				if (lastParam || !nextParamIsProperty) {
					// the parameter is the last property
 
					Iif (!propParam) {
						/* istanbul ignore next */
						throw new Error(`Parent of property ${param.name} is missing or incorrect`);
					}
 
					// create an interface from the typedef
					// the property param can also be an array, e. g. @param {fuu[]}, @param {fuu[].bar}
					const interfaceTypeMatches = typeDef.type.names[0].match(/(?:Array\.<([^>]+)>)|(?:([^\[]*)\[\])/i);
					const isArray = (!!interfaceTypeMatches);
					typeDef.type.names[0] = ((interfaceTypeMatches) ? interfaceTypeMatches[1] : typeDef.type.names[0]) as any;
					const domInterface: dom.InterfaceDeclaration = this.parseTypeDefinition(typeDef) as dom.InterfaceDeclaration;
					Eif (domInterface) {
						this.parsedItems.set(typeDef.longname, [{
							longname: typeDef.longname,
							memberof: typeDef.memberof,
							original: typeDef,
							parsed: domInterface,
						}]);
 
						// create the parameter with the interface as type
						let interfaceType;
						if (isArray) {
							interfaceType = dom.create.array(domInterface);
						} else {
							interfaceType = dom.create.typeParameter(typeDef.name, domInterface);
						}
 
						if (typeDef.type && typeDef.type && typeDef.type.names.length > 0) {
							interfaceType = dom.create.union([interfaceType, ...typeDef.type.names.map(n => this.mapVariableType(n, jsdocItem))]);
						}
 
						domParam = dom.create.parameter(propParam.name, interfaceType);
						if (propParam.optional) {
							domParam.flags = dom.ParameterFlags.Optional;
						}
					} else {
						Logger.log(`Can't create interface for property param. Invalid typedef: ${JSON.stringify(typeDef)}`);
					}
				}
 
			} else if (param.type && param.type.names.length > 0) {
				// the param has a simple type
				domParam = dom.create.parameter(param.name, this.mapTypesToUnion(param.type.names, jsdocItem));
 
			} else {
				// the param has no type => map to "any"
				domParam = dom.create.parameter(param.name, dom.type.any);
			}
 
			if (domParam) {
				if (param.optional) {
					domParam.flags = dom.ParameterFlags.Optional;
				}
 
				this.handleFlags(param, domParam);
				domParams.push(domParam);
			}
		}
 
		return domParams;
	}
 
	/**
	 * Uses the configured version comparator to check if the passed since tag is in range of the
	 * configured latest since tag.
	 */
	private evaluateSinceTag(item: TDoclet) {
		if (typeof item.since === "string" && item.since !== "") {
			return this.config.compareVersions(item.since, this.config.latestVersion, item.longname);
		} else {
			return true;
		}
	}
 
	private findClassParent(parsedItem: IClassDoclet): dom.ClassDeclaration | undefined {
		Iif (!parsedItem.augments) { return; }
 
		const classes = this.getAllClasses();
		const output = parsedItem.augments
			.map((augments) => {
				try {
					const classItem = classes.find(
						(cls) => {
							return cls.longname === augments ||
								(cls.original.name === augments && parsedItem.memberof === cls.memberof);
						},
					);
 
					return classItem && classItem.parsed;
				} catch (e) {
					return;
				}
			})
			.find((x) => x) as dom.ClassDeclaration;
 
		return output;
	}
 
	/**
	 * Tries to find the parent item of the passed jsdoc item
	 * @param parentItemLongname Long name of the searched item
	 * @param domTopLevelDeclarations Source items to search in
	 */
	private findParentItem(parentItemLongname: string, domTopLevelDeclarations: Map<string, dom.TopLevelDeclaration>): dom.DeclarationBase | null {
		// The parsed items are stored with their longname and by reference.
		// This is why we can simply return the stored elements in the parsedItems-map
		const parentItem = this.parsedItems.get(parentItemLongname);
		if (parentItem) {
			Eif (parentItem.length === 1) {
				return parentItem[0].parsed;
			} else if (parentItem.length > 1) {
				throw new Error(`Found ${parentItem.length} items with name ${parentItemLongname} as possible parent items: ${JSON.stringify(parentItem)}`);
			}
		}
 
		return null;
	}
 
	private getAllClasses(): IParsedJSDocItem[] {
		Iif (this._parsedClassess) { return this._parsedClassess; }
 
		const parsedClasses: IParsedJSDocItem[] = [];
		for (const items of this.parsedItems.values()) {
			for (const item of items) {
				if (item.original.kind === "class") { parsedClasses.push(item); }
			}
		}
 
		return this._parsedClassess = parsedClasses;
	}
 
	/**
	 * Determines the return value of a function declaration
	 * @param jsdocItem
	 */
	private getFunctionReturnValue(jsdocItem: IFunctionDoclet): dom.Type {
		let functionReturnValue: dom.Type;
 
		if (jsdocItem.returns && jsdocItem.returns.length > 0) {
			if (jsdocItem.returns[0].type) {
				functionReturnValue = this.mapTypesToUnion(jsdocItem.returns[0].type.names, jsdocItem);
			} else {
				// the jsdoc comment is incomplete, there is no type information for the return value
				Logger.log(`Invalid return type. Check the documentation of function ${jsdocItem.longname}`);
				functionReturnValue = dom.type.any;
			}
		} else {
			// If no return value was specified, the function has implicity the return type "void"
			functionReturnValue = dom.type.void;
		}
 
		return functionReturnValue;
	}
 
	/**
	 * Sets the correct export flags to the declaration base.
	 */
	private handleFlags(doclet: any, obj: dom.DeclarationBase | dom.Parameter) {
		obj.flags = dom.DeclarationFlags.None;
 
		obj.flags |= this.accessFlagMap[doclet.access];
		obj.flags |= doclet.optional || doclet.defaultvalue !== undefined
			? doclet.kind !== "function"
				? dom.ParameterFlags.Optional
				: dom.DeclarationFlags.None
			: obj.flags
		obj.flags |= doclet.variable ? dom.ParameterFlags.Rest : dom.DeclarationFlags.None;
		obj.flags |= doclet.virtual ? dom.DeclarationFlags.Abstract : dom.DeclarationFlags.None;
		obj.flags |= doclet.readonly ? dom.DeclarationFlags.ReadOnly : dom.DeclarationFlags.None;
		obj.flags |= doclet.scope === "static" ? dom.DeclarationFlags.Static : dom.DeclarationFlags.None;
 
		const cast = obj as any;
		if (doclet.optional && cast.kind === "property" && cast.flags === ParameterFlags.Optional) {
			obj.flags = dom.DeclarationFlags.Optional;
		}
	}
 
	/**
	 * Handler for template-functions.
	 */
	private handleTags(doclet: IDocletBase, obj: any) {
		if (doclet.tags) {
			for (const tag of doclet.tags) {
				switch (tag.title) {
					case "template":
						Eif (obj.typeParameters) {
							obj.typeParameters.push(
								dom.create.typeParameter(tag.value),
							);
						}
						break;
				}
			}
		} else if (doclet.comment) {
			const matches = doclet.comment.match(/@template\s?([^\r\n]+)\r?\n?/);
			Iif (matches) {
				obj.typeParameters.push(
					dom.create.typeParameter(matches[1]),
				);
			}
		}
	}
 
	private mapTypesToUnion(types: string[], jsdocItem: TDoclet): dom.UnionType {
		const domTypes: dom.Type[] = [];
		for (const type of types) {
			domTypes.push(this.mapVariableType(type, jsdocItem));
		}
 
		return dom.create.union(domTypes);
	}
 
	private mapVariableType(variableType: string, jsdocItem: TDoclet) {
		// resolve array types
		// jsdoc will provide arrays always as "Array.<>" if it's typed or as "Array" if it's not typed
		let resultType: dom.Type = dom.type.any;
		if (variableType.startsWith("external:")) {
			return dom.type.any;
		}
 
		if (jsdocItem && jsdocItem.memberof && variableType.startsWith(jsdocItem.memberof)) {
			if (variableType === jsdocItem.memberof) {
				const index = variableType.replace(/~/g, ".").lastIndexOf(".");
				variableType = variableType.substring(index);
			} else {
				variableType = variableType.substring(jsdocItem.memberof.length);
			}
 
			Eif (variableType.startsWith(".") || variableType.startsWith("~")) {
				variableType = variableType.substring(1);
			}
		}
 
		while (/^Array/i.test(variableType)) {
			// it's an array, check if it's typed
			//                                           Array.< (bllaaa|bla)  >
			const arrayTypeMatches = variableType.match(/Array\.<(\(?[\w|~:]+\)?)>/i); // @todo: can contain namepaths
			if (arrayTypeMatches && arrayTypeMatches[1]) {
				const arrayTypeString: string = arrayTypeMatches[1];
				const arrayType = (arrayTypeString.toLowerCase() === "array") ? dom.type.array(dom.type.any) : this.mapVariableTypeString(arrayTypeString, jsdocItem);
				resultType = (resultType === dom.type.any)
					? dom.type.array(arrayType)
					: dom.type.array(resultType); // nested array
 
				// remove the string from the variable type (nested arrays)
				const regExp = new RegExp(`Array.<${arrayTypeString.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")}>`, "i");
				variableType = variableType.replace(regExp, "");
			} else {
				resultType = dom.type.array(resultType);
 
				// remove the array keyword
				variableType = variableType.replace(/^Array(\.<)?/i, "");
			}
		}
 
		if (resultType === dom.type.any) {
			// check if it's an object type (Object.<string, number>)
			const objectTypeMatches = variableType.match(/^Object\.<([^,]+),\s?([^>]+)>$/);
			if (objectTypeMatches && objectTypeMatches.length === 3) {
				resultType = `{ [key: ${objectTypeMatches[1]}]: ${objectTypeMatches[2]} }` as dom.Type;
			} else {
				resultType = this.mapVariableTypeString(variableType, jsdocItem);
			}
		}
 
		return resultType;
	}
 
	private mapVariableTypeString(variableType: string, jsdocItem: TDoclet): dom.Type {
		let resultTypeStr: string = "";
		let resultType: dom.Type | null = null;
		if (variableType === "bool") {
			resultTypeStr = "boolean";
		} else if (variableType === "function") {
			resultTypeStr = "Function";
		} else if (variableType === "*") {
			resultTypeStr = "any";
		} else {
			// check if it's a module member
			// e.g. module:<moduleName> or module:<moduleName>~<moduleMember>
			const moduleMemberMatches = variableType.match(/^module:([^~]+)~?(.*)$/);
			if (moduleMemberMatches) {
				const moduleName = moduleMemberMatches[1];
				const memberName = (moduleMemberMatches.length === 3) ? moduleMemberMatches[2] : null;
				resultTypeStr = moduleName;
				Eif (memberName) {
					resultTypeStr += `.${memberName}`;
				}
			}
 
			// check if it's a union type
			if (!resultTypeStr && !resultType && variableType.indexOf("|") > -1) {
				variableType = variableType.replace(/\(|\)/g, "");
				resultType = this.mapTypesToUnion(variableType.split("|"), jsdocItem);
			}
 
			// check if it's a type parameter
			// e.g. "Promise.<*>" (JSDoc always separate the type with a dot)
			const typeParameterMatches = variableType.match(/^([^<.]+)\.<([^>]+)>$/);
			if (!resultTypeStr && !resultType && typeParameterMatches && typeParameterMatches.length === 3) {
				// it's not a pretty nice solution, but it works for now
				resultType = dom.create.typeParameter(
					`${typeParameterMatches[1]}<${this.mapVariableType(typeParameterMatches[2], jsdocItem).toString()}>`,
				);
			}
		}
 
		if (!resultType) {
			resultType = (resultTypeStr || variableType) as dom.Type;
		}
 
		Iif (resultType === null) {
			resultType = dom.type.null;
		}
 
		return resultType;
	}
 
	private parseClass(jsdocItem: IClassDoclet, domClass?: dom.ClassDeclaration): dom.DeclarationBase {
		if (!domClass) {
			domClass = dom.create.class(jsdocItem.name);
			domClass.jsDocComment = jsdocItem.classdesc;
		}
 
		if (!jsdocItem.hideconstructor) {
			// Add the constructor
			let constructorDeclaration: dom.ConstructorDeclaration;
			if (jsdocItem.params && jsdocItem.params.length > 0) {
				constructorDeclaration = dom.create.constructor(this.createDomParams(jsdocItem.params, `${jsdocItem.name}Constructor`, jsdocItem));
			} else {
				// no params
				constructorDeclaration = dom.create.constructor([]);
			}
 
			constructorDeclaration.jsDocComment = this.cleanJSDocComment(jsdocItem.comment);
			domClass.members.push(constructorDeclaration);
		}
 
		return domClass;
	}
 
	private parseConstant(jsdocItem: IMemberDoclet) {
		if (jsdocItem.isEnum) {
			return this.parseEnum(jsdocItem);
		}
 
		let propertyType: dom.Type = dom.type.any;
		Eif (jsdocItem.type && jsdocItem.type.names.length > 0) {
			propertyType = this.mapTypesToUnion(jsdocItem.type.names, jsdocItem);
		}
 
		return dom.create.const(jsdocItem.name, propertyType);
	}
 
	private parseEnum(jsdocItem: IMemberDoclet): dom.DeclarationBase {
		Iif (!jsdocItem.isEnum) {
			/* istanbul ignore next */
			throw new Error(`item ${jsdocItem.longname} is not an enum`);
		}
 
		const domEnum: dom.EnumDeclaration = dom.create.enum(jsdocItem.name, (jsdocItem.kind === "constant"));
		Eif (jsdocItem.properties) {
			for (const property of jsdocItem.properties) {
				let isJSONValue = false;
				Eif (property.defaultvalue) {
					try {
						JSON.parse(property.defaultvalue as string);
						isJSONValue = true;
					} catch (err) {
						isJSONValue = false;
					}
				}
 
				const domEnumMember: dom.EnumMemberDeclaration = dom.create.enumValue(property.name, isJSONValue ? undefined : property.defaultvalue);
				domEnumMember.jsDocComment = this.cleanJSDocComment(property.comment);
				domEnum.members.push(domEnumMember);
			}
		}
 
		return domEnum;
	}
 
	private parseFunction(jsdocItem: IFunctionDoclet): dom.DeclarationBase {
		const functionReturnValue: dom.Type = this.getFunctionReturnValue(jsdocItem);
		let domFunction: dom.FunctionDeclaration;
		if (jsdocItem.this) {
			jsdocItem.params = jsdocItem.params || [];
			jsdocItem.params.unshift({
				comment: "",
				description: "",
				name: "this",
				type: {
					names: [jsdocItem.this],
				},
			});
		}
 
		if (jsdocItem.params && jsdocItem.params.length > 0) {
			domFunction = dom.create.function(jsdocItem.name, this.createDomParams(jsdocItem.params, jsdocItem.name, jsdocItem), functionReturnValue);
		} else {
			// no params => create a single function declaration
			domFunction = dom.create.function(jsdocItem.name, [], functionReturnValue);
		}
 
		return domFunction;
	}
 
	private parseInterface(jsdocItem: IClassDoclet) {
		return dom.create.interface(jsdocItem.name);
	}
 
	/**
	 * Converts a JSDoc item to a declaration base which can be printed
	 * with the dts-dom module in a declaration file.
	 *
	 * The resulting item can be passed to dts-dom.emit which will then
	 * output the item in the declaration file.
	 * @param item JSDoc item from the taffy DB
	 */
	private parseJSDocItem(item: TDoclet): dom.DeclarationBase | null {
		switch (item.kind) {
			case "function":
				return this.parseFunction(item as IFunctionDoclet);
 
			case "constant":
				return this.parseConstant(item as IMemberDoclet);
 
			case "member":
				if (item.isEnum) {
					return this.parseEnum(item as IMemberDoclet);
				} else {
					return this.parseMember(item as IMemberDoclet);
				}
 
			case "namespace":
				return this.parseNamespace(item as INamespaceDoclet);
 
			case "typedef":
				return this.parseTypeDefinition(item as ITypedefDoclet);
 
			case "class":
				if (this.parsedItems.has(item.longname)) {
					const parsedItems = this.parsedItems.get(item.longname) as IParsedJSDocItem[];
					Eif (parsedItems.length > 0) {
						// @ts-ignore
						const parsedClass = parsedItems.filter((parsedItem) => parsedItem.parsed.kind === "class");
						Eif (parsedClass.length > 0) {
							// class is already created, only add the constructor to the class
							this.parseClass(item as IClassDoclet, parsedClass[0].parsed as dom.ClassDeclaration);
							return null;
						}
					}
 
				}
				return this.parseClass(item as IClassDoclet);
 
			case "interface":
				return this.parseInterface(item as IClassDoclet);
 
			case "module":
				return this.parseModule(item as INamespaceDoclet);
 
			// suppress warnings for this type
			case "file":
				return null;
 
			default:
				Iif ((item as any).kind !== "package" && (item as any).kind !== "external") {
					/* istanbul ignore next */
					Logger.log(`Unsupported jsdoc item kind: ${item.kind} (item name: ${item.longname})`);
				}
				return null;
		}
	}
 
	private parseMember(jsdocItem: IMemberDoclet) {
		Iif (jsdocItem.isEnum) {
			/* istanbul ignore next */
			throw new Error(`item ${jsdocItem.longname} is an enum`);
		}
 
		let propertyType: dom.Type = dom.type.any;
		if (jsdocItem.type && jsdocItem.type.names.length > 0) {
			propertyType = this.mapTypesToUnion(jsdocItem.type.names, jsdocItem);
		}
 
		return dom.create.property(jsdocItem.name, propertyType);
	}
 
	private parseModule(jsdocItem: INamespaceDoclet) {
		return dom.create.module(jsdocItem.name);
	}
 
	private parseNamespace(jsdocItem: INamespaceDoclet): dom.DeclarationBase {
		return dom.create.namespace(jsdocItem.name);
	}
 
	private parseTypeDefinition(jsdocItem: ITypedefDoclet): dom.DeclarationBase | null {
		let result: dom.DeclarationBase | null = null;
		if (jsdocItem.type && jsdocItem.type && jsdocItem.type.names.length > 0) {
			const typedefType = (jsdocItem.type.names.filter(t => t.toLowerCase() === "object" || t.toLowerCase() === "function")[0] || "").toLowerCase();
			if (typedefType === "function") {
				result = this.parseTypeDefinitionAsFunction(jsdocItem);
				jsdocItem.type.names = jsdocItem.type.names.filter(t => t.toLowerCase() !== "function");
			} else if (typedefType === "object") {
				result = this.parseTypeDefinitionAsObject(jsdocItem);
				jsdocItem.type.names = jsdocItem.type.names.filter(t => t.toLowerCase() !== "object");
			} else {
				result = this.parseTypeDefinitionAsType(jsdocItem);
				jsdocItem.type.names.shift();
			}
		} else {
			// No type specified (@typedef <Name> instead of @typedef {<type>} <Name>)
			// We assume that it's of type object
			result = this.parseTypeDefinitionAsObject(jsdocItem);
		}
 
		return result;
	}
 
	private parseTypeDefinitionAsFunction(jsdocItem: ITypedefDoclet): dom.DeclarationBase {
		// if the jsdoc item has a property "type", we can be sure that it isn't a typedef
		// which should be mapped to an interface. Instead we create a typeAlias-Declaration
		const functionType = dom.create.functionType(
			(jsdocItem.params) ? this.createDomParams(jsdocItem.params, jsdocItem.name, jsdocItem) : [],
			this.getFunctionReturnValue(jsdocItem as any),
		);
 
		return dom.create.alias(
			jsdocItem.name,
			functionType,
		);
	}
 
	private parseTypeDefinitionAsObject(jsdocItem: ITypedefDoclet): dom.InterfaceDeclaration {
		const domInterface: dom.InterfaceDeclaration = dom.create.interface(jsdocItem.name);
 
		if (jsdocItem.properties) {
			for (const property of jsdocItem.properties) {
				let propertyType: dom.Type = dom.type.any;
				Eif (property.type) {
					propertyType = this.mapTypesToUnion(property.type.names, jsdocItem);
				}
 
				const domProperty = dom.create.property(property.name, propertyType);
				domProperty.jsDocComment = property.description;
				this.handleFlags(property, domProperty);
 
				domInterface.members.push(domProperty);
			}
		}
 
		return domInterface;
	}
 
	private parseTypeDefinitionAsType(jsdocItem: ITypedefDoclet): dom.TypeAliasDeclaration | null {
		let result = null;
		Iif (jsdocItem.properties) {
			Logger.log(`Invalid typedef. Typedef type is '${jsdocItem.type.names[0]}' and properties are defined.
			Properties are only allowed for type definitions of type 'object': ${JSON.stringify(jsdocItem)}`);
		} else {
			result = dom.create.alias(
				jsdocItem.name,
				jsdocItem.type.names.map(t => this.mapVariableType(t, jsdocItem)).join("|") as dom.Type
			);
		}
 
		return result;
	}
 
	/**
	 * Adds the class item to the class
	 * @param classMember The parsed class member item
	 * @param parsedClass The parsed class item
	 */
	private resolveClassMembership(classMember: dom.ClassMember, parsedClass: dom.ClassDeclaration) {
		let classMemberToAdd: dom.ClassMember | null = null;
		const kind = classMember.kind;
		switch (kind) {
			// @ts-ignore
			case "function":
				// Classes can only contain method declarations
				const classMemberFunction = (classMember as unknown) as dom.FunctionDeclaration;
				classMemberToAdd = this.transformFunctionDeclarationToMethod(classMemberFunction);
				break;
 
			case "index-signature":
			case "constructor":
			case "property":
			case "method":
				classMemberToAdd = classMember;
				break;
 
			/* istanbul ignore next */
			default:
				Logger.log(`Can't add member '${(classMember as any).name}' to parent item '${(parsedClass as any).name}'. Unsupported member type: '${kind}'`);
				break;
		}
 
		Eif (classMemberToAdd) {
			parsedClass.members.push(classMemberToAdd);
		}
	}
 
	/**
	 * Adds the enum item to the parent enum
	 * @param enumMember The parsed enum member item
	 * @param parsedEnum The parsed enum item
	 */
	private resolveEnumMembership(enumMember: dom.EnumMemberDeclaration, parsedEnum: dom.EnumDeclaration) {
		// enum members can already exists
		const enumMemberExists = parsedEnum.members.some((member) => {
			return member.name === enumMember.name;
		});
 
		Iif (!enumMemberExists) {
			parsedEnum.members.push(enumMember);
		}
	}
 
	/**
	 * Adds the interface member to it's parent interface
	 * @param interfaceMember The parsed interface member
	 * @param parsedInterface The parsed interface
	 */
	private resolveInterfaceMembership(interfaceMember: dom.ObjectTypeMember, parsedInterface: dom.InterfaceDeclaration) {
		let interfaceMemberToAdd: dom.ObjectTypeMember | null = null;
		switch (interfaceMember.kind) {
			// @ts-ignore
			case "function":
				// Interfaces can only have method declarations as members
				interfaceMemberToAdd = this.transformFunctionDeclarationToMethod(interfaceMember);
				break;
 
			case "property":
				interfaceMemberToAdd = interfaceMember;
				break;
 
			/* istanbul ignore next*/
			default:
				Logger.log(`Can't add member '${(interfaceMember as any).name}' to parent item '${(parsedInterface as any).name}'. Unsupported member type: '${interfaceMember.kind}'`);
				break;
		}
 
		Eif (interfaceMemberToAdd) {
			parsedInterface.members.push(interfaceMemberToAdd);
		}
	}
 
	/**
	 * Adds the member item to it's parent module
	 * @param moduleMember The parsed module member item
	 * @param parsedModule The parsed module item
	 */
	private resolveModuleMembership(moduleMember: dom.ModuleMember, parsedModule: dom.ModuleDeclaration) {
		let moduleMemberToAdd: dom.ModuleMember | null = null;
		switch (moduleMember.kind) {
			// @ts-ignore
			case "property":
				this.resolveModuleMembership(
					this.transformPropertyDeclarationToVariable(moduleMember),
					parsedModule,
				);
				break;
 
			case "function":
			case "alias":
			case "interface":
			case "class":
			case "namespace":
			case "const":
			case "var":
			// @ts-ignore
			case "enum":
				moduleMemberToAdd = moduleMember;
				break;
 
			/* istanbul ignore next */
			default:
				Logger.log(`Can't add member '${(moduleMember as any).name}' to parent item '${(parsedModule as any).name}'. Unsupported member type: '${moduleMember.kind}'`);
				break;
		}
 
		if (moduleMemberToAdd) {
			Iif (parsedModule.flags && ((parsedModule.flags & dom.DeclarationFlags.Export) || (parsedModule.flags & dom.DeclarationFlags.Static))) {
				moduleMemberToAdd.flags = dom.DeclarationFlags.Export;
			}
 
			parsedModule.members.push(moduleMemberToAdd);
		}
	}
 
	/**
	 * Adds the namespace member item to it's parent namespace
	 * @param namespaceMember The parsed namespace member
	 * @param parsedNamespace The parsed namespace item
	 */
	private resolveNamespaceMembership(namespaceMember: dom.NamespaceMember, parsedNamespace: dom.NamespaceDeclaration) {
		let namespaceMemberToAdd: dom.NamespaceMember | null = null;
		switch (namespaceMember.kind) {
			// @ts-ignore
			case "property":
				namespaceMemberToAdd = this.transformPropertyDeclarationToVariable(namespaceMember);
				break;
 
			case "function":
				// if (!dtsItem.flags || 0 === (dtsItem.flags & dom.DeclarationFlags.Private)) {
				// 	namespaceMember.flags = dom.DeclarationFlags.Export;
				// }
				namespaceMemberToAdd = namespaceMember;
				break;
 
			// @ts-ignore
			case "enum":
			case "interface":
			case "class":
			case "namespace":
			case "var":
			case "alias":
			case "const":
				namespaceMemberToAdd = namespaceMember;
				break;
 
			/* istanbul ignore next*/
			default:
				Logger.log(`Can't add member '${(namespaceMember as any).name}' to parent item '${parsedNamespace.name}'. Unsupported member type: '${(namespaceMember as any).kind}'`);
				break;
		}
 
		Eif (namespaceMemberToAdd) {
			Eif (namespaceMember.flags && ((namespaceMember.flags & dom.DeclarationFlags.Export) || (namespaceMember.flags & dom.DeclarationFlags.Static))) {
				namespaceMember.flags = dom.DeclarationFlags.Export;
			}
 
			parsedNamespace.members.push(namespaceMemberToAdd);
		}
	}
 
	/**
	 * Transforms a method declaration to a function declaration.
	 * @param functionDeclaration
	 */
	private transformFunctionDeclarationToMethod(functionDeclaration: dom.FunctionDeclaration): dom.MethodDeclaration {
		const methodDeclaration = dom.create.method(
			functionDeclaration.name,
			functionDeclaration.parameters,
			functionDeclaration.returnType,
			functionDeclaration.flags,
		);
 
		methodDeclaration.typeParameters = functionDeclaration.typeParameters;
		methodDeclaration.comment = functionDeclaration.comment;
		methodDeclaration.jsDocComment = functionDeclaration.jsDocComment;
		return methodDeclaration;
	}
 
	/**
	 * Transforms a property declaration to a variable declaration.
	 * @param propertyDeclaration
	 */
	private transformPropertyDeclarationToVariable(propertyDeclaration: dom.PropertyDeclaration): dom.VariableDeclaration {
		const variableDeclaration = dom.create.variable(
			propertyDeclaration.name,
			propertyDeclaration.type,
		);
 
		variableDeclaration.comment = propertyDeclaration.comment;
		variableDeclaration.flags = propertyDeclaration.flags;
		variableDeclaration.jsDocComment = propertyDeclaration.jsDocComment;
		return variableDeclaration;
	}
}