@itwin/imodel-transformer 0.3.2 → 0.3.3-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"IModelTransformer.js","sourceRoot":"","sources":["../../src/IModelTransformer.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,6BAA6B;AAC7B,iCAAiC;AACjC,qCAAqC;AACrC,sDAG6B;AAE7B,wDAA0D;AAC1D,sDAM6B;AAC7B,oDAI4B;AAC5B,qDAAsI;AACtI,qDAAgG;AAChG,2EAAwE;AACxE,+DAA8E;AAC9E,2CAAmD;AACnD,6DAA0D;AAC1D,mDAAgD;AAEhD,MAAM,cAAc,GAAW,qDAAyB,CAAC,iBAAiB,CAAC;AAE3E,MAAM,4BAA4B,GAAG;IACnC,QAAQ,EAAE,mBAAI,CAAC,OAAO;IACtB,QAAQ,EAAE,mBAAI,CAAC,OAAO;IACtB,aAAa,EAAE,EAAE;IACjB,UAAU,EAAE,mCAAoB,CAAC,IAAI,CAAC,OAAO;CAC9C,CAAC;AA6GF;;;GAGG;AACH,MAAM,wBAAwB;IAC5B;IACE;;;;OAIG;IACK,kBAAsC,EACtC,WAAuB;QADvB,uBAAkB,GAAlB,kBAAkB,CAAoB;QACtC,gBAAW,GAAX,WAAW,CAAY;IAC9B,CAAC;IACG,gBAAgB,CAAC,EAAmB;QACzC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC;YACpC,IAAI,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;IACM,aAAa;QAClB,IAAI,CAAC,WAAW,EAAE,CAAC;IACrB,CAAC;CACF;AAED;;;;;GAKG;AACH,SAAS,OAAO,CACd,WAAwD,EACxD,IAA2B;IAE3B,MAAM,YAAY,GAAG,CAAC,GAAQ,EAAqB,EAAE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AAS,CAAC,OAAO,EAAE;gBACrB,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,YAAa,CAAC,CAAC;gBAC/C,kBAA8C,CAAC,SAAS,GAAG,SAAS,CAAC;aACvE;SACF;aAAM,IAAI,aAAa,YAAY,iCAAkB,EAAE;YACtD,MAAM,SAAS,GAAG,yBAAW,CAAC,QAAQ,CAAE,kBAA8C,CAAC,SAAS,CAAC,CAAC;YAClG,IAAI,SAAS,CAAC,OAAO,EAAE;gBACrB,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,YAAa,CAAC,CAAC;gBAC/C,kBAA8C,CAAC,SAAS,GAAG,SAAS,CAAC;aACvE;SACF;QACD,IAAI,CAAC,sBAAuB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,EAAE,mBAAI,CAAC,OAAO,CAAC,CAAC,CAAC,qGAAqG;QACvK,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF;AAlGD,kDAkGC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module iModels\n */\nimport * as path from \"path\";\nimport * as Semver from \"semver\";\nimport * as nodeAssert from \"assert\";\nimport {\n AccessToken, assert, DbResult, Guid, Id64, Id64String, IModelStatus, Logger, MarkRequired,\n OpenMode, YieldManager,\n} from \"@itwin/core-bentley\";\nimport * as ECSchemaMetaData from \"@itwin/ecschema-metadata\";\nimport { Point3d, Transform } from \"@itwin/core-geometry\";\nimport {\n ChangeSummaryManager,\n ChannelRootAspect, ConcreteEntity, DefinitionElement, DefinitionModel, DefinitionPartition, ECSchemaXmlContext, ECSqlStatement, Element, ElementAspect, ElementMultiAspect, ElementOwnsExternalSourceAspects,\n ElementRefersToElements, ElementUniqueAspect, Entity, EntityReferences, ExternalSource, ExternalSourceAspect, ExternalSourceAttachment,\n FolderLink, GeometricElement2d, GeometricElement3d, IModelDb, IModelHost, IModelJsFs, InformationPartitionElement, KnownLocations, Model,\n RecipeDefinitionElement, Relationship, RelationshipProps, Schema, SQLiteDb, Subject, SynchronizationConfigLink,\n} from \"@itwin/core-backend\";\nimport {\n ChangeOpCode, Code, CodeProps, CodeSpec, ConcreteEntityTypes, ElementAspectProps, ElementProps, EntityReference, EntityReferenceSet,\n ExternalSourceAspectProps, FontProps, GeometricElement2dProps, GeometricElement3dProps, IModel, IModelError, ModelProps,\n Placement2d, Placement3d, PrimitiveTypeCode, PropertyMetaData, RelatedElement,\n} from \"@itwin/core-common\";\nimport { ExportChangesOptions, ExportSchemaResult, IModelExporter, IModelExporterState, IModelExportHandler } from \"./IModelExporter\";\nimport { IModelImporter, IModelImporterState, OptimizeGeometryOptions } from \"./IModelImporter\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { PendingReference, PendingReferenceMap } from \"./PendingReferenceMap\";\nimport { EntityKey, EntityMap } from \"./EntityMap\";\nimport { IModelCloneContext } from \"./IModelCloneContext\";\nimport { EntityUnifier } from \"./EntityUnifier\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelTransformer;\n\nconst nullLastProvenanceEntityInfo = {\n entityId: Id64.invalid,\n aspectId: Id64.invalid,\n aspectVersion: \"\",\n aspectKind: ExternalSourceAspect.Kind.Element,\n};\n\ntype EntityTransformHandler = (entity: ConcreteEntity) => ElementProps | ModelProps | RelationshipProps | ElementAspectProps;\n\n/** Options provided to the [[IModelTransformer]] constructor.\n * @beta\n * @note if adding an option, you must explicitly add its serialization to [[IModelTransformer.saveStateToFile]]!\n */\nexport interface IModelTransformOptions {\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances.\n * When the goal is to consolidate multiple source iModels into a single target iModel, this option must be specified.\n */\n targetScopeElementId?: Id64String;\n\n /** Set to `true` if IModelTransformer should not record its provenance.\n * Provenance tracks a target element back to its corresponding source element and is essential for [[IModelTransformer.processChanges]] to work properly.\n * Turning off IModelTransformer provenance is really only relevant for producing snapshots or another one time transformations.\n * @note See the [[includeSourceProvenance]] option for determining whether existing source provenance is cloned into the target.\n * @note The default is `false` which means that new IModelTransformer provenance will be recorded.\n */\n noProvenance?: boolean;\n\n /** Set to `true` to clone existing source provenance into the target.\n * @note See the [[noProvenance]] option for determining whether new IModelTransformer provenance is recorded.\n * @note The default is `false` which means that existing provenance in the source will not be carried into the target.\n */\n includeSourceProvenance?: boolean;\n\n /** Flag that indicates that the target iModel was created by copying the source iModel.\n * This is common when the target iModel is intended to be a *branch* of the source iModel.\n * This *hint* is essential to properly initialize the source to target element mapping and to cause provenance to be recorded for future synchronizations.\n * @note This *hint* is typically only set for the first synchronization after the iModel was copied since every other synchronization can utilize the provenance.\n */\n wasSourceIModelCopiedToTarget?: boolean;\n\n /** Flag that indicates that the current source and target iModels are now synchronizing in the reverse direction from a prior synchronization.\n * The most common example is to first synchronize master to branch, make changes to the branch, and then reverse directions to synchronize from branch to master.\n * This means that the provenance on the (current) source is used instead.\n * @note This also means that only [[IModelTransformer.processChanges]] can detect deletes.\n */\n isReverseSynchronization?: boolean;\n\n /** Flag that indicates whether or not the transformation process needs to consider the source geometry before cloning/transforming.\n * For standard cases, it is not required to load the source GeometryStream in JavaScript since the cloning happens in native code.\n * Also, the target GeometryStream will be available in JavaScript prior to insert.\n * @note If the source geometry affects the class mapping or transformation logic, then this flag should be set to `true`. The default is `false`.\n * @see [IModelExporter.wantGeometry]($transformer)\n */\n loadSourceGeometry?: boolean;\n\n /** Flag that indicates whether or not the transformation process should clone using binary geometry.\n *\n * Prefer to never to set this flag. If you need geometry changes, instead override [[IModelTransformer.onTransformElement]]\n * and provide an [ElementGeometryBuilderParams]($common) to the `elementGeometryBuilderParams`\n * property of [ElementProps]($common) instead, it is much faster. You can read geometry during the transformation by setting the\n * [[IModelTransformOptions.loadSourceGeometry]] property to `true`, and passing that to a [GeometryStreamIterator]($common)\n * @note this flag will be deprecated when `elementGeometryBuilderParams` is no longer an alpha API\n *\n * @default true\n */\n cloneUsingBinaryGeometry?: boolean;\n\n /** Flag that indicates that ids should be preserved while copying elements to the target\n * Intended only for pure-filter transforms, so you can keep parts of the source, while deleting others,\n * and element ids are guaranteed to be the same, (other entity ids are not, however)\n * @note The target must be empty.\n * @note It is invalid to insert elements during the transformation, do not use this with transformers that try to.\n * @note This does not preserve the ids of non-element entities such as link table relationships, or aspects, etc.\n * @default false\n * @beta\n */\n preserveElementIdsForFiltering?: boolean;\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n * @deprecated in 3.x. use [[danglingReferencesBehavior]] instead, the use of the term *predecessors* was confusing and became inaccurate when the transformer could handle cycles\n */\n danglingPredecessorsBehavior?: \"reject\" | \"ignore\";\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n */\n danglingReferencesBehavior?: \"reject\" | \"ignore\";\n\n /** If defined, options to be supplied to [[IModelImporter.optimizeGeometry]] by [[IModelTransformer.processChanges]] and [[IModelTransformer.processAll]]\n * as a post-processing step to optimize the geometry in the iModel.\n * @beta\n */\n optimizeGeometry?: OptimizeGeometryOptions;\n}\n\n/**\n * A container for tracking the state of a partially committed entity and finalizing it when it's ready to be fully committed\n * @internal\n */\nclass PartiallyCommittedEntity {\n public constructor(\n /**\n * A set of \"model|element ++ ID64\" pairs, (e.g. `model0x11` or `element0x12`)\n * It is possible for the submodel of an element to be separately resolved from the actual element,\n * so its resolution must be tracked separately\n */\n private _missingReferences: EntityReferenceSet,\n private _onComplete: () => void\n ) {}\n public resolveReference(id: EntityReference) {\n this._missingReferences.delete(id);\n if (this._missingReferences.size === 0)\n this._onComplete();\n }\n public forceComplete() {\n this._onComplete();\n }\n}\n\n/**\n * Apply a function to each Id64 in a supported container type of Id64s.\n * Currently only supports raw Id64String or RelatedElement-like objects containing an `id` property that is a Id64String,\n * which matches the possible containers of references in [Element.requiredReferenceKeys]($backend).\n * @internal\n */\nfunction mapId64<R>(\n idContainer: Id64String | { id: Id64String } | undefined,\n func: (id: Id64String) => R\n): R[] {\n const isId64String = (arg: any): arg is Id64String => {\n const isString = typeof arg === \"string\";\n assert(() => !isString || Id64.isValidId64(arg));\n return isString;\n };\n const isRelatedElem = (arg: any): arg is RelatedElement =>\n arg && typeof arg === \"object\" && \"id\" in arg;\n\n const results = [];\n\n // is a string if compressed or singular id64, but check for singular just checks if it's a string so do this test first\n if (idContainer === undefined) {\n // nothing\n } else if (isId64String(idContainer)) {\n results.push(func(idContainer));\n } else if (isRelatedElem(idContainer)) {\n results.push(func(idContainer.id));\n } else {\n throw Error([\n `Id64 container '${idContainer}' is unsupported.`,\n \"Currently only singular Id64 strings or prop-like objects containing an 'id' property are supported.\",\n ].join(\"\\n\"));\n }\n return results;\n}\n\n/** Arguments you can pass to [[IModelTransformer.initExternalSourceAspects]]\n * @beta\n */\nexport interface InitFromExternalSourceAspectsArgs {\n accessToken?: AccessToken;\n /**\n * Include changes from this changeset up through and including the current changeset.\n * @note To form a range of versions to process, set `startChangeset` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n * @default the current changeset of the sourceDb, if undefined\n */\n startChangeset?: {\n id?: string;\n index?: number;\n };\n}\n\n/**\n * Arguments for [[IModelTransformer.processChanges]]\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface ProcessChangesOptions extends ExportChangesOptions {\n}\n\n/** Base class used to transform a source iModel into a different target iModel.\n * @see [iModel Transformation and Data Exchange]($docs/learning/transformer/index.md), [IModelExporter]($transformer), [IModelImporter]($transformer)\n * @beta\n */\nexport class IModelTransformer extends IModelExportHandler {\n /** The IModelExporter that will export from the source iModel. */\n public readonly exporter: IModelExporter;\n /** The IModelImporter that will import into the target iModel. */\n public readonly importer: IModelImporter;\n /** The normally read-only source iModel.\n * @note The source iModel will need to be read/write when provenance is being stored during a reverse synchronization.\n */\n public readonly sourceDb: IModelDb;\n /** The read/write target iModel. */\n public readonly targetDb: IModelDb;\n /** The IModelTransformContext for this IModelTransformer. */\n public readonly context: IModelCloneContext;\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances. */\n public get targetScopeElementId(): Id64String {\n return this._options.targetScopeElementId;\n }\n\n /** map of (unprocessed element, referencing processed element) pairs to the partially committed element that needs the reference resolved\n * and have some helper methods below for now */\n protected _pendingReferences = new PendingReferenceMap<PartiallyCommittedEntity>();\n\n /** map of partially committed entities to their partial commit progress */\n protected _partiallyCommittedEntities = new EntityMap<PartiallyCommittedEntity>();\n\n /** the options that were used to initialize this transformer */\n private readonly _options: MarkRequired<IModelTransformOptions, \"targetScopeElementId\" | \"danglingReferencesBehavior\">;\n\n /** Set if it can be determined whether this is the first source --> target synchronization. */\n private _isFirstSynchronization?: boolean;\n\n /** The element classes that are considered to define provenance in the iModel */\n public static get provenanceElementClasses(): (typeof Entity)[] {\n return [FolderLink, SynchronizationConfigLink, ExternalSource, ExternalSourceAttachment];\n }\n\n /** The element aspect classes that are considered to define provenance in the iModel */\n public static get provenanceElementAspectClasses(): (typeof Entity)[] {\n return [ExternalSourceAspect];\n }\n\n /** Set of entity keys which were not exported and don't need to be tracked for pending reference resolution.\n * @note Currently only tracks elements which were not exported.\n */\n protected _skippedEntities = new Set<EntityKey>();\n\n /** Construct a new IModelTransformer\n * @param source Specifies the source IModelExporter or the source IModelDb that will be used to construct the source IModelExporter.\n * @param target Specifies the target IModelImporter or the target IModelDb that will be used to construct the target IModelImporter.\n * @param options The options that specify how the transformation should be done.\n */\n public constructor(source: IModelDb | IModelExporter, target: IModelDb | IModelImporter, options?: IModelTransformOptions) {\n super();\n // initialize IModelTransformOptions\n this._options = {\n ...options,\n // non-falsy defaults\n cloneUsingBinaryGeometry: options?.cloneUsingBinaryGeometry ?? true,\n targetScopeElementId: options?.targetScopeElementId ?? IModel.rootSubjectId,\n // eslint-disable-next-line deprecation/deprecation\n danglingReferencesBehavior: options?.danglingReferencesBehavior ?? options?.danglingPredecessorsBehavior ?? \"reject\",\n };\n this._isFirstSynchronization = this._options.wasSourceIModelCopiedToTarget ? true : undefined;\n // initialize exporter and sourceDb\n if (source instanceof IModelDb) {\n this.exporter = new IModelExporter(source);\n } else {\n this.exporter = source;\n }\n this.sourceDb = this.exporter.sourceDb;\n this.exporter.registerHandler(this);\n this.exporter.wantGeometry = options?.loadSourceGeometry ?? false; // optimization to not load source GeometryStreams by default\n if (!this._options.includeSourceProvenance) { // clone provenance from the source iModel into the target iModel?\n IModelTransformer.provenanceElementClasses.forEach((cls) => this.exporter.excludeElementClass(cls.classFullName));\n IModelTransformer.provenanceElementAspectClasses.forEach((cls) => this.exporter.excludeElementAspectClass(cls.classFullName));\n }\n this.exporter.excludeElementAspectClass(ChannelRootAspect.classFullName); // Channel boundaries within the source iModel are not relevant to the target iModel\n this.exporter.excludeElementAspectClass(\"BisCore:TextAnnotationData\"); // This ElementAspect is auto-created by the BisCore:TextAnnotation2d/3d element handlers\n // initialize importer and targetDb\n if (target instanceof IModelDb) {\n this.importer = new IModelImporter(target, { preserveElementIdsForFiltering: this._options.preserveElementIdsForFiltering });\n } else {\n this.importer = target;\n /* eslint-disable deprecation/deprecation */\n if (Boolean(this._options.preserveElementIdsForFiltering) !== this.importer.preserveElementIdsForFiltering) {\n Logger.logWarning(\n loggerCategory,\n [\n \"A custom importer was passed as a target but its 'preserveElementIdsForFiltering' option is out of sync with the transformer's option.\",\n \"The custom importer target's option will be force updated to use the transformer's value.\",\n \"This behavior is deprecated and will be removed in a future version, throwing an error if they are out of sync.\",\n ].join(\"\\n\")\n );\n this.importer.preserveElementIdsForFiltering = Boolean(this._options.preserveElementIdsForFiltering);\n }\n /* eslint-enable deprecation/deprecation */\n }\n this.targetDb = this.importer.targetDb;\n // create the IModelCloneContext, it must be initialized later\n this.context = new IModelCloneContext(this.sourceDb, this.targetDb);\n\n // this internal is guaranteed stable for just transformer usage\n /* eslint-disable @itwin/no-internal */\n if (\"codeValueBehavior\" in this.sourceDb as any) {\n (this.sourceDb as any).codeValueBehavior = \"exact\";\n (this.targetDb as any).codeValueBehavior = \"exact\";\n }\n /* eslint-enable @itwin/no-internal */\n }\n\n /** Dispose any native resources associated with this IModelTransformer. */\n public dispose(): void {\n Logger.logTrace(loggerCategory, \"dispose()\");\n this.context.dispose();\n }\n\n /** Log current settings that affect IModelTransformer's behavior. */\n private logSettings(): void {\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitElements=${this.exporter.visitElements}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitRelationships=${this.exporter.visitRelationships}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantGeometry=${this.exporter.wantGeometry}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantSystemSchemas=${this.exporter.wantSystemSchemas}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantTemplateModels=${this.exporter.wantTemplateModels}`);\n Logger.logInfo(loggerCategory, `this.targetScopeElementId=${this.targetScopeElementId}`);\n Logger.logInfo(loggerCategory, `this._noProvenance=${this._options.noProvenance}`);\n Logger.logInfo(loggerCategory, `this._includeSourceProvenance=${this._options.includeSourceProvenance}`);\n Logger.logInfo(loggerCategory, `this._cloneUsingBinaryGeometry=${this._options.cloneUsingBinaryGeometry}`);\n Logger.logInfo(loggerCategory, `this._wasSourceIModelCopiedToTarget=${this._options.wasSourceIModelCopiedToTarget}`);\n Logger.logInfo(loggerCategory, `this._isReverseSynchronization=${this._options.isReverseSynchronization}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.autoExtendProjectExtents=${this.importer.options.autoExtendProjectExtents}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.simplifyElementGeometry=${this.importer.options.simplifyElementGeometry}`);\n }\n\n /** Return the IModelDb where IModelTransformer will store its provenance.\n * @note This will be [[targetDb]] except when it is a reverse synchronization. In that case it be [[sourceDb]].\n */\n public get provenanceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.sourceDb : this.targetDb;\n }\n\n /** Return the IModelDb where IModelTransformer looks for entities referred to by stored provenance.\n * @note This will be [[sourceDb]] except when it is a reverse synchronization. In that case it be [[targetDb]].\n */\n public get provenanceSourceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.targetDb : this.sourceDb;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n public static initElementProvenanceOptions(\n sourceElementId: Id64String,\n targetElementId: Id64String,\n args: {\n sourceDb: IModelDb;\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n },\n ): ExternalSourceAspectProps {\n const elementId = args.isReverseSynchronization ? sourceElementId : targetElementId;\n const aspectIdentifier = args.isReverseSynchronization ? targetElementId : sourceElementId;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Element,\n version: args.sourceDb.elements.queryLastModifiedTime(sourceElementId),\n };\n return aspectProps;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n private initElementProvenance(sourceElementId: Id64String, targetElementId: Id64String): ExternalSourceAspectProps {\n return IModelTransformer.initElementProvenanceOptions(\n sourceElementId,\n targetElementId,\n {\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n sourceDb: this.sourceDb,\n },\n );\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for a Relationship in an iModel --> iModel transformations.\n * The ExternalSourceAspect is meant to be owned by the Element in the target iModel that is the `sourceId` of transformed relationship.\n * The `identifier` property of the ExternalSourceAspect will be the ECInstanceId of the relationship in the source iModel.\n * The ECInstanceId of the relationship in the target iModel will be stored in the JsonProperties of the ExternalSourceAspect.\n */\n private initRelationshipProvenance(sourceRelationship: Relationship, targetRelInstanceId: Id64String): ExternalSourceAspectProps {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, targetRelInstanceId);\n const elementId = this._options.isReverseSynchronization ? sourceRelationship.sourceId : targetRelationship.sourceId;\n const aspectIdentifier = this._options.isReverseSynchronization ? targetRelInstanceId : sourceRelationship.id;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: this.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Relationship,\n jsonProperties: JSON.stringify({ targetRelInstanceId }),\n };\n aspectProps.id = this.queryExternalSourceAspectId(aspectProps);\n return aspectProps;\n }\n\n private validateScopeProvenance(): void {\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: this.targetScopeElementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: this._options.isReverseSynchronization ? this.targetDb.iModelId : this.sourceDb.iModelId, // the opposite side of where provenance is stored\n kind: ExternalSourceAspect.Kind.Scope,\n };\n aspectProps.id = this.queryExternalSourceAspectId(aspectProps); // this query includes \"identifier\"\n if (undefined === aspectProps.id) {\n // this query does not include \"identifier\" to find possible conflicts\n const sql = `SELECT ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind LIMIT 1`;\n const hasConflictingScope = this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): boolean => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n statement.bindId(\"scopeId\", aspectProps.scope.id); // this scope.id can never be invalid, we create it above\n statement.bindString(\"kind\", aspectProps.kind);\n return DbResult.BE_SQLITE_ROW === statement.step();\n });\n if (hasConflictingScope) {\n throw new IModelError(IModelStatus.InvalidId, \"Provenance scope conflict\");\n }\n if (!this._options.noProvenance) {\n this.provenanceDb.elements.insertAspect(aspectProps);\n }\n }\n }\n\n private queryExternalSourceAspectId(aspectProps: ExternalSourceAspectProps): Id64String | undefined {\n const sql = `SELECT ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind AND Identifier=:identifier LIMIT 1`;\n return this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): Id64String | undefined => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n if (aspectProps.scope === undefined)\n return undefined; // return undefined instead of binding an invalid id\n statement.bindId(\"scopeId\", aspectProps.scope.id);\n statement.bindString(\"kind\", aspectProps.kind);\n statement.bindString(\"identifier\", aspectProps.identifier);\n return (DbResult.BE_SQLITE_ROW === statement.step()) ? statement.getValue(0).getId() : undefined;\n });\n }\n\n /** Iterate all matching ExternalSourceAspects in the provenance iModel (target unless reverse sync) and call a function for each one. */\n public static forEachTrackedElement(args: {\n provenanceSourceDb: IModelDb;\n provenanceDb: IModelDb;\n targetScopeElementId: Id64String;\n isReverseSynchronization: boolean;\n fn: (sourceElementId: Id64String, targetElementId: Id64String) => void;\n }): void {\n if (!args.provenanceDb.containsClass(ExternalSourceAspect.classFullName)) {\n throw new IModelError(IModelStatus.BadSchema, \"The BisCore schema version of the target database is too old\");\n }\n const sql = `SELECT Identifier,Element.Id FROM ${ExternalSourceAspect.classFullName} WHERE Scope.Id=:scopeId AND Kind=:kind`;\n args.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {\n statement.bindId(\"scopeId\", args.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const aspectIdentifier: Id64String = statement.getValue(0).getString(); // ExternalSourceAspect.Identifier is of type string\n const elementId: Id64String = statement.getValue(1).getId();\n if (args.isReverseSynchronization) {\n args.fn(elementId, aspectIdentifier); // provenance coming from the sourceDb\n } else {\n args.fn(aspectIdentifier, elementId); // provenance coming from the targetDb\n }\n }\n });\n }\n\n private forEachTrackedElement(fn: (sourceElementId: Id64String, targetElementId: Id64String) => void): void {\n return IModelTransformer.forEachTrackedElement({\n provenanceSourceDb: this._options.isReverseSynchronization ? this.sourceDb : this.targetDb,\n provenanceDb: this.provenanceDb,\n targetScopeElementId: this.targetScopeElementId,\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n fn,\n });\n }\n\n /** Initialize the source to target Element mapping from ExternalSourceAspects in the target iModel.\n * @note This method is called from all `process*` functions and should never need to be called directly.\n * @deprecated in 3.x. call [[initialize]] instead, it does the same thing among other initialization\n * @note Passing an [[InitFromExternalSourceAspectsArgs]] is required when processing changes, to remap any elements that may have been deleted.\n * You must await the returned promise as well in this case. The synchronous behavior has not changed but is deprecated and won't process everything.\n */\n public initFromExternalSourceAspects(args?: InitFromExternalSourceAspectsArgs): void | Promise<void> {\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n this.context.remapElement(sourceElementId, targetElementId);\n });\n\n if (args)\n return this.remapDeletedSourceElements(args);\n }\n\n /** When processing deleted elements in a reverse synchronization, the [[provenanceDb]] (usually a branch iModel) has already\n * deleted the [ExternalSourceAspect]($backend)s that tell us which elements in the reverse synchronization target (usually\n * a master iModel) should be deleted. We must use the changesets to get the values of those before they were deleted.\n */\n private async remapDeletedSourceElements(args: InitFromExternalSourceAspectsArgs) {\n // we need a connected iModel with changes to remap elements with deletions\n if (this.sourceDb.iTwinId === undefined)\n return;\n\n try {\n\n const startChangesetIndexOrId\n = args.startChangeset?.index\n ?? args.startChangeset?.id\n ?? this.sourceDb.changeset.index\n ?? this.sourceDb.changeset.id;\n const endChangesetId = this.sourceDb.changeset.id;\n\n const [firstChangesetIndex, endChangesetIndex] = await Promise.all(\n ([startChangesetIndexOrId, endChangesetId])\n .map(async (indexOrId) => typeof indexOrId === \"number\"\n ? indexOrId\n : IModelHost.hubAccess\n .queryChangeset({\n iModelId: this.sourceDb.iModelId,\n // eslint-disable-next-line deprecation/deprecation\n changeset: { id: indexOrId },\n accessToken: args.accessToken,\n })\n .then((changeset) => changeset.index)\n )\n );\n\n const changesetIds = await ChangeSummaryManager.createChangeSummaries({\n accessToken: args.accessToken,\n iModelId: this.sourceDb.iModelId,\n iTwinId: this.sourceDb.iTwinId,\n range: { first: firstChangesetIndex, end: endChangesetIndex },\n });\n\n ChangeSummaryManager.attachChangeCache(this.sourceDb);\n for (const changesetId of changesetIds) {\n this.sourceDb.withPreparedStatement(\n `\n SELECT esac.Element.Id, esac.Identifier\n FROM ecchange.change.InstanceChange ic\n JOIN BisCore.ExternalSourceAspect.Changes(:changesetId, 'BeforeDelete') esac\n ON ic.ChangedInstance.Id=esac.ECInstanceId\n WHERE ic.OpCode=:opcode\n AND ic.Summary.Id=:changesetId\n AND esac.Scope.Id=:targetScopeElementId\n -- not yet documented ecsql feature to check class id\n AND ic.ChangedInstance.ClassId IS (ONLY BisCore.ExternalSourceAspect)\n `,\n (stmt) => {\n stmt.bindInteger(\"opcode\", ChangeOpCode.Delete);\n stmt.bindInteger(\"changesetId\", changesetId);\n stmt.bindInteger(\"targetScopeElementId\", this.targetScopeElementId);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n const targetId = stmt.getValue(0).getId();\n const sourceId: Id64String = stmt.getValue(1).getString(); // BisCore.ExternalSourceAspect.Identifier stores a hex Id64String\n // TODO: maybe delete and don't just remap\n this.context.remapElement(targetId, sourceId);\n }\n }\n );\n }\n } finally {\n if (ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))\n ChangeSummaryManager.detachChangeCache(this.sourceDb);\n }\n }\n\n /** Returns `true` if *brute force* delete detections should be run.\n * @note Not relevant for processChanges when change history is known.\n */\n protected shouldDetectDeletes(): boolean {\n if (this._isFirstSynchronization)\n return false; // not necessary the first time since there are no deletes to detect\n\n if (this._options.isReverseSynchronization)\n return false; // not possible for a reverse synchronization since provenance will be deleted when element is deleted\n\n return true;\n }\n\n /** Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements in the source iModel.\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectElementDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const targetElementsToDelete: Id64String[] = [];\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n if (undefined === this.sourceDb.elements.tryGetElementProps(sourceElementId)) {\n // if the sourceElement is not found, then it must have been deleted, so propagate the delete to the target iModel\n targetElementsToDelete.push(targetElementId);\n }\n });\n targetElementsToDelete.forEach((targetElementId: Id64String) => {\n try {\n // TODO: make it possible to delete more elements at once to prevent redundant expensive\n // element reference scanning\n this.importer.deleteElement(targetElementId);\n } catch (err: any) {\n // ignore not found elements, iterative element tree deletion might have already deleted them\n if (err.name !== \"Not Found\")\n throw err;\n }\n });\n }\n\n /**\n * @deprecated in 3.x, this no longer has any effect except emitting a warning\n */\n protected skipElement(_sourceElement: Element): void {\n Logger.logWarning(loggerCategory, `Tried to defer/skip an element, which is no longer necessary`);\n }\n\n /** Transform the specified sourceElement into ElementProps for the target iModel.\n * @param sourceElement The Element from the source iModel to transform.\n * @returns ElementProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n * @note This can be called more than once for an element in arbitrary order, so it should not have side-effects.\n */\n public onTransformElement(sourceElement: Element): ElementProps {\n Logger.logTrace(loggerCategory, `onTransformElement(${sourceElement.id}) \"${sourceElement.getDisplayLabel()}\"`);\n const targetElementProps: ElementProps = this.context.cloneElement(sourceElement, { binaryGeometry: this._options.cloneUsingBinaryGeometry });\n if (sourceElement instanceof Subject) {\n if (targetElementProps.jsonProperties?.Subject?.Job) {\n // don't propagate source channels into target (legacy bridge case)\n targetElementProps.jsonProperties.Subject.Job = undefined;\n }\n }\n return targetElementProps;\n }\n\n /** Returns true if a change within sourceElement is detected.\n * @param sourceElement The Element from the source iModel\n * @param targetElementId The Element from the target iModel to compare against.\n * @note A subclass can override this method to provide custom change detection behavior.\n */\n protected hasElementChanged(sourceElement: Element, targetElementId: Id64String): boolean {\n const sourceAspects = this.targetDb.elements.getAspects(targetElementId, ExternalSourceAspect.classFullName) as ExternalSourceAspect[];\n for (const sourceAspect of sourceAspects) {\n if (sourceAspect.scope === undefined) // if the scope was lost, we can't correlate so assume it changed\n return true;\n if (\n sourceAspect.identifier === sourceElement.id &&\n sourceAspect.scope.id === this.targetScopeElementId &&\n sourceAspect.kind === ExternalSourceAspect.Kind.Element\n ) {\n const lastModifiedTime = sourceElement.iModel.elements.queryLastModifiedTime(sourceElement.id);\n return lastModifiedTime !== sourceAspect.version;\n }\n }\n return true;\n }\n\n private static transformCallbackFor(transformer: IModelTransformer, entity: ConcreteEntity): EntityTransformHandler {\n if (entity instanceof Element)\n return transformer.onTransformElement as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Element)\n return transformer.onTransformModel as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Relationship)\n return transformer.onTransformRelationship as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof ElementAspect)\n return transformer.onTransformElementAspect as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n /** callback to perform when a partial element says it's ready to be completed\n * transforms the source element with all references now valid, then updates the partial element with the results\n */\n private makePartialEntityCompleter(\n sourceEntity: ConcreteEntity\n ) {\n return () => {\n const targetId = this.context.findTargetEntityId(EntityReferences.from(sourceEntity));\n if (!EntityReferences.isValid(targetId))\n throw Error(`${sourceEntity.id} has not been inserted into the target yet, the completer is invalid. This is a bug.`);\n const onEntityTransform = IModelTransformer.transformCallbackFor(this, sourceEntity);\n const updateEntity = EntityUnifier.updaterFor(this.targetDb, sourceEntity);\n const targetProps = onEntityTransform.call(this, sourceEntity);\n if (sourceEntity instanceof Relationship) {\n (targetProps as RelationshipProps).sourceId = this.context.findTargetElementId(sourceEntity.sourceId);\n (targetProps as RelationshipProps).targetId = this.context.findTargetElementId(sourceEntity.targetId);\n }\n updateEntity({ ...targetProps, id: EntityReferences.toId64(targetId) });\n this._partiallyCommittedEntities.delete(sourceEntity);\n };\n }\n\n /** collect references this entity has that are yet to be mapped, and if there are any\n * create a [[PartiallyCommittedEntity]] to track resolution of those references\n */\n private collectUnmappedReferences(entity: ConcreteEntity) {\n const missingReferences = new EntityReferenceSet();\n let thisPartialElem: PartiallyCommittedEntity | undefined;\n\n // eslint-disable-next-line deprecation/deprecation\n for (const referenceId of entity.getReferenceConcreteIds()) {\n // TODO: probably need to rename from 'id' to 'ref' so these names aren't so ambiguous\n const referenceIdInTarget = this.context.findTargetEntityId(referenceId);\n const alreadyProcessed = EntityReferences.isValid(referenceIdInTarget) || this._skippedEntities.has(referenceId);\n if (alreadyProcessed)\n continue;\n Logger.logTrace(loggerCategory, `Deferring resolution of reference '${referenceId}' of element '${entity.id}'`);\n const referencedExistsInSource = EntityUnifier.exists(this.sourceDb, { entityReference: referenceId });\n if (!referencedExistsInSource) {\n Logger.logWarning(loggerCategory, `Source ${EntityUnifier.getReadableType(entity)} (${entity.id}) has a dangling reference to (${referenceId})`);\n switch (this._options.danglingReferencesBehavior) {\n case \"ignore\":\n continue;\n case \"reject\":\n throw new IModelError(\n IModelStatus.NotFound,\n [\n `Found a reference to an element \"${referenceId}\" that doesn't exist while looking for references of \"${entity.id}\".`,\n \"This must have been caused by an upstream application that changed the iModel.\",\n \"You can set the IModelTransformerOptions.danglingReferencesBehavior option to 'ignore' to ignore this, but this will leave the iModel\",\n \"in a state where downstream consuming applications will need to handle the invalidity themselves. In some cases, writing a custom\",\n \"transformer to remove the reference and fix affected elements may be suitable.\",\n ].join(\"\\n\")\n );\n }\n }\n if (thisPartialElem === undefined) {\n thisPartialElem = new PartiallyCommittedEntity(missingReferences, this.makePartialEntityCompleter(entity));\n if (!this._partiallyCommittedEntities.has(entity))\n this._partiallyCommittedEntities.set(entity, thisPartialElem);\n }\n missingReferences.add(referenceId);\n const entityReference = EntityReferences.from(entity);\n this._pendingReferences.set({ referenced: referenceId, referencer: entityReference }, thisPartialElem);\n }\n }\n\n /** Cause the specified Element and its child Elements (if applicable) to be exported from the source iModel and imported into the target iModel.\n * @param sourceElementId Identifies the Element from the source iModel to import.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processElement(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n if (sourceElementId === IModel.rootSubjectId) {\n throw new IModelError(IModelStatus.BadRequest, \"The root Subject should not be directly imported\");\n }\n return this.exporter.exportElement(sourceElementId);\n }\n\n /** Import child elements into the target IModelDb\n * @param sourceElementId Import the child elements of this element in the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processChildElements(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportChildElements(sourceElementId);\n }\n\n /** Override of [IModelExportHandler.shouldExportElement]($transformer) that is called to determine if an element should be exported from the source iModel.\n * @note Reaching this point means that the element has passed the standard exclusion checks in IModelExporter.\n */\n public override shouldExportElement(_sourceElement: Element): boolean { return true; }\n\n public override onSkipElement(sourceElementId: Id64String): void {\n if (this.context.findTargetElementId(sourceElementId) !== Id64.invalid) {\n // element already has provenance\n return;\n }\n\n Logger.logInfo(loggerCategory, `Element '${sourceElementId}' won't be exported. Marking its references as resolved`);\n const elementKey: EntityKey = `e${sourceElementId}`;\n this._skippedEntities.add(elementKey);\n\n // Mark any existing pending references to the skipped element as resolved.\n for (const referencer of this._pendingReferences.getReferencersByEntityKey(elementKey)) {\n const key = PendingReference.from(referencer, elementKey);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(elementKey);\n this._pendingReferences.delete(key);\n }\n }\n\n /**\n * If they haven't been already, import all of the required references\n * @internal do not call, override or implement this, it will be removed\n */\n public override async preExportElement(sourceElement: Element): Promise<void> {\n const elemClass = sourceElement.constructor as typeof Element;\n\n const unresolvedReferences = elemClass.requiredReferenceKeys\n .map((referenceKey) => {\n const idContainer = sourceElement[referenceKey as keyof Element];\n const referenceType = elemClass.requiredReferenceKeyTypeMap[referenceKey];\n // For now we just consider all required references to be elements (as they are in biscore), and do not support\n // entities that refuse to be inserted without a different kind of entity (e.g. aspect or relationship) first being inserted\n assert(referenceType === ConcreteEntityTypes.Element || referenceType === ConcreteEntityTypes.Model);\n return mapId64(idContainer, (id) => {\n if (id === Id64.invalid || id === IModel.rootSubjectId)\n return undefined; // not allowed to directly export the root subject\n if (!this.context.isBetweenIModels) {\n // Within the same iModel, can use existing DefinitionElements without remapping\n // This is relied upon by the TemplateModelCloner\n // TODO: extract this out to only be in the TemplateModelCloner\n const asDefinitionElem = this.sourceDb.elements.tryGetElement(id, DefinitionElement);\n if (asDefinitionElem && !(asDefinitionElem instanceof RecipeDefinitionElement)) {\n this.context.remapElement(id, id);\n }\n }\n return id;\n })\n .filter((sourceReferenceId: Id64String | undefined): sourceReferenceId is Id64String => {\n if (sourceReferenceId === undefined)\n return false;\n const referenceInTargetId = this.context.findTargetElementId(sourceReferenceId);\n const isInTarget = Id64.isValid(referenceInTargetId);\n return !isInTarget;\n });\n })\n .flat();\n\n if (unresolvedReferences.length > 0) {\n for (const reference of unresolvedReferences) {\n const processState = this.getElemTransformState(reference);\n // must export element first\n if (processState.needsElemImport)\n await this.exporter.exportElement(reference);\n if (processState.needsModelImport)\n await this.exporter.exportModel(reference);\n }\n }\n }\n\n private getElemTransformState(elementId: Id64String) {\n const dbHasModel = (db: IModelDb, id: Id64String) => {\n const maybeModelId = EntityReferences.fromEntityType(id, ConcreteEntityTypes.Model);\n return EntityUnifier.exists(db, { entityReference: maybeModelId });\n };\n const isSubModeled = dbHasModel(this.sourceDb, elementId);\n const idOfElemInTarget = this.context.findTargetElementId(elementId);\n const isElemInTarget = Id64.invalid !== idOfElemInTarget;\n const needsModelImport = isSubModeled && (!isElemInTarget || !dbHasModel(this.targetDb, idOfElemInTarget));\n return { needsElemImport: !isElemInTarget, needsModelImport };\n }\n\n /** Override of [IModelExportHandler.onExportElement]($transformer) that imports an element into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElement]] and then [IModelImporter.importElement]($transformer) to update the target iModel.\n */\n public override onExportElement(sourceElement: Element): void {\n let targetElementId: Id64String | undefined;\n let targetElementProps: ElementProps;\n if (this._options.preserveElementIdsForFiltering) {\n targetElementId = sourceElement.id;\n targetElementProps = this.onTransformElement(sourceElement);\n } else if (this._options.wasSourceIModelCopiedToTarget) {\n targetElementId = sourceElement.id;\n targetElementProps = this.targetDb.elements.getElementProps(targetElementId);\n } else {\n targetElementId = this.context.findTargetElementId(sourceElement.id);\n targetElementProps = this.onTransformElement(sourceElement);\n }\n // if an existing remapping was not yet found, check by Code as long as the CodeScope is valid (invalid means a missing reference so not worth checking)\n if (!Id64.isValidId64(targetElementId) && Id64.isValidId64(targetElementProps.code.scope)) {\n // respond the same way to undefined code value as the @see Code class, but don't use that class because it trims\n // whitespace from the value, and there are iModels out there with untrimmed whitespace that we ought not to trim\n targetElementProps.code.value = targetElementProps.code.value ?? \"\";\n targetElementId = this.targetDb.elements.queryElementIdByCode(targetElementProps.code as Required<CodeProps>);\n if (undefined !== targetElementId) {\n const targetElement: Element = this.targetDb.elements.getElement(targetElementId);\n if (targetElement.classFullName === targetElementProps.classFullName) { // ensure code remapping doesn't change the target class\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code\n } else {\n targetElementId = undefined;\n targetElementProps.code = Code.createEmpty(); // clear out invalid code\n }\n }\n }\n if (undefined !== targetElementId && Id64.isValidId64(targetElementId)) {\n // compare LastMod of sourceElement to ExternalSourceAspect of targetElement to see there are changes to import\n if (!this.hasElementChanged(sourceElement, targetElementId)) {\n return;\n }\n }\n\n this.collectUnmappedReferences(sourceElement);\n\n // TODO: untangle targetElementId state...\n if (targetElementId === Id64.invalid)\n targetElementId = undefined;\n\n targetElementProps.id = targetElementId; // targetElementId will be valid (indicating update) or undefined (indicating insert)\n if (!this._options.wasSourceIModelCopiedToTarget) {\n this.importer.importElement(targetElementProps); // don't need to import if iModel was copied\n }\n this.context.remapElement(sourceElement.id, targetElementProps.id!); // targetElementProps.id assigned by importElement\n // now that we've mapped this elem we can fix unmapped references to it\n this.resolvePendingReferences(sourceElement);\n\n if (!this._options.noProvenance) {\n const aspectProps: ExternalSourceAspectProps = this.initElementProvenance(sourceElement.id, targetElementProps.id!);\n let aspectId = this.queryExternalSourceAspectId(aspectProps);\n if (aspectId === undefined) {\n aspectId = this.provenanceDb.elements.insertAspect(aspectProps);\n } else {\n this.provenanceDb.elements.updateAspect(aspectProps);\n }\n aspectProps.id = aspectId;\n this.markLastProvenance(aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship: false });\n }\n }\n\n private resolvePendingReferences(entity: ConcreteEntity) {\n for (const referencer of this._pendingReferences.getReferencers(entity)) {\n const key = PendingReference.from(referencer, entity);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(EntityReferences.from(entity));\n this._pendingReferences.delete(key);\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteElement]($transformer) that is called when [IModelExporter]($transformer) detects that an Element has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteElement]($transformer).\n */\n public override onDeleteElement(sourceElementId: Id64String): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceElementId);\n if (Id64.isValidId64(targetElementId)) {\n this.importer.deleteElement(targetElementId);\n }\n }\n\n /** Override of [IModelExportHandler.onExportModel]($transformer) that is called when a Model should be exported from the source iModel.\n * This override calls [[onTransformModel]] and then [IModelImporter.importModel]($transformer) to update the target iModel.\n */\n public override onExportModel(sourceModel: Model): void {\n if (IModel.repositoryModelId === sourceModel.id) {\n return; // The RepositoryModel should not be directly imported\n }\n const targetModeledElementId: Id64String = this.context.findTargetElementId(sourceModel.id);\n const targetModelProps: ModelProps = this.onTransformModel(sourceModel, targetModeledElementId);\n this.importer.importModel(targetModelProps);\n this.resolvePendingReferences(sourceModel);\n }\n\n /** Override of [IModelExportHandler.onDeleteModel]($transformer) that is called when [IModelExporter]($transformer) detects that a [Model]($backend) has been deleted from the source iModel. */\n public override onDeleteModel(sourceModelId: Id64String): void {\n // It is possible and apparently occasionally sensical to delete a model without deleting its underlying element.\n // - If only the model is deleted, [[initFromExternalSourceAspects]] will have already remapped the underlying element since it still exists.\n // - If both were deleted, [[remapDeletedSourceElements]] will find and remap the deleted element making this operation valid\n const targetModelId: Id64String = this.context.findTargetElementId(sourceModelId);\n\n if (!Id64.isValidId64(targetModelId))\n return;\n\n if (this.exporter.sourceDbChanges?.element.deleteIds.has(sourceModelId)) {\n const isDefinitionPartition = this.targetDb.withPreparedStatement(`\n SELECT 1\n FROM bis.DefinitionPartition\n WHERE ECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, targetModelId);\n const val: DbResult = stmt.step();\n switch (val) {\n case DbResult.BE_SQLITE_ROW: return true;\n case DbResult.BE_SQLITE_DONE: return false;\n default: assert(false, `unexpected db result: '${stmt}'`);\n }\n });\n if (isDefinitionPartition) {\n // Skipping model deletion because model's partition will also be deleted.\n // It expects that model will be present and will fail if it's missing.\n // Model will be deleted when its partition will be deleted.\n return;\n }\n }\n\n try {\n this.importer.deleteModel(targetModelId);\n } catch (error) {\n const isDeletionProhibitedErr = error instanceof IModelError && (error.errorNumber === IModelStatus.DeletionProhibited || error.errorNumber === IModelStatus.ForeignKeyConstraint);\n if (!isDeletionProhibitedErr)\n throw error;\n\n // Transformer tries to delete models before it deletes elements. Definition models cannot be deleted unless all of their modeled elements are deleted first.\n // In case a definition model needs to be deleted we need to skip it for now and register its modeled partition for deletion.\n // The `OnDeleteElement` calls `DeleteElementTree` Which deletes the model together with its partition after deleting all of the modeled elements.\n this.scheduleModeledPartitionDeletion(sourceModelId);\n }\n }\n\n /** Schedule modeled partition deletion */\n private scheduleModeledPartitionDeletion(sourceModelId: Id64String): void {\n const deletedElements = this.exporter.sourceDbChanges?.element.deleteIds as Set<Id64String>;\n if (!deletedElements.has(sourceModelId)) {\n deletedElements.add(sourceModelId);\n }\n }\n\n /** Cause the model container, contents, and sub-models to be exported from the source iModel and imported into the target iModel.\n * @param sourceModeledElementId Import this [Model]($backend) from the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModel(sourceModeledElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportModel(sourceModeledElementId);\n }\n\n /** Cause the model contents to be exported from the source iModel and imported into the target iModel.\n * @param sourceModelId Import the contents of this model from the source IModelDb.\n * @param targetModelId Import into this model in the target IModelDb. The target model must exist prior to this call.\n * @param elementClassFullName Optional classFullName of an element subclass to limit import query against the source model.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModelContents(sourceModelId: Id64String, targetModelId: Id64String, elementClassFullName: string = Element.classFullName): Promise<void> {\n await this.initialize();\n this.targetDb.models.getModel(targetModelId); // throws if Model does not exist\n this.context.remapElement(sourceModelId, targetModelId); // set remapping in case importModelContents is called directly\n return this.exporter.exportModelContents(sourceModelId, elementClassFullName);\n }\n\n /** Cause all sub-models that recursively descend from the specified Subject to be exported from the source iModel and imported into the target iModel. */\n private async processSubjectSubModels(sourceSubjectId: Id64String): Promise<void> {\n await this.initialize();\n // import DefinitionModels first\n const childDefinitionPartitionSql = `SELECT ECInstanceId FROM ${DefinitionPartition.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childDefinitionPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processModel(statement.getValue(0).getId());\n }\n });\n // import other partitions next\n const childPartitionSql = `SELECT ECInstanceId FROM ${InformationPartitionElement.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const modelId: Id64String = statement.getValue(0).getId();\n const model: Model = this.sourceDb.models.getModel(modelId);\n if (!(model instanceof DefinitionModel)) {\n await this.processModel(modelId);\n }\n }\n });\n // recurse into child Subjects\n const childSubjectSql = `SELECT ECInstanceId FROM ${Subject.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childSubjectSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processSubjectSubModels(statement.getValue(0).getId());\n }\n });\n }\n\n /** Transform the specified sourceModel into ModelProps for the target iModel.\n * @param sourceModel The Model from the source iModel to be transformed.\n * @param targetModeledElementId The transformed Model will *break down* or *detail* this Element in the target iModel.\n * @returns ModelProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n public onTransformModel(sourceModel: Model, targetModeledElementId: Id64String): ModelProps {\n const targetModelProps: ModelProps = sourceModel.toJSON();\n // don't directly edit deep object since toJSON performs a shallow clone\n targetModelProps.modeledElement = { ...targetModelProps.modeledElement, id: targetModeledElementId };\n targetModelProps.id = targetModeledElementId;\n targetModelProps.parentModel = this.context.findTargetElementId(targetModelProps.parentModel!);\n return targetModelProps;\n }\n\n /** Import elements that were deferred in a prior pass.\n * @deprecated in 3.x. This method is no longer necessary since the transformer no longer needs to defer elements\n */\n public async processDeferredElements(_numRetries: number = 3): Promise<void> {}\n\n private finalizeTransformation() {\n if (this._partiallyCommittedEntities.size > 0) {\n Logger.logWarning(\n loggerCategory,\n [\n \"The following elements were never fully resolved:\",\n [...this._partiallyCommittedEntities.keys()].join(\",\"),\n \"This indicates that either some references were excluded from the transformation\",\n \"or the source has dangling references.\",\n ].join(\"\\n\")\n );\n for (const partiallyCommittedElem of this._partiallyCommittedEntities.values()) {\n partiallyCommittedElem.forceComplete();\n }\n }\n // this internal is guaranteed stable for just transformer usage\n /* eslint-disable @itwin/no-internal */\n if (\"codeValueBehavior\" in this.sourceDb as any) {\n (this.sourceDb as any).codeValueBehavior = \"trim-unicode-whitespace\";\n (this.targetDb as any).codeValueBehavior = \"trim-unicode-whitespace\";\n }\n /* eslint-enable @itwin/no-internal */\n }\n\n /** Imports all relationships that subclass from the specified base class.\n * @param baseRelClassFullName The specified base relationship class.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processRelationships(baseRelClassFullName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportRelationships(baseRelClassFullName);\n }\n\n /** Override of [IModelExportHandler.shouldExportRelationship]($transformer) that is called to determine if a [Relationship]($backend) should be exported.\n * @note Reaching this point means that the relationship has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportRelationship(_sourceRelationship: Relationship): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportRelationship]($transformer) that imports a relationship into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformRelationship]] and then [IModelImporter.importRelationship]($transformer) to update the target iModel.\n */\n public override onExportRelationship(sourceRelationship: Relationship): void {\n const targetRelationshipProps: RelationshipProps = this.onTransformRelationship(sourceRelationship);\n const targetRelationshipInstanceId: Id64String = this.importer.importRelationship(targetRelationshipProps);\n if (!this._options.noProvenance && Id64.isValidId64(targetRelationshipInstanceId)) {\n const aspectProps: ExternalSourceAspectProps = this.initRelationshipProvenance(sourceRelationship, targetRelationshipInstanceId);\n if (undefined === aspectProps.id) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n }\n assert(aspectProps.id !== undefined);\n this.markLastProvenance(aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship: true });\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteRelationship]($transformer) that is called when [IModelExporter]($transformer) detects that a [Relationship]($backend) has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteRelationship]($transformer).\n */\n public override onDeleteRelationship(sourceRelInstanceId: Id64String): void {\n const sql = `SELECT ECInstanceId,JsonProperties FROM ${ExternalSourceAspect.classFullName} aspect` +\n ` WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind AND aspect.Identifier=:identifier LIMIT 1`;\n this.targetDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n statement.bindString(\"identifier\", sourceRelInstanceId);\n if (DbResult.BE_SQLITE_ROW === statement.step()) {\n const json: any = JSON.parse(statement.getValue(1).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship = this.targetDb.relationships.tryGetInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n if (targetRelationship) {\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n this.targetDb.elements.deleteAspect(statement.getValue(0).getId());\n }\n }\n });\n }\n\n private _yieldManager = new YieldManager();\n\n /** Detect Relationship deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against relationships in the source iModel.\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectRelationshipDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const aspectDeleteIds: Id64String[] = [];\n const sql = `SELECT ECInstanceId,Identifier,JsonProperties FROM ${ExternalSourceAspect.classFullName} aspect WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind`;\n await this.targetDb.withPreparedStatement(sql, async (statement: ECSqlStatement) => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const sourceRelInstanceId: Id64String = Id64.fromJSON(statement.getValue(1).getString());\n if (undefined === this.sourceDb.relationships.tryGetInstanceProps(ElementRefersToElements.classFullName, sourceRelInstanceId)) {\n const json: any = JSON.parse(statement.getValue(2).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n aspectDeleteIds.push(statement.getValue(0).getId());\n }\n await this._yieldManager.allowYield();\n }\n });\n this.targetDb.elements.deleteAspect(aspectDeleteIds);\n }\n\n /** Transform the specified sourceRelationship into RelationshipProps for the target iModel.\n * @param sourceRelationship The Relationship from the source iModel to be transformed.\n * @returns RelationshipProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformRelationship(sourceRelationship: Relationship): RelationshipProps {\n const targetRelationshipProps: RelationshipProps = sourceRelationship.toJSON();\n targetRelationshipProps.sourceId = this.context.findTargetElementId(sourceRelationship.sourceId);\n targetRelationshipProps.targetId = this.context.findTargetElementId(sourceRelationship.targetId);\n sourceRelationship.forEachProperty((propertyName: string, propertyMetaData: PropertyMetaData) => {\n if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetRelationshipProps as any)[propertyName] = this.context.findTargetElementId(sourceRelationship.asAny[propertyName]);\n }\n });\n return targetRelationshipProps;\n }\n\n /** Override of [IModelExportHandler.onExportElementUniqueAspect]($transformer) that imports an ElementUniqueAspect into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElementAspect]] and then [IModelImporter.importElementUniqueAspect]($transformer) to update the target iModel.\n */\n public override onExportElementUniqueAspect(sourceAspect: ElementUniqueAspect): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspect.element.id);\n const targetAspectProps = this.onTransformElementAspect(sourceAspect, targetElementId);\n this.collectUnmappedReferences(sourceAspect);\n const targetId = this.importer.importElementUniqueAspect(targetAspectProps);\n this.context.remapElementAspect(sourceAspect.id, targetId);\n this.resolvePendingReferences(sourceAspect);\n }\n\n /** Override of [IModelExportHandler.onExportElementMultiAspects]($transformer) that imports ElementMultiAspects into the target iModel when they are exported from the source iModel.\n * This override calls [[onTransformElementAspect]] for each ElementMultiAspect and then [IModelImporter.importElementMultiAspects]($transformer) to update the target iModel.\n * @note ElementMultiAspects are handled as a group to make it easier to differentiate between insert, update, and delete.\n */\n public override onExportElementMultiAspects(sourceAspects: ElementMultiAspect[]): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspects[0].element.id);\n // Transform source ElementMultiAspects into target ElementAspectProps\n const targetAspectPropsArray = sourceAspects.map((srcA) => this.onTransformElementAspect(srcA, targetElementId));\n sourceAspects.forEach((a) => this.collectUnmappedReferences(a));\n // const targetAspectsToImport = targetAspectPropsArray.filter((targetAspect, i) => hasEntityChanged(sourceAspects[i], targetAspect));\n const targetIds = this.importer.importElementMultiAspects(targetAspectPropsArray, (a) => {\n const isExternalSourceAspectFromTransformer = a instanceof ExternalSourceAspect && a.scope?.id === this.targetScopeElementId;\n return !this._options.includeSourceProvenance || !isExternalSourceAspectFromTransformer;\n });\n for (let i = 0; i < targetIds.length; ++i) {\n this.context.remapElementAspect(sourceAspects[i].id, targetIds[i]);\n this.resolvePendingReferences(sourceAspects[i]);\n }\n }\n\n /** Transform the specified sourceElementAspect into ElementAspectProps for the target iModel.\n * @param sourceElementAspect The ElementAspect from the source iModel to be transformed.\n * @param _targetElementId The ElementId of the target Element that will own the ElementAspects after transformation.\n * @returns ElementAspectProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformElementAspect(sourceElementAspect: ElementAspect, _targetElementId: Id64String): ElementAspectProps {\n const targetElementAspectProps = this.context.cloneElementAspect(sourceElementAspect);\n return targetElementAspectProps;\n }\n\n /** The directory where schemas will be exported, a random temporary directory */\n protected _schemaExportDir: string = path.join(KnownLocations.tmpdir, Guid.createValue());\n\n /** Override of [IModelExportHandler.shouldExportSchema]($transformer) that is called to determine if a schema should be exported\n * @note the default behavior doesn't import schemas older than those already in the target\n */\n public override shouldExportSchema(schemaKey: ECSchemaMetaData.SchemaKey): boolean {\n const versionInTarget = this.targetDb.querySchemaVersion(schemaKey.name);\n if (versionInTarget === undefined)\n return true;\n return Semver.gt(`${schemaKey.version.read}.${schemaKey.version.write}.${schemaKey.version.minor}`, Schema.toSemverString(versionInTarget));\n }\n\n private _longNamedSchemasMap = new Map<string, string>();\n\n /** Override of [IModelExportHandler.onExportSchema]($transformer) that serializes a schema to disk for [[processSchemas]] to import into\n * the target iModel when it is exported from the source iModel.\n * @returns {Promise<ExportSchemaResult>} Although the type is possibly void for backwards compatibility of subclasses,\n * `IModelTransformer.onExportSchema` always returns an[[IModelExportHandler.ExportSchemaResult]]\n * with a defined `schemaPath` property, for subclasses to know where the schema was written.\n * Schemas are *not* guaranteed to be written to [[IModelTransformer._schemaExportDir]] by a\n * known pattern derivable from the schema's name, so you must use this to find it.\n */\n public override async onExportSchema(schema: ECSchemaMetaData.Schema): Promise<void | ExportSchemaResult> {\n const ext = \".ecschema.xml\";\n let schemaFileName = schema.name + ext;\n // many file systems have a max file-name/path-segment size of 255, so we workaround that on all systems\n const systemMaxPathSegmentSize = 255;\n if (schemaFileName.length > systemMaxPathSegmentSize) {\n // this name should be well under 255 bytes\n // ( 100 + (Number.MAX_SAFE_INTEGER.toString().length = 16) + (ext.length = 13) ) = 129 which is less than 255\n // You'd have to be past 2**53-1 (Number.MAX_SAFE_INTEGER) long named schemas in order to hit decimal formatting,\n // and that's on the scale of at least petabytes. `Map.prototype.size` shouldn't return floating points, and even\n // if they do they're in scientific notation, size bound and contain no invalid windows path chars\n schemaFileName = `${schema.name.slice(0, 100)}${this._longNamedSchemasMap.size}${ext}`;\n nodeAssert(schemaFileName.length <= systemMaxPathSegmentSize, \"Schema name was still long. This is a bug.\");\n this._longNamedSchemasMap.set(schema.name, schemaFileName);\n }\n this.sourceDb.nativeDb.exportSchema(schema.name, this._schemaExportDir, schemaFileName);\n return { schemaPath: path.join(this._schemaExportDir, schemaFileName) };\n }\n\n private _makeLongNameResolvingSchemaCtx(): ECSchemaXmlContext {\n const result = new ECSchemaXmlContext();\n result.setSchemaLocater((key) => {\n const match = this._longNamedSchemasMap.get(key.name);\n if (match !== undefined)\n return path.join(this._schemaExportDir, match);\n return undefined;\n });\n return result;\n }\n\n /** Cause all schemas to be exported from the source iModel and imported into the target iModel.\n * @note For performance reasons, it is recommended that [IModelDb.saveChanges]($backend) be called after `processSchemas` is complete.\n * It is more efficient to process *data* changes after the schema changes have been saved.\n */\n public async processSchemas(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n try {\n IModelJsFs.mkdirSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n await this.exporter.exportSchemas();\n const exportedSchemaFiles = IModelJsFs.readdirSync(this._schemaExportDir);\n if (exportedSchemaFiles.length === 0)\n return;\n const schemaFullPaths = exportedSchemaFiles.map((s) => path.join(this._schemaExportDir, s));\n const maybeLongNameResolvingSchemaCtx = this._longNamedSchemasMap.size > 0\n ? this._makeLongNameResolvingSchemaCtx()\n : undefined;\n return await this.targetDb.importSchemas(schemaFullPaths, { ecSchemaXmlContext: maybeLongNameResolvingSchemaCtx });\n } finally {\n IModelJsFs.removeSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n }\n }\n\n /** Cause all fonts to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processFonts(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n await this.initialize();\n return this.exporter.exportFonts();\n }\n\n /** Override of [IModelExportHandler.onExportFont]($transformer) that imports a font into the target iModel when it is exported from the source iModel. */\n public override onExportFont(font: FontProps, _isUpdate: boolean | undefined): void {\n this.context.importFont(font.id);\n }\n\n /** Cause all CodeSpecs to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpecs(): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecs();\n }\n\n /** Cause a single CodeSpec to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpec(codeSpecName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecByName(codeSpecName);\n }\n\n /** Override of [IModelExportHandler.shouldExportCodeSpec]($transformer) that is called to determine if a CodeSpec should be exported from the source iModel.\n * @note Reaching this point means that the CodeSpec has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportCodeSpec(_sourceCodeSpec: CodeSpec): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportCodeSpec]($transformer) that imports a CodeSpec into the target iModel when it is exported from the source iModel. */\n public override onExportCodeSpec(sourceCodeSpec: CodeSpec): void {\n this.context.importCodeSpec(sourceCodeSpec.id);\n }\n\n /** Recursively import all Elements and sub-Models that descend from the specified Subject */\n public async processSubject(sourceSubjectId: Id64String, targetSubjectId: Id64String): Promise<void> {\n await this.initialize();\n this.sourceDb.elements.getElement(sourceSubjectId, Subject); // throws if sourceSubjectId is not a Subject\n this.targetDb.elements.getElement(targetSubjectId, Subject); // throws if targetSubjectId is not a Subject\n this.context.remapElement(sourceSubjectId, targetSubjectId);\n await this.processChildElements(sourceSubjectId);\n await this.processSubjectSubModels(sourceSubjectId);\n return this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n }\n\n /** state to prevent reinitialization, @see [[initialize]] */\n private _initialized = false;\n\n /**\n * Initialize prerequisites of processing, you must initialize with an [[InitFromExternalSourceAspectsArgs]] if you\n * are intending process changes, but prefer using [[processChanges]]\n * Called by all `process*` functions implicitly.\n * Overriders must call `super.initialize()` first\n */\n public async initialize(args?: InitFromExternalSourceAspectsArgs) {\n if (this._initialized)\n return;\n await this.context.initialize();\n // eslint-disable-next-line deprecation/deprecation\n await this.initFromExternalSourceAspects(args);\n this._initialized = true;\n }\n\n /** Export everything from the source iModel and import the transformed entities into the target iModel.\n * @note [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.\n */\n public async processAll(): Promise<void> {\n Logger.logTrace(loggerCategory, \"processAll()\");\n this.logSettings();\n this.validateScopeProvenance();\n await this.initialize();\n await this.exporter.exportCodeSpecs();\n await this.exporter.exportFonts();\n // The RepositoryModel and root Subject of the target iModel should not be transformed.\n await this.exporter.exportChildElements(IModel.rootSubjectId); // start below the root Subject\n await this.exporter.exportModelContents(IModel.repositoryModelId, Element.classFullName, true); // after the Subject hierarchy, process the other elements of the RepositoryModel\n await this.exporter.exportSubModels(IModel.repositoryModelId); // start below the RepositoryModel\n await this.exporter.exportRelationships(ElementRefersToElements.classFullName);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n if (this.shouldDetectDeletes()) {\n await this.detectElementDeletes();\n await this.detectRelationshipDeletes();\n }\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n\n private _lastProvenanceEntityInfo = nullLastProvenanceEntityInfo;\n\n private markLastProvenance(sourceAspect: MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship = false }) {\n this._lastProvenanceEntityInfo = {\n entityId: sourceAspect.element.id,\n aspectId: sourceAspect.id,\n aspectVersion: sourceAspect.version ?? \"\",\n aspectKind: isRelationship ? ExternalSourceAspect.Kind.Relationship : ExternalSourceAspect.Kind.Element,\n };\n }\n\n /** @internal the name of the table where javascript state of the transformer is serialized in transformer state dumps */\n public static readonly jsStateTable = \"TransformerJsState\";\n\n /** @internal the name of the table where the target state heuristics is serialized in transformer state dumps */\n public static readonly lastProvenanceEntityInfoTable = \"LastProvenanceEntityInfo\";\n\n /**\n * Load the state of the active transformation from an open SQLiteDb\n * You can override this if you'd like to load from custom tables in the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected loadStateFromDb(db: SQLiteDb): void {\n const lastProvenanceEntityInfo: IModelTransformer[\"_lastProvenanceEntityInfo\"] = db.withSqliteStatement(\n `SELECT entityId, aspectId, aspectVersion, aspectKind FROM ${IModelTransformer.lastProvenanceEntityInfoTable}`,\n (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\n \"expected row when getting lastProvenanceEntityId from target state table\"\n );\n return {\n entityId: stmt.getValueString(0),\n aspectId: stmt.getValueString(1),\n aspectVersion: stmt.getValueString(2),\n aspectKind: stmt.getValueString(3) as ExternalSourceAspect.Kind,\n };\n }\n );\n const targetHasCorrectLastProvenance =\n // ignore provenance check if it's null since we can't bind those ids\n !Id64.isValidId64(lastProvenanceEntityInfo.aspectId) ||\n !Id64.isValidId64(lastProvenanceEntityInfo.entityId) ||\n this.provenanceDb.withPreparedStatement(`\n SELECT Version FROM ${ExternalSourceAspect.classFullName}\n WHERE Scope.Id=:scopeId\n AND ECInstanceId=:aspectId\n AND Kind=:kind\n AND Element.Id=:entityId\n `,\n (statement: ECSqlStatement): boolean => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindId(\"aspectId\", lastProvenanceEntityInfo.aspectId);\n statement.bindString(\"kind\", lastProvenanceEntityInfo.aspectKind);\n statement.bindId(\"entityId\", lastProvenanceEntityInfo.entityId);\n const stepResult = statement.step();\n switch (stepResult) {\n case DbResult.BE_SQLITE_ROW:\n const version = statement.getValue(0).getString();\n return version === lastProvenanceEntityInfo.aspectVersion;\n case DbResult.BE_SQLITE_DONE:\n return false;\n default:\n throw new IModelError(IModelStatus.SQLiteError, `got sql error ${stepResult}`);\n }\n });\n if (!targetHasCorrectLastProvenance)\n throw Error([\n \"Target for resuming from does not have the expected provenance \",\n \"from the target that the resume state was made with\",\n ].join(\"\\n\"));\n this._lastProvenanceEntityInfo = lastProvenanceEntityInfo;\n\n const state = db.withSqliteStatement(`SELECT data FROM ${IModelTransformer.jsStateTable}`, (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\"expected row when getting data from js state table\");\n return JSON.parse(stmt.getValueString(0)) as TransformationJsonState;\n });\n if (state.transformerClass !== this.constructor.name)\n throw Error(\"resuming from a differently named transformer class, it is not necessarily valid to resume with a different transformer class\");\n // force assign to readonly options since we do not know how the transformer subclass takes options to pass to the superclass\n (this as any)._options = state.options;\n this.context.loadStateFromDb(db);\n this.importer.loadStateFromJson(state.importerState);\n this.exporter.loadStateFromJson(state.exporterState);\n this.loadAdditionalStateJson(state.additionalState);\n }\n\n /**\n * Return a new transformer instance with the same remappings state as saved from a previous [[IModelTransformer.saveStateToFile]] call.\n * This allows you to \"resume\" an iModel transformation, you will have to call [[IModelTransformer.processChanges]]/[[IModelTransformer.processAll]]\n * again but the remapping state will cause already mapped elements to be skipped.\n * To \"resume\" an iModel Transformation you need:\n * - the sourceDb at the same changeset\n * - the same targetDb in the state in which it was before\n * @param statePath the path to the serialized state of the transformer, use [[IModelTransformer.saveStateToFile]] to get this from an existing transformer instance\n * @param constructorArgs remaining arguments that you would normally pass to the Transformer subclass you are using, usually (sourceDb, targetDb)\n * @note custom transformers with custom state may need to override this method in order to handle loading their own custom state somewhere\n */\n public static resumeTransformation<SubClass extends new(...a: any[]) => IModelTransformer = typeof IModelTransformer>(\n this: SubClass,\n statePath: string,\n ...constructorArgs: ConstructorParameters<SubClass>\n ): InstanceType<SubClass> {\n const transformer = new this(...constructorArgs);\n const db = new SQLiteDb();\n db.openDb(statePath, OpenMode.Readonly);\n try {\n transformer.loadStateFromDb(db);\n } finally {\n db.closeDb();\n }\n return transformer as InstanceType<SubClass>;\n }\n\n /**\n * You may override this to store arbitrary json state in a transformer state dump, useful for some resumptions\n * @see [[IModelTransformer.saveStateToFile]]\n */\n protected getAdditionalStateJson(): any {\n return {};\n }\n\n /**\n * You may override this to load arbitrary json state in a transformer state dump, useful for some resumptions\n * @see [[IModelTransformer.loadStateFromFile]]\n */\n protected loadAdditionalStateJson(_additionalState: any): void {}\n\n /**\n * Save the state of the active transformation to an open SQLiteDb\n * You can override this if you'd like to write custom tables to the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected saveStateToDb(db: SQLiteDb): void {\n const jsonState: TransformationJsonState = {\n transformerClass: this.constructor.name,\n options: this._options,\n importerState: this.importer.saveStateToJson(),\n exporterState: this.exporter.saveStateToJson(),\n additionalState: this.getAdditionalStateJson(),\n };\n\n this.context.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`CREATE TABLE ${IModelTransformer.jsStateTable} (data TEXT)`))\n throw Error(\"Failed to create the js state table in the state database\");\n\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`\n CREATE TABLE ${IModelTransformer.lastProvenanceEntityInfoTable} (\n -- because we cannot bind the invalid id which we use for our null state, we actually store the id as a hex string\n entityId TEXT,\n aspectId TEXT,\n aspectVersion TEXT,\n aspectKind TEXT\n )\n `))\n throw Error(\"Failed to create the target state table in the state database\");\n\n db.saveChanges();\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.jsStateTable} (data) VALUES (?)`,\n (stmt) => {\n stmt.bindString(1, JSON.stringify(jsonState));\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.lastProvenanceEntityInfoTable} (entityId, aspectId, aspectVersion, aspectKind) VALUES (?,?,?,?)`,\n (stmt) => {\n stmt.bindString(1, this._lastProvenanceEntityInfo.entityId);\n stmt.bindString(2, this._lastProvenanceEntityInfo.aspectId);\n stmt.bindString(3, this._lastProvenanceEntityInfo.aspectVersion);\n stmt.bindString(4, this._lastProvenanceEntityInfo.aspectKind);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.saveChanges();\n }\n\n /**\n * Save the state of the active transformation to a file path, if a file at the path already exists, it will be overwritten\n * This state can be used by [[IModelTransformer.resumeTransformation]] to resume a transformation from this point.\n * The serialization format is a custom sqlite database.\n * @note custom transformers with custom state may override [[IModelTransformer.saveStateToDb]] or [[IModelTransformer.getAdditionalStateJson]]\n * and [[IModelTransformer.loadStateFromDb]] (with a super call) or [[IModelTransformer.loadAdditionalStateJson]]\n * if they have custom state that needs to be stored with\n * potentially inside the same sqlite file in separate tables\n */\n public saveStateToFile(nativeStatePath: string): void {\n const db = new SQLiteDb();\n if (IModelJsFs.existsSync(nativeStatePath))\n IModelJsFs.unlinkSync(nativeStatePath);\n db.createDb(nativeStatePath);\n try {\n this.saveStateToDb(db);\n db.saveChanges();\n } finally {\n db.closeDb();\n }\n }\n\n /** Export changes from the source iModel and import the transformed entities into the target iModel.\n * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n */\n public async processChanges(args: ProcessChangesOptions): Promise<void>;\n /** @deprecated in 0.1.x, use a single [[ProcessChangesOptions]] object instead */\n public async processChanges(accessToken: AccessToken, startChangesetId?: string): Promise<void>;\n public async processChanges(accessTokenOrArgs: AccessToken | ProcessChangesOptions, startChangesetId?: string): Promise<void> {\n Logger.logTrace(loggerCategory, \"processChanges()\");\n this.logSettings();\n this.validateScopeProvenance();\n\n const options: ProcessChangesOptions = typeof accessTokenOrArgs === \"string\"\n ? {\n accessToken: accessTokenOrArgs,\n startChangeset: startChangesetId ? { id: startChangesetId } : this.sourceDb.changeset,\n changedInstanceIds: undefined,\n }\n : accessTokenOrArgs;\n\n await this.initialize(options);\n await this.exporter.exportChanges(options);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n}\n\n/** @internal the json part of a transformation's state */\ninterface TransformationJsonState {\n transformerClass: string;\n options: IModelTransformOptions;\n importerState: IModelImporterState;\n exporterState: IModelExporterState;\n additionalState?: any;\n}\n\n/** IModelTransformer that clones the contents of a template model.\n * @beta\n */\nexport class TemplateModelCloner extends IModelTransformer {\n /** The Placement to apply to the template. */\n private _transform3d?: Transform;\n /** Accumulates the mapping of sourceElementIds to targetElementIds from the elements in the template model that were cloned. */\n private _sourceIdToTargetIdMap?: Map<Id64String, Id64String>;\n /** Construct a new TemplateModelCloner\n * @param sourceDb The source IModelDb that contains the templates to clone\n * @param targetDb Optionally specify the target IModelDb where the cloned template will be inserted.\n * Typically this is left unspecified, and the default is to use the sourceDb as the target\n * @note The expectation is that the template definitions are within the same iModel where instances will be placed.\n */\n public constructor(sourceDb: IModelDb, targetDb: IModelDb = sourceDb) {\n const target = new IModelImporter(targetDb, {\n autoExtendProjectExtents: false, // autoExtendProjectExtents is intended for transformation service use cases, not template --> instance cloning\n });\n super(sourceDb, target, { noProvenance: true }); // WIP: need to decide the proper way to handle provenance\n }\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel3d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the SpatialCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate3d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement3d): Promise<Map<Id64String, Id64String>> {\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(placement.origin, placement.angles.toMatrix3d());\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel2d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the DrawingCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate2d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement2d): Promise<Map<Id64String, Id64String>> {\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(Point3d.createFrom(placement.origin), placement.rotation);\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Cloning from a template requires this override of onTransformElement. */\n public override onTransformElement(sourceElement: Element): ElementProps {\n // eslint-disable-next-line deprecation/deprecation\n const referenceIds = sourceElement.getReferenceConcreteIds();\n referenceIds.forEach((referenceId) => {\n // FIXME: consider going through all definition elements at once and remapping them to themselves\n if (!EntityReferences.isValid(this.context.findTargetEntityId(referenceId))) {\n if (this.context.isBetweenIModels) {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for source dependency ${referenceId} not found for target iModel`);\n } else {\n const definitionElement = this.sourceDb.elements.tryGetElement<DefinitionElement>(referenceId, DefinitionElement);\n if (definitionElement && !(definitionElement instanceof RecipeDefinitionElement)) {\n this.context.remapElement(referenceId, referenceId); // when in the same iModel, can use existing DefinitionElements without remapping\n } else {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for dependency ${referenceId} not found`);\n }\n }\n }\n });\n\n const targetElementProps: ElementProps = super.onTransformElement(sourceElement);\n targetElementProps.federationGuid = Guid.createValue(); // clone from template should create a new federationGuid\n targetElementProps.code = Code.createEmpty(); // clone from template should not maintain codes\n if (sourceElement instanceof GeometricElement3d) {\n const placement = Placement3d.fromJSON((targetElementProps as GeometricElement3dProps).placement);\n if (placement.isValid) {\n placement.multiplyTransform(this._transform3d!);\n (targetElementProps as GeometricElement3dProps).placement = placement;\n }\n } else if (sourceElement instanceof GeometricElement2d) {\n const placement = Placement2d.fromJSON((targetElementProps as GeometricElement2dProps).placement);\n if (placement.isValid) {\n placement.multiplyTransform(this._transform3d!);\n (targetElementProps as GeometricElement2dProps).placement = placement;\n }\n }\n this._sourceIdToTargetIdMap!.set(sourceElement.id, Id64.invalid); // keep track of (source) elementIds from the template model, but the target hasn't been inserted yet\n return targetElementProps;\n }\n}\n"]}
1
+ {"version":3,"file":"IModelTransformer.js","sourceRoot":"","sources":["../../src/IModelTransformer.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,6BAA6B;AAC7B,iCAAiC;AACjC,qCAAqC;AACrC,sDAG6B;AAE7B,wDAA0D;AAC1D,sDAM6B;AAC7B,oDAI4B;AAC5B,qDAAsI;AACtI,qDAAgG;AAChG,2EAAwE;AACxE,+DAA8E;AAC9E,2CAAmD;AACnD,6DAA0D;AAC1D,mDAAgD;AAEhD,MAAM,cAAc,GAAW,qDAAyB,CAAC,iBAAiB,CAAC;AAE3E,MAAM,4BAA4B,GAAG;IACnC,QAAQ,EAAE,mBAAI,CAAC,OAAO;IACtB,QAAQ,EAAE,mBAAI,CAAC,OAAO;IACtB,aAAa,EAAE,EAAE;IACjB,UAAU,EAAE,mCAAoB,CAAC,IAAI,CAAC,OAAO;CAC9C,CAAC;AA6GF;;;GAGG;AACH,MAAM,wBAAwB;IAC5B;IACE;;;;OAIG;IACK,kBAAsC,EACtC,WAAuB;QADvB,uBAAkB,GAAlB,kBAAkB,CAAoB;QACtC,gBAAW,GAAX,WAAW,CAAY;IAC9B,CAAC;IACG,gBAAgB,CAAC,EAAmB;QACzC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC;YACpC,IAAI,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;IACM,aAAa;QAClB,IAAI,CAAC,WAAW,EAAE,CAAC;IACrB,CAAC;CACF;AAED;;;;;GAKG;AACH,SAAS,OAAO,CACd,WAAwD,EACxD,IAA2B;IAE3B,MAAM,YAAY,GAAG,CAAC,GAAQ,EAAqB,EAAE;QACnD,MA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AAK,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC;QACjF,kBAAkB,CAAC,cAAc,GAAG,mBAAI,CAAC,WAAW,EAAE,CAAC,CAAC,yDAAyD;QACjH,kBAAkB,CAAC,IAAI,GAAG,kBAAI,CAAC,WAAW,EAAE,CAAC,CAAC,gDAAgD;QAC9F,IAAI,aAAa,YAAY,iCAAkB,EAAE;YAC/C,MAAM,SAAS,GAAG,yBAAW,CAAC,QAAQ,CAAE,kBAA8C,CAAC,SAAS,CAAC,CAAC;YAClG,IAAI,SAAS,CAAC,OAAO,EAAE;gBACrB,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,YAAa,CAAC,CAAC;gBAC/C,kBAA8C,CAAC,SAAS,GAAG,SAAS,CAAC;aACvE;SACF;aAAM,IAAI,aAAa,YAAY,iCAAkB,EAAE;YACtD,MAAM,SAAS,GAAG,yBAAW,CAAC,QAAQ,CAAE,kBAA8C,CAAC,SAAS,CAAC,CAAC;YAClG,IAAI,SAAS,CAAC,OAAO,EAAE;gBACrB,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,YAAa,CAAC,CAAC;gBAC/C,kBAA8C,CAAC,SAAS,GAAG,SAAS,CAAC;aACvE;SACF;QACD,IAAI,CAAC,sBAAuB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,EAAE,mBAAI,CAAC,OAAO,CAAC,CAAC,CAAC,qGAAqG;QACvK,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF;AAlGD,kDAkGC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module iModels\n */\nimport * as path from \"path\";\nimport * as Semver from \"semver\";\nimport * as nodeAssert from \"assert\";\nimport {\n AccessToken, assert, DbResult, Guid, Id64, Id64String, IModelStatus, Logger, MarkRequired,\n OpenMode, YieldManager,\n} from \"@itwin/core-bentley\";\nimport * as ECSchemaMetaData from \"@itwin/ecschema-metadata\";\nimport { Point3d, Transform } from \"@itwin/core-geometry\";\nimport {\n ChangeSummaryManager,\n ChannelRootAspect, ConcreteEntity, DefinitionElement, DefinitionModel, DefinitionPartition, ECSchemaXmlContext, ECSqlStatement, Element, ElementAspect, ElementMultiAspect, ElementOwnsExternalSourceAspects,\n ElementRefersToElements, ElementUniqueAspect, Entity, EntityReferences, ExternalSource, ExternalSourceAspect, ExternalSourceAttachment,\n FolderLink, GeometricElement2d, GeometricElement3d, IModelDb, IModelHost, IModelJsFs, InformationPartitionElement, KnownLocations, Model,\n RecipeDefinitionElement, Relationship, RelationshipProps, Schema, SQLiteDb, Subject, SynchronizationConfigLink,\n} from \"@itwin/core-backend\";\nimport {\n ChangeOpCode, Code, CodeProps, CodeSpec, ConcreteEntityTypes, ElementAspectProps, ElementProps, EntityReference, EntityReferenceSet,\n ExternalSourceAspectProps, FontProps, GeometricElement2dProps, GeometricElement3dProps, IModel, IModelError, ModelProps,\n Placement2d, Placement3d, PrimitiveTypeCode, PropertyMetaData, RelatedElement,\n} from \"@itwin/core-common\";\nimport { ExportChangesOptions, ExportSchemaResult, IModelExporter, IModelExporterState, IModelExportHandler } from \"./IModelExporter\";\nimport { IModelImporter, IModelImporterState, OptimizeGeometryOptions } from \"./IModelImporter\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { PendingReference, PendingReferenceMap } from \"./PendingReferenceMap\";\nimport { EntityKey, EntityMap } from \"./EntityMap\";\nimport { IModelCloneContext } from \"./IModelCloneContext\";\nimport { EntityUnifier } from \"./EntityUnifier\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelTransformer;\n\nconst nullLastProvenanceEntityInfo = {\n entityId: Id64.invalid,\n aspectId: Id64.invalid,\n aspectVersion: \"\",\n aspectKind: ExternalSourceAspect.Kind.Element,\n};\n\ntype EntityTransformHandler = (entity: ConcreteEntity) => ElementProps | ModelProps | RelationshipProps | ElementAspectProps;\n\n/** Options provided to the [[IModelTransformer]] constructor.\n * @beta\n * @note if adding an option, you must explicitly add its serialization to [[IModelTransformer.saveStateToFile]]!\n */\nexport interface IModelTransformOptions {\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances.\n * When the goal is to consolidate multiple source iModels into a single target iModel, this option must be specified.\n */\n targetScopeElementId?: Id64String;\n\n /** Set to `true` if IModelTransformer should not record its provenance.\n * Provenance tracks a target element back to its corresponding source element and is essential for [[IModelTransformer.processChanges]] to work properly.\n * Turning off IModelTransformer provenance is really only relevant for producing snapshots or another one time transformations.\n * @note See the [[includeSourceProvenance]] option for determining whether existing source provenance is cloned into the target.\n * @note The default is `false` which means that new IModelTransformer provenance will be recorded.\n */\n noProvenance?: boolean;\n\n /** Set to `true` to clone existing source provenance into the target.\n * @note See the [[noProvenance]] option for determining whether new IModelTransformer provenance is recorded.\n * @note The default is `false` which means that existing provenance in the source will not be carried into the target.\n */\n includeSourceProvenance?: boolean;\n\n /** Flag that indicates that the target iModel was created by copying the source iModel.\n * This is common when the target iModel is intended to be a *branch* of the source iModel.\n * This *hint* is essential to properly initialize the source to target element mapping and to cause provenance to be recorded for future synchronizations.\n * @note This *hint* is typically only set for the first synchronization after the iModel was copied since every other synchronization can utilize the provenance.\n */\n wasSourceIModelCopiedToTarget?: boolean;\n\n /** Flag that indicates that the current source and target iModels are now synchronizing in the reverse direction from a prior synchronization.\n * The most common example is to first synchronize master to branch, make changes to the branch, and then reverse directions to synchronize from branch to master.\n * This means that the provenance on the (current) source is used instead.\n * @note This also means that only [[IModelTransformer.processChanges]] can detect deletes.\n */\n isReverseSynchronization?: boolean;\n\n /** Flag that indicates whether or not the transformation process needs to consider the source geometry before cloning/transforming.\n * For standard cases, it is not required to load the source GeometryStream in JavaScript since the cloning happens in native code.\n * Also, the target GeometryStream will be available in JavaScript prior to insert.\n * @note If the source geometry affects the class mapping or transformation logic, then this flag should be set to `true`. The default is `false`.\n * @see [IModelExporter.wantGeometry]($transformer)\n */\n loadSourceGeometry?: boolean;\n\n /** Flag that indicates whether or not the transformation process should clone using binary geometry.\n *\n * Prefer to never to set this flag. If you need geometry changes, instead override [[IModelTransformer.onTransformElement]]\n * and provide an [ElementGeometryBuilderParams]($common) to the `elementGeometryBuilderParams`\n * property of [ElementProps]($common) instead, it is much faster. You can read geometry during the transformation by setting the\n * [[IModelTransformOptions.loadSourceGeometry]] property to `true`, and passing that to a [GeometryStreamIterator]($common)\n * @note this flag will be deprecated when `elementGeometryBuilderParams` is no longer an alpha API\n *\n * @default true\n */\n cloneUsingBinaryGeometry?: boolean;\n\n /** Flag that indicates that ids should be preserved while copying elements to the target\n * Intended only for pure-filter transforms, so you can keep parts of the source, while deleting others,\n * and element ids are guaranteed to be the same, (other entity ids are not, however)\n * @note The target must be empty.\n * @note It is invalid to insert elements during the transformation, do not use this with transformers that try to.\n * @note This does not preserve the ids of non-element entities such as link table relationships, or aspects, etc.\n * @default false\n * @beta\n */\n preserveElementIdsForFiltering?: boolean;\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n * @deprecated in 3.x. use [[danglingReferencesBehavior]] instead, the use of the term *predecessors* was confusing and became inaccurate when the transformer could handle cycles\n */\n danglingPredecessorsBehavior?: \"reject\" | \"ignore\";\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n */\n danglingReferencesBehavior?: \"reject\" | \"ignore\";\n\n /** If defined, options to be supplied to [[IModelImporter.optimizeGeometry]] by [[IModelTransformer.processChanges]] and [[IModelTransformer.processAll]]\n * as a post-processing step to optimize the geometry in the iModel.\n * @beta\n */\n optimizeGeometry?: OptimizeGeometryOptions;\n}\n\n/**\n * A container for tracking the state of a partially committed entity and finalizing it when it's ready to be fully committed\n * @internal\n */\nclass PartiallyCommittedEntity {\n public constructor(\n /**\n * A set of \"model|element ++ ID64\" pairs, (e.g. `model0x11` or `element0x12`)\n * It is possible for the submodel of an element to be separately resolved from the actual element,\n * so its resolution must be tracked separately\n */\n private _missingReferences: EntityReferenceSet,\n private _onComplete: () => void\n ) {}\n public resolveReference(id: EntityReference) {\n this._missingReferences.delete(id);\n if (this._missingReferences.size === 0)\n this._onComplete();\n }\n public forceComplete() {\n this._onComplete();\n }\n}\n\n/**\n * Apply a function to each Id64 in a supported container type of Id64s.\n * Currently only supports raw Id64String or RelatedElement-like objects containing an `id` property that is a Id64String,\n * which matches the possible containers of references in [Element.requiredReferenceKeys]($backend).\n * @internal\n */\nfunction mapId64<R>(\n idContainer: Id64String | { id: Id64String } | undefined,\n func: (id: Id64String) => R\n): R[] {\n const isId64String = (arg: any): arg is Id64String => {\n const isString = typeof arg === \"string\";\n assert(() => !isString || Id64.isValidId64(arg));\n return isString;\n };\n const isRelatedElem = (arg: any): arg is RelatedElement =>\n arg && typeof arg === \"object\" && \"id\" in arg;\n\n const results = [];\n\n // is a string if compressed or singular id64, but check for singular just checks if it's a string so do this test first\n if (idContainer === undefined) {\n // nothing\n } else if (isId64String(idContainer)) {\n results.push(func(idContainer));\n } else if (isRelatedElem(idContainer)) {\n results.push(func(idContainer.id));\n } else {\n throw Error([\n `Id64 container '${idContainer}' is unsupported.`,\n \"Currently only singular Id64 strings or prop-like objects containing an 'id' property are supported.\",\n ].join(\"\\n\"));\n }\n return results;\n}\n\n/** Arguments you can pass to [[IModelTransformer.initExternalSourceAspects]]\n * @beta\n */\nexport interface InitFromExternalSourceAspectsArgs {\n accessToken?: AccessToken;\n /**\n * Include changes from this changeset up through and including the current changeset.\n * @note To form a range of versions to process, set `startChangeset` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n * @default the current changeset of the sourceDb, if undefined\n */\n startChangeset?: {\n id?: string;\n index?: number;\n };\n}\n\n/**\n * Arguments for [[IModelTransformer.processChanges]]\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface ProcessChangesOptions extends ExportChangesOptions {\n}\n\n/** Base class used to transform a source iModel into a different target iModel.\n * @see [iModel Transformation and Data Exchange]($docs/learning/transformer/index.md), [IModelExporter]($transformer), [IModelImporter]($transformer)\n * @beta\n */\nexport class IModelTransformer extends IModelExportHandler {\n /** The IModelExporter that will export from the source iModel. */\n public readonly exporter: IModelExporter;\n /** The IModelImporter that will import into the target iModel. */\n public readonly importer: IModelImporter;\n /** The normally read-only source iModel.\n * @note The source iModel will need to be read/write when provenance is being stored during a reverse synchronization.\n */\n public readonly sourceDb: IModelDb;\n /** The read/write target iModel. */\n public readonly targetDb: IModelDb;\n /** The IModelTransformContext for this IModelTransformer. */\n public readonly context: IModelCloneContext;\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances. */\n public get targetScopeElementId(): Id64String {\n return this._options.targetScopeElementId;\n }\n\n /** map of (unprocessed element, referencing processed element) pairs to the partially committed element that needs the reference resolved\n * and have some helper methods below for now */\n protected _pendingReferences = new PendingReferenceMap<PartiallyCommittedEntity>();\n\n /** map of partially committed entities to their partial commit progress */\n protected _partiallyCommittedEntities = new EntityMap<PartiallyCommittedEntity>();\n\n /** the options that were used to initialize this transformer */\n private readonly _options: MarkRequired<IModelTransformOptions, \"targetScopeElementId\" | \"danglingReferencesBehavior\">;\n\n /** Set if it can be determined whether this is the first source --> target synchronization. */\n private _isFirstSynchronization?: boolean;\n\n /** The element classes that are considered to define provenance in the iModel */\n public static get provenanceElementClasses(): (typeof Entity)[] {\n return [FolderLink, SynchronizationConfigLink, ExternalSource, ExternalSourceAttachment];\n }\n\n /** The element aspect classes that are considered to define provenance in the iModel */\n public static get provenanceElementAspectClasses(): (typeof Entity)[] {\n return [ExternalSourceAspect];\n }\n\n /** Set of entity keys which were not exported and don't need to be tracked for pending reference resolution.\n * @note Currently only tracks elements which were not exported.\n */\n protected _skippedEntities = new Set<EntityKey>();\n\n /** Construct a new IModelTransformer\n * @param source Specifies the source IModelExporter or the source IModelDb that will be used to construct the source IModelExporter.\n * @param target Specifies the target IModelImporter or the target IModelDb that will be used to construct the target IModelImporter.\n * @param options The options that specify how the transformation should be done.\n */\n public constructor(source: IModelDb | IModelExporter, target: IModelDb | IModelImporter, options?: IModelTransformOptions) {\n super();\n // initialize IModelTransformOptions\n this._options = {\n ...options,\n // non-falsy defaults\n cloneUsingBinaryGeometry: options?.cloneUsingBinaryGeometry ?? true,\n targetScopeElementId: options?.targetScopeElementId ?? IModel.rootSubjectId,\n // eslint-disable-next-line deprecation/deprecation\n danglingReferencesBehavior: options?.danglingReferencesBehavior ?? options?.danglingPredecessorsBehavior ?? \"reject\",\n };\n this._isFirstSynchronization = this._options.wasSourceIModelCopiedToTarget ? true : undefined;\n // initialize exporter and sourceDb\n if (source instanceof IModelDb) {\n this.exporter = new IModelExporter(source);\n } else {\n this.exporter = source;\n }\n this.sourceDb = this.exporter.sourceDb;\n this.exporter.registerHandler(this);\n this.exporter.wantGeometry = options?.loadSourceGeometry ?? false; // optimization to not load source GeometryStreams by default\n if (!this._options.includeSourceProvenance) { // clone provenance from the source iModel into the target iModel?\n IModelTransformer.provenanceElementClasses.forEach((cls) => this.exporter.excludeElementClass(cls.classFullName));\n IModelTransformer.provenanceElementAspectClasses.forEach((cls) => this.exporter.excludeElementAspectClass(cls.classFullName));\n }\n this.exporter.excludeElementAspectClass(ChannelRootAspect.classFullName); // Channel boundaries within the source iModel are not relevant to the target iModel\n this.exporter.excludeElementAspectClass(\"BisCore:TextAnnotationData\"); // This ElementAspect is auto-created by the BisCore:TextAnnotation2d/3d element handlers\n // initialize importer and targetDb\n if (target instanceof IModelDb) {\n this.importer = new IModelImporter(target, { preserveElementIdsForFiltering: this._options.preserveElementIdsForFiltering });\n } else {\n this.importer = target;\n /* eslint-disable deprecation/deprecation */\n if (Boolean(this._options.preserveElementIdsForFiltering) !== this.importer.preserveElementIdsForFiltering) {\n Logger.logWarning(\n loggerCategory,\n [\n \"A custom importer was passed as a target but its 'preserveElementIdsForFiltering' option is out of sync with the transformer's option.\",\n \"The custom importer target's option will be force updated to use the transformer's value.\",\n \"This behavior is deprecated and will be removed in a future version, throwing an error if they are out of sync.\",\n ].join(\"\\n\")\n );\n this.importer.preserveElementIdsForFiltering = Boolean(this._options.preserveElementIdsForFiltering);\n }\n /* eslint-enable deprecation/deprecation */\n }\n this.targetDb = this.importer.targetDb;\n // create the IModelCloneContext, it must be initialized later\n this.context = new IModelCloneContext(this.sourceDb, this.targetDb);\n\n // this internal is guaranteed stable for just transformer usage\n /* eslint-disable @itwin/no-internal */\n if (\"codeValueBehavior\" in this.sourceDb as any) {\n (this.sourceDb as any).codeValueBehavior = \"exact\";\n (this.targetDb as any).codeValueBehavior = \"exact\";\n }\n /* eslint-enable @itwin/no-internal */\n }\n\n /** Dispose any native resources associated with this IModelTransformer. */\n public dispose(): void {\n Logger.logTrace(loggerCategory, \"dispose()\");\n this.context.dispose();\n }\n\n /** Log current settings that affect IModelTransformer's behavior. */\n private logSettings(): void {\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitElements=${this.exporter.visitElements}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitRelationships=${this.exporter.visitRelationships}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantGeometry=${this.exporter.wantGeometry}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantSystemSchemas=${this.exporter.wantSystemSchemas}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantTemplateModels=${this.exporter.wantTemplateModels}`);\n Logger.logInfo(loggerCategory, `this.targetScopeElementId=${this.targetScopeElementId}`);\n Logger.logInfo(loggerCategory, `this._noProvenance=${this._options.noProvenance}`);\n Logger.logInfo(loggerCategory, `this._includeSourceProvenance=${this._options.includeSourceProvenance}`);\n Logger.logInfo(loggerCategory, `this._cloneUsingBinaryGeometry=${this._options.cloneUsingBinaryGeometry}`);\n Logger.logInfo(loggerCategory, `this._wasSourceIModelCopiedToTarget=${this._options.wasSourceIModelCopiedToTarget}`);\n Logger.logInfo(loggerCategory, `this._isReverseSynchronization=${this._options.isReverseSynchronization}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.autoExtendProjectExtents=${this.importer.options.autoExtendProjectExtents}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.simplifyElementGeometry=${this.importer.options.simplifyElementGeometry}`);\n }\n\n /** Return the IModelDb where IModelTransformer will store its provenance.\n * @note This will be [[targetDb]] except when it is a reverse synchronization. In that case it be [[sourceDb]].\n */\n public get provenanceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.sourceDb : this.targetDb;\n }\n\n /** Return the IModelDb where IModelTransformer looks for entities referred to by stored provenance.\n * @note This will be [[sourceDb]] except when it is a reverse synchronization. In that case it be [[targetDb]].\n */\n public get provenanceSourceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.targetDb : this.sourceDb;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n public static initElementProvenanceOptions(\n sourceElementId: Id64String,\n targetElementId: Id64String,\n args: {\n sourceDb: IModelDb;\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n },\n ): ExternalSourceAspectProps {\n const elementId = args.isReverseSynchronization ? sourceElementId : targetElementId;\n const aspectIdentifier = args.isReverseSynchronization ? targetElementId : sourceElementId;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Element,\n version: args.sourceDb.elements.queryLastModifiedTime(sourceElementId),\n };\n return aspectProps;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n private initElementProvenance(sourceElementId: Id64String, targetElementId: Id64String): ExternalSourceAspectProps {\n return IModelTransformer.initElementProvenanceOptions(\n sourceElementId,\n targetElementId,\n {\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n sourceDb: this.sourceDb,\n },\n );\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for a Relationship in an iModel --> iModel transformations.\n * The ExternalSourceAspect is meant to be owned by the Element in the target iModel that is the `sourceId` of transformed relationship.\n * The `identifier` property of the ExternalSourceAspect will be the ECInstanceId of the relationship in the source iModel.\n * The ECInstanceId of the relationship in the target iModel will be stored in the JsonProperties of the ExternalSourceAspect.\n */\n private initRelationshipProvenance(sourceRelationship: Relationship, targetRelInstanceId: Id64String): ExternalSourceAspectProps {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, targetRelInstanceId);\n const elementId = this._options.isReverseSynchronization ? sourceRelationship.sourceId : targetRelationship.sourceId;\n const aspectIdentifier = this._options.isReverseSynchronization ? targetRelInstanceId : sourceRelationship.id;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: this.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Relationship,\n jsonProperties: JSON.stringify({ targetRelInstanceId }),\n };\n aspectProps.id = this.queryExternalSourceAspectId(aspectProps);\n return aspectProps;\n }\n\n private validateScopeProvenance(): void {\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: this.targetScopeElementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: this._options.isReverseSynchronization ? this.targetDb.iModelId : this.sourceDb.iModelId, // the opposite side of where provenance is stored\n kind: ExternalSourceAspect.Kind.Scope,\n };\n aspectProps.id = this.queryExternalSourceAspectId(aspectProps); // this query includes \"identifier\"\n if (undefined === aspectProps.id) {\n // this query does not include \"identifier\" to find possible conflicts\n const sql = `SELECT ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind LIMIT 1`;\n const hasConflictingScope = this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): boolean => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n statement.bindId(\"scopeId\", aspectProps.scope.id); // this scope.id can never be invalid, we create it above\n statement.bindString(\"kind\", aspectProps.kind);\n return DbResult.BE_SQLITE_ROW === statement.step();\n });\n if (hasConflictingScope) {\n throw new IModelError(IModelStatus.InvalidId, \"Provenance scope conflict\");\n }\n if (!this._options.noProvenance) {\n this.provenanceDb.elements.insertAspect(aspectProps);\n }\n }\n }\n\n private queryExternalSourceAspectId(aspectProps: ExternalSourceAspectProps): Id64String | undefined {\n const sql = `SELECT ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind AND Identifier=:identifier LIMIT 1`;\n return this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): Id64String | undefined => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n if (aspectProps.scope === undefined)\n return undefined; // return undefined instead of binding an invalid id\n statement.bindId(\"scopeId\", aspectProps.scope.id);\n statement.bindString(\"kind\", aspectProps.kind);\n statement.bindString(\"identifier\", aspectProps.identifier);\n return (DbResult.BE_SQLITE_ROW === statement.step()) ? statement.getValue(0).getId() : undefined;\n });\n }\n\n /** Iterate all matching ExternalSourceAspects in the provenance iModel (target unless reverse sync) and call a function for each one. */\n public static forEachTrackedElement(args: {\n provenanceSourceDb: IModelDb;\n provenanceDb: IModelDb;\n targetScopeElementId: Id64String;\n isReverseSynchronization: boolean;\n fn: (sourceElementId: Id64String, targetElementId: Id64String) => void;\n }): void {\n if (!args.provenanceDb.containsClass(ExternalSourceAspect.classFullName)) {\n throw new IModelError(IModelStatus.BadSchema, \"The BisCore schema version of the target database is too old\");\n }\n const sql = `SELECT Identifier,Element.Id FROM ${ExternalSourceAspect.classFullName} WHERE Scope.Id=:scopeId AND Kind=:kind`;\n args.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {\n statement.bindId(\"scopeId\", args.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const aspectIdentifier: Id64String = statement.getValue(0).getString(); // ExternalSourceAspect.Identifier is of type string\n const elementId: Id64String = statement.getValue(1).getId();\n if (args.isReverseSynchronization) {\n args.fn(elementId, aspectIdentifier); // provenance coming from the sourceDb\n } else {\n args.fn(aspectIdentifier, elementId); // provenance coming from the targetDb\n }\n }\n });\n }\n\n private forEachTrackedElement(fn: (sourceElementId: Id64String, targetElementId: Id64String) => void): void {\n return IModelTransformer.forEachTrackedElement({\n provenanceSourceDb: this._options.isReverseSynchronization ? this.sourceDb : this.targetDb,\n provenanceDb: this.provenanceDb,\n targetScopeElementId: this.targetScopeElementId,\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n fn,\n });\n }\n\n /** Initialize the source to target Element mapping from ExternalSourceAspects in the target iModel.\n * @note This method is called from all `process*` functions and should never need to be called directly.\n * @deprecated in 3.x. call [[initialize]] instead, it does the same thing among other initialization\n * @note Passing an [[InitFromExternalSourceAspectsArgs]] is required when processing changes, to remap any elements that may have been deleted.\n * You must await the returned promise as well in this case. The synchronous behavior has not changed but is deprecated and won't process everything.\n */\n public initFromExternalSourceAspects(args?: InitFromExternalSourceAspectsArgs): void | Promise<void> {\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n this.context.remapElement(sourceElementId, targetElementId);\n });\n\n if (args)\n return this.remapDeletedSourceElements(args);\n }\n\n /** When processing deleted elements in a reverse synchronization, the [[provenanceDb]] (usually a branch iModel) has already\n * deleted the [ExternalSourceAspect]($backend)s that tell us which elements in the reverse synchronization target (usually\n * a master iModel) should be deleted. We must use the changesets to get the values of those before they were deleted.\n */\n private async remapDeletedSourceElements(args: InitFromExternalSourceAspectsArgs) {\n // we need a connected iModel with changes to remap elements with deletions\n if (this.sourceDb.iTwinId === undefined)\n return;\n\n try {\n\n const startChangesetIndexOrId\n = args.startChangeset?.index\n ?? args.startChangeset?.id\n ?? this.sourceDb.changeset.index\n ?? this.sourceDb.changeset.id;\n const endChangesetId = this.sourceDb.changeset.id;\n\n const [firstChangesetIndex, endChangesetIndex] = await Promise.all(\n ([startChangesetIndexOrId, endChangesetId])\n .map(async (indexOrId) => typeof indexOrId === \"number\"\n ? indexOrId\n : IModelHost.hubAccess\n .queryChangeset({\n iModelId: this.sourceDb.iModelId,\n // eslint-disable-next-line deprecation/deprecation\n changeset: { id: indexOrId },\n accessToken: args.accessToken,\n })\n .then((changeset) => changeset.index)\n )\n );\n\n const changesetIds = await ChangeSummaryManager.createChangeSummaries({\n accessToken: args.accessToken,\n iModelId: this.sourceDb.iModelId,\n iTwinId: this.sourceDb.iTwinId,\n range: { first: firstChangesetIndex, end: endChangesetIndex },\n });\n\n ChangeSummaryManager.attachChangeCache(this.sourceDb);\n for (const changesetId of changesetIds) {\n this.sourceDb.withPreparedStatement(\n `\n SELECT esac.Element.Id, esac.Identifier\n FROM ecchange.change.InstanceChange ic\n JOIN BisCore.ExternalSourceAspect.Changes(:changesetId, 'BeforeDelete') esac\n ON ic.ChangedInstance.Id=esac.ECInstanceId\n WHERE ic.OpCode=:opcode\n AND ic.Summary.Id=:changesetId\n AND esac.Scope.Id=:targetScopeElementId\n -- not yet documented ecsql feature to check class id\n AND ic.ChangedInstance.ClassId IS (ONLY BisCore.ExternalSourceAspect)\n `,\n (stmt) => {\n stmt.bindInteger(\"opcode\", ChangeOpCode.Delete);\n stmt.bindInteger(\"changesetId\", changesetId);\n stmt.bindInteger(\"targetScopeElementId\", this.targetScopeElementId);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n const targetId = stmt.getValue(0).getId();\n const sourceId: Id64String = stmt.getValue(1).getString(); // BisCore.ExternalSourceAspect.Identifier stores a hex Id64String\n // TODO: maybe delete and don't just remap\n this.context.remapElement(targetId, sourceId);\n }\n }\n );\n }\n } finally {\n if (ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))\n ChangeSummaryManager.detachChangeCache(this.sourceDb);\n }\n }\n\n /** Returns `true` if *brute force* delete detections should be run.\n * @note Not relevant for processChanges when change history is known.\n */\n protected shouldDetectDeletes(): boolean {\n if (this._isFirstSynchronization)\n return false; // not necessary the first time since there are no deletes to detect\n\n if (this._options.isReverseSynchronization)\n return false; // not possible for a reverse synchronization since provenance will be deleted when element is deleted\n\n return true;\n }\n\n /** Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements in the source iModel.\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectElementDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const targetElementsToDelete: Id64String[] = [];\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n if (undefined === this.sourceDb.elements.tryGetElementProps(sourceElementId)) {\n // if the sourceElement is not found, then it must have been deleted, so propagate the delete to the target iModel\n targetElementsToDelete.push(targetElementId);\n }\n });\n targetElementsToDelete.forEach((targetElementId: Id64String) => {\n try {\n // TODO: make it possible to delete more elements at once to prevent redundant expensive\n // element reference scanning\n this.importer.deleteElement(targetElementId);\n } catch (err: any) {\n // ignore not found elements, iterative element tree deletion might have already deleted them\n if (err.name !== \"Not Found\")\n throw err;\n }\n });\n }\n\n /**\n * @deprecated in 3.x, this no longer has any effect except emitting a warning\n */\n protected skipElement(_sourceElement: Element): void {\n Logger.logWarning(loggerCategory, `Tried to defer/skip an element, which is no longer necessary`);\n }\n\n /** Transform the specified sourceElement into ElementProps for the target iModel.\n * @param sourceElement The Element from the source iModel to transform.\n * @returns ElementProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n * @note This can be called more than once for an element in arbitrary order, so it should not have side-effects.\n */\n public onTransformElement(sourceElement: Element): ElementProps {\n Logger.logTrace(loggerCategory, `onTransformElement(${sourceElement.id}) \"${sourceElement.getDisplayLabel()}\"`);\n const targetElementProps: ElementProps = this.context.cloneElement(sourceElement, { binaryGeometry: this._options.cloneUsingBinaryGeometry });\n if (sourceElement instanceof Subject) {\n if (targetElementProps.jsonProperties?.Subject?.Job) {\n // don't propagate source channels into target (legacy bridge case)\n targetElementProps.jsonProperties.Subject.Job = undefined;\n }\n }\n return targetElementProps;\n }\n\n /** Returns true if a change within sourceElement is detected.\n * @param sourceElement The Element from the source iModel\n * @param targetElementId The Element from the target iModel to compare against.\n * @note A subclass can override this method to provide custom change detection behavior.\n */\n protected hasElementChanged(sourceElement: Element, targetElementId: Id64String): boolean {\n const sourceAspects = this.targetDb.elements.getAspects(targetElementId, ExternalSourceAspect.classFullName) as ExternalSourceAspect[];\n for (const sourceAspect of sourceAspects) {\n if (sourceAspect.scope === undefined) // if the scope was lost, we can't correlate so assume it changed\n return true;\n if (\n sourceAspect.identifier === sourceElement.id &&\n sourceAspect.scope.id === this.targetScopeElementId &&\n sourceAspect.kind === ExternalSourceAspect.Kind.Element\n ) {\n const lastModifiedTime = sourceElement.iModel.elements.queryLastModifiedTime(sourceElement.id);\n return lastModifiedTime !== sourceAspect.version;\n }\n }\n return true;\n }\n\n private static transformCallbackFor(transformer: IModelTransformer, entity: ConcreteEntity): EntityTransformHandler {\n if (entity instanceof Element)\n return transformer.onTransformElement as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Element)\n return transformer.onTransformModel as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Relationship)\n return transformer.onTransformRelationship as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof ElementAspect)\n return transformer.onTransformElementAspect as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n /** callback to perform when a partial element says it's ready to be completed\n * transforms the source element with all references now valid, then updates the partial element with the results\n */\n private makePartialEntityCompleter(\n sourceEntity: ConcreteEntity\n ) {\n return () => {\n const targetId = this.context.findTargetEntityId(EntityReferences.from(sourceEntity));\n if (!EntityReferences.isValid(targetId))\n throw Error(`${sourceEntity.id} has not been inserted into the target yet, the completer is invalid. This is a bug.`);\n const onEntityTransform = IModelTransformer.transformCallbackFor(this, sourceEntity);\n const updateEntity = EntityUnifier.updaterFor(this.targetDb, sourceEntity);\n const targetProps = onEntityTransform.call(this, sourceEntity);\n if (sourceEntity instanceof Relationship) {\n (targetProps as RelationshipProps).sourceId = this.context.findTargetElementId(sourceEntity.sourceId);\n (targetProps as RelationshipProps).targetId = this.context.findTargetElementId(sourceEntity.targetId);\n }\n updateEntity({ ...targetProps, id: EntityReferences.toId64(targetId) });\n this._partiallyCommittedEntities.delete(sourceEntity);\n };\n }\n\n /** collect references this entity has that are yet to be mapped, and if there are any\n * create a [[PartiallyCommittedEntity]] to track resolution of those references\n */\n private collectUnmappedReferences(entity: ConcreteEntity) {\n const missingReferences = new EntityReferenceSet();\n let thisPartialElem: PartiallyCommittedEntity | undefined;\n\n // eslint-disable-next-line deprecation/deprecation\n for (const referenceId of entity.getReferenceConcreteIds()) {\n // TODO: probably need to rename from 'id' to 'ref' so these names aren't so ambiguous\n const referenceIdInTarget = this.context.findTargetEntityId(referenceId);\n const alreadyProcessed = EntityReferences.isValid(referenceIdInTarget) || this._skippedEntities.has(referenceId);\n if (alreadyProcessed)\n continue;\n Logger.logTrace(loggerCategory, `Deferring resolution of reference '${referenceId}' of element '${entity.id}'`);\n const referencedExistsInSource = EntityUnifier.exists(this.sourceDb, { entityReference: referenceId });\n if (!referencedExistsInSource) {\n Logger.logWarning(loggerCategory, `Source ${EntityUnifier.getReadableType(entity)} (${entity.id}) has a dangling reference to (${referenceId})`);\n switch (this._options.danglingReferencesBehavior) {\n case \"ignore\":\n continue;\n case \"reject\":\n throw new IModelError(\n IModelStatus.NotFound,\n [\n `Found a reference to an element \"${referenceId}\" that doesn't exist while looking for references of \"${entity.id}\".`,\n \"This must have been caused by an upstream application that changed the iModel.\",\n \"You can set the IModelTransformerOptions.danglingReferencesBehavior option to 'ignore' to ignore this, but this will leave the iModel\",\n \"in a state where downstream consuming applications will need to handle the invalidity themselves. In some cases, writing a custom\",\n \"transformer to remove the reference and fix affected elements may be suitable.\",\n ].join(\"\\n\")\n );\n }\n }\n if (thisPartialElem === undefined) {\n thisPartialElem = new PartiallyCommittedEntity(missingReferences, this.makePartialEntityCompleter(entity));\n if (!this._partiallyCommittedEntities.has(entity))\n this._partiallyCommittedEntities.set(entity, thisPartialElem);\n }\n missingReferences.add(referenceId);\n const entityReference = EntityReferences.from(entity);\n this._pendingReferences.set({ referenced: referenceId, referencer: entityReference }, thisPartialElem);\n }\n }\n\n /** Cause the specified Element and its child Elements (if applicable) to be exported from the source iModel and imported into the target iModel.\n * @param sourceElementId Identifies the Element from the source iModel to import.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processElement(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n if (sourceElementId === IModel.rootSubjectId) {\n throw new IModelError(IModelStatus.BadRequest, \"The root Subject should not be directly imported\");\n }\n return this.exporter.exportElement(sourceElementId);\n }\n\n /** Import child elements into the target IModelDb\n * @param sourceElementId Import the child elements of this element in the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processChildElements(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportChildElements(sourceElementId);\n }\n\n /** Override of [IModelExportHandler.shouldExportElement]($transformer) that is called to determine if an element should be exported from the source iModel.\n * @note Reaching this point means that the element has passed the standard exclusion checks in IModelExporter.\n */\n public override shouldExportElement(_sourceElement: Element): boolean { return true; }\n\n public override onSkipElement(sourceElementId: Id64String): void {\n if (this.context.findTargetElementId(sourceElementId) !== Id64.invalid) {\n // element already has provenance\n return;\n }\n\n Logger.logInfo(loggerCategory, `Element '${sourceElementId}' won't be exported. Marking its references as resolved`);\n const elementKey: EntityKey = `e${sourceElementId}`;\n this._skippedEntities.add(elementKey);\n\n // Mark any existing pending references to the skipped element as resolved.\n for (const referencer of this._pendingReferences.getReferencersByEntityKey(elementKey)) {\n const key = PendingReference.from(referencer, elementKey);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(elementKey);\n this._pendingReferences.delete(key);\n }\n }\n\n /**\n * If they haven't been already, import all of the required references\n * @internal do not call, override or implement this, it will be removed\n */\n public override async preExportElement(sourceElement: Element): Promise<void> {\n const elemClass = sourceElement.constructor as typeof Element;\n\n const unresolvedReferences = elemClass.requiredReferenceKeys\n .map((referenceKey) => {\n const idContainer = sourceElement[referenceKey as keyof Element];\n const referenceType = elemClass.requiredReferenceKeyTypeMap[referenceKey];\n // For now we just consider all required references to be elements (as they are in biscore), and do not support\n // entities that refuse to be inserted without a different kind of entity (e.g. aspect or relationship) first being inserted\n assert(referenceType === ConcreteEntityTypes.Element || referenceType === ConcreteEntityTypes.Model);\n return mapId64(idContainer, (id) => {\n if (id === Id64.invalid || id === IModel.rootSubjectId)\n return undefined; // not allowed to directly export the root subject\n if (!this.context.isBetweenIModels) {\n // Within the same iModel, can use existing DefinitionElements without remapping\n // This is relied upon by the TemplateModelCloner\n // TODO: extract this out to only be in the TemplateModelCloner\n const asDefinitionElem = this.sourceDb.elements.tryGetElement(id, DefinitionElement);\n if (asDefinitionElem && !(asDefinitionElem instanceof RecipeDefinitionElement)) {\n this.context.remapElement(id, id);\n }\n }\n return id;\n })\n .filter((sourceReferenceId: Id64String | undefined): sourceReferenceId is Id64String => {\n if (sourceReferenceId === undefined)\n return false;\n const referenceInTargetId = this.context.findTargetElementId(sourceReferenceId);\n const isInTarget = Id64.isValid(referenceInTargetId);\n return !isInTarget;\n });\n })\n .flat();\n\n if (unresolvedReferences.length > 0) {\n for (const reference of unresolvedReferences) {\n const processState = this.getElemTransformState(reference);\n // must export element first\n if (processState.needsElemImport)\n await this.exporter.exportElement(reference);\n if (processState.needsModelImport)\n await this.exporter.exportModel(reference);\n }\n }\n }\n\n private getElemTransformState(elementId: Id64String) {\n const dbHasModel = (db: IModelDb, id: Id64String) => {\n const maybeModelId = EntityReferences.fromEntityType(id, ConcreteEntityTypes.Model);\n return EntityUnifier.exists(db, { entityReference: maybeModelId });\n };\n const isSubModeled = dbHasModel(this.sourceDb, elementId);\n const idOfElemInTarget = this.context.findTargetElementId(elementId);\n const isElemInTarget = Id64.invalid !== idOfElemInTarget;\n const needsModelImport = isSubModeled && (!isElemInTarget || !dbHasModel(this.targetDb, idOfElemInTarget));\n return { needsElemImport: !isElemInTarget, needsModelImport };\n }\n\n /** Override of [IModelExportHandler.onExportElement]($transformer) that imports an element into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElement]] and then [IModelImporter.importElement]($transformer) to update the target iModel.\n */\n public override onExportElement(sourceElement: Element): void {\n let targetElementId: Id64String | undefined;\n let targetElementProps: ElementProps;\n if (this._options.preserveElementIdsForFiltering) {\n targetElementId = sourceElement.id;\n targetElementProps = this.onTransformElement(sourceElement);\n } else if (this._options.wasSourceIModelCopiedToTarget) {\n targetElementId = sourceElement.id;\n targetElementProps = this.targetDb.elements.getElementProps(targetElementId);\n } else {\n targetElementId = this.context.findTargetElementId(sourceElement.id);\n targetElementProps = this.onTransformElement(sourceElement);\n }\n // if an existing remapping was not yet found, check by Code as long as the CodeScope is valid (invalid means a missing reference so not worth checking)\n if (!Id64.isValidId64(targetElementId) && Id64.isValidId64(targetElementProps.code.scope)) {\n // respond the same way to undefined code value as the @see Code class, but don't use that class because it trims\n // whitespace from the value, and there are iModels out there with untrimmed whitespace that we ought not to trim\n targetElementProps.code.value = targetElementProps.code.value ?? \"\";\n targetElementId = this.targetDb.elements.queryElementIdByCode(targetElementProps.code as Required<CodeProps>);\n if (undefined !== targetElementId) {\n const targetElement: Element = this.targetDb.elements.getElement(targetElementId);\n if (targetElement.classFullName === targetElementProps.classFullName) { // ensure code remapping doesn't change the target class\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code\n } else {\n targetElementId = undefined;\n targetElementProps.code = Code.createEmpty(); // clear out invalid code\n }\n }\n }\n if (undefined !== targetElementId && Id64.isValidId64(targetElementId)) {\n // compare LastMod of sourceElement to ExternalSourceAspect of targetElement to see there are changes to import\n if (!this.hasElementChanged(sourceElement, targetElementId)) {\n return;\n }\n }\n\n this.collectUnmappedReferences(sourceElement);\n\n // TODO: untangle targetElementId state...\n if (targetElementId === Id64.invalid)\n targetElementId = undefined;\n\n targetElementProps.id = targetElementId; // targetElementId will be valid (indicating update) or undefined (indicating insert)\n if (!this._options.wasSourceIModelCopiedToTarget) {\n this.importer.importElement(targetElementProps); // don't need to import if iModel was copied\n }\n this.context.remapElement(sourceElement.id, targetElementProps.id!); // targetElementProps.id assigned by importElement\n // now that we've mapped this elem we can fix unmapped references to it\n this.resolvePendingReferences(sourceElement);\n\n if (!this._options.noProvenance) {\n const aspectProps: ExternalSourceAspectProps = this.initElementProvenance(sourceElement.id, targetElementProps.id!);\n let aspectId = this.queryExternalSourceAspectId(aspectProps);\n if (aspectId === undefined) {\n aspectId = this.provenanceDb.elements.insertAspect(aspectProps);\n } else {\n this.provenanceDb.elements.updateAspect(aspectProps);\n }\n aspectProps.id = aspectId;\n this.markLastProvenance(aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship: false });\n }\n }\n\n private resolvePendingReferences(entity: ConcreteEntity) {\n for (const referencer of this._pendingReferences.getReferencers(entity)) {\n const key = PendingReference.from(referencer, entity);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(EntityReferences.from(entity));\n this._pendingReferences.delete(key);\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteElement]($transformer) that is called when [IModelExporter]($transformer) detects that an Element has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteElement]($transformer).\n */\n public override onDeleteElement(sourceElementId: Id64String): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceElementId);\n if (Id64.isValidId64(targetElementId)) {\n this.importer.deleteElement(targetElementId);\n }\n }\n\n /** Override of [IModelExportHandler.onExportModel]($transformer) that is called when a Model should be exported from the source iModel.\n * This override calls [[onTransformModel]] and then [IModelImporter.importModel]($transformer) to update the target iModel.\n */\n public override onExportModel(sourceModel: Model): void {\n if (IModel.repositoryModelId === sourceModel.id) {\n return; // The RepositoryModel should not be directly imported\n }\n const targetModeledElementId: Id64String = this.context.findTargetElementId(sourceModel.id);\n const targetModelProps: ModelProps = this.onTransformModel(sourceModel, targetModeledElementId);\n this.importer.importModel(targetModelProps);\n this.resolvePendingReferences(sourceModel);\n }\n\n /** Override of [IModelExportHandler.onDeleteModel]($transformer) that is called when [IModelExporter]($transformer) detects that a [Model]($backend) has been deleted from the source iModel. */\n public override onDeleteModel(sourceModelId: Id64String): void {\n // It is possible and apparently occasionally sensical to delete a model without deleting its underlying element.\n // - If only the model is deleted, [[initFromExternalSourceAspects]] will have already remapped the underlying element since it still exists.\n // - If both were deleted, [[remapDeletedSourceElements]] will find and remap the deleted element making this operation valid\n const targetModelId: Id64String = this.context.findTargetElementId(sourceModelId);\n\n if (!Id64.isValidId64(targetModelId))\n return;\n\n if (this.exporter.sourceDbChanges?.element.deleteIds.has(sourceModelId)) {\n const isDefinitionPartition = this.targetDb.withPreparedStatement(`\n SELECT 1\n FROM bis.DefinitionPartition\n WHERE ECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, targetModelId);\n const val: DbResult = stmt.step();\n switch (val) {\n case DbResult.BE_SQLITE_ROW: return true;\n case DbResult.BE_SQLITE_DONE: return false;\n default: assert(false, `unexpected db result: '${stmt}'`);\n }\n });\n if (isDefinitionPartition) {\n // Skipping model deletion because model's partition will also be deleted.\n // It expects that model will be present and will fail if it's missing.\n // Model will be deleted when its partition will be deleted.\n return;\n }\n }\n\n try {\n this.importer.deleteModel(targetModelId);\n } catch (error) {\n const isDeletionProhibitedErr = error instanceof IModelError && (error.errorNumber === IModelStatus.DeletionProhibited || error.errorNumber === IModelStatus.ForeignKeyConstraint);\n if (!isDeletionProhibitedErr)\n throw error;\n\n // Transformer tries to delete models before it deletes elements. Definition models cannot be deleted unless all of their modeled elements are deleted first.\n // In case a definition model needs to be deleted we need to skip it for now and register its modeled partition for deletion.\n // The `OnDeleteElement` calls `DeleteElementTree` Which deletes the model together with its partition after deleting all of the modeled elements.\n this.scheduleModeledPartitionDeletion(sourceModelId);\n }\n }\n\n /** Schedule modeled partition deletion */\n private scheduleModeledPartitionDeletion(sourceModelId: Id64String): void {\n const deletedElements = this.exporter.sourceDbChanges?.element.deleteIds as Set<Id64String>;\n if (!deletedElements.has(sourceModelId)) {\n deletedElements.add(sourceModelId);\n }\n }\n\n /** Cause the model container, contents, and sub-models to be exported from the source iModel and imported into the target iModel.\n * @param sourceModeledElementId Import this [Model]($backend) from the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModel(sourceModeledElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportModel(sourceModeledElementId);\n }\n\n /** Cause the model contents to be exported from the source iModel and imported into the target iModel.\n * @param sourceModelId Import the contents of this model from the source IModelDb.\n * @param targetModelId Import into this model in the target IModelDb. The target model must exist prior to this call.\n * @param elementClassFullName Optional classFullName of an element subclass to limit import query against the source model.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModelContents(sourceModelId: Id64String, targetModelId: Id64String, elementClassFullName: string = Element.classFullName): Promise<void> {\n await this.initialize();\n this.targetDb.models.getModel(targetModelId); // throws if Model does not exist\n this.context.remapElement(sourceModelId, targetModelId); // set remapping in case importModelContents is called directly\n return this.exporter.exportModelContents(sourceModelId, elementClassFullName);\n }\n\n /** Cause all sub-models that recursively descend from the specified Subject to be exported from the source iModel and imported into the target iModel. */\n private async processSubjectSubModels(sourceSubjectId: Id64String): Promise<void> {\n await this.initialize();\n // import DefinitionModels first\n const childDefinitionPartitionSql = `SELECT ECInstanceId FROM ${DefinitionPartition.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childDefinitionPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processModel(statement.getValue(0).getId());\n }\n });\n // import other partitions next\n const childPartitionSql = `SELECT ECInstanceId FROM ${InformationPartitionElement.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const modelId: Id64String = statement.getValue(0).getId();\n const model: Model = this.sourceDb.models.getModel(modelId);\n if (!(model instanceof DefinitionModel)) {\n await this.processModel(modelId);\n }\n }\n });\n // recurse into child Subjects\n const childSubjectSql = `SELECT ECInstanceId FROM ${Subject.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childSubjectSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processSubjectSubModels(statement.getValue(0).getId());\n }\n });\n }\n\n /** Transform the specified sourceModel into ModelProps for the target iModel.\n * @param sourceModel The Model from the source iModel to be transformed.\n * @param targetModeledElementId The transformed Model will *break down* or *detail* this Element in the target iModel.\n * @returns ModelProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n public onTransformModel(sourceModel: Model, targetModeledElementId: Id64String): ModelProps {\n const targetModelProps: ModelProps = sourceModel.toJSON();\n // don't directly edit deep object since toJSON performs a shallow clone\n targetModelProps.modeledElement = { ...targetModelProps.modeledElement, id: targetModeledElementId };\n targetModelProps.id = targetModeledElementId;\n targetModelProps.parentModel = this.context.findTargetElementId(targetModelProps.parentModel!);\n return targetModelProps;\n }\n\n /** Import elements that were deferred in a prior pass.\n * @deprecated in 3.x. This method is no longer necessary since the transformer no longer needs to defer elements\n */\n public async processDeferredElements(_numRetries: number = 3): Promise<void> {}\n\n private finalizeTransformation() {\n if (this._partiallyCommittedEntities.size > 0) {\n Logger.logWarning(\n loggerCategory,\n [\n \"The following elements were never fully resolved:\",\n [...this._partiallyCommittedEntities.keys()].join(\",\"),\n \"This indicates that either some references were excluded from the transformation\",\n \"or the source has dangling references.\",\n ].join(\"\\n\")\n );\n for (const partiallyCommittedElem of this._partiallyCommittedEntities.values()) {\n partiallyCommittedElem.forceComplete();\n }\n }\n // this internal is guaranteed stable for just transformer usage\n /* eslint-disable @itwin/no-internal */\n if (\"codeValueBehavior\" in this.sourceDb as any) {\n (this.sourceDb as any).codeValueBehavior = \"trim-unicode-whitespace\";\n (this.targetDb as any).codeValueBehavior = \"trim-unicode-whitespace\";\n }\n /* eslint-enable @itwin/no-internal */\n }\n\n /** Imports all relationships that subclass from the specified base class.\n * @param baseRelClassFullName The specified base relationship class.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processRelationships(baseRelClassFullName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportRelationships(baseRelClassFullName);\n }\n\n /** Override of [IModelExportHandler.shouldExportRelationship]($transformer) that is called to determine if a [Relationship]($backend) should be exported.\n * @note Reaching this point means that the relationship has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportRelationship(_sourceRelationship: Relationship): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportRelationship]($transformer) that imports a relationship into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformRelationship]] and then [IModelImporter.importRelationship]($transformer) to update the target iModel.\n */\n public override onExportRelationship(sourceRelationship: Relationship): void {\n const targetRelationshipProps: RelationshipProps = this.onTransformRelationship(sourceRelationship);\n const targetRelationshipInstanceId: Id64String = this.importer.importRelationship(targetRelationshipProps);\n if (!this._options.noProvenance && Id64.isValidId64(targetRelationshipInstanceId)) {\n const aspectProps: ExternalSourceAspectProps = this.initRelationshipProvenance(sourceRelationship, targetRelationshipInstanceId);\n if (undefined === aspectProps.id) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n }\n assert(aspectProps.id !== undefined);\n this.markLastProvenance(aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship: true });\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteRelationship]($transformer) that is called when [IModelExporter]($transformer) detects that a [Relationship]($backend) has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteRelationship]($transformer).\n */\n public override onDeleteRelationship(sourceRelInstanceId: Id64String): void {\n const sql = `SELECT ECInstanceId,JsonProperties FROM ${ExternalSourceAspect.classFullName} aspect` +\n ` WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind AND aspect.Identifier=:identifier LIMIT 1`;\n this.targetDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n statement.bindString(\"identifier\", sourceRelInstanceId);\n if (DbResult.BE_SQLITE_ROW === statement.step()) {\n const json: any = JSON.parse(statement.getValue(1).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship = this.targetDb.relationships.tryGetInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n if (targetRelationship) {\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n this.targetDb.elements.deleteAspect(statement.getValue(0).getId());\n }\n }\n });\n }\n\n private _yieldManager = new YieldManager();\n\n /** Detect Relationship deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against relationships in the source iModel.\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectRelationshipDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const aspectDeleteIds: Id64String[] = [];\n const sql = `SELECT ECInstanceId,Identifier,JsonProperties FROM ${ExternalSourceAspect.classFullName} aspect WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind`;\n await this.targetDb.withPreparedStatement(sql, async (statement: ECSqlStatement) => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const sourceRelInstanceId: Id64String = Id64.fromJSON(statement.getValue(1).getString());\n if (undefined === this.sourceDb.relationships.tryGetInstanceProps(ElementRefersToElements.classFullName, sourceRelInstanceId)) {\n const json: any = JSON.parse(statement.getValue(2).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n aspectDeleteIds.push(statement.getValue(0).getId());\n }\n await this._yieldManager.allowYield();\n }\n });\n this.targetDb.elements.deleteAspect(aspectDeleteIds);\n }\n\n /** Transform the specified sourceRelationship into RelationshipProps for the target iModel.\n * @param sourceRelationship The Relationship from the source iModel to be transformed.\n * @returns RelationshipProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformRelationship(sourceRelationship: Relationship): RelationshipProps {\n const targetRelationshipProps: RelationshipProps = sourceRelationship.toJSON();\n targetRelationshipProps.sourceId = this.context.findTargetElementId(sourceRelationship.sourceId);\n targetRelationshipProps.targetId = this.context.findTargetElementId(sourceRelationship.targetId);\n sourceRelationship.forEachProperty((propertyName: string, propertyMetaData: PropertyMetaData) => {\n if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetRelationshipProps as any)[propertyName] = this.context.findTargetElementId(sourceRelationship.asAny[propertyName]);\n }\n });\n return targetRelationshipProps;\n }\n\n public override shouldExportElementAspect(aspect: ElementAspect) {\n // This override is needed to ensure that aspects are not exported if their element is not exported.\n // This is needed in case DetachedExportElementAspectsStrategy is used.\n return this.context.findTargetElementId(aspect.element.id) !== Id64.invalid;\n }\n\n /** Override of [IModelExportHandler.onExportElementUniqueAspect]($transformer) that imports an ElementUniqueAspect into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElementAspect]] and then [IModelImporter.importElementUniqueAspect]($transformer) to update the target iModel.\n */\n public override onExportElementUniqueAspect(sourceAspect: ElementUniqueAspect): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspect.element.id);\n const targetAspectProps = this.onTransformElementAspect(sourceAspect, targetElementId);\n this.collectUnmappedReferences(sourceAspect);\n const targetId = this.importer.importElementUniqueAspect(targetAspectProps);\n this.context.remapElementAspect(sourceAspect.id, targetId);\n this.resolvePendingReferences(sourceAspect);\n }\n\n /** Override of [IModelExportHandler.onExportElementMultiAspects]($transformer) that imports ElementMultiAspects into the target iModel when they are exported from the source iModel.\n * This override calls [[onTransformElementAspect]] for each ElementMultiAspect and then [IModelImporter.importElementMultiAspects]($transformer) to update the target iModel.\n * @note ElementMultiAspects are handled as a group to make it easier to differentiate between insert, update, and delete.\n */\n public override onExportElementMultiAspects(sourceAspects: ElementMultiAspect[]): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspects[0].element.id);\n // Transform source ElementMultiAspects into target ElementAspectProps\n const targetAspectPropsArray = sourceAspects.map((srcA) => this.onTransformElementAspect(srcA, targetElementId));\n sourceAspects.forEach((a) => this.collectUnmappedReferences(a));\n // const targetAspectsToImport = targetAspectPropsArray.filter((targetAspect, i) => hasEntityChanged(sourceAspects[i], targetAspect));\n const targetIds = this.importer.importElementMultiAspects(targetAspectPropsArray, (a) => {\n const isExternalSourceAspectFromTransformer = a instanceof ExternalSourceAspect && a.scope?.id === this.targetScopeElementId;\n return !this._options.includeSourceProvenance || !isExternalSourceAspectFromTransformer;\n });\n for (let i = 0; i < targetIds.length; ++i) {\n this.context.remapElementAspect(sourceAspects[i].id, targetIds[i]);\n this.resolvePendingReferences(sourceAspects[i]);\n }\n }\n\n /** Transform the specified sourceElementAspect into ElementAspectProps for the target iModel.\n * @param sourceElementAspect The ElementAspect from the source iModel to be transformed.\n * @param _targetElementId The ElementId of the target Element that will own the ElementAspects after transformation.\n * @returns ElementAspectProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformElementAspect(sourceElementAspect: ElementAspect, _targetElementId: Id64String): ElementAspectProps {\n const targetElementAspectProps = this.context.cloneElementAspect(sourceElementAspect);\n return targetElementAspectProps;\n }\n\n /** The directory where schemas will be exported, a random temporary directory */\n protected _schemaExportDir: string = path.join(KnownLocations.tmpdir, Guid.createValue());\n\n /** Override of [IModelExportHandler.shouldExportSchema]($transformer) that is called to determine if a schema should be exported\n * @note the default behavior doesn't import schemas older than those already in the target\n */\n public override shouldExportSchema(schemaKey: ECSchemaMetaData.SchemaKey): boolean {\n const versionInTarget = this.targetDb.querySchemaVersion(schemaKey.name);\n if (versionInTarget === undefined)\n return true;\n return Semver.gt(`${schemaKey.version.read}.${schemaKey.version.write}.${schemaKey.version.minor}`, Schema.toSemverString(versionInTarget));\n }\n\n private _longNamedSchemasMap = new Map<string, string>();\n\n /** Override of [IModelExportHandler.onExportSchema]($transformer) that serializes a schema to disk for [[processSchemas]] to import into\n * the target iModel when it is exported from the source iModel.\n * @returns {Promise<ExportSchemaResult>} Although the type is possibly void for backwards compatibility of subclasses,\n * `IModelTransformer.onExportSchema` always returns an[[IModelExportHandler.ExportSchemaResult]]\n * with a defined `schemaPath` property, for subclasses to know where the schema was written.\n * Schemas are *not* guaranteed to be written to [[IModelTransformer._schemaExportDir]] by a\n * known pattern derivable from the schema's name, so you must use this to find it.\n */\n public override async onExportSchema(schema: ECSchemaMetaData.Schema): Promise<void | ExportSchemaResult> {\n const ext = \".ecschema.xml\";\n let schemaFileName = schema.name + ext;\n // many file systems have a max file-name/path-segment size of 255, so we workaround that on all systems\n const systemMaxPathSegmentSize = 255;\n if (schemaFileName.length > systemMaxPathSegmentSize) {\n // this name should be well under 255 bytes\n // ( 100 + (Number.MAX_SAFE_INTEGER.toString().length = 16) + (ext.length = 13) ) = 129 which is less than 255\n // You'd have to be past 2**53-1 (Number.MAX_SAFE_INTEGER) long named schemas in order to hit decimal formatting,\n // and that's on the scale of at least petabytes. `Map.prototype.size` shouldn't return floating points, and even\n // if they do they're in scientific notation, size bound and contain no invalid windows path chars\n schemaFileName = `${schema.name.slice(0, 100)}${this._longNamedSchemasMap.size}${ext}`;\n nodeAssert(schemaFileName.length <= systemMaxPathSegmentSize, \"Schema name was still long. This is a bug.\");\n this._longNamedSchemasMap.set(schema.name, schemaFileName);\n }\n this.sourceDb.nativeDb.exportSchema(schema.name, this._schemaExportDir, schemaFileName);\n return { schemaPath: path.join(this._schemaExportDir, schemaFileName) };\n }\n\n private _makeLongNameResolvingSchemaCtx(): ECSchemaXmlContext {\n const result = new ECSchemaXmlContext();\n result.setSchemaLocater((key) => {\n const match = this._longNamedSchemasMap.get(key.name);\n if (match !== undefined)\n return path.join(this._schemaExportDir, match);\n return undefined;\n });\n return result;\n }\n\n /** Cause all schemas to be exported from the source iModel and imported into the target iModel.\n * @note For performance reasons, it is recommended that [IModelDb.saveChanges]($backend) be called after `processSchemas` is complete.\n * It is more efficient to process *data* changes after the schema changes have been saved.\n */\n public async processSchemas(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n try {\n IModelJsFs.mkdirSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n await this.exporter.exportSchemas();\n const exportedSchemaFiles = IModelJsFs.readdirSync(this._schemaExportDir);\n if (exportedSchemaFiles.length === 0)\n return;\n const schemaFullPaths = exportedSchemaFiles.map((s) => path.join(this._schemaExportDir, s));\n const maybeLongNameResolvingSchemaCtx = this._longNamedSchemasMap.size > 0\n ? this._makeLongNameResolvingSchemaCtx()\n : undefined;\n return await this.targetDb.importSchemas(schemaFullPaths, { ecSchemaXmlContext: maybeLongNameResolvingSchemaCtx });\n } finally {\n IModelJsFs.removeSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n }\n }\n\n /** Cause all fonts to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processFonts(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n await this.initialize();\n return this.exporter.exportFonts();\n }\n\n /** Override of [IModelExportHandler.onExportFont]($transformer) that imports a font into the target iModel when it is exported from the source iModel. */\n public override onExportFont(font: FontProps, _isUpdate: boolean | undefined): void {\n this.context.importFont(font.id);\n }\n\n /** Cause all CodeSpecs to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpecs(): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecs();\n }\n\n /** Cause a single CodeSpec to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpec(codeSpecName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecByName(codeSpecName);\n }\n\n /** Override of [IModelExportHandler.shouldExportCodeSpec]($transformer) that is called to determine if a CodeSpec should be exported from the source iModel.\n * @note Reaching this point means that the CodeSpec has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportCodeSpec(_sourceCodeSpec: CodeSpec): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportCodeSpec]($transformer) that imports a CodeSpec into the target iModel when it is exported from the source iModel. */\n public override onExportCodeSpec(sourceCodeSpec: CodeSpec): void {\n this.context.importCodeSpec(sourceCodeSpec.id);\n }\n\n /** Recursively import all Elements and sub-Models that descend from the specified Subject */\n public async processSubject(sourceSubjectId: Id64String, targetSubjectId: Id64String): Promise<void> {\n await this.initialize();\n this.sourceDb.elements.getElement(sourceSubjectId, Subject); // throws if sourceSubjectId is not a Subject\n this.targetDb.elements.getElement(targetSubjectId, Subject); // throws if targetSubjectId is not a Subject\n this.context.remapElement(sourceSubjectId, targetSubjectId);\n await this.processChildElements(sourceSubjectId);\n await this.processSubjectSubModels(sourceSubjectId);\n return this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n }\n\n /** state to prevent reinitialization, @see [[initialize]] */\n private _initialized = false;\n\n /**\n * Initialize prerequisites of processing, you must initialize with an [[InitFromExternalSourceAspectsArgs]] if you\n * are intending process changes, but prefer using [[processChanges]]\n * Called by all `process*` functions implicitly.\n * Overriders must call `super.initialize()` first\n */\n public async initialize(args?: InitFromExternalSourceAspectsArgs) {\n if (this._initialized)\n return;\n await this.context.initialize();\n // eslint-disable-next-line deprecation/deprecation\n await this.initFromExternalSourceAspects(args);\n this._initialized = true;\n }\n\n /** Export everything from the source iModel and import the transformed entities into the target iModel.\n * @note [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.\n */\n public async processAll(): Promise<void> {\n Logger.logTrace(loggerCategory, \"processAll()\");\n this.logSettings();\n this.validateScopeProvenance();\n await this.initialize();\n await this.exporter.exportCodeSpecs();\n await this.exporter.exportFonts();\n // The RepositoryModel and root Subject of the target iModel should not be transformed.\n await this.exporter.exportChildElements(IModel.rootSubjectId); // start below the root Subject\n await this.exporter.exportModelContents(IModel.repositoryModelId, Element.classFullName, true); // after the Subject hierarchy, process the other elements of the RepositoryModel\n await this.exporter.exportSubModels(IModel.repositoryModelId); // start below the RepositoryModel\n await this.exporter[\"exportAllAspects\"](); // eslint-disable-line @typescript-eslint/dot-notation\n await this.exporter.exportRelationships(ElementRefersToElements.classFullName);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n if (this.shouldDetectDeletes()) {\n await this.detectElementDeletes();\n await this.detectRelationshipDeletes();\n }\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n\n private _lastProvenanceEntityInfo = nullLastProvenanceEntityInfo;\n\n private markLastProvenance(sourceAspect: MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship = false }) {\n this._lastProvenanceEntityInfo = {\n entityId: sourceAspect.element.id,\n aspectId: sourceAspect.id,\n aspectVersion: sourceAspect.version ?? \"\",\n aspectKind: isRelationship ? ExternalSourceAspect.Kind.Relationship : ExternalSourceAspect.Kind.Element,\n };\n }\n\n /** @internal the name of the table where javascript state of the transformer is serialized in transformer state dumps */\n public static readonly jsStateTable = \"TransformerJsState\";\n\n /** @internal the name of the table where the target state heuristics is serialized in transformer state dumps */\n public static readonly lastProvenanceEntityInfoTable = \"LastProvenanceEntityInfo\";\n\n /**\n * Load the state of the active transformation from an open SQLiteDb\n * You can override this if you'd like to load from custom tables in the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected loadStateFromDb(db: SQLiteDb): void {\n const lastProvenanceEntityInfo: IModelTransformer[\"_lastProvenanceEntityInfo\"] = db.withSqliteStatement(\n `SELECT entityId, aspectId, aspectVersion, aspectKind FROM ${IModelTransformer.lastProvenanceEntityInfoTable}`,\n (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\n \"expected row when getting lastProvenanceEntityId from target state table\"\n );\n return {\n entityId: stmt.getValueString(0),\n aspectId: stmt.getValueString(1),\n aspectVersion: stmt.getValueString(2),\n aspectKind: stmt.getValueString(3) as ExternalSourceAspect.Kind,\n };\n }\n );\n const targetHasCorrectLastProvenance =\n // ignore provenance check if it's null since we can't bind those ids\n !Id64.isValidId64(lastProvenanceEntityInfo.aspectId) ||\n !Id64.isValidId64(lastProvenanceEntityInfo.entityId) ||\n this.provenanceDb.withPreparedStatement(`\n SELECT Version FROM ${ExternalSourceAspect.classFullName}\n WHERE Scope.Id=:scopeId\n AND ECInstanceId=:aspectId\n AND Kind=:kind\n AND Element.Id=:entityId\n `,\n (statement: ECSqlStatement): boolean => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindId(\"aspectId\", lastProvenanceEntityInfo.aspectId);\n statement.bindString(\"kind\", lastProvenanceEntityInfo.aspectKind);\n statement.bindId(\"entityId\", lastProvenanceEntityInfo.entityId);\n const stepResult = statement.step();\n switch (stepResult) {\n case DbResult.BE_SQLITE_ROW:\n const version = statement.getValue(0).getString();\n return version === lastProvenanceEntityInfo.aspectVersion;\n case DbResult.BE_SQLITE_DONE:\n return false;\n default:\n throw new IModelError(IModelStatus.SQLiteError, `got sql error ${stepResult}`);\n }\n });\n if (!targetHasCorrectLastProvenance)\n throw Error([\n \"Target for resuming from does not have the expected provenance \",\n \"from the target that the resume state was made with\",\n ].join(\"\\n\"));\n this._lastProvenanceEntityInfo = lastProvenanceEntityInfo;\n\n const state = db.withSqliteStatement(`SELECT data FROM ${IModelTransformer.jsStateTable}`, (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\"expected row when getting data from js state table\");\n return JSON.parse(stmt.getValueString(0)) as TransformationJsonState;\n });\n if (state.transformerClass !== this.constructor.name)\n throw Error(\"resuming from a differently named transformer class, it is not necessarily valid to resume with a different transformer class\");\n // force assign to readonly options since we do not know how the transformer subclass takes options to pass to the superclass\n (this as any)._options = state.options;\n this.context.loadStateFromDb(db);\n this.importer.loadStateFromJson(state.importerState);\n this.exporter.loadStateFromJson(state.exporterState);\n this.loadAdditionalStateJson(state.additionalState);\n }\n\n /**\n * Return a new transformer instance with the same remappings state as saved from a previous [[IModelTransformer.saveStateToFile]] call.\n * This allows you to \"resume\" an iModel transformation, you will have to call [[IModelTransformer.processChanges]]/[[IModelTransformer.processAll]]\n * again but the remapping state will cause already mapped elements to be skipped.\n * To \"resume\" an iModel Transformation you need:\n * - the sourceDb at the same changeset\n * - the same targetDb in the state in which it was before\n * @param statePath the path to the serialized state of the transformer, use [[IModelTransformer.saveStateToFile]] to get this from an existing transformer instance\n * @param constructorArgs remaining arguments that you would normally pass to the Transformer subclass you are using, usually (sourceDb, targetDb)\n * @note custom transformers with custom state may need to override this method in order to handle loading their own custom state somewhere\n */\n public static resumeTransformation<SubClass extends new(...a: any[]) => IModelTransformer = typeof IModelTransformer>(\n this: SubClass,\n statePath: string,\n ...constructorArgs: ConstructorParameters<SubClass>\n ): InstanceType<SubClass> {\n const transformer = new this(...constructorArgs);\n const db = new SQLiteDb();\n db.openDb(statePath, OpenMode.Readonly);\n try {\n transformer.loadStateFromDb(db);\n } finally {\n db.closeDb();\n }\n return transformer as InstanceType<SubClass>;\n }\n\n /**\n * You may override this to store arbitrary json state in a transformer state dump, useful for some resumptions\n * @see [[IModelTransformer.saveStateToFile]]\n */\n protected getAdditionalStateJson(): any {\n return {};\n }\n\n /**\n * You may override this to load arbitrary json state in a transformer state dump, useful for some resumptions\n * @see [[IModelTransformer.loadStateFromFile]]\n */\n protected loadAdditionalStateJson(_additionalState: any): void {}\n\n /**\n * Save the state of the active transformation to an open SQLiteDb\n * You can override this if you'd like to write custom tables to the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected saveStateToDb(db: SQLiteDb): void {\n const jsonState: TransformationJsonState = {\n transformerClass: this.constructor.name,\n options: this._options,\n importerState: this.importer.saveStateToJson(),\n exporterState: this.exporter.saveStateToJson(),\n additionalState: this.getAdditionalStateJson(),\n };\n\n this.context.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`CREATE TABLE ${IModelTransformer.jsStateTable} (data TEXT)`))\n throw Error(\"Failed to create the js state table in the state database\");\n\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`\n CREATE TABLE ${IModelTransformer.lastProvenanceEntityInfoTable} (\n -- because we cannot bind the invalid id which we use for our null state, we actually store the id as a hex string\n entityId TEXT,\n aspectId TEXT,\n aspectVersion TEXT,\n aspectKind TEXT\n )\n `))\n throw Error(\"Failed to create the target state table in the state database\");\n\n db.saveChanges();\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.jsStateTable} (data) VALUES (?)`,\n (stmt) => {\n stmt.bindString(1, JSON.stringify(jsonState));\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.lastProvenanceEntityInfoTable} (entityId, aspectId, aspectVersion, aspectKind) VALUES (?,?,?,?)`,\n (stmt) => {\n stmt.bindString(1, this._lastProvenanceEntityInfo.entityId);\n stmt.bindString(2, this._lastProvenanceEntityInfo.aspectId);\n stmt.bindString(3, this._lastProvenanceEntityInfo.aspectVersion);\n stmt.bindString(4, this._lastProvenanceEntityInfo.aspectKind);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.saveChanges();\n }\n\n /**\n * Save the state of the active transformation to a file path, if a file at the path already exists, it will be overwritten\n * This state can be used by [[IModelTransformer.resumeTransformation]] to resume a transformation from this point.\n * The serialization format is a custom sqlite database.\n * @note custom transformers with custom state may override [[IModelTransformer.saveStateToDb]] or [[IModelTransformer.getAdditionalStateJson]]\n * and [[IModelTransformer.loadStateFromDb]] (with a super call) or [[IModelTransformer.loadAdditionalStateJson]]\n * if they have custom state that needs to be stored with\n * potentially inside the same sqlite file in separate tables\n */\n public saveStateToFile(nativeStatePath: string): void {\n const db = new SQLiteDb();\n if (IModelJsFs.existsSync(nativeStatePath))\n IModelJsFs.unlinkSync(nativeStatePath);\n db.createDb(nativeStatePath);\n try {\n this.saveStateToDb(db);\n db.saveChanges();\n } finally {\n db.closeDb();\n }\n }\n\n /** Export changes from the source iModel and import the transformed entities into the target iModel.\n * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n */\n public async processChanges(args: ProcessChangesOptions): Promise<void>;\n /** @deprecated in 0.1.x, use a single [[ProcessChangesOptions]] object instead */\n public async processChanges(accessToken: AccessToken, startChangesetId?: string): Promise<void>;\n public async processChanges(accessTokenOrArgs: AccessToken | ProcessChangesOptions, startChangesetId?: string): Promise<void> {\n Logger.logTrace(loggerCategory, \"processChanges()\");\n this.logSettings();\n this.validateScopeProvenance();\n\n const options: ProcessChangesOptions = typeof accessTokenOrArgs === \"string\"\n ? {\n accessToken: accessTokenOrArgs,\n startChangeset: startChangesetId ? { id: startChangesetId } : this.sourceDb.changeset,\n changedInstanceIds: undefined,\n }\n : accessTokenOrArgs;\n\n await this.initialize(options);\n await this.exporter.exportChanges(options);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n await this.exporter[\"exportAllAspects\"](); // eslint-disable-line @typescript-eslint/dot-notation\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n}\n\n/** @internal the json part of a transformation's state */\ninterface TransformationJsonState {\n transformerClass: string;\n options: IModelTransformOptions;\n importerState: IModelImporterState;\n exporterState: IModelExporterState;\n additionalState?: any;\n}\n\n/** IModelTransformer that clones the contents of a template model.\n * @beta\n */\nexport class TemplateModelCloner extends IModelTransformer {\n /** The Placement to apply to the template. */\n private _transform3d?: Transform;\n /** Accumulates the mapping of sourceElementIds to targetElementIds from the elements in the template model that were cloned. */\n private _sourceIdToTargetIdMap?: Map<Id64String, Id64String>;\n /** Construct a new TemplateModelCloner\n * @param sourceDb The source IModelDb that contains the templates to clone\n * @param targetDb Optionally specify the target IModelDb where the cloned template will be inserted.\n * Typically this is left unspecified, and the default is to use the sourceDb as the target\n * @note The expectation is that the template definitions are within the same iModel where instances will be placed.\n */\n public constructor(sourceDb: IModelDb, targetDb: IModelDb = sourceDb) {\n const target = new IModelImporter(targetDb, {\n autoExtendProjectExtents: false, // autoExtendProjectExtents is intended for transformation service use cases, not template --> instance cloning\n });\n super(sourceDb, target, { noProvenance: true }); // WIP: need to decide the proper way to handle provenance\n }\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel3d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the SpatialCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate3d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement3d): Promise<Map<Id64String, Id64String>> {\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(placement.origin, placement.angles.toMatrix3d());\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel2d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the DrawingCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate2d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement2d): Promise<Map<Id64String, Id64String>> {\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(Point3d.createFrom(placement.origin), placement.rotation);\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Cloning from a template requires this override of onTransformElement. */\n public override onTransformElement(sourceElement: Element): ElementProps {\n // eslint-disable-next-line deprecation/deprecation\n const referenceIds = sourceElement.getReferenceConcreteIds();\n referenceIds.forEach((referenceId) => {\n // FIXME: consider going through all definition elements at once and remapping them to themselves\n if (!EntityReferences.isValid(this.context.findTargetEntityId(referenceId))) {\n if (this.context.isBetweenIModels) {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for source dependency ${referenceId} not found for target iModel`);\n } else {\n const definitionElement = this.sourceDb.elements.tryGetElement<DefinitionElement>(referenceId, DefinitionElement);\n if (definitionElement && !(definitionElement instanceof RecipeDefinitionElement)) {\n this.context.remapElement(referenceId, referenceId); // when in the same iModel, can use existing DefinitionElements without remapping\n } else {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for dependency ${referenceId} not found`);\n }\n }\n }\n });\n\n const targetElementProps: ElementProps = super.onTransformElement(sourceElement);\n targetElementProps.federationGuid = Guid.createValue(); // clone from template should create a new federationGuid\n targetElementProps.code = Code.createEmpty(); // clone from template should not maintain codes\n if (sourceElement instanceof GeometricElement3d) {\n const placement = Placement3d.fromJSON((targetElementProps as GeometricElement3dProps).placement);\n if (placement.isValid) {\n placement.multiplyTransform(this._transform3d!);\n (targetElementProps as GeometricElement3dProps).placement = placement;\n }\n } else if (sourceElement instanceof GeometricElement2d) {\n const placement = Placement2d.fromJSON((targetElementProps as GeometricElement2dProps).placement);\n if (placement.isValid) {\n placement.multiplyTransform(this._transform3d!);\n (targetElementProps as GeometricElement2dProps).placement = placement;\n }\n }\n this._sourceIdToTargetIdMap!.set(sourceElement.id, Id64.invalid); // keep track of (source) elementIds from the template model, but the target hasn't been inserted yet\n return targetElementProps;\n }\n}\n"]}