All files / src/services document-management.service.ts

68.99% Statements 218/316
48.97% Branches 71/145
82.22% Functions 37/45
69.82% Lines 199/285

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                              7x             7x           7x         7x   7x 7x     7x 7x 7x               7x       92x   92x   93x 93x   419x 419x 1x           7x 2x                 10x 10x 54x 54x         30x       24x           24x   24x                 26x     26x 26x 26x 24x 24x 24x 24x 24x 24x     2x             2x 2x     2x       2x     2x 2x 2x 2x                         7x 1x 1x         1x 1x 1x       1x     1x 1x                                                       7x           1x 1x 1x   1x   1x 1x 1x         1x                             1x 1x 1x 1x                   1x                 1x       1x                                     7x     2x     1x 1x                                       7x                 1x                   1x                         7x     1x     1x             1x                       7x                                                             7x     2x 2x 2x   2x 2x 2x             2x 2x                         7x                                     7x                                                                                                                                                         7x                                     7x           1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x     1x             7x 1x     1x     1x 1x 1x 1x 1x     1x                       7x           1x 1x     1x     1x 1x   1x 1x   1x 1x 1x 1x   1x             7x 1x 1x 1x     1x             7x 1x 1x 1x     1x 1x 1x                           7x             1x 1x 1x     1x 1x   1x 1x 1x 1x 1x   1x 1x 1x         1x     1x                 7x 1x 1x     1x     1x 1x 1x       1x 1x 1x     1x                             7x               1x 1x     1x     1x 1x   1x 1x   1x 1x   1x 1x       1x                 7x         1x             1x     1x                 7x         1x             1x     1x 1x 1x           7x 27x 27x 23x   27x 27x   7x  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import {
  CollectionType,
  DocumentType,
  FIELD_PATH_SEPARATOR,
  FieldType,
  InspectionType,
} from '../contracts/common';
import {
  ErrorInfo,
  ErrorLevel,
  ErrorScope,
  ErrorType,
} from '../models/error.model';
import {
  HTTP_STATUS_NO_CONTENT,
  constantTypes,
  propertyTypes,
} from '../common/config.types';
import { Observable, Subscription } from 'rxjs';
 
import { CommonUtil } from '../utils/common-util';
import { ConfigModel } from '../models/config.model';
import { DocumentDefinition } from '../models/document-definition.model';
import { DocumentInspectionModel } from '../models/inspect/document-inspection.model';
import { DocumentInspectionUtil } from '../utils/document-inspection-util';
import { Field } from '../models/field.model';
import { Guid } from '../utils';
import ky from 'ky';
 
/**
 * Manages Document object lifecycle. Import a Document source
 * such as JSON/XML schema/instance, request an inspection to the backend,
 * then enable it for mapping by consuming inspection result in UI.
 */
export class DocumentManagementService {
  cfg!: ConfigModel;
 
  private mappingUpdatedSubscription!: Subscription;
  private MAX_SEARCH_MATCH = 10000;
 
  constructor(private api: typeof ky) {}
 
  initialize(): void {
    this.mappingUpdatedSubscription =
      this.cfg.mappingService.mappingUpdated$.subscribe(() => {
        for (const d of this.cfg.getAllDocs()) {
          if (d.initialized) {
            d.updateFromMappings(this.cfg.mappings!); // TODO: check this non null operator
          }
        }
      });
  }
 
  uninitialize(): void {
    this.mappingUpdatedSubscription.unsubscribe();
  }
 
  /**
   * Request Document inspection for each {@link DocumentDefinition} object
   * stored in {@link ConfigModel} and populate it back with the inspection result.
   *
   * @returns
   */
  inspectDocuments(): Observable<DocumentDefinition> {
    return new Observable<DocumentDefinition>((observer) => {
      for (const docDef of this.cfg.getAllDocs()) {
        if (
          docDef === this.cfg.sourcePropertyDoc ||
          docDef === this.cfg.targetPropertyDoc ||
          docDef === this.cfg.constantDoc
        ) {
          docDef.initialized = true;
          continue;
        }
 
        const inspectionModel = DocumentInspectionUtil.fromDocumentDefinition(
          this.cfg,
          docDef
        );
 
        // TODO: check this non null operator
        this.inspectDocument(inspectionModel)
          .then(() => {
            observer.next(docDef);
          })
          .catch((error: any) => {
            observer.error(error);
          });
      }
    });
  }
 
  private inspectDocument(
    inspectionModel: DocumentInspectionModel
  ): Promise<DocumentDefinition> {
    return new Promise<DocumentDefinition>((resolve, reject) => {
      const docDef = inspectionModel.doc;
      if (docDef.inspectionResult) {
        const responseJson: any = JSON.parse(docDef.inspectionResult);
        inspectionModel.parseResponse(responseJson);
        docDef.initializeFromFields();
        docDef.initialized = true;
        resolve(docDef);
        return;
      }
 
      Iif (!inspectionModel.isOnlineInspectionCapable()) {
        docDef.initialized = true;
        docDef.errorOccurred = true;
        reject(docDef);
        return;
      }
 
      const request = inspectionModel.request;
      this.cfg.logger!.debug(
        `Document Inspection Request: ${JSON.stringify(request.options.json)}`
      );
      this.api
        .post(request.url, request.options)
        .json()
        .then((responseJson: any) => {
          this.cfg.logger!.debug(
            `Document Inspection Response: ${JSON.stringify(responseJson)}`
          );
          inspectionModel.parseResponse(responseJson);
          docDef.initializeFromFields();
          docDef.initialized = true;
          resolve(docDef);
        })
        .catch((error: any) => {
          this.cfg.errorService.addBackendError(
            `Failed to inspect Document: ${docDef.name}(${docDef.id})`,
            error
          );
          docDef.errorOccurred = true;
          reject(error);
        });
    });
  }
 
  getLibraryClassNames(): Promise<string[]> {
    return new Promise<string[]>((resolve, reject) => {
      Iif (typeof this.cfg.initCfg.baseMappingServiceUrl === 'undefined') {
        resolve([]);
        return;
      }
      const url: string =
        this.cfg.initCfg.baseMappingServiceUrl + 'library/list';
      this.cfg.logger!.debug('Library Class List Service Request: ' + url);
      this.api
        .get(url)
        .json()
        .then((body: any) => {
          this.cfg.logger!.debug(
            `Library Class List Service Response: ${JSON.stringify(body)}`
          );
          const classNames: string[] = body.ArrayList;
          resolve(classNames);
        })
        .catch((error: any) => {
          if (error.status !== HTTP_STATUS_NO_CONTENT) {
            this.cfg.errorService.addBackendError(
              'Error occurred while accessing the user uploaded JARs from the runtime service.',
              error
            );
            reject(error);
          } else {
            resolve([]);
          }
        });
    });
  }
 
  /**
   * Import user uploaded Document source such as JSON/XML schema/instance, assign
   * a unique Document ID with using GUID and delegate to {@link addNonJavaDocument}
   * to make it available  as a Document for mappings.
   * @see addNonJavaDocument
   *
   * @param selectedFile - user selected file
   * @param isSource - true is source panel, false is target
   * @param isSchema- user specified instance/ schema (true === schema)
   * @param inspectionParameters - CSV parameters
   *
   */
  importNonJavaDocument(
    selectedFile: File,
    isSource: boolean,
    isSchema: boolean,
    inspectionParameters?: { [key: string]: string }
  ): Promise<boolean> {
    return new Promise<boolean>(async (resolve) => {
      let fileText = '';
      const reader = new FileReader();
 
      this.cfg.errorService.clearValidationErrors();
 
      const userFileComps = selectedFile.name.split('.');
      const userFile = userFileComps.slice(0, -1).join('.');
      const userFileSuffix: string =
        userFileComps[userFileComps.length - 1].toUpperCase();
 
      // Wait for the async read of the selected ascii document to be completed.
      try {
        fileText = await CommonUtil.readFile(selectedFile, reader);
      } catch (error) {
        this.cfg.errorService.addError(
          new ErrorInfo({
            message: 'Unable to import the specified schema document.',
            level: ErrorLevel.ERROR,
            scope: ErrorScope.APPLICATION,
            type: ErrorType.USER,
            object: error,
          })
        );
        resolve(false);
        return;
      }
 
      let docType = undefined;
      try {
        docType = userFileSuffix as DocumentType;
        Iif (!docType) {
          throw new Error(docType);
        }
      } catch (error) {
        this.handleError(
          'Unrecognized document suffix (' + userFileSuffix + ')'
        );
        resolve(false);
        return;
      }
      this.addNonJavaDocument(
        fileText,
        userFile + '-' + Guid.newGuid(),
        userFile,
        docType,
        isSchema ? InspectionType.SCHEMA : InspectionType.INSTANCE,
        isSource,
        inspectionParameters
      ).then((value) => {
        Iif (!value) {
          resolve(false);
          return;
        }
        resolve(true);
      });
    });
  }
 
  /**
   * Import a Java class as a Document source and delegate to {@link addJavaDocument}
   * to make it available  as a Document for mappings.
   * JAR file(s) have to be imported and be available in the backend classpath
   * before doing this.
   * @see addJavaDocument
   * @todo https://github.com/atlasmap/atlasmap/issues/2919
   * A unique Document ID should be assigned with using GUID.
   *
   * @param className
   * @param isSource
   * @param collectionType
   * @param collectionClassName
   */
  importJavaDocument(
    className: string,
    isSource: boolean,
    EcollectionType = CollectionType.NONE,
    collectionClassName?: string
  ): Promise<boolean> {
    this.cfg.errorService.clearValidationErrors();
    return this.addJavaDocument(
      className,
      isSource,
      collectionType,
      collectionClassName
    );
  }
  /**
   * Add non-Java Document object into the {@link ConfigModel} store and
   * delegate to {@link doAddDocument}.
   * @see doAddDocument
   *
   * @param docBody
   * @param docId
   * @param docName
   * @param docType
   * @param inspectionType
   * @param isSource
   * @param parameters
   */
  addNonJavaDocument(
    docBody: any,
    docId: string,
    docName: string,
    docType: DocumentType,
    inspectionType: InspectionType,
    isSource: boolean,
    parameters?: { [key: string]: string }
  ): Promise<boolean> {
    const inspectionModel = DocumentInspectionUtil.fromNonJavaProperties(
      this.cfg,
      docId,
      docName,
      docType,
      inspectionType,
      docBody,
      isSource,
      parameters
    );
    return this.doAddDocument(inspectionModel);
  }
 
  /**
   * Add Java Document object into the {@link ConfigModel} store and
   * delegate to {@link doAddDocument}.
   * @see doAddDocument
   *
   * @param className
   * @param isSource
   * @param collectionType {@link CollectionType}
   * @param collectionClassName
   */
  addJavaDocument(
    className: string,
    isSource: boolean,
    IcollectionType: CollectionType = CollectionType.NONE,
    collectionClassName?: string
  ): Promise<boolean> {
    const inspectionModel = DocumentInspectionUtil.fromJavaProperties(
      this.cfg,
      className,
      isSource,
      collectionType,
      collectionClassName
    );
    return this.doAddDocument(inspectionModel);
  }
 
  /**
   * An utility method to look at the {@link DocumentType} passed in as an argument
   * and see if it's a Java or non-Java Document, then delegate to
   * {@link addJavaDocument} or {@link addNonJavaDocument}.
   *
   * @todo https://github.com/atlasmap/atlasmap/issues/2918
   * {@link CollectionType} and collectionClassName has to be persisted into digest
   * so it could be restored here
   */
  addDocument(
    docBody: any,
    docId: string,
    docName: string,
    docType: DocumentType,
    inspectionType: InspectionType,
    isSource: boolean,
    parameters?: { [key: string]: string }
  ): Promise<boolean> {
    if (docType === DocumentType.JAVA) {
      return this.addJavaDocument(docId, isSource);
    }
    return this.addNonJavaDocument(
      docBody,
      docId,
      docName,
      docType,
      inspectionType,
      isSource,
      parameters
    );
  }
 
  /**
   * Add or replace the {@link DocumentDefinition} object stored in {@link ConfigModel}
   * and delegate to {@link inspectDocument} to perform an inspection.
   * Then it gets available for mapping in the canvas.
   *
   * @param inspectionModel {@link DocumentInspectionModel}
   * @returns
   */
  private doAddDocument(
    inspectionModel: DocumentInspectionModel
  ): Promise<boolean> {
    return new Promise<boolean>(async (resolve) => {
      let docdef = inspectionModel.doc;
      const isSource = docdef.isSource;
 
      this.inspectDocument(inspectionModel)
        .then(async (doc: DocumentDefinition) => {
          Iif (doc.fields.length === 0) {
            if (isSource) {
              CommonUtil.removeItemFromArray(docdef, this.cfg.sourceDocs);
            } else {
              CommonUtil.removeItemFromArray(docdef, this.cfg.targetDocs);
            }
          }
          docdef.updateFromMappings(this.cfg.mappings!);
          resolve(true);
        })
        .catch((error) => {
          this.cfg.logger?.error(
            `Failed to inspect Document ${docdef.name}(${docdef.id})`,
            error
          );
          docdef.errorOccurred = true;
          resolve(false);
        });
    });
  }
 
  private handleError(message: string, error?: any): void {
    this.cfg.errorService.addError(
      new ErrorInfo({
        message: message,
        level: ErrorLevel.ERROR,
        scope: ErrorScope.APPLICATION,
        type: ErrorType.INTERNAL,
        object: error,
      })
    );
  }
 
  /**
   * Filter Document fields that is shwon in a Source/Target Document tree.
   * @todo Consolidate with expression field search and Document Details field
   * search - https://github.com/atlasmap/atlasmap/issues/603
   * @param searchFilter
   * @param isSource
   */
  filterDocumentFields(searchFilter: string | undefined, isSource: boolean) {
    const cfg = ConfigModel.getConfig();
 
    let searchResultsExist = false;
    const searchIsEmpty: boolean =
      undefined === searchFilter || '' === searchFilter;
    const defaultVisibility: boolean = searchIsEmpty;
    for (const docDef of cfg.getDocs(isSource)) {
      docDef.visibleInCurrentDocumentSearch = defaultVisibility;
      for (const field of docDef.getAllFields()) {
        field.visibleInCurrentDocumentSearch = defaultVisibility;
      }
      if (!searchIsEmpty) {
        let searchFieldCount = 0;
        for (const field of docDef.getAllFields()) {
          // Skip this field if it's already determined to be visible.
          if (field.visibleInCurrentDocumentSearch && !field.collapsed) {
            continue;
          }
          field.visibleInCurrentDocumentSearch = field.name
            .toLowerCase()
            .includes(searchFilter!.toLowerCase());
          searchResultsExist =
            searchResultsExist || field.visibleInCurrentDocumentSearch;
 
          // The current field matches the user-specified filter.
          if (field.visibleInCurrentDocumentSearch) {
            docDef.visibleInCurrentDocumentSearch = true;
            let parentField = field.parentField;
 
            // Direct lineage is then visible.
            while (
              parentField != null &&
              !parentField.visibleInCurrentDocumentSearch
            ) {
              parentField.visibleInCurrentDocumentSearch = true;
              parentField.collapsed = false;
              parentField = parentField.parentField;
              searchFieldCount++;
            }
 
            // All fields below the matching field are also visible.
            try {
              this.markChildrenVisible(field);
            } catch (error) {
              cfg.errorService.addError(
                new ErrorInfo({
                  message: error.message,
                  level: ErrorLevel.INFO,
                  scope: ErrorScope.APPLICATION,
                  type: ErrorType.USER,
                })
              );
              break;
            }
 
            // The total number of matches is limited to allow the UI to perform.
            if (searchFieldCount++ >= this.MAX_SEARCH_MATCH) {
              cfg.errorService.addError(
                new ErrorInfo({
                  message:
                    'The maximum number of fields matching the specified search filter has beeen exceeded  ' +
                    'Try using a longer field filter.',
                  level: ErrorLevel.INFO,
                  scope: ErrorScope.APPLICATION,
                  type: ErrorType.USER,
                })
              );
              break;
            }
          }
        }
      }
    }
    cfg.mappingService.notifyLineRefresh();
  }
 
  private markChildrenVisible(field: Field): void {
    field.visibleInCurrentDocumentSearch = true;
    field.collapsed = false;
    // if (this.searchFieldCount++ >= this.maxSearchMatch) {
    //   throw new Error('The maximum number of fields matching the specified search filter has beeen exceeded  ' +
    //     'Try using a longer field filter.');
    // }
    for (const childField of field.children) {
      this.markChildrenVisible(childField);
    }
  }
 
  /**
   * Create a constant field.
   * @param constName
   * @param constValue
   * @param constType
   * @param addToActiveMapping
   */
  createConstant(
    constName: string,
    constValue: string,
    constType: string,
    addToActiveMapping?: boolean
  ): void {
    let field = this.cfg.constantDoc.getField(FIELD_PATH_SEPARATOR + constName);
    Eif (!field) {
      field = new Field();
    }
    field.name = constName;
    field.path = FIELD_PATH_SEPARATOR + constName;
    field.value = constValue;
    field.type = FieldType[constType as keyof typeof FieldType];
    field.docDef = this.cfg.constantDoc;
    field.userCreated = true;
    this.cfg.constantDoc.addField(field);
    Iif (addToActiveMapping) {
      this.cfg.mappingService.addFieldToActiveMapping(field);
    }
    this.cfg.mappingService.notifyMappingUpdated();
  }
 
  /**
   * Delete a constant field.
   * @param constName
   */
  deleteConstant(constName: string): void {
    const field = this.cfg.constantDoc.getField(
      FIELD_PATH_SEPARATOR + constName
    );
    Iif (!field) {
      return;
    }
    this.cfg.mappingService.removeFieldFromAllMappings(field);
    this.cfg.constantDoc.removeField(field);
    const activeMapping = this.cfg.mappings?.activeMapping;
    const expression = activeMapping?.transition?.expression;
    Iif (activeMapping && expression) {
      expression.updateFieldReference(activeMapping);
    }
    this.cfg.mappingService.notifyMappingUpdated();
  }
 
  /**
   * Edit a constant field. Look for an existing constant field with the specified name
   * and update the properties. If {@link origName} is specified and different from
   * {@link constName}, the name of the constant field will be changed.
   * @param constName
   * @param constValue
   * @param constType
   * @param origName
   */
  editConstant(
    constName: string,
    constValue: string,
    constType: string,
    origName?: string
  ): void {
    let constFieldName = origName ? origName : constName;
    let field = this.cfg.constantDoc.getField(
      FIELD_PATH_SEPARATOR + constFieldName
    );
    Iif (!field) {
      return;
    }
    Eif (constType.length > 0) {
      field.type = FieldType[constType as keyof typeof FieldType];
    }
    Eif (constValue.length > 0) {
      field.value = constValue;
    }
    Eif (origName && origName !== constName) {
      field.name = constName;
      field.path = FIELD_PATH_SEPARATOR + constName;
      this.cfg.constantDoc.updateField(field, FIELD_PATH_SEPARATOR + constName);
    }
    this.cfg.mappingService.notifyMappingUpdated();
  }
 
  /**
   * Get a {@link FieldType} of the constant field.
   * @param constName
   */
  getConstantType(constName: string): FieldType {
    const cfg = ConfigModel.getConfig();
    const field = cfg.constantDoc.getField(FIELD_PATH_SEPARATOR + constName);
    Iif (!field) {
      return FieldType.NONE;
    }
    return field.type;
  }
 
  /**
   * Get an index of the constant field type.
   * @param constName
   */
  getConstantTypeIndex(constName: string): number {
    const cfg = ConfigModel.getConfig();
    const field = cfg.constantDoc.getField(FIELD_PATH_SEPARATOR + constName);
    Iif (!field) {
      return 0;
    }
    for (let i = 0; i < constantTypes.length; i++) {
      Eif (constantTypes[i].includes(field.type)) {
        return i;
      }
    }
    return 0;
  }
 
  /**
   * Create a property field.
   * @param propName
   * @param propType
   * @param propScope
   * @param isSource
   * @param addToActiveMapping
   */
  createProperty(
    propName: string,
    propType: string,
    propScope: string,
    isSource: boolean,
    addToActiveMapping?: boolean
  ): void {
    const cfg = ConfigModel.getConfig();
    const path = this.getPropertyPath(propScope, propName);
    let field = isSource
      ? cfg.sourcePropertyDoc.getField(path)
      : cfg.targetPropertyDoc.getField(path);
    Eif (!field) {
      field = new Field();
    }
    field.name = propName;
    field.type = FieldType[propType as keyof typeof FieldType];
    field.scope = propScope;
    field.path = path;
    field.userCreated = true;
 
    Eif (isSource) {
      field.docDef = cfg.sourcePropertyDoc;
      cfg.sourcePropertyDoc.addField(field);
    } else {
      field.docDef = cfg.targetPropertyDoc;
      cfg.targetPropertyDoc.addField(field);
    }
    Iif (addToActiveMapping) {
      this.cfg.mappingService.addFieldToActiveMapping(field);
    }
    cfg.mappingService.notifyMappingUpdated();
  }
 
  /**
   * Delete a property field.
   * @param propName
   * @param propScope
   * @param isSource
   */
  deleteProperty(propName: string, propScope: string, isSource: boolean): void {
    const path = this.getPropertyPath(propScope, propName);
    const field = isSource
      ? this.cfg.sourcePropertyDoc.getField(path)
      : this.cfg.targetPropertyDoc.getField(path);
    Iif (!field) {
      return;
    }
    this.cfg.mappingService.removeFieldFromAllMappings(field);
    Eif (isSource) {
      this.cfg.sourcePropertyDoc.removeField(field);
    } else {
      this.cfg.targetPropertyDoc.removeField(field);
    }
    const activeMapping = this.cfg.mappings?.activeMapping;
    const expression = activeMapping?.transition?.expression;
    Iif (activeMapping && expression) {
      expression.updateFieldReference(activeMapping);
    }
    this.cfg.mappingService.notifyMappingUpdated();
  }
 
  /**
   * Edit a property field. When editing a property, the propName/propScope
   * is needed to fetch the existing field.  The newName and newScope may or
   * may not be specified.
   *
   * @param propName
   * @param propType
   * @param propScope
   * @param isSource
   * @param newName
   * @param newScope
   */
  editProperty(
    propName: string,
    propType: string,
    propScope: string,
    isSource: boolean,
    newName?: string,
    newScope?: string
  ): void {
    let oldPath = this.getPropertyPath(propScope, propName);
    let field = isSource
      ? this.cfg.sourcePropertyDoc.getField(oldPath)
      : this.cfg.targetPropertyDoc.getField(oldPath);
    Iif (!field) {
      return;
    }
    Eif (newName) {
      field.name = newName;
    }
    Eif (newScope) {
      field.scope = newScope;
    }
    field.type = FieldType[propType as keyof typeof FieldType];
    field.path = this.getPropertyPath(field.scope, field.name!);
 
    Eif (isSource) {
      this.cfg.sourcePropertyDoc.updateField(field, oldPath);
    } else {
      this.cfg.targetPropertyDoc.updateField(field, oldPath);
    }
    this.cfg.mappingService.notifyMappingUpdated();
  }
 
  /**
   * Get a {@link FieldType} of the property field.
   * @param propName
   * @param propScope
   * @param isSource
   */
  getPropertyType(
    propName: string,
    propScope: string,
    isSource: boolean
  ): FieldType {
    const field = isSource
      ? this.cfg.sourcePropertyDoc.getField(
          this.getPropertyPath(propScope, propName)
        )
      : this.cfg.targetPropertyDoc.getField(
          this.getPropertyPath(propScope, propName)
        );
    Iif (!field) {
      return FieldType.NONE;
    }
    return field.type;
  }
 
  /**
   * Get an index of the property field type.
   * @param propName
   * @param propScope
   * @param isSource
   */
  getPropertyTypeIndex(
    propName: string,
    propScope: string,
    isSource: boolean
  ): number {
    const field = isSource
      ? this.cfg.sourcePropertyDoc.getField(
          this.getPropertyPath(propScope, propName)
        )
      : this.cfg.targetPropertyDoc.getField(
          this.getPropertyPath(propScope, propName)
        );
    Iif (!field) {
      return 0;
    }
    for (let i = 0; i < propertyTypes.length; i++) {
      Eif (propertyTypes[i].includes(field.type)) {
        return i;
      }
    }
    return 0;
  }
 
  getPropertyPath(scope: string | undefined | null, name: string) {
    let answer = FIELD_PATH_SEPARATOR;
    if (scope && scope.length > 0) {
      answer += scope + FIELD_PATH_SEPARATOR;
    }
    answer += name;
    return answer;
  }
}