@itwin/imodel-transformer 2.0.0-dev.2 → 2.0.0-dev.4

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;;;gGAGgG;AAChG;;GAEG;AACH,6BAA6B;AAC7B,iCAAiC;AACjC,qCAAqC;AACrC,sDAa6B;AAE7B,wDAA0D;AAC1D,sDA0C6B;AAC7B,oDAuB4B;AAC5B,qDAO0B;AAC1B,qDAA2E;AAC3E,2EAAwE;AACxE,6DAA0D;AAC1D,mDAAgD;AAChD,iCAAmD;AAEnD,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;AAsJF;;;;;GAKG;AACH,SAAS,OAAO,CACd,WAAoD,EACpD,IAA2B;IAE3B,MAAM,YAAY,GAAG,CAAC,GAAQ,EAAqB,EAAE;QACnD,MAAM,QAAQ,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC;QACzC,IAAA,qBAAM,EAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,IAAI,mBAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;QACjD,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;IACF,MAAM,aAAa,GAAG,CAAC,GAAQ,EAAyB,EAAE,CACxD,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,IAAI,IAAI,GAAG,CAAC;IAChD,MAAM,OAAO,GAAG,EAAE,CAAC;IAEnB,wHAAwH;IACxH,IAAI,WAAW,KAAK,SAAS,EAAE,CA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Q,CAAC,aAAa,CAAC,CAAC;QAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;QAC1C,IAAA,qBAAM,EAAC,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,cAAc,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC,CACF,CAAC;AACJ,CAAC","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 assert,\n DbResult,\n Guid,\n GuidString,\n Id64,\n Id64Array,\n Id64Set,\n Id64String,\n IModelStatus,\n Logger,\n MarkRequired,\n YieldManager,\n} from \"@itwin/core-bentley\";\nimport * as ECSchemaMetaData from \"@itwin/ecschema-metadata\";\nimport { Point3d, Transform } from \"@itwin/core-geometry\";\nimport {\n BriefcaseManager,\n ChangedECInstance,\n ChangesetECAdaptor,\n ChangeSummaryManager,\n ChannelRootAspect,\n ConcreteEntity,\n DefinitionElement,\n DefinitionModel,\n DefinitionPartition,\n ECSchemaXmlContext,\n ECSqlStatement,\n // eslint-disable-next-line @typescript-eslint/no-redeclare\n Element,\n ElementAspect,\n ElementMultiAspect,\n ElementOwnsExternalSourceAspects,\n ElementRefersToElements,\n ElementUniqueAspect,\n Entity,\n EntityReferences,\n ExternalSource,\n ExternalSourceAspect,\n ExternalSourceAttachment,\n FolderLink,\n GeometricElement,\n GeometricElement3d,\n IModelDb,\n IModelHost,\n IModelJsFs,\n InformationPartitionElement,\n KnownLocations,\n Model,\n PartialECChangeUnifier,\n RecipeDefinitionElement,\n Relationship,\n RelationshipProps,\n Schema,\n SqliteChangeOp,\n SqliteChangesetReader,\n Subject,\n SynchronizationConfigLink,\n} from \"@itwin/core-backend\";\nimport {\n ChangesetFileProps,\n ChangesetIndexAndId,\n Code,\n CodeProps,\n CodeSpec,\n ConcreteEntityTypes,\n ElementAspectProps,\n ElementProps,\n EntityReference,\n ExternalSourceAspectProps,\n FontProps,\n GeometricElementProps,\n IModel,\n IModelError,\n ModelProps,\n Placement2d,\n Placement3d,\n PrimitiveTypeCode,\n PropertyMetaData,\n QueryBinder,\n RelatedElement,\n SourceAndTarget,\n} from \"@itwin/core-common\";\nimport {\n ChangedInstanceIds,\n ExportChangesOptions,\n ExporterInitOptions,\n ExportSchemaResult,\n IModelExporter,\n IModelExportHandler,\n} from \"./IModelExporter\";\nimport { IModelImporter, OptimizeGeometryOptions } from \"./IModelImporter\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { IModelCloneContext } from \"./IModelCloneContext\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { rangesFromRangeAndSkipped } from \"./Algo\";\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 LastProvenanceEntityInfo = typeof nullLastProvenanceEntityInfo;\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 * It is always a good idea to define this, although particularly necessary in any multi-source scenario such as multiple branches that reverse synchronize\n * or physical consolidation.\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.process]] to work properly when [[IModelTransformOptions.argsForProcessChanges]] are provided.\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 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 */\n danglingReferencesBehavior?: \"reject\" | \"ignore\";\n\n /** If defined, options to be supplied to [[IModelImporter.optimizeGeometry]] by [[IModelTransformer.process]]\n * as a post-processing step to optimize the geometry in the iModel.\n * @beta\n */\n optimizeGeometry?: OptimizeGeometryOptions;\n\n /**\n * force the insertion of external source aspects to provide provenance, even if there are federation guids\n * in the source that we can use. This can make some operations (like transforming new elements or initializing forks)\n * much slower due to needing to insert aspects, but prevents requiring change information for future merges.\n * @default false\n */\n forceExternalSourceAspectProvenance?: boolean;\n\n /**\n * Do not detach the change cache that we build. Use this if you want to do multiple transformations to\n * the same iModels, to avoid the performance cost of reinitializing the change cache which can be\n * expensive. You should only use this if you know the cache will be reused.\n * @note You must detach the change cache yourself.\n * @default false\n */\n noDetachChangeCache?: boolean;\n\n /**\n * Do not error out if a scoping ESA @see ExternalSourceAspectProps is found without a version or jsonProperties defined on that scoping ESA.\n * If true, the version and jsonproperties will be properly set on the scoping ESA @see TargetScopeProvenanceJsonProps after the transformer is complete.\n * These properties not being defined are a sign that this branching relationship was created with an older version of the transformer, and setting this option to 'unsafe-migrate' is not without risk.\n * Depending on the state of the branching relationship at the time of using this option, some data may be lost.\n * @note This should only need to be set to 'unsafe-migrate' at most once for a branching relationship. For future transformations on the branching relationship, the @see TargetScopeProvenanceJsonProps will be present.\n * @default \"reject\"\n */\n branchRelationshipDataBehavior?: \"unsafe-migrate\" | \"reject\";\n\n /**\n * Skip propagating changes made to the root subject, dictionaryModel and IModelImporter._realityDataSourceLinkPartitionStaticId (0xe)\n * If it is set to false, changes to root elements are propagated, the root subject name gets changed and leads to the iModelDb.name property being updated in .initializeiModelDb\n * @default true\n */\n skipPropagateChangesToRootElements?: boolean;\n\n /**\n * Arguments to use for the processing of changes. The args being defined or not defined will influence the behavior of @see [[IModelTransformer.process]].\n * @default undefined\n */\n argsForProcessChanges?: ProcessChangesOptions;\n}\n\n/**\n * Data type for persisting change version information within provenance Scope ExternalSourceAspect.\n * Additionally, forward synchronization version is stored in Scope aspect's 'version' field.\n * @beta\n */\nexport interface TargetScopeProvenanceJsonProps {\n /** An array of changeset indices to ignore when doing a reverse sync. This array gets appended to during a forward sync and cleared\n * during a reverse sync. Since a forward sync pushes a changeset to the branch db, the changeset pushed to the branch db\n * by the forward sync isn't considered part of the changes made on the branch db and therefore doesn't need to be synced back to master\n * during a forward sync.\n */\n pendingReverseSyncChangesetIndices: number[];\n /** An array of changeset indices to ignore when doing a forward sync. This array gets appended to during a reverse sync and cleared\n * during a forward sync. Since a reverse sync pushes a changeset to the master db, the changeset pushed to the master db\n * by the reverse sync isn't considered part of the changes made on the master db and therefore doesn't need to be synced back to the branch\n * during a forward sync.\n */\n pendingSyncChangesetIndices: number[];\n /** the latest changesetid/index reverse synced into master */\n reverseSyncVersion: string;\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 | RelatedElement | 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 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 [\n `Id64 container '${JSON.stringify(idContainer)}' is unsupported.`,\n \"Currently only singular Id64 strings or prop-like objects containing an 'id' property are supported.\",\n ].join(\"\\n\")\n );\n }\n return results;\n}\n\n/** Arguments you can pass to [[IModelTransformer.initialize]]\n * @beta\n */\nexport interface InitOptions {\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 used during [[IModelTransformer.process]] if provided in [[IModelTransformOptions.argsForProcessChanges]].\n * @beta\n */\nexport type ProcessChangesOptions = ExportChangesOptions & {\n /** how to call saveChanges on the target. Must call targetDb.saveChanges, should not edit the iModel */\n saveTargetChanges?: (transformer: IModelTransformer) => Promise<void>;\n /**\n * The forward sync 'version' to set on the scoping ESA @see ExternalSourceAspectProps upon startup, if the version property on the scoping ESA is undefined or empty string.\n * @note This option is not without risk! You must also set @see branchRelationshipDataBehavior to \"unsafe-migrate\".\n * @note This value is ignored if the version property on the scoping ESA is NOT undefined or empty string.\n * @default \"\"\n */\n unsafeFallbackSyncVersion?: string;\n /**\n * The reverse sync version to set on the scoping ESA @see TargetScopeProvenanceJsonProps upon startup, if the reverseSync property on the scoping ESA is undefined or empty string.\n * @note This option is not without risk! You must also set @see branchRelationshipDataBehavior to \"unsafe-migrate\".\n * @note This value is ignored if the reverseSyncVersion property on the scoping ESA is NOT undefined or empty string.\n * @default \"\"\n */\n unsafeFallbackReverseSyncVersion?: string;\n /**\n * Do not check that process (with [[IModelTransformOptions.argsForProcessChanges]] provided) is called from the next changeset index.\n * This is an unsafe option (e.g. it can cause data loss in future branch operations)\n * and you should not use it.\n * @default false\n */\n ignoreMissingChangesetsInSynchronizations?: boolean;\n};\n\ntype ChangeDataState =\n | \"uninited\"\n | \"has-changes\"\n | \"no-changes\"\n | \"unconnected\";\n\n/**\n * @beta\n */\nexport interface RelationshipPropsForDelete {\n id: Id64String;\n classFullName: string;\n}\n\ntype SyncType = \"not-sync\" | \"forward\" | \"reverse\";\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 private _syncType?: SyncType;\n\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 /** a set of elements for which source provenance will be explicitly tracked by ExternalSourceAspects */\n protected _elementsWithExplicitlyTrackedProvenance = new Set<Id64String>();\n\n protected _partiallyCommittedElementIds: Id64Set = new Set<Id64String>();\n protected _partiallyCommittedAspectIds: Id64Set = new Set<Id64String>();\n\n /** the options that were used to initialize this transformer */\n private readonly _options: MarkRequired<\n IModelTransformOptions,\n \"targetScopeElementId\" | \"danglingReferencesBehavior\"\n >;\n\n /**\n * A private variable meant to be set by tests which have an outdated way of setting up transforms. In all synchronizations today we expect to find an ESA in the branch db which describes the master -> branch relationship.\n * The exception to this is the first transform aka the provenance initializing transform which requires that the master imodel and the branch imodel are identical at the time of provenance initialization.\n * A couple ofoutdated tests run their first transform providing a source and targetdb that are slightly different which is no longer supported. In order to not remove these tests which are still providing value\n * this private property on the IModelTransformer exists.\n */\n private _allowNoScopingESA = false;\n\n public static noEsaSyncDirectionErrorMessage =\n \"Couldn't find an external source aspect to determine sync direction. This often means that the master->branch relationship has not been established. Consider running the transformer with wasSourceIModelCopiedToTarget set to true.\";\n\n /**\n * Queries for an esa which matches the props in the provided aspectProps.\n * @param dbToQuery db to run the query on for scope external source\n * @param aspectProps aspectProps to search for @see ExternalSourceAspectProps\n */\n public static queryScopeExternalSourceAspect(\n dbToQuery: IModelDb,\n aspectProps: ExternalSourceAspectProps\n ):\n | {\n aspectId: Id64String;\n version?: string;\n /** stringified json */\n jsonProperties?: string;\n }\n | undefined {\n const sql = `\n SELECT ECInstanceId, Version, JsonProperties\n FROM ${ExternalSourceAspect.classFullName}\n WHERE Element.Id=:elementId\n AND Scope.Id=:scopeId\n AND Kind=:kind\n AND Identifier=:identifier\n LIMIT 1\n `;\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return dbToQuery.withPreparedStatement(sql, (statement: ECSqlStatement) => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n if (aspectProps.scope === undefined) return undefined; // return 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 if (DbResult.BE_SQLITE_ROW !== statement.step()) return undefined;\n const aspectId = statement.getValue(0).getId();\n const versionValue = statement.getValue(1);\n const version = versionValue.isNull\n ? undefined\n : versionValue.getString();\n const jsonPropsValue = statement.getValue(2);\n const jsonProperties = jsonPropsValue.isNull\n ? undefined\n : jsonPropsValue.getString();\n return { aspectId, version, jsonProperties };\n });\n }\n\n /**\n * Determines the sync direction \"forward\" or \"reverse\" of a given sourceDb and targetDb by looking for the scoping ESA.\n * If the sourceDb's iModelId is found as the identifier of the expected scoping ESA in the targetDb, then it is a forward synchronization.\n * If the targetDb's iModelId is found as the identifier of the expected scoping ESA in the sourceDb, then it is a reverse synchronization.\n * @throws if no scoping ESA can be found in either the sourceDb or targetDb which describes a master branch relationship between the two databases.\n * @returns \"forward\" or \"reverse\"\n */\n public static determineSyncType(\n sourceDb: IModelDb,\n targetDb: IModelDb,\n /** @see [[IModelTransformOptions.targetScopeElementId]] */\n targetScopeElementId: Id64String\n ): \"forward\" | \"reverse\" {\n const aspectProps = {\n id: undefined as string | undefined,\n version: undefined as string | undefined,\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: targetScopeElementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: sourceDb.iModelId,\n kind: ExternalSourceAspect.Kind.Scope,\n jsonProperties: undefined as TargetScopeProvenanceJsonProps | undefined,\n };\n /** First check if the targetDb is the branch (branch is the @see provenanceDb) */\n const esaPropsFromTargetDb = this.queryScopeExternalSourceAspect(\n targetDb,\n aspectProps\n );\n if (esaPropsFromTargetDb !== undefined) {\n return \"forward\"; // we found an esa assuming targetDb is the provenanceDb/branch so this is a forward sync.\n }\n\n // Now check if the sourceDb is the branch\n aspectProps.identifier = targetDb.iModelId;\n const esaPropsFromSourceDb = this.queryScopeExternalSourceAspect(\n sourceDb,\n aspectProps\n );\n\n if (esaPropsFromSourceDb !== undefined) {\n return \"reverse\"; // we found an esa assuming sourceDb is the provenanceDb/branch so this is a reverse sync.\n }\n throw new Error(this.noEsaSyncDirectionErrorMessage);\n }\n\n private determineSyncType(): SyncType {\n if (this._isProvenanceInitTransform) {\n return \"forward\";\n }\n if (!this._options.argsForProcessChanges) {\n return \"not-sync\";\n }\n try {\n return IModelTransformer.determineSyncType(\n this.sourceDb,\n this.targetDb,\n this.targetScopeElementId\n );\n } catch (err) {\n if (\n err instanceof Error &&\n err.message === IModelTransformer.noEsaSyncDirectionErrorMessage &&\n this._allowNoScopingESA\n ) {\n return \"forward\";\n }\n throw err;\n }\n }\n\n public get isReverseSynchronization(): boolean {\n if (this._syncType === undefined) this._syncType = this.determineSyncType();\n return this._syncType === \"reverse\";\n }\n\n public get isForwardSynchronization(): boolean {\n if (this._syncType === undefined) this._syncType = this.determineSyncType();\n return this._syncType === \"forward\";\n }\n\n private _changesetRanges: [number, number][] | undefined = undefined;\n\n /**\n * Set if the transformer is being used to perform the provenance initialization step of a fork initialization.\n * In general don't use the transformer for that, prefer [[BranchProvenanceInitializer.initializeBranchProvenance]]\n */\n private _isProvenanceInitTransform?: boolean;\n\n /** The element classes that are considered to define provenance in the iModel */\n public static get provenanceElementClasses(): (typeof Entity)[] {\n return [\n FolderLink,\n SynchronizationConfigLink,\n ExternalSource,\n ExternalSourceAttachment,\n ];\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 /** 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(\n source: IModelDb | IModelExporter,\n target: IModelDb | IModelImporter,\n options?: IModelTransformOptions\n ) {\n super();\n // initialize IModelTransformOptions\n this._options = {\n ...options,\n // non-falsy defaults\n cloneUsingBinaryGeometry: options?.cloneUsingBinaryGeometry ?? true,\n targetScopeElementId:\n options?.targetScopeElementId ?? IModel.rootSubjectId,\n // eslint-disable-next-line deprecation/deprecation\n danglingReferencesBehavior:\n options?.danglingReferencesBehavior ?? \"reject\",\n branchRelationshipDataBehavior:\n options?.branchRelationshipDataBehavior ?? \"reject\",\n skipPropagateChangesToRootElements:\n options?.skipPropagateChangesToRootElements ?? true,\n };\n // check if authorization client is defined\n if (IModelHost.authorizationClient === undefined) {\n Logger.logWarning(\n loggerCategory,\n \"Authorization client is not set in IModelHost. If the transformer needs an accessToken, then it will fail.\"\n );\n }\n this._isProvenanceInitTransform = this._options\n .wasSourceIModelCopiedToTarget\n ? true\n : 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) {\n // clone provenance from the source iModel into the target iModel?\n IModelTransformer.provenanceElementClasses.forEach((cls) =>\n this.exporter.excludeElementClass(cls.classFullName)\n );\n IModelTransformer.provenanceElementAspectClasses.forEach((cls) =>\n this.exporter.excludeElementAspectClass(cls.classFullName)\n );\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, {\n preserveElementIdsForFiltering:\n this._options.preserveElementIdsForFiltering,\n skipPropagateChangesToRootElements:\n this._options.skipPropagateChangesToRootElements,\n });\n } else {\n this.importer = target;\n this.validateSharedOptionsMatch();\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 if (this.sourceDb.isBriefcase && this.targetDb.isBriefcase) {\n nodeAssert(\n this.sourceDb.changeset.index !== undefined &&\n this.targetDb.changeset.index !== undefined,\n \"database has no changeset index\"\n );\n this._startingChangesetIndices = {\n target: this.targetDb.changeset.index,\n source: this.sourceDb.changeset.index,\n };\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 = \"exact\";\n (this.targetDb as any).codeValueBehavior = \"exact\";\n }\n /* eslint-enable @itwin/no-internal */\n }\n\n /** validates that the importer set on the transformer has the same values for its shared options as the transformer.\n * @note This expects that the importer is already set on the transformer.\n */\n private validateSharedOptionsMatch() {\n if (\n Boolean(this._options.preserveElementIdsForFiltering) !==\n this.importer.options.preserveElementIdsForFiltering\n ) {\n const errMessage =\n \"A custom importer was passed as a target but its 'preserveElementIdsForFiltering' option is out of sync with the transformer's option.\";\n throw new Error(errMessage);\n }\n if (\n Boolean(this._options.skipPropagateChangesToRootElements) !==\n this.importer.options.skipPropagateChangesToRootElements\n ) {\n const errMessage =\n \"A custom importer was passed as a target but its 'skipPropagateChangesToRootElements' option is out of sync with the transformer's option.\";\n throw new Error(errMessage);\n }\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(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.visitElements=${this.exporter.visitElements}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.visitRelationships=${this.exporter.visitRelationships}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.wantGeometry=${this.exporter.wantGeometry}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.wantSystemSchemas=${this.exporter.wantSystemSchemas}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.wantTemplateModels=${this.exporter.wantTemplateModels}`\n );\n Logger.logInfo(\n loggerCategory,\n `this.targetScopeElementId=${this.targetScopeElementId}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._noProvenance=${this._options.noProvenance}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._includeSourceProvenance=${this._options.includeSourceProvenance}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._cloneUsingBinaryGeometry=${this._options.cloneUsingBinaryGeometry}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._wasSourceIModelCopiedToTarget=${this._options.wasSourceIModelCopiedToTarget}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelImporter,\n `this.importer.autoExtendProjectExtents=${JSON.stringify(\n this.importer.options.autoExtendProjectExtents\n )}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelImporter,\n `this.importer.simplifyElementGeometry=${this.importer.options.simplifyElementGeometry}`\n );\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.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.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 targetDb: IModelDb;\n // TODO: Consider making it optional and determining it through ESAs if not provided. This gives opportunity for people to determine it themselves using public static determineSyncType function.\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n }\n ): ExternalSourceAspectProps {\n const elementId = args.isReverseSynchronization\n ? sourceElementId\n : targetElementId;\n const version = args.isReverseSynchronization\n ? args.targetDb.elements.queryLastModifiedTime(targetElementId)\n : args.sourceDb.elements.queryLastModifiedTime(sourceElementId);\n const aspectIdentifier = args.isReverseSynchronization\n ? targetElementId\n : sourceElementId;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: elementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Element,\n version,\n };\n return aspectProps;\n }\n\n public static initRelationshipProvenanceOptions(\n sourceRelInstanceId: Id64String,\n targetRelInstanceId: Id64String,\n args: {\n sourceDb: IModelDb;\n targetDb: IModelDb;\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n forceOldRelationshipProvenanceMethod: boolean;\n }\n ): ExternalSourceAspectProps {\n const provenanceDb = args.isReverseSynchronization\n ? args.sourceDb\n : args.targetDb;\n const aspectIdentifier = args.isReverseSynchronization\n ? targetRelInstanceId\n : sourceRelInstanceId;\n const provenanceRelInstanceId = args.isReverseSynchronization\n ? sourceRelInstanceId\n : targetRelInstanceId;\n\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n const elementId = provenanceDb.withPreparedStatement(\n \"SELECT SourceECInstanceId FROM bis.ElementRefersToElements WHERE ECInstanceId=?\",\n (stmt) => {\n stmt.bindId(1, provenanceRelInstanceId);\n nodeAssert(stmt.step() === DbResult.BE_SQLITE_ROW);\n return stmt.getValue(0).getId();\n }\n );\n\n const jsonProperties = args.forceOldRelationshipProvenanceMethod\n ? { targetRelInstanceId }\n : { provenanceRelInstanceId };\n\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: elementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Relationship,\n jsonProperties: JSON.stringify(jsonProperties),\n };\n\n return aspectProps;\n }\n\n /**\n * Previously the transformer would insert provenance always pointing to the \"target\" relationship.\n * It should (and now by default does) instead insert provenance pointing to the provenanceSource\n * SEE: https://github.com/iTwin/imodel-transformer/issues/54\n * This exists only to facilitate testing that the transformer can handle the older, flawed method\n */\n private _forceOldRelationshipProvenanceMethod = false;\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n public initElementProvenance(\n sourceElementId: Id64String,\n targetElementId: Id64String\n ): ExternalSourceAspectProps {\n return IModelTransformer.initElementProvenanceOptions(\n sourceElementId,\n targetElementId,\n {\n isReverseSynchronization: this.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n sourceDb: this.sourceDb,\n targetDb: this.targetDb,\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 master iModel.\n * The ECInstanceId of the relationship in the branch iModel will be stored in the JsonProperties of the ExternalSourceAspect.\n */\n private initRelationshipProvenance(\n sourceRelationship: Relationship,\n targetRelInstanceId: Id64String\n ): ExternalSourceAspectProps {\n return IModelTransformer.initRelationshipProvenanceOptions(\n sourceRelationship.id,\n targetRelInstanceId,\n {\n sourceDb: this.sourceDb,\n targetDb: this.targetDb,\n isReverseSynchronization: this.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n forceOldRelationshipProvenanceMethod:\n this._forceOldRelationshipProvenanceMethod,\n }\n );\n }\n\n /** NOTE: the json properties must be converted to string before insertion */\n private _targetScopeProvenanceProps:\n | (Omit<ExternalSourceAspectProps, \"jsonProperties\"> & {\n jsonProperties: TargetScopeProvenanceJsonProps;\n })\n | undefined = undefined;\n\n /**\n * Index of the changeset that the transformer was at when the transformation begins (was constructed).\n * Used to determine at the end which changesets were part of a synchronization.\n */\n private _startingChangesetIndices:\n | {\n target: number;\n source: number;\n }\n | undefined = undefined;\n\n private _cachedSynchronizationVersion: ChangesetIndexAndId | undefined =\n undefined;\n\n /**\n * We cache the synchronization version to avoid querying the target scoping ESA multiple times.\n * If the target scoping ESA is ever updated we need to clear any potentially cached sync version otherwise we will get stale values.\n * Sets this._cachedSynchronizationVersion to undefined.\n */\n private clearCachedSynchronizationVersion() {\n this._cachedSynchronizationVersion = undefined;\n }\n\n /** the changeset in the scoping element's source version found for this transformation\n * @note the version depends on whether this is a reverse synchronization or not, as\n * it is stored separately for both synchronization directions.\n * @note empty string and -1 for changeset and index if it has never been transformed\n * @note empty string and -1 for changeset and index if it was transformed before federation guid update (pre 1.x) and @see [[IModelTransformOptions.branchRelationshipDataBehavior]] === \"unsafe-migrate\".\n * @throws if the version is not found in a preexisting scope aspect and @see [[IModelTransformOptions.branchRelationshipDataBehavior]] !== \"unsafe-migrate\"\n */\n protected get synchronizationVersion(): ChangesetIndexAndId {\n if (this._cachedSynchronizationVersion === undefined) {\n const provenanceScopeAspect = this.tryGetProvenanceScopeAspect();\n if (!provenanceScopeAspect) {\n return { index: -1, id: \"\" }; // first synchronization.\n }\n\n const version = this.isReverseSynchronization\n ? (\n JSON.parse(\n provenanceScopeAspect.jsonProperties ?? \"{}\"\n ) as TargetScopeProvenanceJsonProps\n ).reverseSyncVersion\n : provenanceScopeAspect.version;\n if (\n !version &&\n this._options.branchRelationshipDataBehavior === \"unsafe-migrate\"\n ) {\n return { index: -1, id: \"\" }; // previous synchronization was done before fed guid update.\n }\n if (version === undefined) {\n throw new Error(`Could not find synchronization version in scope aspect. This may be due to the last successful run of the transformer being done with an older version.\n Consider running the transformer with branchRelationshipDataBehavior set to 'unsafe-migrate'`);\n }\n const [id, index] = version === \"\" ? [\"\", -1] : version.split(\";\");\n if (Number.isNaN(Number(index)))\n throw new Error(\"Could not parse version data from scope aspect\");\n this._cachedSynchronizationVersion = { index: Number(index), id }; // synchronization version found and cached.\n }\n return this._cachedSynchronizationVersion;\n }\n\n /**\n * @returns provenance scope aspect if it exists in the provenanceDb.\n * Provenance scope aspect is created and inserted into provenanceDb when [[initScopeProvenance]] is invoked.\n */\n protected tryGetProvenanceScopeAspect(): ExternalSourceAspect | undefined {\n const scopeProvenanceAspectProps =\n IModelTransformer.queryScopeExternalSourceAspect(this.provenanceDb, {\n id: undefined,\n classFullName: ExternalSourceAspect.classFullName,\n scope: { id: IModel.rootSubjectId },\n kind: ExternalSourceAspect.Kind.Scope,\n element: { id: this.targetScopeElementId ?? IModel.rootSubjectId },\n identifier: this.provenanceSourceDb.iModelId,\n });\n\n return scopeProvenanceAspectProps !== undefined\n ? (this.provenanceDb.elements.getAspect(\n scopeProvenanceAspectProps.aspectId\n ) as ExternalSourceAspect)\n : undefined;\n }\n\n /**\n * Make sure there are no conflicting other scope-type external source aspects on the *target scope element*,\n * If there are none at all, insert one, then this must be a first synchronization.\n * @returns the last synced version (changesetId) on the target scope's external source aspect,\n * if this was a [BriefcaseDb]($backend)\n */\n protected initScopeProvenance(): void {\n const aspectProps = {\n id: undefined as string | undefined,\n version: undefined as string | undefined,\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: this.targetScopeElementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: this.provenanceSourceDb.iModelId,\n kind: ExternalSourceAspect.Kind.Scope,\n jsonProperties: undefined as TargetScopeProvenanceJsonProps | undefined,\n };\n\n const foundEsaProps = IModelTransformer.queryScopeExternalSourceAspect(\n this.provenanceDb,\n aspectProps\n ); // this query includes \"identifier\"\n\n if (foundEsaProps === undefined) {\n aspectProps.version = \"\"; // empty since never before transformed. Will be updated in [[finalizeTransformation]]\n aspectProps.jsonProperties = {\n pendingReverseSyncChangesetIndices: [],\n pendingSyncChangesetIndices: [],\n reverseSyncVersion: \"\", // empty since never before transformed. Will be updated in first reverse sync\n };\n\n // this query does not include \"identifier\" to find possible conflicts\n const sql = `\n SELECT ECInstanceId\n FROM ${ExternalSourceAspect.classFullName}\n WHERE Element.Id=:elementId\n AND Scope.Id=:scopeId\n AND Kind=:kind\n LIMIT 1\n `;\n\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n const hasConflictingScope = this.provenanceDb.withPreparedStatement(\n sql,\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n (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 );\n\n if (hasConflictingScope) {\n throw new IModelError(\n IModelStatus.InvalidId,\n \"Provenance scope conflict\"\n );\n }\n if (!this._options.noProvenance) {\n const id = this.provenanceDb.elements.insertAspect({\n ...aspectProps,\n jsonProperties: JSON.stringify(aspectProps.jsonProperties) as any,\n });\n aspectProps.id = id;\n // Busting a potential cached version\n this.clearCachedSynchronizationVersion();\n }\n } else {\n // foundEsaProps is defined.\n aspectProps.id = foundEsaProps.aspectId;\n aspectProps.version = foundEsaProps.version;\n aspectProps.jsonProperties = foundEsaProps.jsonProperties\n ? JSON.parse(foundEsaProps.jsonProperties)\n : undefined;\n // Clone oldProps incase they're changed for logging purposes\n const oldProps = JSON.parse(JSON.stringify(aspectProps));\n if (this.handleUnsafeMigrate(aspectProps)) {\n Logger.logInfo(\n loggerCategory,\n \"Unsafe migrate made a change to the target scope's external source aspect. Updating aspect in database.\",\n { oldProps, newProps: aspectProps }\n );\n this.provenanceDb.elements.updateAspect({\n ...aspectProps,\n jsonProperties: JSON.stringify(aspectProps.jsonProperties) as any,\n });\n // Busting a potential cached version\n this.clearCachedSynchronizationVersion();\n }\n }\n\n this._targetScopeProvenanceProps =\n aspectProps as typeof this._targetScopeProvenanceProps;\n }\n\n /** Returns true if a change was made to the aspectProps. */\n private handleUnsafeMigrate(aspectProps: {\n version?: string;\n jsonProperties?: TargetScopeProvenanceJsonProps;\n }): boolean {\n let madeChange = false;\n if (this._options.branchRelationshipDataBehavior !== \"unsafe-migrate\")\n return madeChange;\n const fallbackSyncVersionToUse =\n this._options.argsForProcessChanges?.unsafeFallbackSyncVersion ?? \"\";\n const fallbackReverseSyncVersionToUse =\n this._options.argsForProcessChanges?.unsafeFallbackReverseSyncVersion ??\n \"\";\n\n if (\n aspectProps.version === undefined ||\n (aspectProps.version === \"\" &&\n aspectProps.version !== fallbackSyncVersionToUse)\n ) {\n aspectProps.version = fallbackSyncVersionToUse;\n madeChange = true;\n }\n\n if (aspectProps.jsonProperties === undefined) {\n aspectProps.jsonProperties = {\n pendingReverseSyncChangesetIndices: [],\n pendingSyncChangesetIndices: [],\n reverseSyncVersion: fallbackReverseSyncVersionToUse,\n };\n madeChange = true;\n } else if (\n aspectProps.jsonProperties.reverseSyncVersion === undefined ||\n (aspectProps.jsonProperties.reverseSyncVersion === \"\" &&\n aspectProps.jsonProperties.reverseSyncVersion !==\n fallbackReverseSyncVersionToUse)\n ) {\n aspectProps.jsonProperties.reverseSyncVersion =\n fallbackReverseSyncVersionToUse;\n madeChange = true;\n }\n\n /**\n * This case will only be hit when:\n * - first transformation was performed on pre-fedguid transformer.\n * - a second processAll transformation was performed on the same target-source iModels post-fedguid transformer.\n * - change processing was invoked on for the second 'initial' transformation.\n * NOTE: This case likely does not exist anymore, but we will keep it just to be sure.\n */\n if (\n aspectProps.jsonProperties.pendingReverseSyncChangesetIndices ===\n undefined\n ) {\n Logger.logWarning(\n loggerCategory,\n \"Property pendingReverseSyncChangesetIndices missing on the jsonProperties of the scoping ESA. Setting to [].\"\n );\n aspectProps.jsonProperties.pendingReverseSyncChangesetIndices = [];\n madeChange = true;\n }\n if (aspectProps.jsonProperties.pendingSyncChangesetIndices === undefined) {\n Logger.logWarning(\n loggerCategory,\n \"Property pendingSyncChangesetIndices missing on the jsonProperties of the scoping ESA. Setting to [].\"\n );\n aspectProps.jsonProperties.pendingSyncChangesetIndices = [];\n madeChange = true;\n }\n return madeChange;\n }\n\n /**\n * Iterate all matching federation guids and ExternalSourceAspects in the provenance iModel (target unless reverse sync)\n * and call a function for each one.\n * @note provenance is done by federation guids where possible\n * @note this may execute on each element more than once! Only use in cases where that is handled\n */\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 skipPropagateChangesToRootElements: boolean;\n }): void {\n if (args.provenanceDb === args.provenanceSourceDb) return;\n\n if (!args.provenanceDb.containsClass(ExternalSourceAspect.classFullName)) {\n throw new IModelError(\n IModelStatus.BadSchema,\n \"The BisCore schema version of the target database is too old\"\n );\n }\n\n const sourceDb = args.isReverseSynchronization\n ? args.provenanceDb\n : args.provenanceSourceDb;\n const targetDb = args.isReverseSynchronization\n ? args.provenanceSourceDb\n : args.provenanceDb;\n\n // query for provenanceDb\n const elementIdByFedGuidQuery = `\n SELECT e.ECInstanceId, FederationGuid\n FROM bis.Element e\n ${\n args.skipPropagateChangesToRootElements\n ? \"WHERE e.ECInstanceId NOT IN (0x1, 0xe, 0x10) -- special static elements\"\n : \"\"\n }\n ORDER BY FederationGuid\n `;\n\n // iterate through sorted list of fed guids from both dbs to get the intersection\n // NOTE: if we exposed the native attach database support,\n // we could get the intersection of fed guids in one query, not sure if it would be faster\n // OR we could do a raw sqlite query...\n\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n sourceDb.withStatement(elementIdByFedGuidQuery, (sourceStmt) =>\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n targetDb.withStatement(elementIdByFedGuidQuery, (targetStmt) => {\n if (sourceStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n let sourceRow = sourceStmt.getRow() as {\n federationGuid?: GuidString;\n id: Id64String;\n };\n if (targetStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n let targetRow = targetStmt.getRow() as {\n federationGuid?: GuidString;\n id: Id64String;\n };\n\n // NOTE: these comparisons rely upon the lowercase of the guid,\n // and the fact that '0' < '9' < a' < 'f' in ascii/utf8\n while (true) {\n const currSourceRow = sourceRow,\n currTargetRow = targetRow;\n if (\n currSourceRow.federationGuid !== undefined &&\n currTargetRow.federationGuid !== undefined &&\n currSourceRow.federationGuid === currTargetRow.federationGuid\n ) {\n // data flow direction is always sourceDb -> targetDb and it does not depend on where the explicit element provenance is stored\n args.fn(sourceRow.id, targetRow.id);\n }\n if (\n currTargetRow.federationGuid === undefined ||\n (currSourceRow.federationGuid !== undefined &&\n currSourceRow.federationGuid >= currTargetRow.federationGuid)\n ) {\n if (targetStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n targetRow = targetStmt.getRow();\n }\n if (\n currSourceRow.federationGuid === undefined ||\n (currTargetRow.federationGuid !== undefined &&\n currSourceRow.federationGuid <= currTargetRow.federationGuid)\n ) {\n if (sourceStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n sourceRow = sourceStmt.getRow();\n }\n }\n })\n );\n\n // query for provenanceDb\n const provenanceAspectsQuery = `\n SELECT esa.Identifier, Element.Id\n FROM bis.ExternalSourceAspect esa\n WHERE Scope.Id=:scopeId\n AND Kind=:kind\n `;\n\n // Technically this will a second time call the function (as documented) on\n // victims of the old provenance method that have both fedguids and an inserted aspect.\n // But this is a private function with one known caller where that doesn't matter\n\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n args.provenanceDb.withPreparedStatement(\n provenanceAspectsQuery,\n (stmt): void => {\n const runFnInDataFlowDirection = (\n sourceId: Id64String,\n targetId: Id64String\n ) =>\n args.isReverseSynchronization\n ? args.fn(sourceId, targetId)\n : args.fn(targetId, sourceId);\n stmt.bindId(\"scopeId\", args.targetScopeElementId);\n stmt.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n // ExternalSourceAspect.Identifier is of type string\n const aspectIdentifier: Id64String = stmt.getValue(0).getString();\n const elementId: Id64String = stmt.getValue(1).getId();\n runFnInDataFlowDirection(elementId, aspectIdentifier);\n }\n }\n );\n }\n\n private forEachTrackedElement(\n fn: (sourceElementId: Id64String, targetElementId: Id64String) => void\n ): void {\n return IModelTransformer.forEachTrackedElement({\n provenanceSourceDb: this.provenanceSourceDb,\n provenanceDb: this.provenanceDb,\n targetScopeElementId: this.targetScopeElementId,\n isReverseSynchronization: this.isReverseSynchronization,\n fn,\n skipPropagateChangesToRootElements:\n this._options.skipPropagateChangesToRootElements ?? true,\n });\n }\n\n /**\n * Queries the provenanceDb for an ESA whose identifier is equal to the provided 'entityInProvenanceSourceId'.\n * The identifier on the ESA is the id of the element in the [[IModelTransformer.provenanceSourceDb]]\n * Therefore it only makes sense to call this function when you have an id in the provenanceSourceDb.\n * @param entityInProvenanceSourceId\n * @returns the elementId that the ESA is stored on, esa.Element.Id\n */\n private _queryProvenanceForElement(\n entityInProvenanceSourceId: Id64String\n ): Id64String | undefined {\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return this.provenanceDb.withPreparedStatement(\n `\n SELECT esa.Element.Id\n FROM Bis.ExternalSourceAspect esa\n WHERE esa.Kind=?\n AND esa.Scope.Id=?\n AND esa.Identifier=?\n `,\n (stmt) => {\n stmt.bindString(1, ExternalSourceAspect.Kind.Element);\n stmt.bindId(2, this.targetScopeElementId);\n stmt.bindString(3, entityInProvenanceSourceId);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n else return undefined;\n }\n );\n }\n\n /**\n * Queries the provenanceDb for an ESA whose identifier is equal to the provided 'entityInProvenanceSourceId'.\n * The identifier on the ESA is the id of the relationship in the [[IModelTransformer.provenanceSourceDb]]\n * Therefore it only makes sense to call this function when you have an id in the provenanceSourceDb.\n * @param entityInProvenanceSourceId\n * @returns\n */\n private _queryProvenanceForRelationship(\n entityInProvenanceSourceId: Id64String,\n sourceRelInfo: {\n classFullName: string;\n sourceId: Id64String;\n targetId: Id64String;\n }\n ):\n | {\n aspectId: Id64String;\n /** if undefined, the relationship could not be found, perhaps it was deleted */\n relationshipId: Id64String | undefined;\n }\n | undefined {\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return this.provenanceDb.withPreparedStatement(\n `\n SELECT\n ECInstanceId,\n JSON_EXTRACT(JsonProperties, '$.targetRelInstanceId'),\n JSON_EXTRACT(JsonProperties, '$.provenanceRelInstanceId')\n FROM Bis.ExternalSourceAspect\n WHERE Kind=?\n AND Scope.Id=?\n AND Identifier=?\n `,\n (stmt) => {\n stmt.bindString(1, ExternalSourceAspect.Kind.Relationship);\n stmt.bindId(2, this.targetScopeElementId);\n stmt.bindString(3, entityInProvenanceSourceId);\n if (stmt.step() !== DbResult.BE_SQLITE_ROW) return undefined;\n\n const aspectId = stmt.getValue(0).getId();\n const provenanceRelInstIdVal = stmt.getValue(2);\n const provenanceRelInstanceId = !provenanceRelInstIdVal.isNull\n ? provenanceRelInstIdVal.getString()\n : this._queryTargetRelId(sourceRelInfo);\n return {\n aspectId,\n relationshipId: provenanceRelInstanceId,\n };\n }\n );\n }\n\n private _queryTargetRelId(sourceRelInfo: {\n classFullName: string;\n sourceId: Id64String;\n targetId: Id64String;\n }): Id64String | undefined {\n const targetRelInfo = {\n sourceId: this.context.findTargetElementId(sourceRelInfo.sourceId),\n targetId: this.context.findTargetElementId(sourceRelInfo.targetId),\n };\n if (\n targetRelInfo.sourceId === undefined ||\n targetRelInfo.targetId === undefined\n )\n return undefined; // couldn't find an element, rel is invalid or deleted\n\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return this.targetDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM bis.ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n AND ECClassId=?\n `,\n (stmt) => {\n stmt.bindId(1, targetRelInfo.sourceId);\n stmt.bindId(2, targetRelInfo.targetId);\n stmt.bindId(\n 3,\n this._targetClassNameToClassId(sourceRelInfo.classFullName)\n );\n if (stmt.step() !== DbResult.BE_SQLITE_ROW) return undefined;\n return stmt.getValue(0).getId();\n }\n );\n }\n\n private _targetClassNameToClassIdCache = new Map<string, string>();\n\n private _targetClassNameToClassId(classFullName: string): Id64String {\n let classId = this._targetClassNameToClassIdCache.get(classFullName);\n if (classId === undefined) {\n classId = this._getRelClassId(this.targetDb, classFullName);\n this._targetClassNameToClassIdCache.set(classFullName, classId);\n }\n return classId;\n }\n\n // NOTE: this doesn't handle remapped element classes,\n // but is only used for relationships rn\n private _getRelClassId(db: IModelDb, classFullName: string): Id64String {\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return db.withPreparedStatement(\n `\n SELECT c.ECInstanceId\n FROM ECDbMeta.ECClassDef c\n JOIN ECDbMeta.ECSchemaDef s ON c.Schema.Id=s.ECInstanceId\n WHERE s.Name=? AND c.Name=?\n `,\n (stmt) => {\n const [schemaName, className] =\n classFullName.indexOf(\".\") !== -1\n ? classFullName.split(\".\")\n : classFullName.split(\":\");\n stmt.bindString(1, schemaName);\n stmt.bindString(2, className);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n assert(false, \"relationship was not found\");\n }\n );\n }\n\n private _queryElemIdByFedGuid(\n db: IModelDb,\n fedGuid: GuidString\n ): Id64String | undefined {\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return db.withPreparedStatement(\n \"SELECT ECInstanceId FROM Bis.Element WHERE FederationGuid=?\",\n (stmt) => {\n stmt.bindGuid(1, fedGuid);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n else return undefined;\n }\n );\n }\n\n /** Returns `true` if *brute force* delete detections should be run.\n * @note This is only called if [[IModelTransformOptions.forceExternalSourceAspectProvenance]] option is true\n * @note Not relevant for [[process]] when [[IModelTransformOptions.argsForProcessChanges]] are provided and change history is known.\n */\n protected shouldDetectDeletes(): boolean {\n nodeAssert(this._syncType !== undefined);\n\n return this._syncType === \"not-sync\";\n }\n\n /**\n * Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements\n * in the source iModel.\n * @deprecated in 1.x. Do not use this. // FIXME<MIKE>: how to better explain this?\n * This method is only called during [[process]] when [[IModelTransformOptions.argsForProcessChanges]] is undefined and the option\n * [[IModelTransformOptions.forceExternalSourceAspectProvenance]] is enabled. It is not\n * necessary when calling [[process]] with [[IModelTransformOptions.argsForProcessChanges]] defined, since changeset information is sufficient.\n * @note you do not need to call this directly unless 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 const sql = `\n SELECT Identifier, Element.Id\n FROM BisCore.ExternalSourceAspect\n WHERE Scope.Id=:scopeId\n AND Kind=:kind\n `;\n\n nodeAssert(\n !this.isReverseSynchronization,\n \"synchronizations with processChanges already detect element deletes, don't call detectElementDeletes\"\n );\n\n // Reported issue: https://github.com/iTwin/itwinjs-core/issues/7989\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n this.provenanceDb.withPreparedStatement(sql, (stmt) => {\n stmt.bindId(\"scopeId\", this.targetScopeElementId);\n stmt.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n // ExternalSourceAspect.Identifier is of type string\n const aspectIdentifier = stmt.getValue(0).getString();\n if (!Id64.isValidId64(aspectIdentifier)) {\n continue;\n }\n const targetElemId = stmt.getValue(1).getId();\n const wasDeletedInSource = !EntityUnifier.exists(this.sourceDb, {\n entityReference: `e${aspectIdentifier}`,\n });\n if (wasDeletedInSource) this.importer.deleteElement(targetElemId);\n }\n });\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(\n loggerCategory,\n `onTransformElement(${\n sourceElement.id\n }) \"${sourceElement.getDisplayLabel()}\"`\n );\n const targetElementProps: ElementProps = this.context.cloneElement(\n sourceElement,\n { binaryGeometry: this._options.cloneUsingBinaryGeometry }\n );\n // Special case: source element is the root subject\n if (sourceElement.id === IModel.rootSubjectId) {\n const targetElementId: string = this.context.findTargetElementId(\n sourceElement.id\n );\n // When remapping rootSubject from source to non root subject in target, the code.scope gets remapped incorrectly.\n // This is because the rootSubject has no parent and its code.scope is unique in that it is the id of itself.\n // For all other subjects which do have parents the code.scope and its parent should be in agreement.\n if (\n targetElementId !== Id64.invalid &&\n targetElementId !== IModel.rootSubjectId\n ) {\n const targetElement =\n this.targetDb.elements.getElement(targetElementId);\n targetElementProps.parent =\n targetElement.parent ?? targetElementProps.parent;\n targetElementProps.code.scope = targetElement.code.scope;\n }\n }\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 // if undefined, it can be initialized by calling [[this.processChangesets]]\n private _deletedSourceRelationshipData?: Map<\n Id64String,\n {\n sourceIdInTarget?: Id64String;\n targetIdInTarget?: Id64String;\n classFullName: Id64String;\n relId?: Id64String;\n provenanceAspectId?: Id64String;\n }\n > = undefined;\n\n /** Returns true if a change within sourceElement is detected.\n * @param sourceElement The Element from the source iModel\n * @note A subclass can override this method to provide custom change detection behavior.\n */\n protected hasElementChanged(sourceElement: Element): boolean {\n const sourceDbChanges = this.exporter.sourceDbChanges;\n return (\n !sourceDbChanges || // are we processing changes? if not then element is considered as changed\n sourceDbChanges.element.insertIds.has(sourceElement.id) ||\n sourceDbChanges.element.updateIds.has(sourceElement.id)\n );\n }\n\n protected completePartiallyCommittedElements() {\n for (const sourceElementId of this._partiallyCommittedElementIds) {\n const sourceElement = this.sourceDb.elements.getElement({\n id: sourceElementId,\n wantGeometry: this.exporter.wantGeometry,\n wantBRepData: this.exporter.wantGeometry,\n });\n const targetId = this.context.findTargetElementId(sourceElementId);\n if (Id64.isInvalid(targetId)) {\n throw new Error(\n `source-target element mapping not found for element \"${sourceElementId}\" when completing partially committed elements. This is a bug.`\n );\n }\n\n const targetProps = this.onTransformElement(sourceElement);\n this.targetDb.elements.updateElement({ ...targetProps, id: targetId });\n }\n }\n\n protected completePartiallyCommittedAspects() {\n for (const sourceAspectId of this._partiallyCommittedAspectIds) {\n const sourceAspect = this.sourceDb.elements.getAspect(sourceAspectId);\n const targetAspectId = this.context.findTargetAspectId(sourceAspectId);\n if (Id64.isInvalid(targetAspectId)) {\n throw new Error(\n `source-target aspect mapping not found for aspect \"${sourceAspectId}\" when completing partially committed aspects. This is a bug.`\n );\n }\n const targetAspectProps = this.onTransformElementAspect(sourceAspect);\n this.targetDb.elements.updateAspect({\n ...targetAspectProps,\n id: targetAspectId,\n });\n }\n }\n\n private doAllReferencesExistInTarget(entity: ConcreteEntity) {\n let allReferencesExist = true;\n for (const referenceId of entity.getReferenceIds()) {\n const referencedEntityId = EntityReferences.toId64(referenceId);\n if (\n referencedEntityId === IModel.repositoryModelId ||\n referencedEntityId === IModel.dictionaryId ||\n referencedEntityId === \"0xe\"\n ) {\n continue;\n }\n\n if (\n allReferencesExist &&\n !EntityReferences.isValid(this.context.findTargetEntityId(referenceId))\n ) {\n // if we care about references existing then we cannot return early and must check all other references.\n if (this._options.danglingReferencesBehavior === \"ignore\") {\n return false;\n }\n allReferencesExist = false;\n }\n\n if (this._options.danglingReferencesBehavior === \"reject\") {\n this.assertReferenceExistsInSource(referenceId, entity);\n }\n }\n return allReferencesExist;\n }\n\n private assertReferenceExistsInSource(\n referenceId: EntityReference,\n entity: ConcreteEntity\n ) {\n const referencedExistsInSource = EntityUnifier.exists(this.sourceDb, {\n entityReference: referenceId,\n });\n if (!referencedExistsInSource) {\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 IModelTransformOptions.danglingReferencesBehavior option to 'ignore' to ignore this,\",\n `and the referenceId found on \"${entity.id}\" will not be carried over to corresponding target element.`,\n ].join(\"\\n\")\n );\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 [[process]], 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(\n IModelStatus.BadRequest,\n \"The root Subject should not be directly imported\"\n );\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 [[process]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processChildElements(\n sourceElementId: Id64String\n ): 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 {\n return true;\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(\n sourceElement: Element\n ): 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 =\n 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(\n referenceType === ConcreteEntityTypes.Element ||\n referenceType === ConcreteEntityTypes.Model\n );\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(\n id,\n DefinitionElement\n );\n if (\n asDefinitionElem &&\n !(asDefinitionElem instanceof RecipeDefinitionElement)\n ) {\n this.context.remapElement(id, id);\n }\n }\n return id;\n }).filter(\n (\n sourceReferenceId: Id64String | undefined\n ): sourceReferenceId is Id64String => {\n if (sourceReferenceId === undefined) return false;\n const referenceInTargetId =\n this.context.findTargetElementId(sourceReferenceId);\n const isInTarget = Id64.isValid(referenceInTargetId);\n return !isInTarget;\n }\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(\n id,\n ConcreteEntityTypes.Model\n );\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 =\n isSubModeled &&\n (!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;\n let targetElementProps: ElementProps;\n if (this._options.wasSourceIModelCopiedToTarget) {\n targetElementId = sourceElement.id;\n targetElementProps =\n this.targetDb.elements.getElementProps(targetElementId);\n } else {\n targetElementId = this.context.findTargetElementId(sourceElement.id);\n targetElementProps = this.onTransformElement(sourceElement);\n }\n\n // if an existing remapping was not yet found, check by FederationGuid\n if (\n this.context.isBetweenIModels &&\n !Id64.isValid(targetElementId) &&\n sourceElement.federationGuid !== undefined\n ) {\n targetElementId =\n this._queryElemIdByFedGuid(\n this.targetDb,\n sourceElement.federationGuid\n ) ?? Id64.invalid;\n if (Id64.isValid(targetElementId))\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found\n }\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 (\n !Id64.isValidId64(targetElementId) &&\n Id64.isValidId64(targetElementProps.code.scope)\n ) {\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 const maybeTargetElementId = this.targetDb.elements.queryElementIdByCode(\n targetElementProps.code as Required<CodeProps>\n );\n if (undefined !== maybeTargetElementId) {\n const maybeTargetElem =\n this.targetDb.elements.getElement(maybeTargetElementId);\n if (\n maybeTargetElem.classFullName === targetElementProps.classFullName\n ) {\n // ensure code remapping doesn't change the target class\n targetElementId = maybeTargetElementId;\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code\n } else {\n targetElementProps.code = Code.createEmpty(); // clear out invalid code\n }\n }\n }\n\n if (!this.hasElementChanged(sourceElement)) {\n Logger.logTrace(\n loggerCategory,\n `Skipping unchanged element (${sourceElement.id}, ${sourceElement.getDisplayLabel()}).`\n );\n return;\n }\n\n if (!this.doAllReferencesExistInTarget(sourceElement)) {\n this._partiallyCommittedElementIds.add(sourceElement.id);\n }\n\n // targetElementId will be valid (indicating update) or undefined (indicating insert)\n targetElementProps.id = Id64.isValid(targetElementId)\n ? targetElementId\n : undefined;\n\n if (this._options.preserveElementIdsForFiltering) {\n const isValid = Id64.isValid(targetElementId);\n if (isValid && targetElementId !== sourceElement.id) {\n // Element found with different id\n throw new Error(\n `Element id(${sourceElement.id}) cannot be preserved. Found a different mapping(${targetElementId}) from source element`\n );\n } else if (isValid && targetElementId === sourceElement.id) {\n // targetElementId is valid (indicating update)\n this.importer.markElementToUpdateDuringPreserveIds(sourceElement.id);\n } else if (!isValid) {\n const sourceInTargetElemProps =\n this.targetDb.elements.tryGetElementProps(sourceElement.id);\n\n // if we don't find mapping for source element in target(invalid) but another element with source id exists in target\n if (sourceInTargetElemProps) {\n // Element id is already taken by another element\n throw new Error(\n `Element id(${sourceElement.id}) cannot be preserved. An unrelated element in the target already uses id: ${sourceElement.id}`\n );\n } else {\n // Element id in target is available to be remapped\n targetElementProps.id = sourceElement.id;\n }\n }\n }\n\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\n // the transformer does not currently 'split' or 'join' any elements, therefore, it does not\n // insert external source aspects because federation guids are sufficient for this.\n // Other transformer subclasses must insert the appropriate aspect (as provided by a TBD API)\n // when splitting/joining elements\n // physical consolidation is an example of a 'joining' transform\n // FIXME: verify at finalization time that we don't lose provenance on new elements\n // FIXME: make public and improve `initElementProvenance` API for usage by consolidators\n if (!this._options.noProvenance) {\n let provenance:\n | Parameters<typeof this.markLastProvenance>[0]\n | undefined =\n this._options.forceExternalSourceAspectProvenance ||\n this._elementsWithExplicitlyTrackedProvenance.has(sourceElement.id)\n ? undefined\n : sourceElement.federationGuid;\n if (!provenance) {\n const aspectProps = this.initElementProvenance(\n sourceElement.id,\n targetElementProps.id!\n );\n const foundEsaProps = IModelTransformer.queryScopeExternalSourceAspect(\n this.provenanceDb,\n aspectProps\n );\n if (foundEsaProps === undefined)\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n else {\n // Since initElementProvenance sets a property 'version' on the aspectProps that we wish to persist in the provenanceDb, only grab the id from the foundEsaProps.\n aspectProps.id = foundEsaProps.aspectId;\n this.provenanceDb.elements.updateAspect(aspectProps);\n }\n\n provenance = aspectProps as MarkRequired<\n ExternalSourceAspectProps,\n \"id\"\n >;\n }\n this.markLastProvenance(provenance, { isRelationship: false });\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 =\n 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 (\n this._options.skipPropagateChangesToRootElements &&\n IModel.repositoryModelId === sourceModel.id\n )\n return; // The RepositoryModel should not be directly imported\n const targetModeledElementId: Id64String = this.context.findTargetElementId(\n sourceModel.id\n );\n // there can only be one repositoryModel per database, so ignore the repo model on remapped subjects\n const isRemappedRootSubject =\n sourceModel.id === IModel.repositoryModelId &&\n targetModeledElementId !== sourceModel.id;\n if (isRemappedRootSubject) return;\n const targetModelProps: ModelProps = this.onTransformModel(\n sourceModel,\n targetModeledElementId\n );\n this.importer.importModel(targetModelProps);\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, [[remapDeletedSourceEntities]] will find and remap the deleted element making this operation valid\n const targetModelId: Id64String =\n this.context.findTargetElementId(sourceModelId);\n\n if (!Id64.isValidId64(targetModelId)) return;\n\n const sql = `\n SELECT 1\n FROM bis.DefinitionPartition\n WHERE ECInstanceId=:targetModelId\n UNION\n SELECT 1\n FROM bis.DefinitionContainer\n WHERE ECInstanceId=:targetModelId\n `;\n\n if (this.exporter.sourceDbChanges?.element.deleteIds.has(sourceModelId)) {\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n const isDefinitionPartition = this.targetDb.withPreparedStatement(\n sql,\n (stmt) => {\n stmt.bindId(\"targetModelId\", targetModelId);\n const val: DbResult = stmt.step();\n switch (val) {\n case DbResult.BE_SQLITE_ROW:\n return true;\n case DbResult.BE_SQLITE_DONE:\n return false;\n default:\n assert(false, `unexpected db result: '${JSON.stringify(stmt)}'`);\n }\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 =\n error instanceof IModelError &&\n (error.errorNumber === IModelStatus.DeletionProhibited ||\n error.errorNumber === IModelStatus.ForeignKeyConstraint);\n if (!isDeletionProhibitedErr) 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\n .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 [[process]], 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 [[process]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModelContents(\n sourceModelId: Id64String,\n targetModelId: Id64String,\n elementClassFullName: string = Element.classFullName\n ): 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(\n sourceModelId,\n elementClassFullName\n );\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(\n sourceSubjectId: Id64String\n ): Promise<void> {\n await this.initialize();\n // import DefinitionModels first\n const childDefinitionPartitionSql = `SELECT ECInstanceId FROM ${DefinitionPartition.classFullName} WHERE Parent.Id=:subjectId`;\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n await this.sourceDb.withPreparedStatement(\n childDefinitionPartitionSql,\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n 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 );\n // import other partitions next\n const childPartitionSql = `SELECT ECInstanceId FROM ${InformationPartitionElement.classFullName} WHERE Parent.Id=:subjectId`;\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n await this.sourceDb.withPreparedStatement(\n childPartitionSql,\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n 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 );\n // recurse into child Subjects\n const childSubjectSql = `SELECT ECInstanceId FROM ${Subject.classFullName} WHERE Parent.Id=:subjectId`;\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n await this.sourceDb.withPreparedStatement(\n childSubjectSql,\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n 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\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(\n sourceModel: Model,\n targetModeledElementId: Id64String\n ): ModelProps {\n const targetModelProps: ModelProps = sourceModel.toJSON();\n // don't directly edit deep object since toJSON performs a shallow clone\n targetModelProps.modeledElement = {\n ...targetModelProps.modeledElement,\n id: targetModeledElementId,\n };\n targetModelProps.id = targetModeledElementId;\n targetModelProps.parentModel = this.context.findTargetElementId(\n targetModelProps.parentModel!\n );\n return targetModelProps;\n }\n\n /**\n * Called at the end of a transformation,\n * updates the target scope element to say that transformation up through the\n * source's changeset has been performed. Also stores all changesets that occurred\n * during the transformation as \"pending synchronization changeset indices\" @see TargetScopeProvenanceJsonProps\n *\n * You generally should not call this function yourself and use [[process]] with [[IModelTransformOptions.argsForProcessChanges]] provided instead.\n * It is public for unsupported use cases of custom synchronization transforms.\n * @note If [[IModelTransformOptions.argsForProcessChanges]] is not defined in this transformation, this function will return early without updating the sync version,\n * unless the `initializeReverseSyncVersion` option is set to `true`\n *\n * The `initializeReverseSyncVersion` is added to set the reverse synchronization version during a forward synchronization.\n * When set to `true`, it saves the reverse sync version as the current changeset of the targetDb. This is typically used for the first transformation between a master and branch iModel.\n * Setting `initializeReverseSyncVersion` to `true` has the effect of making it so any changesets in the branch iModel at the time of the first transformation will be ignored during any future reverse synchronizations from the branch to the master iModel.\n *\n * Note that typically, the reverseSyncVersion is saved as the last changeset merged from the branch into master.\n * Setting initializeReverseSyncVersion to true during a forward transformation could overwrite this correct reverseSyncVersion and should only be done during the first transformation between a master and branch iModel.\n */\n public updateSynchronizationVersion({\n initializeReverseSyncVersion = false,\n } = {}) {\n const shouldSkipSyncVersionUpdate =\n !initializeReverseSyncVersion &&\n this._sourceChangeDataState !== \"has-changes\";\n if (shouldSkipSyncVersionUpdate) return;\n\n nodeAssert(this._targetScopeProvenanceProps);\n\n const sourceVersion = `${this.sourceDb.changeset.id};${this.sourceDb.changeset.index}`;\n const targetVersion = `${this.targetDb.changeset.id};${this.targetDb.changeset.index}`;\n\n if (this.isReverseSynchronization) {\n const oldVersion =\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion;\n\n Logger.logInfo(\n loggerCategory,\n `updating reverse version from ${oldVersion} to ${sourceVersion}`\n );\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion =\n sourceVersion;\n } else {\n Logger.logInfo(\n loggerCategory,\n `updating sync version from ${this._targetScopeProvenanceProps.version} to ${sourceVersion}`\n );\n this._targetScopeProvenanceProps.version = sourceVersion;\n\n // save reverse sync version\n if (initializeReverseSyncVersion) {\n Logger.logInfo(\n loggerCategory,\n `updating reverse sync version from ${this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion} to ${targetVersion}`\n );\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion =\n targetVersion;\n }\n }\n\n if (\n this._options.argsForProcessChanges ||\n (this._startingChangesetIndices && initializeReverseSyncVersion)\n ) {\n nodeAssert(\n this.targetDb.changeset.index !== undefined &&\n this._startingChangesetIndices !== undefined,\n \"updateSynchronizationVersion was called without change history\"\n );\n\n const jsonProps = this._targetScopeProvenanceProps.jsonProperties;\n\n Logger.logTrace(\n loggerCategory,\n `previous pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`\n );\n Logger.logTrace(\n loggerCategory,\n `previous pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`\n );\n\n const pendingSyncChangesetIndicesKey =\n \"pendingSyncChangesetIndices\" as const;\n const pendingReverseSyncChangesetIndicesKey =\n \"pendingReverseSyncChangesetIndices\" as const;\n\n // Determine which keys to clear and update based on the synchronization direction\n let syncChangesetsToClearKey;\n let syncChangesetsToUpdateKey;\n\n if (this.isReverseSynchronization) {\n syncChangesetsToClearKey = pendingReverseSyncChangesetIndicesKey;\n syncChangesetsToUpdateKey = pendingSyncChangesetIndicesKey;\n } else {\n syncChangesetsToClearKey = pendingSyncChangesetIndicesKey;\n syncChangesetsToUpdateKey = pendingReverseSyncChangesetIndicesKey;\n }\n\n // NOTE that as documented in [[processChanges]], this assumes that right after\n // transformation finalization, the work will be saved immediately, otherwise we've\n // just marked this changeset as a synchronization to ignore, and the user can add other\n // stuff to it which would break future synchronizations\n for (\n let i = this._startingChangesetIndices.target + 1;\n i <= this.targetDb.changeset.index + 1;\n i++\n )\n jsonProps[syncChangesetsToUpdateKey].push(i);\n // Only keep the changeset indices which are greater than the source, this means they haven't been processed yet.\n jsonProps[syncChangesetsToClearKey] = jsonProps[\n syncChangesetsToClearKey\n ].filter((csIndex) => {\n return csIndex > this._startingChangesetIndices!.source;\n });\n\n // if reverse sync then we may have received provenance changes which should be marked as sync changes\n if (this.isReverseSynchronization) {\n nodeAssert(\n this.sourceDb.changeset.index !== undefined,\n \"changeset didn't exist\"\n );\n for (\n let i = this._startingChangesetIndices.source + 1;\n i <= this.sourceDb.changeset.index + 1;\n i++\n )\n jsonProps.pendingReverseSyncChangesetIndices.push(i);\n }\n\n Logger.logTrace(\n loggerCategory,\n `new pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`\n );\n Logger.logTrace(\n loggerCategory,\n `new pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`\n );\n }\n\n this.provenanceDb.elements.updateAspect({\n ...this._targetScopeProvenanceProps,\n jsonProperties: JSON.stringify(\n this._targetScopeProvenanceProps.jsonProperties\n ) as any,\n });\n this.clearCachedSynchronizationVersion();\n }\n\n // FIXME<MIKE>: is this necessary when manually using low level transform APIs? (document if so)\n private finalizeTransformation() {\n this.importer.finalize();\n this.updateSynchronizationVersion({\n initializeReverseSyncVersion: this._isProvenanceInitTransform,\n });\n\n // TODO: ignore if we remove change cache usage\n if (!this._options.noDetachChangeCache) {\n if (ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))\n ChangeSummaryManager.detachChangeCache(this.sourceDb);\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 [[process]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processRelationships(\n baseRelClassFullName: string\n ): 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(\n _sourceRelationship: Relationship\n ): boolean {\n return true;\n }\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 sourceFedGuid = queryElemFedGuid(\n this.sourceDb,\n sourceRelationship.sourceId\n );\n const targetFedGuid = queryElemFedGuid(\n this.sourceDb,\n sourceRelationship.targetId\n );\n const targetRelationshipProps =\n this.onTransformRelationship(sourceRelationship);\n const targetRelationshipInstanceId = this.importer.importRelationship(\n targetRelationshipProps\n );\n\n if (\n !this._options.noProvenance &&\n Id64.isValid(targetRelationshipInstanceId)\n ) {\n let provenance:\n | Parameters<typeof this.markLastProvenance>[0]\n | undefined = !this._options.forceExternalSourceAspectProvenance\n ? sourceFedGuid && targetFedGuid && `${sourceFedGuid}/${targetFedGuid}`\n : undefined;\n if (!provenance) {\n const aspectProps = this.initRelationshipProvenance(\n sourceRelationship,\n targetRelationshipInstanceId\n );\n const foundEsaProps = IModelTransformer.queryScopeExternalSourceAspect(\n this.provenanceDb,\n aspectProps\n );\n // onExportRelationship doesn't need to call updateAspect if esaProps were found, because relationship provenance doesn't have the same concept of a version as element provenance (which uses last mod time on the elements).\n if (undefined === foundEsaProps) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n }\n provenance = aspectProps as MarkRequired<\n ExternalSourceAspectProps,\n \"id\"\n >;\n }\n this.markLastProvenance(provenance, { 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 nodeAssert(\n this._deletedSourceRelationshipData,\n \"should be defined at initialization by now\"\n );\n\n const deletedRelData =\n this._deletedSourceRelationshipData.get(sourceRelInstanceId);\n if (!deletedRelData) {\n // this can occur if both the source and target deleted it\n Logger.logWarning(\n loggerCategory,\n \"tried to delete a relationship that wasn't in change data\"\n );\n return;\n }\n\n const id =\n deletedRelData.relId ??\n this.targetDb.relationships.tryGetInstance(deletedRelData.classFullName, {\n sourceId: deletedRelData.sourceIdInTarget,\n targetId: deletedRelData.targetIdInTarget,\n } as SourceAndTarget)?.id;\n if (id) {\n this.importer.deleteRelationship({\n id,\n classFullName: deletedRelData.classFullName,\n });\n }\n\n if (deletedRelData.provenanceAspectId) {\n try {\n this.provenanceDb.elements.deleteAspect(\n deletedRelData.provenanceAspectId\n );\n } catch (error: any) {\n // This aspect may no longer exist if it was deleted at some other point during the transformation. This is fine.\n if (error.errorNumber === IModelStatus.NotFound) return;\n throw error;\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 * @deprecated in 1.x. Don't use this anymore\n * @see [[process]] with [[IModelTransformOptions.argsForProcessChanges]] provided.\n * @note This method is called from [[process]] when [[IModelTransformOptions.argsForProcessChanges]] are undefined, 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.isReverseSynchronization) {\n throw new IModelError(\n IModelStatus.BadRequest,\n \"Cannot detect deletes when isReverseSynchronization=true\"\n );\n }\n const aspectDeleteIds: Id64String[] = [];\n const sql = `\n SELECT ECInstanceId, Identifier, JsonProperties\n FROM ${ExternalSourceAspect.classFullName} aspect\n WHERE aspect.Scope.Id=:scopeId\n AND aspect.Kind=:kind\n `;\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n await this.targetDb.withPreparedStatement(\n sql,\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n 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(\n statement.getValue(1).getString()\n );\n if (\n undefined ===\n this.sourceDb.relationships.tryGetInstanceProps(\n ElementRefersToElements.classFullName,\n sourceRelInstanceId\n )\n ) {\n // this function exists only to support some in-imodel transformations, which must\n // use the old (external source aspect) provenance method anyway so we don't need to support\n // new provenance\n const json: any = JSON.parse(statement.getValue(2).getString());\n const targetRelInstanceId =\n json.targetRelInstanceId ?? json.provenanceRelInstanceId;\n if (targetRelInstanceId) {\n this.importer.deleteRelationship({\n id: targetRelInstanceId,\n classFullName: ElementRefersToElements.classFullName,\n });\n }\n aspectDeleteIds.push(statement.getValue(0).getId());\n }\n await this._yieldManager.allowYield();\n }\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(\n sourceRelationship: Relationship\n ): RelationshipProps {\n const targetRelationshipProps: RelationshipProps =\n sourceRelationship.toJSON();\n targetRelationshipProps.sourceId = this.context.findTargetElementId(\n sourceRelationship.sourceId\n );\n targetRelationshipProps.targetId = this.context.findTargetElementId(\n sourceRelationship.targetId\n );\n // TODO: move to cloneRelationship in IModelCloneContext\n sourceRelationship.forEachProperty(\n (propertyName: string, propertyMetaData: PropertyMetaData) => {\n if (\n PrimitiveTypeCode.Long === propertyMetaData.primitiveType &&\n \"Id\" === propertyMetaData.extendedType\n ) {\n (targetRelationshipProps as any)[propertyName] =\n this.context.findTargetElementId(\n sourceRelationship.asAny[propertyName]\n );\n }\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(\n sourceAspect: ElementUniqueAspect\n ): void {\n const targetAspectProps = this.onTransformElementAspect(sourceAspect);\n if (!this.doAllReferencesExistInTarget(sourceAspect)) {\n this._partiallyCommittedAspectIds.add(sourceAspect.id);\n }\n const targetId = this.importer.importElementUniqueAspect(targetAspectProps);\n this.context.remapElementAspect(sourceAspect.id, targetId);\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(\n sourceAspects: ElementMultiAspect[]\n ): void {\n // Transform source ElementMultiAspects into target ElementAspectProps\n const targetAspectPropsArray = sourceAspects.map((srcA) =>\n this.onTransformElementAspect(srcA)\n );\n sourceAspects.forEach((a) => {\n if (!this.doAllReferencesExistInTarget(a)) {\n this._partiallyCommittedAspectIds.add(a.id);\n }\n });\n // const targetAspectsToImport = targetAspectPropsArray.filter((targetAspect, i) => hasEntityChanged(sourceAspects[i], targetAspect));\n const targetIds = this.importer.importElementMultiAspects(\n targetAspectPropsArray,\n (a) => {\n const isExternalSourceAspectFromTransformer =\n a instanceof ExternalSourceAspect &&\n a.scope?.id === this.targetScopeElementId;\n return (\n !this._options.includeSourceProvenance ||\n !isExternalSourceAspectFromTransformer\n );\n }\n );\n for (let i = 0; i < targetIds.length; ++i) {\n this.context.remapElementAspect(sourceAspects[i].id, targetIds[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 * @returns ElementAspectProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformElementAspect(\n sourceElementAspect: ElementAspect\n ): ElementAspectProps {\n const targetElementAspectProps =\n 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(\n KnownLocations.tmpdir,\n Guid.createValue()\n );\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(\n schemaKey: ECSchemaMetaData.SchemaKey\n ): boolean {\n const versionInTarget = this.targetDb.querySchemaVersion(schemaKey.name);\n if (versionInTarget === undefined) return true;\n return Semver.gt(\n `${schemaKey.version.read}.${schemaKey.version.write}.${schemaKey.version.minor}`,\n Schema.toSemverString(versionInTarget)\n );\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(\n schema: ECSchemaMetaData.Schema\n ): 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 // windows usually has a limit for the total path length of 260\n const windowsMaxPathLimit = 260;\n if (\n schemaFileName.length > systemMaxPathSegmentSize ||\n path.join(this._schemaExportDir, schemaFileName).length >=\n windowsMaxPathLimit\n ) {\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)}${\n this._longNamedSchemasMap.size\n }${ext}`;\n nodeAssert(\n schemaFileName.length <= systemMaxPathSegmentSize,\n \"Schema name was still long. This is a bug.\"\n );\n this._longNamedSchemasMap.set(schema.name, schemaFileName);\n }\n /* eslint-disable-next-line deprecation/deprecation */\n this.sourceDb.exportSchema({\n schemaName: schema.name,\n outputDirectory: this._schemaExportDir,\n outputFileName: schemaFileName,\n });\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) 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) return;\n const schemaFullPaths = exportedSchemaFiles.map((s) =>\n path.join(this._schemaExportDir, s)\n );\n const maybeLongNameResolvingSchemaCtx =\n this._longNamedSchemasMap.size > 0\n ? this._makeLongNameResolvingSchemaCtx()\n : undefined;\n return await this.targetDb.importSchemas(schemaFullPaths, {\n ecSchemaXmlContext: maybeLongNameResolvingSchemaCtx,\n });\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 [[process]], 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(\n font: FontProps,\n _isUpdate: boolean | undefined\n ): 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 [[process]], 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 [[process]], 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 {\n return true;\n }\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(\n sourceSubjectId: Id64String,\n targetSubjectId: Id64String\n ): 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 this.completePartiallyCommittedElements();\n this.completePartiallyCommittedAspects();\n }\n\n /** state to prevent reinitialization, @see [[initialize]] */\n private _initialized = false;\n private _sourceChangeDataState: ChangeDataState = \"uninited\";\n /** length === 0 when _changeDataState = \"no-change\", length > 0 means \"has-changes\", otherwise undefined */\n private _csFileProps?: ChangesetFileProps[] = undefined;\n\n /**\n * Initialize prerequisites of processing, you must initialize with an [[InitOptions]] if you\n * are intending to process changes. Callers may wish to explicitly call initialize if they need to execute code after initialize but before [[process]] is called.\n * @note Called by all `process*` functions implicitly.\n * Overriders must call `super.initialize()` first\n */\n public async initialize(): Promise<void> {\n if (this._initialized) return;\n\n this.initScopeProvenance();\n\n await this._tryInitChangesetData(this._options.argsForProcessChanges);\n await this.context.initialize();\n\n // need exporter initialized to do remapdeletedsourceentities.\n await this.exporter.initialize(\n this.getExportInitOpts(this._options.argsForProcessChanges ?? {})\n );\n\n // Exporter must be initialized prior to processing changesets in order to properly handle entity recreations (an entity delete followed by an insert of that same entity).\n await this.processChangesets();\n\n this._initialized = true;\n }\n\n /**\n * Reads all the changeset files in the private member of the transformer: _csFileProps\n * and finds the corresponding target entity for any deleted source entities and remaps the sourceId to the targetId.\n * This function returns early if csFileProps is undefined or is of length 0.\n * @returns void\n */\n private async processChangesets(): Promise<void> {\n this.forEachTrackedElement(\n (sourceElementId: Id64String, targetElementId: Id64String) => {\n this.context.remapElement(sourceElementId, targetElementId);\n }\n );\n if (this.exporter.sourceDbChanges)\n await this.addCustomChanges(this.exporter.sourceDbChanges);\n\n if (this._csFileProps === undefined || this._csFileProps.length === 0) {\n if (\n this.exporter.sourceDbChanges === undefined ||\n !this.exporter.sourceDbChanges.hasChanges\n )\n return;\n // our sourcedbChanges aren't empty (probably due to someone adding custom changes), change our sourceChangeDataState to has-changes\n if (this._sourceChangeDataState === \"no-changes\")\n this._sourceChangeDataState = \"has-changes\";\n }\n\n const relationshipECClassIdsToSkip = new Set<string>();\n for await (const row of this.sourceDb.createQueryReader(\n \"SELECT ECInstanceId FROM ECDbMeta.ECClassDef where ECInstanceId IS (BisCore.ElementDrivesElement)\"\n )) {\n relationshipECClassIdsToSkip.add(row.ECInstanceId);\n }\n const relationshipECClassIds = new Set<string>();\n for await (const row of this.sourceDb.createQueryReader(\n \"SELECT ECInstanceId FROM ECDbMeta.ECClassDef where ECInstanceId IS (BisCore.ElementRefersToElements)\"\n )) {\n relationshipECClassIds.add(row.ECInstanceId);\n }\n\n // For later use when processing deletes.\n const alreadyImportedElementInserts = new Set<Id64String>();\n const alreadyImportedModelInserts = new Set<Id64String>();\n this.exporter.sourceDbChanges?.element.insertIds.forEach(\n (insertedSourceElementId) => {\n const targetElementId = this.context.findTargetElementId(\n insertedSourceElementId\n );\n if (Id64.isValid(targetElementId))\n alreadyImportedElementInserts.add(targetElementId);\n }\n );\n this.exporter.sourceDbChanges?.model.insertIds.forEach(\n (insertedSourceModelId) => {\n const targetModelId = this.context.findTargetElementId(\n insertedSourceModelId\n );\n if (Id64.isValid(targetModelId))\n alreadyImportedModelInserts.add(targetModelId);\n }\n );\n\n this._deletedSourceRelationshipData = new Map();\n\n for (const csFile of this._csFileProps ?? []) {\n const csReader = SqliteChangesetReader.openFile({\n fileName: csFile.pathname,\n db: this.sourceDb,\n disableSchemaCheck: true,\n });\n const csAdaptor = new ChangesetECAdaptor(csReader);\n const ecChangeUnifier = new PartialECChangeUnifier();\n while (csAdaptor.step()) {\n ecChangeUnifier.appendFrom(csAdaptor);\n }\n const changes: ChangedECInstance[] = [...ecChangeUnifier.instances];\n\n /** a map of element ids to this transformation scope's ESA data for that element, in case the ESA is deleted in the target */\n const elemIdToScopeEsa = new Map<Id64String, ChangedECInstance>();\n for (const change of changes) {\n if (\n change.ECClassId !== undefined &&\n relationshipECClassIdsToSkip.has(change.ECClassId)\n )\n continue;\n const changeType: SqliteChangeOp | undefined = change.$meta?.op;\n if (\n changeType === \"Deleted\" &&\n change?.$meta?.classFullName === ExternalSourceAspect.classFullName &&\n change.Scope.Id === this.targetScopeElementId &&\n change.Kind === ExternalSourceAspect.Kind.Element\n ) {\n elemIdToScopeEsa.set(change.Element.Id, change);\n }\n }\n // Loop to process deletes.\n for (const change of changes) {\n const changeType: SqliteChangeOp | undefined = change.$meta?.op;\n const ecClassId = change.ECClassId ?? change.$meta?.fallbackClassId;\n if (ecClassId === undefined)\n throw new Error(\n `ECClassId was not found for id: ${change.ECInstanceId}! Table is : ${change?.$meta?.tables}`\n );\n if (changeType === undefined)\n throw new Error(\n `ChangeType was undefined for id: ${change.ECInstanceId}.`\n );\n if (\n changeType !== \"Deleted\" ||\n relationshipECClassIdsToSkip.has(ecClassId)\n )\n continue;\n await this.processDeletedOp(\n change,\n elemIdToScopeEsa,\n relationshipECClassIds.has(ecClassId ?? \"\"),\n alreadyImportedElementInserts,\n alreadyImportedModelInserts\n );\n }\n\n csReader.close();\n }\n return;\n }\n\n /**\n * This will be called when transformer is called with [[IModelTransformOptions.argsForProcessChanges]] to process changes.\n * It will be executed after changes in changesets are populated into `sourceDbChanges` and before data processing begins.\n * Remap table between the source and target iModels will be built at that time, meaning that functions like [[IModelTransformer.context.findTargetElementId]] will return meaningful results.\n * This function should be used to modify the `sourceDbChanges`, if necessary, using `add custom change` methods in [[ChangedInstanceIds]], such as [[ChangedInstanceIds.addCustomElementChange]], [[ChangedInstanceIds.addCustomModelChange]] and other.\n * @param sourceDbChanges the ChangedInstanceIds already populated by the exporter with the changes in source changesets, if any, passed to the transformer.\n * @note Its expected that this function be overridden by a subclass of transformer if it needs to modify sourceDbChanges.\n */\n protected async addCustomChanges(\n _sourceDbChanges: ChangedInstanceIds\n ): Promise<void> {}\n\n /**\n * Helper function for processChangesets. Remaps the id of element deleted found in the 'change' to an element in the targetDb.\n * @param change the change to process, must be of changeType \"Deleted\"\n * @param mapOfDeletedElemIdToScopeEsas a map of elementIds to changedECInstances (which are ESAs). the elementId is not the id of the esa itself, but the elementid that the esa was stored on before the esa's deletion.\n * All ESAs in this map are part of the transformer's scope / ESA data and are tracked in case the ESA is deleted in the target.\n * @param isRelationship is relationship or not\n * @param alreadyImportedElementInserts used to handle entity recreation and not delete already handled element inserts.\n * @param alreadyImportedModelInserts used to handle entity recreation and not delete already handled model inserts.\n * @returns void\n */\n private async processDeletedOp(\n change: ChangedECInstance,\n mapOfDeletedElemIdToScopeEsas: Map<string, ChangedECInstance>,\n isRelationship: boolean,\n alreadyImportedElementInserts: Set<Id64String>,\n alreadyImportedModelInserts: Set<Id64String>\n ) {\n // we need a connected iModel with changes to remap elements with deletions\n const notConnectedModel = this.sourceDb.iTwinId === undefined;\n const noChanges =\n this.synchronizationVersion.index === this.sourceDb.changeset.index &&\n (this.exporter.sourceDbChanges === undefined ||\n !this.exporter.sourceDbChanges.hasChanges);\n if (notConnectedModel || noChanges) return;\n\n /**\n * if our ChangedECInstance is in the provenanceDb, then we can use the ids we find in the ChangedECInstance to query for ESAs.\n * This is because the ESAs are stored on an element Id thats present in the provenanceDb.\n */\n const changeDataInProvenanceDb = this.sourceDb === this.provenanceDb;\n\n const getTargetIdFromSourceId = async (id: Id64String) => {\n let identifierValue: string | undefined;\n let element;\n if (isRelationship) {\n element = this.sourceDb.elements.tryGetElement(id);\n }\n const fedGuid = isRelationship\n ? element?.federationGuid\n : change.FederationGuid;\n if (changeDataInProvenanceDb) {\n // TODO: clarify what happens if there are multiple (e.g. elements were merged)\n for await (const row of this.sourceDb.createQueryReader(\n \"SELECT esa.Identifier FROM bis.ExternalSourceAspect esa WHERE Scope.Id=:scopeId AND Kind=:kind AND Element.Id=:relatedElementId LIMIT 1\",\n QueryBinder.from([\n this.targetScopeElementId,\n ExternalSourceAspect.Kind.Element,\n id,\n ])\n )) {\n identifierValue = row.Identifier;\n }\n identifierValue =\n identifierValue ?? mapOfDeletedElemIdToScopeEsas.get(id)?.Identifier;\n }\n\n // Check for targetId by an esa first\n if (changeDataInProvenanceDb && identifierValue) {\n const targetId = identifierValue;\n return targetId;\n }\n\n // Check for targetId using sourceId's fedguid if we didn't find an esa.\n if (fedGuid) {\n const targetId = this._queryElemIdByFedGuid(this.targetDb, fedGuid);\n return targetId;\n }\n return undefined;\n };\n\n const changedInstanceId = change.ECInstanceId;\n if (isRelationship) {\n const sourceIdOfRelationshipInSource = change.SourceECInstanceId;\n const targetIdOfRelationshipInSource = change.TargetECInstanceId;\n const classFullName = change.$meta?.classFullName;\n\n const sourceIdOfRelationshipInTarget = await getTargetIdFromSourceId(\n sourceIdOfRelationshipInSource\n );\n const targetIdOfRelationshipInTarget = await getTargetIdFromSourceId(\n targetIdOfRelationshipInSource\n );\n if (sourceIdOfRelationshipInTarget && targetIdOfRelationshipInTarget) {\n this._deletedSourceRelationshipData!.set(changedInstanceId, {\n classFullName: classFullName ?? \"\",\n sourceIdInTarget: sourceIdOfRelationshipInTarget,\n targetIdInTarget: targetIdOfRelationshipInTarget,\n });\n } else if (this.sourceDb === this.provenanceSourceDb) {\n const relProvenance = this._queryProvenanceForRelationship(\n changedInstanceId,\n {\n classFullName: classFullName ?? \"\",\n sourceId: sourceIdOfRelationshipInSource,\n targetId: targetIdOfRelationshipInSource,\n }\n );\n if (relProvenance && relProvenance.relationshipId)\n this._deletedSourceRelationshipData!.set(changedInstanceId, {\n classFullName: classFullName ?? \"\",\n relId: relProvenance.relationshipId,\n provenanceAspectId: relProvenance.aspectId,\n });\n }\n } else {\n let targetId = await getTargetIdFromSourceId(changedInstanceId);\n if (targetId === undefined && this.sourceDb === this.provenanceSourceDb) {\n targetId = this._queryProvenanceForElement(changedInstanceId);\n }\n // since we are processing one changeset at a time, we can see local source deletes\n // of entities that were never synced and can be safely ignored\n const deletionNotInTarget = !targetId;\n if (deletionNotInTarget) return;\n this.context.remapElement(changedInstanceId, targetId!);\n // If an entity insert and an entity delete both point to the same entity in target iModel, that means that entity was recreated.\n // In such case an entity update will be triggered and we no longer need to delete the entity.\n if (alreadyImportedElementInserts.has(targetId!)) {\n this.exporter.sourceDbChanges?.element.deleteIds.delete(\n changedInstanceId\n );\n }\n if (alreadyImportedModelInserts.has(targetId!)) {\n this.exporter.sourceDbChanges?.model.deleteIds.delete(\n changedInstanceId\n );\n }\n }\n }\n\n private async _tryInitChangesetData(args?: ProcessChangesOptions) {\n if (\n !args ||\n this.sourceDb.iTwinId === undefined ||\n this.sourceDb.changeset.index === undefined\n ) {\n this._sourceChangeDataState = \"unconnected\";\n return;\n }\n\n const noChanges =\n this.synchronizationVersion.index === this.sourceDb.changeset.index;\n if (noChanges) {\n this._sourceChangeDataState = \"no-changes\";\n this._csFileProps = [];\n return;\n }\n const startChangeset =\n \"startChangeset\" in args ? args.startChangeset : undefined;\n\n // NOTE: that we do NOT download the changesummary for the last transformed version, we want\n // to ignore those already processed changes\n const startChangesetIndexOrId =\n startChangeset?.index ??\n startChangeset?.id ??\n this.synchronizationVersion.index + 1;\n const endChangesetId = this.sourceDb.changeset.id;\n\n const [startChangesetIndex, endChangesetIndex] = await Promise.all(\n [startChangesetIndexOrId, endChangesetId].map(async (indexOrId) =>\n typeof indexOrId === \"number\"\n ? indexOrId\n : BriefcaseManager\n .queryChangeset({\n iModelId: this.sourceDb.iModelId,\n // eslint-disable-next-line deprecation/deprecation\n changeset: { id: indexOrId },\n })\n .then((changeset) => changeset.index)\n )\n );\n\n const missingChangesets =\n startChangesetIndex > this.synchronizationVersion.index + 1;\n if (\n !this._options.argsForProcessChanges\n ?.ignoreMissingChangesetsInSynchronizations &&\n startChangesetIndex !== this.synchronizationVersion.index + 1 &&\n this.synchronizationVersion.index !== -1\n ) {\n throw Error(\n `synchronization is ${missingChangesets ? \"missing changesets\" : \"\"},` +\n \" startChangesetId should be\" +\n \" exactly the first changeset *after* the previous synchronization to not miss data.\" +\n ` You specified '${startChangesetIndexOrId}' which is changeset #${startChangesetIndex}` +\n ` but the previous synchronization for this targetScopeElement was '${this.synchronizationVersion.id}'` +\n ` which is changeset #${this.synchronizationVersion.index}. The transformer expected` +\n ` #${this.synchronizationVersion.index + 1}.`\n );\n }\n\n nodeAssert(\n this._targetScopeProvenanceProps,\n \"_targetScopeProvenanceProps should be set by now\"\n );\n\n const changesetsToSkip = this.isReverseSynchronization\n ? this._targetScopeProvenanceProps.jsonProperties\n .pendingReverseSyncChangesetIndices\n : this._targetScopeProvenanceProps.jsonProperties\n .pendingSyncChangesetIndices;\n\n Logger.logTrace(loggerCategory, `changesets to skip: ${changesetsToSkip}`);\n this._changesetRanges = rangesFromRangeAndSkipped(\n startChangesetIndex,\n endChangesetIndex,\n changesetsToSkip\n );\n Logger.logTrace(loggerCategory, `ranges: ${this._changesetRanges}`);\n\n const csFileProps: ChangesetFileProps[] = [];\n for (const [first, end] of this._changesetRanges) {\n // TODO: should the first changeset in a reverse sync really be included even though its 'initialized branch provenance'? The answer is no, its a bug that needs to be fixed.\n const fileProps = await BriefcaseManager.downloadChangesets({\n iModelId: this.sourceDb.iModelId,\n targetDir: BriefcaseManager.getChangeSetsPath(this.sourceDb.iModelId),\n range: { first, end },\n });\n csFileProps.push(...fileProps);\n }\n this._csFileProps = csFileProps;\n\n /** Theres a possibility that our csFileProps length is still 0 here, since we skip cs indices found in the pendingSync and pendingReverseSync indices arrays. */\n this._sourceChangeDataState =\n this._csFileProps.length === 0 ? \"no-changes\" : \"has-changes\";\n }\n\n /**\n * The behavior of process is influenced by [[IModelTransformOptions.argsForProcessChanges]] being defined or not defined during construction passed of the IModelTransformer.\n * @section When argsForProcessChanges are defined:\n *\n * Export changes from the source iModel and import the transformed entities into the target iModel.\n * Inserts, updates, and deletes are determined by inspecting the changeset(s).\n *\n * Notes:\n * - the transformer assumes that you saveChanges after processing changes. You should not modify the iModel after processChanges until saveChanges,\n * failure to do so may result in corrupted\n * data loss in future branch operations\n * - if no startChangesetId or startChangeset option is provided as part of the ProcessChangesOptions, the next unsynchronized changeset\n * will automatically be determined and used\n * - To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n *\n * @section When argsForProcessChanges are undefined:\n *\n * Export everything from the source iModel and import the transformed entities into the target iModel.\n *\n * Notes:\n * - [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.\n *\n */\n public async process(): Promise<void> {\n await this.initialize();\n\n this.logSettings();\n\n return this._options.argsForProcessChanges !== undefined\n ? this.processChanges(this._options.argsForProcessChanges)\n : this.processAll();\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 private async processAll(): Promise<void> {\n await this.exporter.exportCodeSpecs();\n await this.exporter.exportFonts();\n\n if (this._options.skipPropagateChangesToRootElements) {\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(\n IModel.repositoryModelId,\n Element.classFullName,\n true\n ); // after the Subject hierarchy, process the other elements of the RepositoryModel\n await this.exporter.exportSubModels(IModel.repositoryModelId); // start below the RepositoryModel\n } else {\n await this.exporter.exportModel(IModel.repositoryModelId);\n }\n this.completePartiallyCommittedElements();\n await this.exporter[\"exportAllAspects\"](); // eslint-disable-line @typescript-eslint/dot-notation\n this.completePartiallyCommittedAspects();\n await this.exporter.exportRelationships(\n ElementRefersToElements.classFullName\n );\n if (\n this._options.forceExternalSourceAspectProvenance &&\n this.shouldDetectDeletes()\n ) {\n // eslint-disable-next-line deprecation/deprecation\n await this.detectElementDeletes();\n // eslint-disable-next-line deprecation/deprecation\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 /** previous provenance, either a federation guid, a `${sourceFedGuid}/${targetFedGuid}` pair, or required aspect props */\n private _lastProvenanceEntityInfo: string | LastProvenanceEntityInfo =\n nullLastProvenanceEntityInfo;\n\n private markLastProvenance(\n sourceAspect: string | MarkRequired<ExternalSourceAspectProps, \"id\">,\n { isRelationship = false }\n ) {\n this._lastProvenanceEntityInfo =\n typeof sourceAspect === \"string\"\n ? sourceAspect\n : {\n entityId: sourceAspect.element.id,\n aspectId: sourceAspect.id,\n aspectVersion: sourceAspect.version ?? \"\",\n aspectKind: isRelationship\n ? ExternalSourceAspect.Kind.Relationship\n : ExternalSourceAspect.Kind.Element,\n };\n }\n\n /** Export changes from the source iModel and import the transformed entities into the target iModel.\n * Inserts, updates, and deletes are determined by inspecting the changeset(s).\n * @note the transformer assumes that you saveChanges after processing changes. You should not\n * modify the iModel after processChanges until saveChanges, failure to do so may result in corrupted\n * data loss in future branch operations\n * @note if no startChangesetId or startChangeset option is provided as part of the ProcessChangesOptions, the next unsynchronized changeset\n * will automatically be determined and used\n * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n */\n private async processChanges(options: ProcessChangesOptions): Promise<void> {\n // must wait for initialization of synchronization provenance data\n await this.exporter.exportChanges(this.getExportInitOpts(options));\n this.completePartiallyCommittedElements();\n this.completePartiallyCommittedAspects();\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n\n const defaultSaveTargetChanges = () => {\n this.targetDb.saveChanges();\n };\n\n await (options.saveTargetChanges ?? defaultSaveTargetChanges)(this);\n }\n\n /** Changeset data must be initialized in order to build correct changeOptions.\n * Call [[IModelTransformer.initialize]] for initialization of synchronization provenance data\n */\n private getExportInitOpts(opts: ExportChangesOptions): ExporterInitOptions {\n if (!this._options.argsForProcessChanges) return {};\n const startChangeset =\n \"startChangeset\" in opts ? opts.startChangeset : undefined;\n return {\n skipPropagateChangesToRootElements:\n this._options.skipPropagateChangesToRootElements,\n ...(this._csFileProps\n ? { csFileProps: this._csFileProps }\n : this._changesetRanges\n ? { changesetRanges: this._changesetRanges }\n : startChangeset\n ? { startChangeset }\n : {\n startChangeset: {\n index: this.synchronizationVersion.index + 1,\n },\n }),\n };\n }\n\n /** Combine an array of source elements into a single target element.\n * All source and target elements must be created before calling this method.\n * The \"combine\" operation is a remap and no properties from the source elements will be exported into the target\n * and provenance will be explicitly tracked by ExternalSourceAspects\n */\n public combineElements(\n sourceElementIds: Id64Array,\n targetElementId: Id64String\n ) {\n for (const elementId of sourceElementIds) {\n this.context.remapElement(elementId, targetElementId);\n this._elementsWithExplicitlyTrackedProvenance.add(elementId);\n }\n }\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(\n sourceTemplateModelId: Id64String,\n targetModelId: Id64String,\n placement: Placement3d\n ): Promise<Map<Id64String, Id64String>> {\n await this.initialize();\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(\n placement.origin,\n placement.angles.toMatrix3d()\n );\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(\n sourceTemplateModelId: Id64String,\n targetModelId: Id64String,\n placement: Placement2d\n ): Promise<Map<Id64String, Id64String>> {\n await this.initialize();\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(\n Point3d.createFrom(placement.origin),\n placement.rotation\n );\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 const referenceIds = sourceElement.getReferenceIds();\n referenceIds.forEach((referenceId) => {\n // TODO: consider going through all definition elements at once and remapping them to themselves\n if (\n !EntityReferences.isValid(this.context.findTargetEntityId(referenceId))\n ) {\n if (this.context.isBetweenIModels) {\n throw new IModelError(\n IModelStatus.BadRequest,\n `Remapping for source dependency ${referenceId} not found for target iModel`\n );\n } else {\n const definitionElement =\n this.sourceDb.elements.tryGetElement<DefinitionElement>(\n referenceId,\n DefinitionElement\n );\n if (\n definitionElement &&\n !(definitionElement instanceof RecipeDefinitionElement)\n ) {\n this.context.remapElement(referenceId, referenceId); // when in the same iModel, can use existing DefinitionElements without remapping\n } else {\n throw new IModelError(\n IModelStatus.BadRequest,\n `Remapping for dependency ${referenceId} not found`\n );\n }\n }\n }\n });\n\n const targetElementProps: ElementProps = super.onTransformElement(\n sourceElement\n );\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 GeometricElement) {\n const is3d = sourceElement instanceof GeometricElement3d;\n const placementClass = is3d ? Placement3d : Placement2d;\n const placement = placementClass.fromJSON(\n (targetElementProps as GeometricElementProps).placement as any\n );\n if (placement.isValid) {\n nodeAssert(this._transform3d);\n placement.multiplyTransform(this._transform3d);\n (targetElementProps as GeometricElementProps).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\nfunction queryElemFedGuid(db: IModelDb, elemId: Id64String) {\n // eslint-disable-next-line @itwin/no-internal, deprecation/deprecation\n return db.withPreparedStatement(\n `\n SELECT FederationGuid\n FROM bis.Element\n WHERE ECInstanceId=?\n `,\n (stmt) => {\n stmt.bindId(1, elemId);\n assert(stmt.step() === DbResult.BE_SQLITE_ROW);\n const result = stmt.getValue(0).getGuid();\n assert(stmt.step() === DbResult.BE_SQLITE_DONE);\n return result;\n }\n );\n}\n"]}
1
+ {"version":3,"file":"IModelTransformer.js","sourceRoot":"","sources":["../../src/IModelTransformer.ts"],"names":[],"mappings":";;;AAAA;;;gGAGgG;AAChG;;GAEG;AACH,6BAA6B;AAC7B,iCAAiC;AACjC,qCAAqC;AACrC,sDAa6B;AAE7B,wDAO8B;AAC9B,sDA0C6B;AAC7B,oDAyB4B;AAC5B,qDAO0B;AAC1B,qDAA2E;AAC3E,2EAAwE;AACxE,6DAA0D;AAC1D,mDAAgD;AAChD,iCAAmD;AAEnD,MAAM,cAAc,GAAW,qD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AI,aAAa,YAAY,+BAAgB,EAAE,CAAC;YAC9C,MAAM,IAAI,GAAG,aAAa,YAAY,iCAAkB,CAAC;YACzD,MAAM,cAAc,GAAG,IAAI,CAAC,CAAC,CAAC,yBAAW,CAAC,CAAC,CAAC,yBAAW,CAAC;YACxD,MAAM,SAAS,GAAG,cAAc,CAAC,QAAQ,CACtC,kBAA4C,CAAC,SAAgB,CAC/D,CAAC;YACF,IAAI,SAAS,CAAC,OAAO,EAAE,CAAC;gBACtB,UAAU,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;gBAC9B,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;gBAC9C,kBAA4C,CAAC,SAAS,GAAG,SAAS,CAAC;YACtE,CAAC;QACH,CAAC;QACD,IAAI,CAAC,sBAAsB,EAAE,GAAG,CAAC,aAAa,CAAC,EAAE,EAAE,mBAAI,CAAC,OAAO,CAAC,CAAC,CAAC,qGAAqG;QACvK,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF;AAjID,kDAiIC;AAED,SAAS,gBAAgB,CAAC,EAAY,EAAE,MAAkB;IACxD,gFAAgF;IAChF,OAAO,EAAE,CAAC,qBAAqB,CAC7B;;;;GAID,EACC,CAAC,IAAI,EAAE,EAAE;QACP,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACvB,IAAA,qBAAM,EAAC,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,aAAa,CAAC,CAAC;QAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;QAC1C,IAAA,qBAAM,EAAC,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,cAAc,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC,CACF,CAAC;AACJ,CAAC","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 assert,\n DbResult,\n Guid,\n GuidString,\n Id64,\n Id64Array,\n Id64Set,\n Id64String,\n IModelStatus,\n Logger,\n MarkRequired,\n YieldManager,\n} from \"@itwin/core-bentley\";\nimport * as ECSchemaMetaData from \"@itwin/ecschema-metadata\";\nimport {\n Angle,\n AxisIndex,\n Matrix3d,\n Point3d,\n Transform,\n Vector3d,\n} from \"@itwin/core-geometry\";\nimport {\n BriefcaseManager,\n ChangedECInstance,\n ChangesetECAdaptor,\n ChangeSummaryManager,\n ChannelRootAspect,\n ConcreteEntity,\n DefinitionElement,\n DefinitionModel,\n DefinitionPartition,\n ECSchemaXmlContext,\n ECSqlStatement,\n // eslint-disable-next-line @typescript-eslint/no-redeclare\n Element,\n ElementAspect,\n ElementMultiAspect,\n ElementOwnsExternalSourceAspects,\n ElementRefersToElements,\n ElementUniqueAspect,\n Entity,\n EntityReferences,\n ExternalSource,\n ExternalSourceAspect,\n ExternalSourceAttachment,\n FolderLink,\n GeometricElement,\n GeometricElement3d,\n IModelDb,\n IModelHost,\n IModelJsFs,\n InformationPartitionElement,\n KnownLocations,\n Model,\n PartialECChangeUnifier,\n RecipeDefinitionElement,\n Relationship,\n RelationshipProps,\n Schema,\n SqliteChangeOp,\n SqliteChangesetReader,\n Subject,\n SynchronizationConfigLink,\n} from \"@itwin/core-backend\";\nimport {\n ChangesetFileProps,\n ChangesetIndexAndId,\n Code,\n CodeProps,\n CodeSpec,\n ConcreteEntityTypes,\n ElementAspectProps,\n ElementProps,\n EntityReference,\n ExternalSourceAspectProps,\n FontProps,\n GeometricElement3dProps,\n GeometricElementProps,\n Helmert2DWithZOffset,\n IModel,\n IModelError,\n ModelProps,\n Placement2d,\n Placement3d,\n PrimitiveTypeCode,\n PropertyMetaData,\n QueryBinder,\n RelatedElement,\n SourceAndTarget,\n} from \"@itwin/core-common\";\nimport {\n ChangedInstanceIds,\n ExportChangesOptions,\n ExporterInitOptions,\n ExportSchemaResult,\n IModelExporter,\n IModelExportHandler,\n} from \"./IModelExporter\";\nimport { IModelImporter, OptimizeGeometryOptions } from \"./IModelImporter\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { IModelCloneContext } from \"./IModelCloneContext\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { rangesFromRangeAndSkipped } from \"./Algo\";\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 LastProvenanceEntityInfo = typeof nullLastProvenanceEntityInfo;\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 * It is always a good idea to define this, although particularly necessary in any multi-source scenario such as multiple branches that reverse synchronize\n * or physical consolidation.\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.process]] to work properly when [[IModelTransformOptions.argsForProcessChanges]] are provided.\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 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 */\n danglingReferencesBehavior?: \"reject\" | \"ignore\";\n\n /** If defined, options to be supplied to [[IModelImporter.optimizeGeometry]] by [[IModelTransformer.process]]\n * as a post-processing step to optimize the geometry in the iModel.\n * @beta\n */\n optimizeGeometry?: OptimizeGeometryOptions;\n\n /**\n * force the insertion of external source aspects to provide provenance, even if there are federation guids\n * in the source that we can use. This can make some operations (like transforming new elements or initializing forks)\n * much slower due to needing to insert aspects, but prevents requiring change information for future merges.\n * @default false\n */\n forceExternalSourceAspectProvenance?: boolean;\n\n /**\n * Do not detach the change cache that we build. Use this if you want to do multiple transformations to\n * the same iModels, to avoid the performance cost of reinitializing the change cache which can be\n * expensive. You should only use this if you know the cache will be reused.\n * @note You must detach the change cache yourself.\n * @default false\n */\n noDetachChangeCache?: boolean;\n\n /**\n * Do not error out if a scoping ESA @see ExternalSourceAspectProps is found without a version or jsonProperties defined on that scoping ESA.\n * If true, the version and jsonproperties will be properly set on the scoping ESA @see TargetScopeProvenanceJsonProps after the transformer is complete.\n * These properties not being defined are a sign that this branching relationship was created with an older version of the transformer, and setting this option to 'unsafe-migrate' is not without risk.\n * Depending on the state of the branching relationship at the time of using this option, some data may be lost.\n * @note This should only need to be set to 'unsafe-migrate' at most once for a branching relationship. For future transformations on the branching relationship, the @see TargetScopeProvenanceJsonProps will be present.\n * @default \"reject\"\n */\n branchRelationshipDataBehavior?: \"unsafe-migrate\" | \"reject\";\n\n /**\n * Skip propagating changes made to the root subject, dictionaryModel and IModelImporter._realityDataSourceLinkPartitionStaticId (0xe)\n * If it is set to false, changes to root elements are propagated, the root subject name gets changed and leads to the iModelDb.name property being updated in .initializeiModelDb\n * @default true\n */\n skipPropagateChangesToRootElements?: boolean;\n\n /**\n * Arguments to use for the processing of changes. The args being defined or not defined will influence the behavior of @see [[IModelTransformer.process]].\n * @default undefined\n */\n argsForProcessChanges?: ProcessChangesOptions;\n\n /**\n * A flag that determines if spatial elements from the source db should be transformed if:\n * source and target iModel GCS/CRS data is the same, but they have differing additional transforms\n * source and target iModel ECEF locations differ\n * @default false\n */\n tryAlignGeolocation?: boolean;\n}\n\n/**\n * Data type for persisting change version information within provenance Scope ExternalSourceAspect.\n * Additionally, forward synchronization version is stored in Scope aspect's 'version' field.\n * @beta\n */\nexport interface TargetScopeProvenanceJsonProps {\n /** An array of changeset indices to ignore when doing a reverse sync. This array gets appended to during a forward sync and cleared\n * during a reverse sync. Since a forward sync pushes a changeset to the branch db, the changeset pushed to the branch db\n * by the forward sync isn't considered part of the changes made on the branch db and therefore doesn't need to be synced back to master\n * during a forward sync.\n */\n pendingReverseSyncChangesetIndices: number[];\n /** An array of changeset indices to ignore when doing a forward sync. This array gets appended to during a reverse sync and cleared\n * during a forward sync. Since a reverse sync pushes a changeset to the master db, the changeset pushed to the master db\n * by the reverse sync isn't considered part of the changes made on the master db and therefore doesn't need to be synced back to the branch\n * during a forward sync.\n */\n pendingSyncChangesetIndices: number[];\n /** the latest changesetid/index reverse synced into master */\n reverseSyncVersion: string;\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 | RelatedElement | 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 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 [\n `Id64 container '${JSON.stringify(idContainer)}' is unsupported.`,\n \"Currently only singular Id64 strings or prop-like objects containing an 'id' property are supported.\",\n ].join(\"\\n\")\n );\n }\n return results;\n}\n\n/** Arguments you can pass to [[IModelTransformer.initialize]]\n * @beta\n */\nexport interface InitOptions {\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 used during [[IModelTransformer.process]] if provided in [[IModelTransformOptions.argsForProcessChanges]].\n * @beta\n */\nexport type ProcessChangesOptions = ExportChangesOptions & {\n /** how to call saveChanges on the target. Must call targetDb.saveChanges, should not edit the iModel */\n saveTargetChanges?: (transformer: IModelTransformer) => Promise<void>;\n /**\n * The forward sync 'version' to set on the scoping ESA @see ExternalSourceAspectProps upon startup, if the version property on the scoping ESA is undefined or empty string.\n * @note This option is not without risk! You must also set @see branchRelationshipDataBehavior to \"unsafe-migrate\".\n * @note This value is ignored if the version property on the scoping ESA is NOT undefined or empty string.\n * @default \"\"\n */\n unsafeFallbackSyncVersion?: string;\n /**\n * The reverse sync version to set on the scoping ESA @see TargetScopeProvenanceJsonProps upon startup, if the reverseSync property on the scoping ESA is undefined or empty string.\n * @note This option is not without risk! You must also set @see branchRelationshipDataBehavior to \"unsafe-migrate\".\n * @note This value is ignored if the reverseSyncVersion property on the scoping ESA is NOT undefined or empty string.\n * @default \"\"\n */\n unsafeFallbackReverseSyncVersion?: string;\n /**\n * Do not check that process (with [[IModelTransformOptions.argsForProcessChanges]] provided) is called from the next changeset index.\n * This is an unsafe option (e.g. it can cause data loss in future branch operations)\n * and you should not use it.\n * @default false\n */\n ignoreMissingChangesetsInSynchronizations?: boolean;\n};\n\ntype ChangeDataState =\n | \"uninited\"\n | \"has-changes\"\n | \"no-changes\"\n | \"unconnected\";\n\n/**\n * @beta\n */\nexport interface RelationshipPropsForDelete {\n id: Id64String;\n classFullName: string;\n}\n\ntype SyncType = \"not-sync\" | \"forward\" | \"reverse\";\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 transform to be applied to the placement of spatial elements\n * This transform should be applied when:\n * - source and target db have different ECEF locations\n * - source and target db have matching GCS/CRS data, but differing `geographicCoordinateSystem.additionalTransform.helmert2DWithZOffset`\n * @note for ECEF transforms, this can only be used when source and target are linearly located imodels\n * @note for non linearly located imodels, this transform will be a linear transform derived from Helmert Transforms from the src and target iModels.\n * @beta\n */\n private _linearSpatialTransform?: Transform;\n private _syncType?: SyncType;\n\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 /** a set of elements for which source provenance will be explicitly tracked by ExternalSourceAspects */\n protected _elementsWithExplicitlyTrackedProvenance = new Set<Id64String>();\n\n protected _partiallyCommittedElementIds: Id64Set = new Set<Id64String>();\n protected _partiallyCommittedAspectIds: Id64Set = new Set<Id64String>();\n\n /** the options that were used to initialize this transformer */\n private readonly _options: MarkRequired<\n IModelTransformOptions,\n \"targetScopeElementId\" | \"danglingReferencesBehavior\"\n >;\n\n /**\n * A private variable meant to be set by tests which have an outdated way of setting up transforms. In all synchronizations today we expect to find an ESA in the branch db which describes the master -> branch relationship.\n * The exception to this is the first transform aka the provenance initializing transform which requires that the master imodel and the branch imodel are identical at the time of provenance initialization.\n * A couple ofoutdated tests run their first transform providing a source and targetdb that are slightly different which is no longer supported. In order to not remove these tests which are still providing value\n * this private property on the IModelTransformer exists.\n */\n private _allowNoScopingESA = false;\n\n public static noEsaSyncDirectionErrorMessage =\n \"Couldn't find an external source aspect to determine sync direction. This often means that the master->branch relationship has not been established. Consider running the transformer with wasSourceIModelCopiedToTarget set to true.\";\n\n /**\n * Queries for an esa which matches the props in the provided aspectProps.\n * @param dbToQuery db to run the query on for scope external source\n * @param aspectProps aspectProps to search for @see ExternalSourceAspectProps\n */\n public static queryScopeExternalSourceAspect(\n dbToQuery: IModelDb,\n aspectProps: ExternalSourceAspectProps\n ):\n | {\n aspectId: Id64String;\n version?: string;\n /** stringified json */\n jsonProperties?: string;\n }\n | undefined {\n const sql = `\n SELECT ECInstanceId, Version, JsonProperties\n FROM ${ExternalSourceAspect.classFullName}\n WHERE Element.Id=:elementId\n AND Scope.Id=:scopeId\n AND Kind=:kind\n AND Identifier=:identifier\n LIMIT 1\n `;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return dbToQuery.withPreparedStatement(sql, (statement: ECSqlStatement) => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n if (aspectProps.scope === undefined) return undefined; // return 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 if (DbResult.BE_SQLITE_ROW !== statement.step()) return undefined;\n const aspectId = statement.getValue(0).getId();\n const versionValue = statement.getValue(1);\n const version = versionValue.isNull\n ? undefined\n : versionValue.getString();\n const jsonPropsValue = statement.getValue(2);\n const jsonProperties = jsonPropsValue.isNull\n ? undefined\n : jsonPropsValue.getString();\n return { aspectId, version, jsonProperties };\n });\n }\n\n /**\n * Determines the sync direction \"forward\" or \"reverse\" of a given sourceDb and targetDb by looking for the scoping ESA.\n * If the sourceDb's iModelId is found as the identifier of the expected scoping ESA in the targetDb, then it is a forward synchronization.\n * If the targetDb's iModelId is found as the identifier of the expected scoping ESA in the sourceDb, then it is a reverse synchronization.\n * @throws if no scoping ESA can be found in either the sourceDb or targetDb which describes a master branch relationship between the two databases.\n * @returns \"forward\" or \"reverse\"\n */\n public static determineSyncType(\n sourceDb: IModelDb,\n targetDb: IModelDb,\n /** @see [[IModelTransformOptions.targetScopeElementId]] */\n targetScopeElementId: Id64String\n ): \"forward\" | \"reverse\" {\n const aspectProps = {\n id: undefined as string | undefined,\n version: undefined as string | undefined,\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: targetScopeElementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: sourceDb.iModelId,\n kind: ExternalSourceAspect.Kind.Scope,\n jsonProperties: undefined as TargetScopeProvenanceJsonProps | undefined,\n };\n /** First check if the targetDb is the branch (branch is the @see provenanceDb) */\n const esaPropsFromTargetDb = this.queryScopeExternalSourceAspect(\n targetDb,\n aspectProps\n );\n if (esaPropsFromTargetDb !== undefined) {\n return \"forward\"; // we found an esa assuming targetDb is the provenanceDb/branch so this is a forward sync.\n }\n\n // Now check if the sourceDb is the branch\n aspectProps.identifier = targetDb.iModelId;\n const esaPropsFromSourceDb = this.queryScopeExternalSourceAspect(\n sourceDb,\n aspectProps\n );\n\n if (esaPropsFromSourceDb !== undefined) {\n return \"reverse\"; // we found an esa assuming sourceDb is the provenanceDb/branch so this is a reverse sync.\n }\n throw new Error(this.noEsaSyncDirectionErrorMessage);\n }\n\n private determineSyncType(): SyncType {\n if (this._isProvenanceInitTransform) {\n return \"forward\";\n }\n if (!this._options.argsForProcessChanges) {\n return \"not-sync\";\n }\n try {\n return IModelTransformer.determineSyncType(\n this.sourceDb,\n this.targetDb,\n this.targetScopeElementId\n );\n } catch (err) {\n if (\n err instanceof Error &&\n err.message === IModelTransformer.noEsaSyncDirectionErrorMessage &&\n this._allowNoScopingESA\n ) {\n return \"forward\";\n }\n throw err;\n }\n }\n\n public get isReverseSynchronization(): boolean {\n if (this._syncType === undefined) this._syncType = this.determineSyncType();\n return this._syncType === \"reverse\";\n }\n\n public get isForwardSynchronization(): boolean {\n if (this._syncType === undefined) this._syncType = this.determineSyncType();\n return this._syncType === \"forward\";\n }\n\n private _changesetRanges: [number, number][] | undefined = undefined;\n\n /**\n * Set if the transformer is being used to perform the provenance initialization step of a fork initialization.\n * In general don't use the transformer for that, prefer [[BranchProvenanceInitializer.initializeBranchProvenance]]\n */\n private _isProvenanceInitTransform?: boolean;\n\n /** The element classes that are considered to define provenance in the iModel */\n public static get provenanceElementClasses(): (typeof Entity)[] {\n return [\n FolderLink,\n SynchronizationConfigLink,\n ExternalSource,\n ExternalSourceAttachment,\n ];\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 /** 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(\n source: IModelDb | IModelExporter,\n target: IModelDb | IModelImporter,\n options?: IModelTransformOptions\n ) {\n super();\n // initialize IModelTransformOptions\n this._options = {\n ...options,\n // non-falsy defaults\n cloneUsingBinaryGeometry: options?.cloneUsingBinaryGeometry ?? true,\n targetScopeElementId:\n options?.targetScopeElementId ?? IModel.rootSubjectId,\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n danglingReferencesBehavior:\n options?.danglingReferencesBehavior ?? \"reject\",\n branchRelationshipDataBehavior:\n options?.branchRelationshipDataBehavior ?? \"reject\",\n skipPropagateChangesToRootElements:\n options?.skipPropagateChangesToRootElements ?? true,\n tryAlignGeolocation: options?.tryAlignGeolocation ?? false,\n };\n // check if authorization client is defined\n if (IModelHost.authorizationClient === undefined) {\n Logger.logWarning(\n loggerCategory,\n \"Authorization client is not set in IModelHost. If the transformer needs an accessToken, then it will fail.\"\n );\n }\n this._isProvenanceInitTransform = this._options\n .wasSourceIModelCopiedToTarget\n ? true\n : 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) {\n // clone provenance from the source iModel into the target iModel?\n IModelTransformer.provenanceElementClasses.forEach((cls) =>\n this.exporter.excludeElementClass(cls.classFullName)\n );\n IModelTransformer.provenanceElementAspectClasses.forEach((cls) =>\n this.exporter.excludeElementAspectClass(cls.classFullName)\n );\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, {\n preserveElementIdsForFiltering:\n this._options.preserveElementIdsForFiltering,\n skipPropagateChangesToRootElements:\n this._options.skipPropagateChangesToRootElements,\n });\n } else {\n this.importer = target;\n this.validateSharedOptionsMatch();\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 if (this.sourceDb.isBriefcase && this.targetDb.isBriefcase) {\n nodeAssert(\n this.sourceDb.changeset.index !== undefined &&\n this.targetDb.changeset.index !== undefined,\n \"database has no changeset index\"\n );\n this._startingChangesetIndices = {\n target: this.targetDb.changeset.index,\n source: this.sourceDb.changeset.index,\n };\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 = \"exact\";\n (this.targetDb as any).codeValueBehavior = \"exact\";\n }\n /* eslint-enable @itwin/no-internal */\n if (this._options.tryAlignGeolocation) {\n if (\n this.sourceDb.geographicCoordinateSystem ||\n this.targetDb.geographicCoordinateSystem\n ) {\n Logger.logTrace(\n loggerCategory,\n \"Aligning Additional transforms between imodels due to imodels containing GeographicCoordinateSystem data\"\n );\n this._linearSpatialTransform =\n this.calculateTransformFromHelmertTransforms();\n } else if (this.sourceDb.ecefLocation && this.targetDb.ecefLocation) {\n Logger.logTrace(\n loggerCategory,\n \"Aligning ECEF Location's between imodels due to imodels not containing GeographicCoordinateSystem data\"\n );\n this._linearSpatialTransform = this.calculateEcefTransform();\n } else\n Logger.logTrace(\n loggerCategory,\n \"No Geolcation data to align, both GCS and ECEF are undefined\"\n );\n }\n }\n\n /** validates that the importer set on the transformer has the same values for its shared options as the transformer.\n * @note This expects that the importer is already set on the transformer.\n */\n private validateSharedOptionsMatch() {\n if (\n Boolean(this._options.preserveElementIdsForFiltering) !==\n this.importer.options.preserveElementIdsForFiltering\n ) {\n const errMessage =\n \"A custom importer was passed as a target but its 'preserveElementIdsForFiltering' option is out of sync with the transformer's option.\";\n throw new Error(errMessage);\n }\n if (\n Boolean(this._options.skipPropagateChangesToRootElements) !==\n this.importer.options.skipPropagateChangesToRootElements\n ) {\n const errMessage =\n \"A custom importer was passed as a target but its 'skipPropagateChangesToRootElements' option is out of sync with the transformer's option.\";\n throw new Error(errMessage);\n }\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(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.visitElements=${this.exporter.visitElements}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.visitRelationships=${this.exporter.visitRelationships}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.wantGeometry=${this.exporter.wantGeometry}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.wantSystemSchemas=${this.exporter.wantSystemSchemas}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelExporter,\n `this.exporter.wantTemplateModels=${this.exporter.wantTemplateModels}`\n );\n Logger.logInfo(\n loggerCategory,\n `this.targetScopeElementId=${this.targetScopeElementId}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._noProvenance=${this._options.noProvenance}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._includeSourceProvenance=${this._options.includeSourceProvenance}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._cloneUsingBinaryGeometry=${this._options.cloneUsingBinaryGeometry}`\n );\n Logger.logInfo(\n loggerCategory,\n `this._wasSourceIModelCopiedToTarget=${this._options.wasSourceIModelCopiedToTarget}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelImporter,\n `this.importer.autoExtendProjectExtents=${JSON.stringify(\n this.importer.options.autoExtendProjectExtents\n )}`\n );\n Logger.logInfo(\n TransformerLoggerCategory.IModelImporter,\n `this.importer.simplifyElementGeometry=${this.importer.options.simplifyElementGeometry}`\n );\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.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.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 targetDb: IModelDb;\n // TODO: Consider making it optional and determining it through ESAs if not provided. This gives opportunity for people to determine it themselves using public static determineSyncType function.\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n }\n ): ExternalSourceAspectProps {\n const elementId = args.isReverseSynchronization\n ? sourceElementId\n : targetElementId;\n const version = args.isReverseSynchronization\n ? args.targetDb.elements.queryLastModifiedTime(targetElementId)\n : args.sourceDb.elements.queryLastModifiedTime(sourceElementId);\n const aspectIdentifier = args.isReverseSynchronization\n ? targetElementId\n : sourceElementId;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: elementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Element,\n version,\n };\n return aspectProps;\n }\n\n public static initRelationshipProvenanceOptions(\n sourceRelInstanceId: Id64String,\n targetRelInstanceId: Id64String,\n args: {\n sourceDb: IModelDb;\n targetDb: IModelDb;\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n forceOldRelationshipProvenanceMethod: boolean;\n }\n ): ExternalSourceAspectProps {\n const provenanceDb = args.isReverseSynchronization\n ? args.sourceDb\n : args.targetDb;\n const aspectIdentifier = args.isReverseSynchronization\n ? targetRelInstanceId\n : sourceRelInstanceId;\n const provenanceRelInstanceId = args.isReverseSynchronization\n ? sourceRelInstanceId\n : targetRelInstanceId;\n\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n const elementId = provenanceDb.withPreparedStatement(\n \"SELECT SourceECInstanceId FROM bis.ElementRefersToElements WHERE ECInstanceId=?\",\n (stmt) => {\n stmt.bindId(1, provenanceRelInstanceId);\n nodeAssert(stmt.step() === DbResult.BE_SQLITE_ROW);\n return stmt.getValue(0).getId();\n }\n );\n\n const jsonProperties = args.forceOldRelationshipProvenanceMethod\n ? { targetRelInstanceId }\n : { provenanceRelInstanceId };\n\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: elementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Relationship,\n jsonProperties: JSON.stringify(jsonProperties),\n };\n\n return aspectProps;\n }\n\n /**\n * Previously the transformer would insert provenance always pointing to the \"target\" relationship.\n * It should (and now by default does) instead insert provenance pointing to the provenanceSource\n * SEE: https://github.com/iTwin/imodel-transformer/issues/54\n * This exists only to facilitate testing that the transformer can handle the older, flawed method\n */\n private _forceOldRelationshipProvenanceMethod = false;\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n public initElementProvenance(\n sourceElementId: Id64String,\n targetElementId: Id64String\n ): ExternalSourceAspectProps {\n return IModelTransformer.initElementProvenanceOptions(\n sourceElementId,\n targetElementId,\n {\n isReverseSynchronization: this.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n sourceDb: this.sourceDb,\n targetDb: this.targetDb,\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 master iModel.\n * The ECInstanceId of the relationship in the branch iModel will be stored in the JsonProperties of the ExternalSourceAspect.\n */\n private initRelationshipProvenance(\n sourceRelationship: Relationship,\n targetRelInstanceId: Id64String\n ): ExternalSourceAspectProps {\n return IModelTransformer.initRelationshipProvenanceOptions(\n sourceRelationship.id,\n targetRelInstanceId,\n {\n sourceDb: this.sourceDb,\n targetDb: this.targetDb,\n isReverseSynchronization: this.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n forceOldRelationshipProvenanceMethod:\n this._forceOldRelationshipProvenanceMethod,\n }\n );\n }\n\n /** NOTE: the json properties must be converted to string before insertion */\n private _targetScopeProvenanceProps:\n | (Omit<ExternalSourceAspectProps, \"jsonProperties\"> & {\n jsonProperties: TargetScopeProvenanceJsonProps;\n })\n | undefined = undefined;\n\n /**\n * Index of the changeset that the transformer was at when the transformation begins (was constructed).\n * Used to determine at the end which changesets were part of a synchronization.\n */\n private _startingChangesetIndices:\n | {\n target: number;\n source: number;\n }\n | undefined = undefined;\n\n private _cachedSynchronizationVersion: ChangesetIndexAndId | undefined =\n undefined;\n\n /**\n * We cache the synchronization version to avoid querying the target scoping ESA multiple times.\n * If the target scoping ESA is ever updated we need to clear any potentially cached sync version otherwise we will get stale values.\n * Sets this._cachedSynchronizationVersion to undefined.\n */\n private clearCachedSynchronizationVersion() {\n this._cachedSynchronizationVersion = undefined;\n }\n\n /** the changeset in the scoping element's source version found for this transformation\n * @note the version depends on whether this is a reverse synchronization or not, as\n * it is stored separately for both synchronization directions.\n * @note empty string and -1 for changeset and index if it has never been transformed\n * @note empty string and -1 for changeset and index if it was transformed before federation guid update (pre 1.x) and @see [[IModelTransformOptions.branchRelationshipDataBehavior]] === \"unsafe-migrate\".\n * @throws if the version is not found in a preexisting scope aspect and @see [[IModelTransformOptions.branchRelationshipDataBehavior]] !== \"unsafe-migrate\"\n */\n protected get synchronizationVersion(): ChangesetIndexAndId {\n if (this._cachedSynchronizationVersion === undefined) {\n const provenanceScopeAspect = this.tryGetProvenanceScopeAspect();\n if (!provenanceScopeAspect) {\n return { index: -1, id: \"\" }; // first synchronization.\n }\n\n const version = this.isReverseSynchronization\n ? (\n JSON.parse(\n provenanceScopeAspect.jsonProperties ?? \"{}\"\n ) as TargetScopeProvenanceJsonProps\n ).reverseSyncVersion\n : provenanceScopeAspect.version;\n if (\n !version &&\n this._options.branchRelationshipDataBehavior === \"unsafe-migrate\"\n ) {\n return { index: -1, id: \"\" }; // previous synchronization was done before fed guid update.\n }\n if (version === undefined) {\n throw new Error(`Could not find synchronization version in scope aspect. This may be due to the last successful run of the transformer being done with an older version.\n Consider running the transformer with branchRelationshipDataBehavior set to 'unsafe-migrate'`);\n }\n const [id, index] = version === \"\" ? [\"\", -1] : version.split(\";\");\n if (Number.isNaN(Number(index)))\n throw new Error(\"Could not parse version data from scope aspect\");\n this._cachedSynchronizationVersion = { index: Number(index), id }; // synchronization version found and cached.\n }\n return this._cachedSynchronizationVersion;\n }\n\n /**\n * @returns provenance scope aspect if it exists in the provenanceDb.\n * Provenance scope aspect is created and inserted into provenanceDb when [[initScopeProvenance]] is invoked.\n */\n protected tryGetProvenanceScopeAspect(): ExternalSourceAspect | undefined {\n const scopeProvenanceAspectProps =\n IModelTransformer.queryScopeExternalSourceAspect(this.provenanceDb, {\n id: undefined,\n classFullName: ExternalSourceAspect.classFullName,\n scope: { id: IModel.rootSubjectId },\n kind: ExternalSourceAspect.Kind.Scope,\n element: { id: this.targetScopeElementId ?? IModel.rootSubjectId },\n identifier: this.provenanceSourceDb.iModelId,\n });\n\n return scopeProvenanceAspectProps !== undefined\n ? (this.provenanceDb.elements.getAspect(\n scopeProvenanceAspectProps.aspectId\n ) as ExternalSourceAspect)\n : undefined;\n }\n\n /**\n * Make sure there are no conflicting other scope-type external source aspects on the *target scope element*,\n * If there are none at all, insert one, then this must be a first synchronization.\n * @returns the last synced version (changesetId) on the target scope's external source aspect,\n * if this was a [BriefcaseDb]($backend)\n */\n protected initScopeProvenance(): void {\n const aspectProps = {\n id: undefined as string | undefined,\n version: undefined as string | undefined,\n classFullName: ExternalSourceAspect.classFullName,\n element: {\n id: this.targetScopeElementId,\n relClassName: ElementOwnsExternalSourceAspects.classFullName,\n },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: this.provenanceSourceDb.iModelId,\n kind: ExternalSourceAspect.Kind.Scope,\n jsonProperties: undefined as TargetScopeProvenanceJsonProps | undefined,\n };\n\n const foundEsaProps = IModelTransformer.queryScopeExternalSourceAspect(\n this.provenanceDb,\n aspectProps\n ); // this query includes \"identifier\"\n\n if (foundEsaProps === undefined) {\n aspectProps.version = \"\"; // empty since never before transformed. Will be updated in [[finalizeTransformation]]\n aspectProps.jsonProperties = {\n pendingReverseSyncChangesetIndices: [],\n pendingSyncChangesetIndices: [],\n reverseSyncVersion: \"\", // empty since never before transformed. Will be updated in first reverse sync\n };\n\n // this query does not include \"identifier\" to find possible conflicts\n const sql = `\n SELECT ECInstanceId\n FROM ${ExternalSourceAspect.classFullName}\n WHERE Element.Id=:elementId\n AND Scope.Id=:scopeId\n AND Kind=:kind\n LIMIT 1\n `;\n\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n const hasConflictingScope = this.provenanceDb.withPreparedStatement(\n sql,\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n (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 );\n\n if (hasConflictingScope) {\n throw new IModelError(\n IModelStatus.InvalidId,\n \"Provenance scope conflict\"\n );\n }\n if (!this._options.noProvenance) {\n const id = this.provenanceDb.elements.insertAspect({\n ...aspectProps,\n jsonProperties: JSON.stringify(aspectProps.jsonProperties) as any,\n });\n aspectProps.id = id;\n // Busting a potential cached version\n this.clearCachedSynchronizationVersion();\n }\n } else {\n // foundEsaProps is defined.\n aspectProps.id = foundEsaProps.aspectId;\n aspectProps.version = foundEsaProps.version;\n aspectProps.jsonProperties = foundEsaProps.jsonProperties\n ? JSON.parse(foundEsaProps.jsonProperties)\n : undefined;\n // Clone oldProps incase they're changed for logging purposes\n const oldProps = JSON.parse(JSON.stringify(aspectProps));\n if (this.handleUnsafeMigrate(aspectProps)) {\n Logger.logInfo(\n loggerCategory,\n \"Unsafe migrate made a change to the target scope's external source aspect. Updating aspect in database.\",\n { oldProps, newProps: aspectProps }\n );\n this.provenanceDb.elements.updateAspect({\n ...aspectProps,\n jsonProperties: JSON.stringify(aspectProps.jsonProperties) as any,\n });\n // Busting a potential cached version\n this.clearCachedSynchronizationVersion();\n }\n }\n\n this._targetScopeProvenanceProps =\n aspectProps as typeof this._targetScopeProvenanceProps;\n }\n\n /** Returns true if a change was made to the aspectProps. */\n private handleUnsafeMigrate(aspectProps: {\n version?: string;\n jsonProperties?: TargetScopeProvenanceJsonProps;\n }): boolean {\n let madeChange = false;\n if (this._options.branchRelationshipDataBehavior !== \"unsafe-migrate\")\n return madeChange;\n const fallbackSyncVersionToUse =\n this._options.argsForProcessChanges?.unsafeFallbackSyncVersion ?? \"\";\n const fallbackReverseSyncVersionToUse =\n this._options.argsForProcessChanges?.unsafeFallbackReverseSyncVersion ??\n \"\";\n\n if (\n aspectProps.version === undefined ||\n (aspectProps.version === \"\" &&\n aspectProps.version !== fallbackSyncVersionToUse)\n ) {\n aspectProps.version = fallbackSyncVersionToUse;\n madeChange = true;\n }\n\n if (aspectProps.jsonProperties === undefined) {\n aspectProps.jsonProperties = {\n pendingReverseSyncChangesetIndices: [],\n pendingSyncChangesetIndices: [],\n reverseSyncVersion: fallbackReverseSyncVersionToUse,\n };\n madeChange = true;\n } else if (\n aspectProps.jsonProperties.reverseSyncVersion === undefined ||\n (aspectProps.jsonProperties.reverseSyncVersion === \"\" &&\n aspectProps.jsonProperties.reverseSyncVersion !==\n fallbackReverseSyncVersionToUse)\n ) {\n aspectProps.jsonProperties.reverseSyncVersion =\n fallbackReverseSyncVersionToUse;\n madeChange = true;\n }\n\n /**\n * This case will only be hit when:\n * - first transformation was performed on pre-fedguid transformer.\n * - a second processAll transformation was performed on the same target-source iModels post-fedguid transformer.\n * - change processing was invoked on for the second 'initial' transformation.\n * NOTE: This case likely does not exist anymore, but we will keep it just to be sure.\n */\n if (\n aspectProps.jsonProperties.pendingReverseSyncChangesetIndices ===\n undefined\n ) {\n Logger.logWarning(\n loggerCategory,\n \"Property pendingReverseSyncChangesetIndices missing on the jsonProperties of the scoping ESA. Setting to [].\"\n );\n aspectProps.jsonProperties.pendingReverseSyncChangesetIndices = [];\n madeChange = true;\n }\n if (aspectProps.jsonProperties.pendingSyncChangesetIndices === undefined) {\n Logger.logWarning(\n loggerCategory,\n \"Property pendingSyncChangesetIndices missing on the jsonProperties of the scoping ESA. Setting to [].\"\n );\n aspectProps.jsonProperties.pendingSyncChangesetIndices = [];\n madeChange = true;\n }\n return madeChange;\n }\n\n /**\n * Iterate all matching federation guids and ExternalSourceAspects in the provenance iModel (target unless reverse sync)\n * and call a function for each one.\n * @note provenance is done by federation guids where possible\n * @note this may execute on each element more than once! Only use in cases where that is handled\n */\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 skipPropagateChangesToRootElements: boolean;\n }): void {\n if (args.provenanceDb === args.provenanceSourceDb) return;\n\n if (!args.provenanceDb.containsClass(ExternalSourceAspect.classFullName)) {\n throw new IModelError(\n IModelStatus.BadSchema,\n \"The BisCore schema version of the target database is too old\"\n );\n }\n\n const sourceDb = args.isReverseSynchronization\n ? args.provenanceDb\n : args.provenanceSourceDb;\n const targetDb = args.isReverseSynchronization\n ? args.provenanceSourceDb\n : args.provenanceDb;\n\n // query for provenanceDb\n const elementIdByFedGuidQuery = `\n SELECT e.ECInstanceId, FederationGuid\n FROM bis.Element e\n ${\n args.skipPropagateChangesToRootElements\n ? \"WHERE e.ECInstanceId NOT IN (0x1, 0xe, 0x10) -- special static elements\"\n : \"\"\n }\n ORDER BY FederationGuid\n `;\n\n // iterate through sorted list of fed guids from both dbs to get the intersection\n // NOTE: if we exposed the native attach database support,\n // we could get the intersection of fed guids in one query, not sure if it would be faster\n // OR we could do a raw sqlite query...\n\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n sourceDb.withStatement(elementIdByFedGuidQuery, (sourceStmt) =>\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n targetDb.withStatement(elementIdByFedGuidQuery, (targetStmt) => {\n if (sourceStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n let sourceRow = sourceStmt.getRow() as {\n federationGuid?: GuidString;\n id: Id64String;\n };\n if (targetStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n let targetRow = targetStmt.getRow() as {\n federationGuid?: GuidString;\n id: Id64String;\n };\n\n // NOTE: these comparisons rely upon the lowercase of the guid,\n // and the fact that '0' < '9' < a' < 'f' in ascii/utf8\n while (true) {\n const currSourceRow = sourceRow,\n currTargetRow = targetRow;\n if (\n currSourceRow.federationGuid !== undefined &&\n currTargetRow.federationGuid !== undefined &&\n currSourceRow.federationGuid === currTargetRow.federationGuid\n ) {\n // data flow direction is always sourceDb -> targetDb and it does not depend on where the explicit element provenance is stored\n args.fn(sourceRow.id, targetRow.id);\n }\n if (\n currTargetRow.federationGuid === undefined ||\n (currSourceRow.federationGuid !== undefined &&\n currSourceRow.federationGuid >= currTargetRow.federationGuid)\n ) {\n if (targetStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n targetRow = targetStmt.getRow();\n }\n if (\n currSourceRow.federationGuid === undefined ||\n (currTargetRow.federationGuid !== undefined &&\n currSourceRow.federationGuid <= currTargetRow.federationGuid)\n ) {\n if (sourceStmt.step() !== DbResult.BE_SQLITE_ROW) return;\n sourceRow = sourceStmt.getRow();\n }\n }\n })\n );\n\n // query for provenanceDb\n const provenanceAspectsQuery = `\n SELECT esa.Identifier, Element.Id\n FROM bis.ExternalSourceAspect esa\n WHERE Scope.Id=:scopeId\n AND Kind=:kind\n `;\n\n // Technically this will a second time call the function (as documented) on\n // victims of the old provenance method that have both fedguids and an inserted aspect.\n // But this is a private function with one known caller where that doesn't matter\n\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n args.provenanceDb.withPreparedStatement(\n provenanceAspectsQuery,\n (stmt): void => {\n const runFnInDataFlowDirection = (\n sourceId: Id64String,\n targetId: Id64String\n ) =>\n args.isReverseSynchronization\n ? args.fn(sourceId, targetId)\n : args.fn(targetId, sourceId);\n stmt.bindId(\"scopeId\", args.targetScopeElementId);\n stmt.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n // ExternalSourceAspect.Identifier is of type string\n const aspectIdentifier: Id64String = stmt.getValue(0).getString();\n const elementId: Id64String = stmt.getValue(1).getId();\n runFnInDataFlowDirection(elementId, aspectIdentifier);\n }\n }\n );\n }\n\n private forEachTrackedElement(\n fn: (sourceElementId: Id64String, targetElementId: Id64String) => void\n ): void {\n return IModelTransformer.forEachTrackedElement({\n provenanceSourceDb: this.provenanceSourceDb,\n provenanceDb: this.provenanceDb,\n targetScopeElementId: this.targetScopeElementId,\n isReverseSynchronization: this.isReverseSynchronization,\n fn,\n skipPropagateChangesToRootElements:\n this._options.skipPropagateChangesToRootElements ?? true,\n });\n }\n\n /**\n * Queries the provenanceDb for an ESA whose identifier is equal to the provided 'entityInProvenanceSourceId'.\n * The identifier on the ESA is the id of the element in the [[IModelTransformer.provenanceSourceDb]]\n * Therefore it only makes sense to call this function when you have an id in the provenanceSourceDb.\n * @param entityInProvenanceSourceId\n * @returns the elementId that the ESA is stored on, esa.Element.Id\n */\n private _queryProvenanceForElement(\n entityInProvenanceSourceId: Id64String\n ): Id64String | undefined {\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return this.provenanceDb.withPreparedStatement(\n `\n SELECT esa.Element.Id\n FROM Bis.ExternalSourceAspect esa\n WHERE esa.Kind=?\n AND esa.Scope.Id=?\n AND esa.Identifier=?\n `,\n (stmt) => {\n stmt.bindString(1, ExternalSourceAspect.Kind.Element);\n stmt.bindId(2, this.targetScopeElementId);\n stmt.bindString(3, entityInProvenanceSourceId);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n else return undefined;\n }\n );\n }\n\n /**\n * Queries the provenanceDb for an ESA whose identifier is equal to the provided 'entityInProvenanceSourceId'.\n * The identifier on the ESA is the id of the relationship in the [[IModelTransformer.provenanceSourceDb]]\n * Therefore it only makes sense to call this function when you have an id in the provenanceSourceDb.\n * @param entityInProvenanceSourceId\n * @returns\n */\n private _queryProvenanceForRelationship(\n entityInProvenanceSourceId: Id64String,\n sourceRelInfo: {\n classFullName: string;\n sourceId: Id64String;\n targetId: Id64String;\n }\n ):\n | {\n aspectId: Id64String;\n /** if undefined, the relationship could not be found, perhaps it was deleted */\n relationshipId: Id64String | undefined;\n }\n | undefined {\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return this.provenanceDb.withPreparedStatement(\n `\n SELECT\n ECInstanceId,\n JSON_EXTRACT(JsonProperties, '$.targetRelInstanceId'),\n JSON_EXTRACT(JsonProperties, '$.provenanceRelInstanceId')\n FROM Bis.ExternalSourceAspect\n WHERE Kind=?\n AND Scope.Id=?\n AND Identifier=?\n `,\n (stmt) => {\n stmt.bindString(1, ExternalSourceAspect.Kind.Relationship);\n stmt.bindId(2, this.targetScopeElementId);\n stmt.bindString(3, entityInProvenanceSourceId);\n if (stmt.step() !== DbResult.BE_SQLITE_ROW) return undefined;\n\n const aspectId = stmt.getValue(0).getId();\n const provenanceRelInstIdVal = stmt.getValue(2);\n const provenanceRelInstanceId = !provenanceRelInstIdVal.isNull\n ? provenanceRelInstIdVal.getString()\n : this._queryTargetRelId(sourceRelInfo);\n return {\n aspectId,\n relationshipId: provenanceRelInstanceId,\n };\n }\n );\n }\n\n private _queryTargetRelId(sourceRelInfo: {\n classFullName: string;\n sourceId: Id64String;\n targetId: Id64String;\n }): Id64String | undefined {\n const targetRelInfo = {\n sourceId: this.context.findTargetElementId(sourceRelInfo.sourceId),\n targetId: this.context.findTargetElementId(sourceRelInfo.targetId),\n };\n if (\n targetRelInfo.sourceId === undefined ||\n targetRelInfo.targetId === undefined\n )\n return undefined; // couldn't find an element, rel is invalid or deleted\n\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return this.targetDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM bis.ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n AND ECClassId=?\n `,\n (stmt) => {\n stmt.bindId(1, targetRelInfo.sourceId);\n stmt.bindId(2, targetRelInfo.targetId);\n stmt.bindId(\n 3,\n this._targetClassNameToClassId(sourceRelInfo.classFullName)\n );\n if (stmt.step() !== DbResult.BE_SQLITE_ROW) return undefined;\n return stmt.getValue(0).getId();\n }\n );\n }\n\n private _targetClassNameToClassIdCache = new Map<string, string>();\n\n private _targetClassNameToClassId(classFullName: string): Id64String {\n let classId = this._targetClassNameToClassIdCache.get(classFullName);\n if (classId === undefined) {\n classId = this._getRelClassId(this.targetDb, classFullName);\n this._targetClassNameToClassIdCache.set(classFullName, classId);\n }\n return classId;\n }\n\n // NOTE: this doesn't handle remapped element classes,\n // but is only used for relationships rn\n private _getRelClassId(db: IModelDb, classFullName: string): Id64String {\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return db.withPreparedStatement(\n `\n SELECT c.ECInstanceId\n FROM ECDbMeta.ECClassDef c\n JOIN ECDbMeta.ECSchemaDef s ON c.Schema.Id=s.ECInstanceId\n WHERE s.Name=? AND c.Name=?\n `,\n (stmt) => {\n const [schemaName, className] =\n classFullName.indexOf(\".\") !== -1\n ? classFullName.split(\".\")\n : classFullName.split(\":\");\n stmt.bindString(1, schemaName);\n stmt.bindString(2, className);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n assert(false, \"relationship was not found\");\n }\n );\n }\n\n private _queryElemIdByFedGuid(\n db: IModelDb,\n fedGuid: GuidString\n ): Id64String | undefined {\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return db.withPreparedStatement(\n \"SELECT ECInstanceId FROM Bis.Element WHERE FederationGuid=?\",\n (stmt) => {\n stmt.bindGuid(1, fedGuid);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n else return undefined;\n }\n );\n }\n\n /** Returns `true` if *brute force* delete detections should be run.\n * @note This is only called if [[IModelTransformOptions.forceExternalSourceAspectProvenance]] option is true\n * @note Not relevant for [[process]] when [[IModelTransformOptions.argsForProcessChanges]] are provided and change history is known.\n */\n protected shouldDetectDeletes(): boolean {\n nodeAssert(this._syncType !== undefined);\n\n return this._syncType === \"not-sync\";\n }\n\n /**\n * Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements\n * in the source iModel.\n * @deprecated in 1.x. Do not use this. // FIXME<MIKE>: how to better explain this?\n * This method is only called during [[process]] when [[IModelTransformOptions.argsForProcessChanges]] is undefined and the option\n * [[IModelTransformOptions.forceExternalSourceAspectProvenance]] is enabled. It is not\n * necessary when calling [[process]] with [[IModelTransformOptions.argsForProcessChanges]] defined, since changeset information is sufficient.\n * @note you do not need to call this directly unless 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 const sql = `\n SELECT Identifier, Element.Id\n FROM BisCore.ExternalSourceAspect\n WHERE Scope.Id=:scopeId\n AND Kind=:kind\n `;\n\n nodeAssert(\n !this.isReverseSynchronization,\n \"synchronizations with processChanges already detect element deletes, don't call detectElementDeletes\"\n );\n\n // Reported issue: https://github.com/iTwin/itwinjs-core/issues/7989\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n this.provenanceDb.withPreparedStatement(sql, (stmt) => {\n stmt.bindId(\"scopeId\", this.targetScopeElementId);\n stmt.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n // ExternalSourceAspect.Identifier is of type string\n const aspectIdentifier = stmt.getValue(0).getString();\n if (!Id64.isValidId64(aspectIdentifier)) {\n continue;\n }\n const targetElemId = stmt.getValue(1).getId();\n const wasDeletedInSource = !EntityUnifier.exists(this.sourceDb, {\n entityReference: `e${aspectIdentifier}`,\n });\n if (wasDeletedInSource) this.importer.deleteElement(targetElemId);\n }\n });\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(\n loggerCategory,\n `onTransformElement(${\n sourceElement.id\n }) \"${sourceElement.getDisplayLabel()}\"`\n );\n const targetElementProps: ElementProps = this.context.cloneElement(\n sourceElement,\n { binaryGeometry: this._options.cloneUsingBinaryGeometry }\n );\n // Special case: source element is the root subject\n if (sourceElement.id === IModel.rootSubjectId) {\n const targetElementId: string = this.context.findTargetElementId(\n sourceElement.id\n );\n // When remapping rootSubject from source to non root subject in target, the code.scope gets remapped incorrectly.\n // This is because the rootSubject has no parent and its code.scope is unique in that it is the id of itself.\n // For all other subjects which do have parents the code.scope and its parent should be in agreement.\n if (\n targetElementId !== Id64.invalid &&\n targetElementId !== IModel.rootSubjectId\n ) {\n const targetElement =\n this.targetDb.elements.getElement(targetElementId);\n targetElementProps.parent =\n targetElement.parent ?? targetElementProps.parent;\n targetElementProps.code.scope = targetElement.code.scope;\n }\n }\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\n if (\n this._linearSpatialTransform !== undefined &&\n sourceElement instanceof GeometricElement3d\n ) {\n // can check the sourceElement since this IModelTransformer does not remap classes\n const placement = Placement3d.fromJSON(\n (targetElementProps as GeometricElement3dProps).placement\n );\n\n if (placement.isValid) {\n placement.multiplyTransform(this._linearSpatialTransform);\n (targetElementProps as GeometricElement3dProps).placement = placement;\n }\n }\n return targetElementProps;\n }\n\n /**\n * Calculate the transform between two ECEF locations\n * @param srcDb\n * @param targetDb\n * @returns Transform that converts relative coordinates in the source iModel to relative coordinates in the target iModel.\n * @note This can only be used if both source and target iModels are linearly located\n */\n public calculateEcefTransform(): Transform | undefined {\n const srcEcefLoc = this.sourceDb.ecefLocation;\n const targetEcefLoc = this.targetDb.ecefLocation;\n\n if (srcEcefLoc === undefined || targetEcefLoc === undefined) {\n throw new IModelError(\n IModelStatus.NoGeoLocation,\n \"Both source and target ECEF locations must be defined to calculate the transform.\"\n );\n }\n if (srcEcefLoc.getTransform().isAlmostEqual(targetEcefLoc.getTransform())) {\n Logger.logTrace(\n loggerCategory,\n \"ECEF data is already aligned. No spatial transforms needed.\"\n );\n return undefined;\n }\n\n const srcSpatialToECEF = srcEcefLoc.getTransform(); // converts relative to ECEF in relation to source\n const targetECEFToSpatial = targetEcefLoc.getTransform().inverse(); // converts ECEF to relative in relation to target\n if (!targetECEFToSpatial) {\n throw new IModelError(\n IModelStatus.NoGeoLocation,\n \"Failed to invert target ECEF transform.\"\n );\n }\n const ecefTransform =\n targetECEFToSpatial.multiplyTransformTransform(srcSpatialToECEF); // chain both transforms\n\n return ecefTransform;\n }\n\n public static convertHelmertToTransform(\n helmert: Helmert2DWithZOffset | undefined\n ): Transform {\n if (!helmert) {\n return Transform.createIdentity();\n }\n\n const rotationXY = Matrix3d.createRotationAroundAxisIndex(\n AxisIndex.Z,\n Angle.createDegrees(helmert?.rotDeg)\n );\n rotationXY.scaleColumnsInPlace(helmert.scale, helmert.scale, 1.0);\n const translation = Vector3d.create(\n helmert.translationX,\n helmert.translationY,\n helmert.translationZ\n );\n const helmertTransform = Transform.createRefs(translation, rotationXY);\n\n return helmertTransform;\n }\n\n public calculateTransformFromHelmertTransforms(): Transform | undefined {\n if (\n this.sourceDb.geographicCoordinateSystem?.horizontalCRS === undefined ||\n this.sourceDb.geographicCoordinateSystem?.verticalCRS === undefined\n ) {\n throw new IModelError(\n IModelStatus.BadRequest,\n \"Source iModel does not have a geographic coordinate system defined.\"\n );\n }\n if (\n this.targetDb.geographicCoordinateSystem?.horizontalCRS === undefined ||\n this.targetDb.geographicCoordinateSystem.verticalCRS === undefined\n ) {\n throw new IModelError(\n IModelStatus.BadRequest,\n \"Target iModel does not have a geographic coordinate system defined.\"\n );\n }\n if (\n !this.sourceDb.geographicCoordinateSystem.horizontalCRS.equals(\n this.targetDb.geographicCoordinateSystem.horizontalCRS\n ) ||\n !this.sourceDb.geographicCoordinateSystem.verticalCRS.equals(\n this.targetDb.geographicCoordinateSystem.verticalCRS\n )\n ) {\n throw new IModelError(\n IModelStatus.MismatchGcs,\n \"Source and target geographic coordinate systems must match to calculate the spatial transform.\"\n );\n }\n if (\n this.sourceDb.geographicCoordinateSystem.additionalTransform ===\n this.targetDb.geographicCoordinateSystem.additionalTransform\n ) {\n Logger.logTrace(\n loggerCategory,\n \"Geolocation data is already aligned. No spatial transforms needed.\"\n );\n return undefined;\n }\n\n const srcScale =\n this.sourceDb.geographicCoordinateSystem.additionalTransform\n ?.helmert2DWithZOffset?.scale ?? 1;\n const targetScale =\n this.targetDb.geographicCoordinateSystem.additionalTransform\n ?.helmert2DWithZOffset?.scale ?? 1;\n\n if (srcScale !== targetScale) {\n throw new IModelError(\n IModelStatus.MismatchGcs,\n \"Spatial transform is non rigid. Source and target Helmert transforms must have the same scale to calculate a rigid spatial transform.\"\n );\n }\n\n const srcTransform = IModelTransformer.convertHelmertToTransform(\n this.sourceDb.geographicCoordinateSystem.additionalTransform\n ?.helmert2DWithZOffset\n ); // moves elements to where src helmert transform would move them at render time\n const targetTransformInv = IModelTransformer.convertHelmertToTransform(\n this.targetDb.geographicCoordinateSystem.additionalTransform\n ?.helmert2DWithZOffset\n ).inverse(); // negates target helmert transform that is applied at render time\n\n if (!targetTransformInv) {\n throw new IModelError(\n IModelStatus.NoGeoLocation,\n \"Failed to invert target Helmert transform.\"\n );\n }\n\n const combinedTransform =\n targetTransformInv.multiplyTransformTransform(srcTransform);\n\n return combinedTransform;\n }\n\n // if undefined, it can be initialized by calling [[this.processChangesets]]\n private _deletedSourceRelationshipData?: Map<\n Id64String,\n {\n sourceIdInTarget?: Id64String;\n targetIdInTarget?: Id64String;\n classFullName: Id64String;\n relId?: Id64String;\n provenanceAspectId?: Id64String;\n }\n > = undefined;\n\n /** Returns true if a change within sourceElement is detected.\n * @param sourceElement The Element from the source iModel\n * @note A subclass can override this method to provide custom change detection behavior.\n */\n protected hasElementChanged(sourceElement: Element): boolean {\n const sourceDbChanges = this.exporter.sourceDbChanges;\n return (\n !sourceDbChanges || // are we processing changes? if not then element is considered as changed\n sourceDbChanges.element.insertIds.has(sourceElement.id) ||\n sourceDbChanges.element.updateIds.has(sourceElement.id)\n );\n }\n\n protected completePartiallyCommittedElements() {\n for (const sourceElementId of this._partiallyCommittedElementIds) {\n const sourceElement = this.sourceDb.elements.getElement({\n id: sourceElementId,\n wantGeometry: this.exporter.wantGeometry,\n wantBRepData: this.exporter.wantGeometry,\n });\n const targetId = this.context.findTargetElementId(sourceElementId);\n if (Id64.isInvalid(targetId)) {\n throw new Error(\n `source-target element mapping not found for element \"${sourceElementId}\" when completing partially committed elements. This is a bug.`\n );\n }\n\n const targetProps = this.onTransformElement(sourceElement);\n this.targetDb.elements.updateElement({ ...targetProps, id: targetId });\n }\n }\n\n protected completePartiallyCommittedAspects() {\n for (const sourceAspectId of this._partiallyCommittedAspectIds) {\n const sourceAspect = this.sourceDb.elements.getAspect(sourceAspectId);\n const targetAspectId = this.context.findTargetAspectId(sourceAspectId);\n if (Id64.isInvalid(targetAspectId)) {\n throw new Error(\n `source-target aspect mapping not found for aspect \"${sourceAspectId}\" when completing partially committed aspects. This is a bug.`\n );\n }\n const targetAspectProps = this.onTransformElementAspect(sourceAspect);\n this.targetDb.elements.updateAspect({\n ...targetAspectProps,\n id: targetAspectId,\n });\n }\n }\n\n private doAllReferencesExistInTarget(entity: ConcreteEntity) {\n let allReferencesExist = true;\n for (const referenceId of entity.getReferenceIds()) {\n const referencedEntityId = EntityReferences.toId64(referenceId);\n if (\n referencedEntityId === IModel.repositoryModelId ||\n referencedEntityId === IModel.dictionaryId ||\n referencedEntityId === \"0xe\"\n ) {\n continue;\n }\n\n if (\n allReferencesExist &&\n !EntityReferences.isValid(this.context.findTargetEntityId(referenceId))\n ) {\n // if we care about references existing then we cannot return early and must check all other references.\n if (this._options.danglingReferencesBehavior === \"ignore\") {\n return false;\n }\n allReferencesExist = false;\n }\n\n if (this._options.danglingReferencesBehavior === \"reject\") {\n this.assertReferenceExistsInSource(referenceId, entity);\n }\n }\n return allReferencesExist;\n }\n\n private assertReferenceExistsInSource(\n referenceId: EntityReference,\n entity: ConcreteEntity\n ) {\n const referencedExistsInSource = EntityUnifier.exists(this.sourceDb, {\n entityReference: referenceId,\n });\n if (!referencedExistsInSource) {\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 IModelTransformOptions.danglingReferencesBehavior option to 'ignore' to ignore this,\",\n `and the referenceId found on \"${entity.id}\" will not be carried over to corresponding target element.`,\n ].join(\"\\n\")\n );\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 [[process]], 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(\n IModelStatus.BadRequest,\n \"The root Subject should not be directly imported\"\n );\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 [[process]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processChildElements(\n sourceElementId: Id64String\n ): 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 {\n return true;\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(\n sourceElement: Element\n ): 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 =\n 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(\n referenceType === ConcreteEntityTypes.Element ||\n referenceType === ConcreteEntityTypes.Model\n );\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(\n id,\n DefinitionElement\n );\n if (\n asDefinitionElem &&\n !(asDefinitionElem instanceof RecipeDefinitionElement)\n ) {\n this.context.remapElement(id, id);\n }\n }\n return id;\n }).filter(\n (\n sourceReferenceId: Id64String | undefined\n ): sourceReferenceId is Id64String => {\n if (sourceReferenceId === undefined) return false;\n const referenceInTargetId =\n this.context.findTargetElementId(sourceReferenceId);\n const isInTarget = Id64.isValid(referenceInTargetId);\n return !isInTarget;\n }\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(\n id,\n ConcreteEntityTypes.Model\n );\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 =\n isSubModeled &&\n (!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;\n let targetElementProps: ElementProps;\n if (this._options.wasSourceIModelCopiedToTarget) {\n targetElementId = sourceElement.id;\n targetElementProps =\n this.targetDb.elements.getElementProps(targetElementId);\n } else {\n targetElementId = this.context.findTargetElementId(sourceElement.id);\n targetElementProps = this.onTransformElement(sourceElement);\n }\n\n // if an existing remapping was not yet found, check by FederationGuid\n if (\n this.context.isBetweenIModels &&\n !Id64.isValid(targetElementId) &&\n sourceElement.federationGuid !== undefined\n ) {\n targetElementId =\n this._queryElemIdByFedGuid(\n this.targetDb,\n sourceElement.federationGuid\n ) ?? Id64.invalid;\n if (Id64.isValid(targetElementId))\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found\n }\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 (\n !Id64.isValidId64(targetElementId) &&\n Id64.isValidId64(targetElementProps.code.scope)\n ) {\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 const maybeTargetElementId = this.targetDb.elements.queryElementIdByCode(\n targetElementProps.code as Required<CodeProps>\n );\n if (undefined !== maybeTargetElementId) {\n const maybeTargetElem =\n this.targetDb.elements.getElement(maybeTargetElementId);\n if (\n maybeTargetElem.classFullName === targetElementProps.classFullName\n ) {\n // ensure code remapping doesn't change the target class\n targetElementId = maybeTargetElementId;\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code\n } else {\n targetElementProps.code = Code.createEmpty(); // clear out invalid code\n }\n }\n }\n\n if (!this.hasElementChanged(sourceElement)) {\n Logger.logTrace(\n loggerCategory,\n `Skipping unchanged element (${sourceElement.id}, ${sourceElement.getDisplayLabel()}).`\n );\n return;\n }\n\n if (!this.doAllReferencesExistInTarget(sourceElement)) {\n this._partiallyCommittedElementIds.add(sourceElement.id);\n }\n\n // targetElementId will be valid (indicating update) or undefined (indicating insert)\n targetElementProps.id = Id64.isValid(targetElementId)\n ? targetElementId\n : undefined;\n\n if (this._options.preserveElementIdsForFiltering) {\n const isValid = Id64.isValid(targetElementId);\n if (isValid && targetElementId !== sourceElement.id) {\n // Element found with different id\n throw new Error(\n `Element id(${sourceElement.id}) cannot be preserved. Found a different mapping(${targetElementId}) from source element`\n );\n } else if (isValid && targetElementId === sourceElement.id) {\n // targetElementId is valid (indicating update)\n this.importer.markElementToUpdateDuringPreserveIds(sourceElement.id);\n } else if (!isValid) {\n const sourceInTargetElemProps =\n this.targetDb.elements.tryGetElementProps(sourceElement.id);\n\n // if we don't find mapping for source element in target(invalid) but another element with source id exists in target\n if (sourceInTargetElemProps) {\n // Element id is already taken by another element\n throw new Error(\n `Element id(${sourceElement.id}) cannot be preserved. An unrelated element in the target already uses id: ${sourceElement.id}`\n );\n } else {\n // Element id in target is available to be remapped\n targetElementProps.id = sourceElement.id;\n }\n }\n }\n\n if (!this._options.wasSourceIModelCopiedToTarget) {\n this.importer.importElement(targetElementProps); // don't need to import if iModel was copied\n }\n\n if (targetElementProps.id === undefined) {\n throw new IModelError(\n IModelStatus.BadElement,\n \"targetElementProps.id should be assigned by importElement\"\n );\n }\n this.context.remapElement(sourceElement.id, targetElementProps.id);\n\n // the transformer does not currently 'split' or 'join' any elements, therefore, it does not\n // insert external source aspects because federation guids are sufficient for this.\n // Other transformer subclasses must insert the appropriate aspect (as provided by a TBD API)\n // when splitting/joining elements\n // physical consolidation is an example of a 'joining' transform\n // FIXME: verify at finalization time that we don't lose provenance on new elements\n // FIXME: make public and improve `initElementProvenance` API for usage by consolidators\n if (!this._options.noProvenance) {\n let provenance:\n | Parameters<typeof this.markLastProvenance>[0]\n | undefined =\n this._options.forceExternalSourceAspectProvenance ||\n this._elementsWithExplicitlyTrackedProvenance.has(sourceElement.id)\n ? undefined\n : sourceElement.federationGuid;\n if (!provenance) {\n const aspectProps = this.initElementProvenance(\n sourceElement.id,\n targetElementProps.id\n );\n const foundEsaProps = IModelTransformer.queryScopeExternalSourceAspect(\n this.provenanceDb,\n aspectProps\n );\n if (foundEsaProps === undefined)\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n else {\n // Since initElementProvenance sets a property 'version' on the aspectProps that we wish to persist in the provenanceDb, only grab the id from the foundEsaProps.\n aspectProps.id = foundEsaProps.aspectId;\n this.provenanceDb.elements.updateAspect(aspectProps);\n }\n\n provenance = aspectProps as MarkRequired<\n ExternalSourceAspectProps,\n \"id\"\n >;\n }\n this.markLastProvenance(provenance, { isRelationship: false });\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 =\n 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 (\n this._options.skipPropagateChangesToRootElements &&\n IModel.repositoryModelId === sourceModel.id\n )\n return; // The RepositoryModel should not be directly imported\n const targetModeledElementId: Id64String = this.context.findTargetElementId(\n sourceModel.id\n );\n // there can only be one repositoryModel per database, so ignore the repo model on remapped subjects\n const isRemappedRootSubject =\n sourceModel.id === IModel.repositoryModelId &&\n targetModeledElementId !== sourceModel.id;\n if (isRemappedRootSubject) return;\n const targetModelProps: ModelProps = this.onTransformModel(\n sourceModel,\n targetModeledElementId\n );\n this.importer.importModel(targetModelProps);\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, [[remapDeletedSourceEntities]] will find and remap the deleted element making this operation valid\n const targetModelId: Id64String =\n this.context.findTargetElementId(sourceModelId);\n\n if (!Id64.isValidId64(targetModelId)) return;\n\n const sql = `\n SELECT 1\n FROM bis.DefinitionPartition\n WHERE ECInstanceId=:targetModelId\n UNION\n SELECT 1\n FROM bis.DefinitionContainer\n WHERE ECInstanceId=:targetModelId\n `;\n\n if (this.exporter.sourceDbChanges?.element.deleteIds.has(sourceModelId)) {\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n const isDefinitionPartition = this.targetDb.withPreparedStatement(\n sql,\n (stmt) => {\n stmt.bindId(\"targetModelId\", targetModelId);\n const val: DbResult = stmt.step();\n switch (val) {\n case DbResult.BE_SQLITE_ROW:\n return true;\n case DbResult.BE_SQLITE_DONE:\n return false;\n default:\n assert(false, `unexpected db result: '${JSON.stringify(stmt)}'`);\n }\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 =\n error instanceof IModelError &&\n (error.errorNumber === IModelStatus.DeletionProhibited ||\n error.errorNumber === IModelStatus.ForeignKeyConstraint);\n if (!isDeletionProhibitedErr) 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\n .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 [[process]], 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 [[process]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModelContents(\n sourceModelId: Id64String,\n targetModelId: Id64String,\n elementClassFullName: string = Element.classFullName\n ): 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(\n sourceModelId,\n elementClassFullName\n );\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(\n sourceSubjectId: Id64String\n ): Promise<void> {\n await this.initialize();\n // import DefinitionModels first\n const childDefinitionPartitionSql = `SELECT ECInstanceId FROM ${DefinitionPartition.classFullName} WHERE Parent.Id=:subjectId`;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n await this.sourceDb.withPreparedStatement(\n childDefinitionPartitionSql,\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n 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 );\n // import other partitions next\n const childPartitionSql = `SELECT ECInstanceId FROM ${InformationPartitionElement.classFullName} WHERE Parent.Id=:subjectId`;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n await this.sourceDb.withPreparedStatement(\n childPartitionSql,\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n 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 );\n // recurse into child Subjects\n const childSubjectSql = `SELECT ECInstanceId FROM ${Subject.classFullName} WHERE Parent.Id=:subjectId`;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n await this.sourceDb.withPreparedStatement(\n childSubjectSql,\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n 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\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(\n sourceModel: Model,\n targetModeledElementId: Id64String\n ): ModelProps {\n const targetModelProps: ModelProps = sourceModel.toJSON();\n // don't directly edit deep object since toJSON performs a shallow clone\n targetModelProps.modeledElement = {\n ...targetModelProps.modeledElement,\n id: targetModeledElementId,\n };\n targetModelProps.id = targetModeledElementId;\n if (targetModelProps.parentModel === undefined) {\n throw new IModelError(\n IModelStatus.BadElement,\n \"targetElementProps must have a defined parentModel\"\n );\n }\n targetModelProps.parentModel = this.context.findTargetElementId(\n targetModelProps.parentModel\n );\n return targetModelProps;\n }\n\n /**\n * Called at the end of a transformation,\n * updates the target scope element to say that transformation up through the\n * source's changeset has been performed. Also stores all changesets that occurred\n * during the transformation as \"pending synchronization changeset indices\" @see TargetScopeProvenanceJsonProps\n *\n * You generally should not call this function yourself and use [[process]] with [[IModelTransformOptions.argsForProcessChanges]] provided instead.\n * It is public for unsupported use cases of custom synchronization transforms.\n * @note If [[IModelTransformOptions.argsForProcessChanges]] is not defined in this transformation, this function will return early without updating the sync version,\n * unless the `initializeReverseSyncVersion` option is set to `true`\n *\n * The `initializeReverseSyncVersion` is added to set the reverse synchronization version during a forward synchronization.\n * When set to `true`, it saves the reverse sync version as the current changeset of the targetDb. This is typically used for the first transformation between a master and branch iModel.\n * Setting `initializeReverseSyncVersion` to `true` has the effect of making it so any changesets in the branch iModel at the time of the first transformation will be ignored during any future reverse synchronizations from the branch to the master iModel.\n *\n * Note that typically, the reverseSyncVersion is saved as the last changeset merged from the branch into master.\n * Setting initializeReverseSyncVersion to true during a forward transformation could overwrite this correct reverseSyncVersion and should only be done during the first transformation between a master and branch iModel.\n */\n public updateSynchronizationVersion({\n initializeReverseSyncVersion = false,\n } = {}) {\n const shouldSkipSyncVersionUpdate =\n !initializeReverseSyncVersion &&\n this._sourceChangeDataState !== \"has-changes\";\n if (shouldSkipSyncVersionUpdate) return;\n\n nodeAssert(this._targetScopeProvenanceProps);\n\n const sourceVersion = `${this.sourceDb.changeset.id};${this.sourceDb.changeset.index}`;\n const targetVersion = `${this.targetDb.changeset.id};${this.targetDb.changeset.index}`;\n\n if (this.isReverseSynchronization) {\n const oldVersion =\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion;\n\n Logger.logInfo(\n loggerCategory,\n `updating reverse version from ${oldVersion} to ${sourceVersion}`\n );\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion =\n sourceVersion;\n } else {\n Logger.logInfo(\n loggerCategory,\n `updating sync version from ${this._targetScopeProvenanceProps.version} to ${sourceVersion}`\n );\n this._targetScopeProvenanceProps.version = sourceVersion;\n\n // save reverse sync version\n if (initializeReverseSyncVersion) {\n Logger.logInfo(\n loggerCategory,\n `updating reverse sync version from ${this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion} to ${targetVersion}`\n );\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion =\n targetVersion;\n }\n }\n\n if (\n this._options.argsForProcessChanges ||\n (this._startingChangesetIndices && initializeReverseSyncVersion)\n ) {\n nodeAssert(\n this.targetDb.changeset.index !== undefined &&\n this._startingChangesetIndices !== undefined,\n \"updateSynchronizationVersion was called without change history\"\n );\n\n // Store in a local variable, so typescript knows it's defined (due to the assert above)\n const startingChangesetIndices = this._startingChangesetIndices;\n const jsonProps = this._targetScopeProvenanceProps.jsonProperties;\n\n Logger.logTrace(\n loggerCategory,\n `previous pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`\n );\n Logger.logTrace(\n loggerCategory,\n `previous pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`\n );\n\n const pendingSyncChangesetIndicesKey =\n \"pendingSyncChangesetIndices\" as const;\n const pendingReverseSyncChangesetIndicesKey =\n \"pendingReverseSyncChangesetIndices\" as const;\n\n // Determine which keys to clear and update based on the synchronization direction\n let syncChangesetsToClearKey;\n let syncChangesetsToUpdateKey;\n\n if (this.isReverseSynchronization) {\n syncChangesetsToClearKey = pendingReverseSyncChangesetIndicesKey;\n syncChangesetsToUpdateKey = pendingSyncChangesetIndicesKey;\n } else {\n syncChangesetsToClearKey = pendingSyncChangesetIndicesKey;\n syncChangesetsToUpdateKey = pendingReverseSyncChangesetIndicesKey;\n }\n\n // NOTE that as documented in [[processChanges]], this assumes that right after\n // transformation finalization, the work will be saved immediately, otherwise we've\n // just marked this changeset as a synchronization to ignore, and the user can add other\n // stuff to it which would break future synchronizations\n for (\n let i = startingChangesetIndices.target + 1;\n i <= this.targetDb.changeset.index + 1;\n i++\n )\n jsonProps[syncChangesetsToUpdateKey].push(i);\n // Only keep the changeset indices which are greater than the source, this means they haven't been processed yet.\n jsonProps[syncChangesetsToClearKey] = jsonProps[\n syncChangesetsToClearKey\n ].filter((csIndex) => {\n return csIndex > startingChangesetIndices.source;\n });\n\n // if reverse sync then we may have received provenance changes which should be marked as sync changes\n if (this.isReverseSynchronization) {\n nodeAssert(\n this.sourceDb.changeset.index !== undefined,\n \"changeset didn't exist\"\n );\n for (\n let i = startingChangesetIndices.source + 1;\n i <= this.sourceDb.changeset.index + 1;\n i++\n )\n jsonProps.pendingReverseSyncChangesetIndices.push(i);\n }\n\n Logger.logTrace(\n loggerCategory,\n `new pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`\n );\n Logger.logTrace(\n loggerCategory,\n `new pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`\n );\n }\n\n this.provenanceDb.elements.updateAspect({\n ...this._targetScopeProvenanceProps,\n jsonProperties: JSON.stringify(\n this._targetScopeProvenanceProps.jsonProperties\n ) as any,\n });\n this.clearCachedSynchronizationVersion();\n }\n\n // FIXME<MIKE>: is this necessary when manually using low level transform APIs? (document if so)\n private finalizeTransformation() {\n this.importer.finalize();\n this.updateSynchronizationVersion({\n initializeReverseSyncVersion: this._isProvenanceInitTransform,\n });\n\n // TODO: ignore if we remove change cache usage\n if (!this._options.noDetachChangeCache) {\n if (ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))\n ChangeSummaryManager.detachChangeCache(this.sourceDb);\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 [[process]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processRelationships(\n baseRelClassFullName: string\n ): 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(\n _sourceRelationship: Relationship\n ): boolean {\n return true;\n }\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 sourceFedGuid = queryElemFedGuid(\n this.sourceDb,\n sourceRelationship.sourceId\n );\n const targetFedGuid = queryElemFedGuid(\n this.sourceDb,\n sourceRelationship.targetId\n );\n const targetRelationshipProps =\n this.onTransformRelationship(sourceRelationship);\n const targetRelationshipInstanceId = this.importer.importRelationship(\n targetRelationshipProps\n );\n\n if (\n !this._options.noProvenance &&\n Id64.isValid(targetRelationshipInstanceId)\n ) {\n let provenance:\n | Parameters<typeof this.markLastProvenance>[0]\n | undefined = !this._options.forceExternalSourceAspectProvenance\n ? sourceFedGuid && targetFedGuid && `${sourceFedGuid}/${targetFedGuid}`\n : undefined;\n if (!provenance) {\n const aspectProps = this.initRelationshipProvenance(\n sourceRelationship,\n targetRelationshipInstanceId\n );\n const foundEsaProps = IModelTransformer.queryScopeExternalSourceAspect(\n this.provenanceDb,\n aspectProps\n );\n // onExportRelationship doesn't need to call updateAspect if esaProps were found, because relationship provenance doesn't have the same concept of a version as element provenance (which uses last mod time on the elements).\n if (undefined === foundEsaProps) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n }\n provenance = aspectProps as MarkRequired<\n ExternalSourceAspectProps,\n \"id\"\n >;\n }\n this.markLastProvenance(provenance, { 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 nodeAssert(\n this._deletedSourceRelationshipData,\n \"should be defined at initialization by now\"\n );\n\n const deletedRelData =\n this._deletedSourceRelationshipData.get(sourceRelInstanceId);\n if (!deletedRelData) {\n // this can occur if both the source and target deleted it\n Logger.logWarning(\n loggerCategory,\n \"tried to delete a relationship that wasn't in change data\"\n );\n return;\n }\n\n const id =\n deletedRelData.relId ??\n this.targetDb.relationships.tryGetInstance(deletedRelData.classFullName, {\n sourceId: deletedRelData.sourceIdInTarget,\n targetId: deletedRelData.targetIdInTarget,\n } as SourceAndTarget)?.id;\n if (id) {\n this.importer.deleteRelationship({\n id,\n classFullName: deletedRelData.classFullName,\n });\n }\n\n if (deletedRelData.provenanceAspectId) {\n try {\n this.provenanceDb.elements.deleteAspect(\n deletedRelData.provenanceAspectId\n );\n } catch (error: any) {\n // This aspect may no longer exist if it was deleted at some other point during the transformation. This is fine.\n if (error.errorNumber === IModelStatus.NotFound) return;\n throw error;\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 * @deprecated in 1.x. Don't use this anymore\n * @see [[process]] with [[IModelTransformOptions.argsForProcessChanges]] provided.\n * @note This method is called from [[process]] when [[IModelTransformOptions.argsForProcessChanges]] are undefined, 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.isReverseSynchronization) {\n throw new IModelError(\n IModelStatus.BadRequest,\n \"Cannot detect deletes when isReverseSynchronization=true\"\n );\n }\n const aspectDeleteIds: Id64String[] = [];\n const sql = `\n SELECT ECInstanceId, Identifier, JsonProperties\n FROM ${ExternalSourceAspect.classFullName} aspect\n WHERE aspect.Scope.Id=:scopeId\n AND aspect.Kind=:kind\n `;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n await this.targetDb.withPreparedStatement(\n sql,\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n 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(\n statement.getValue(1).getString()\n );\n if (\n undefined ===\n this.sourceDb.relationships.tryGetInstanceProps(\n ElementRefersToElements.classFullName,\n sourceRelInstanceId\n )\n ) {\n // this function exists only to support some in-imodel transformations, which must\n // use the old (external source aspect) provenance method anyway so we don't need to support\n // new provenance\n const json: any = JSON.parse(statement.getValue(2).getString());\n const targetRelInstanceId =\n json.targetRelInstanceId ?? json.provenanceRelInstanceId;\n if (targetRelInstanceId) {\n this.importer.deleteRelationship({\n id: targetRelInstanceId,\n classFullName: ElementRefersToElements.classFullName,\n });\n }\n aspectDeleteIds.push(statement.getValue(0).getId());\n }\n await this._yieldManager.allowYield();\n }\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(\n sourceRelationship: Relationship\n ): RelationshipProps {\n const targetRelationshipProps: RelationshipProps =\n sourceRelationship.toJSON();\n targetRelationshipProps.sourceId = this.context.findTargetElementId(\n sourceRelationship.sourceId\n );\n targetRelationshipProps.targetId = this.context.findTargetElementId(\n sourceRelationship.targetId\n );\n // TODO: move to cloneRelationship in IModelCloneContext\n sourceRelationship.forEachProperty(\n (propertyName: string, propertyMetaData: PropertyMetaData) => {\n if (\n PrimitiveTypeCode.Long === propertyMetaData.primitiveType &&\n \"Id\" === propertyMetaData.extendedType\n ) {\n (targetRelationshipProps as any)[propertyName] =\n this.context.findTargetElementId(\n sourceRelationship.asAny[propertyName]\n );\n }\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(\n sourceAspect: ElementUniqueAspect\n ): void {\n const targetAspectProps = this.onTransformElementAspect(sourceAspect);\n if (!this.doAllReferencesExistInTarget(sourceAspect)) {\n this._partiallyCommittedAspectIds.add(sourceAspect.id);\n }\n const targetId = this.importer.importElementUniqueAspect(targetAspectProps);\n this.context.remapElementAspect(sourceAspect.id, targetId);\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(\n sourceAspects: ElementMultiAspect[]\n ): void {\n // Transform source ElementMultiAspects into target ElementAspectProps\n const targetAspectPropsArray = sourceAspects.map((srcA) =>\n this.onTransformElementAspect(srcA)\n );\n sourceAspects.forEach((a) => {\n if (!this.doAllReferencesExistInTarget(a)) {\n this._partiallyCommittedAspectIds.add(a.id);\n }\n });\n // const targetAspectsToImport = targetAspectPropsArray.filter((targetAspect, i) => hasEntityChanged(sourceAspects[i], targetAspect));\n const targetIds = this.importer.importElementMultiAspects(\n targetAspectPropsArray,\n (a) => {\n const isExternalSourceAspectFromTransformer =\n a instanceof ExternalSourceAspect &&\n a.scope?.id === this.targetScopeElementId;\n return (\n !this._options.includeSourceProvenance ||\n !isExternalSourceAspectFromTransformer\n );\n }\n );\n for (let i = 0; i < targetIds.length; ++i) {\n this.context.remapElementAspect(sourceAspects[i].id, targetIds[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 * @returns ElementAspectProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformElementAspect(\n sourceElementAspect: ElementAspect\n ): ElementAspectProps {\n const targetElementAspectProps =\n 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(\n KnownLocations.tmpdir,\n Guid.createValue()\n );\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(\n schemaKey: ECSchemaMetaData.SchemaKey\n ): boolean {\n const versionInTarget = this.targetDb.querySchemaVersion(schemaKey.name);\n if (versionInTarget === undefined) return true;\n return Semver.gt(\n `${schemaKey.version.read}.${schemaKey.version.write}.${schemaKey.version.minor}`,\n Schema.toSemverString(versionInTarget)\n );\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(\n schema: ECSchemaMetaData.Schema\n ): 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 // windows usually has a limit for the total path length of 260\n const windowsMaxPathLimit = 260;\n if (\n schemaFileName.length > systemMaxPathSegmentSize ||\n path.join(this._schemaExportDir, schemaFileName).length >=\n windowsMaxPathLimit\n ) {\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)}${\n this._longNamedSchemasMap.size\n }${ext}`;\n nodeAssert(\n schemaFileName.length <= systemMaxPathSegmentSize,\n \"Schema name was still long. This is a bug.\"\n );\n this._longNamedSchemasMap.set(schema.name, schemaFileName);\n }\n /* eslint-disable-next-line @typescript-eslint/no-deprecated */\n this.sourceDb.exportSchema({\n schemaName: schema.name,\n outputDirectory: this._schemaExportDir,\n outputFileName: schemaFileName,\n });\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) 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) return;\n const schemaFullPaths = exportedSchemaFiles.map((s) =>\n path.join(this._schemaExportDir, s)\n );\n const maybeLongNameResolvingSchemaCtx =\n this._longNamedSchemasMap.size > 0\n ? this._makeLongNameResolvingSchemaCtx()\n : undefined;\n return await this.targetDb.importSchemas(schemaFullPaths, {\n ecSchemaXmlContext: maybeLongNameResolvingSchemaCtx,\n });\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 [[process]], 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(\n font: FontProps,\n _isUpdate: boolean | undefined\n ): 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 [[process]], 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 [[process]], 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 {\n return true;\n }\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(\n sourceSubjectId: Id64String,\n targetSubjectId: Id64String\n ): 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 this.completePartiallyCommittedElements();\n this.completePartiallyCommittedAspects();\n }\n\n /** state to prevent reinitialization, @see [[initialize]] */\n private _initialized = false;\n private _sourceChangeDataState: ChangeDataState = \"uninited\";\n /** length === 0 when _changeDataState = \"no-change\", length > 0 means \"has-changes\", otherwise undefined */\n private _csFileProps?: ChangesetFileProps[] = undefined;\n\n /**\n * Initialize prerequisites of processing, you must initialize with an [[InitOptions]] if you\n * are intending to process changes. Callers may wish to explicitly call initialize if they need to execute code after initialize but before [[process]] is called.\n * @note Called by all `process*` functions implicitly.\n * Overriders must call `super.initialize()` first\n */\n public async initialize(): Promise<void> {\n if (this._initialized) return;\n\n this.initScopeProvenance();\n\n await this._tryInitChangesetData(this._options.argsForProcessChanges);\n await this.context.initialize();\n\n // need exporter initialized to do remapdeletedsourceentities.\n await this.exporter.initialize(\n this.getExportInitOpts(this._options.argsForProcessChanges ?? {})\n );\n\n // Exporter must be initialized prior to processing changesets in order to properly handle entity recreations (an entity delete followed by an insert of that same entity).\n await this.processChangesets();\n\n this._initialized = true;\n }\n\n /**\n * Reads all the changeset files in the private member of the transformer: _csFileProps\n * and finds the corresponding target entity for any deleted source entities and remaps the sourceId to the targetId.\n * This function returns early if csFileProps is undefined or is of length 0.\n * @returns void\n */\n private async processChangesets(): Promise<void> {\n this.forEachTrackedElement(\n (sourceElementId: Id64String, targetElementId: Id64String) => {\n this.context.remapElement(sourceElementId, targetElementId);\n }\n );\n if (this.exporter.sourceDbChanges)\n await this.addCustomChanges(this.exporter.sourceDbChanges);\n\n if (this._csFileProps === undefined || this._csFileProps.length === 0) {\n if (\n this.exporter.sourceDbChanges === undefined ||\n !this.exporter.sourceDbChanges.hasChanges\n )\n return;\n // our sourcedbChanges aren't empty (probably due to someone adding custom changes), change our sourceChangeDataState to has-changes\n if (this._sourceChangeDataState === \"no-changes\")\n this._sourceChangeDataState = \"has-changes\";\n }\n\n const relationshipECClassIdsToSkip = new Set<string>();\n for await (const row of this.sourceDb.createQueryReader(\n \"SELECT ECInstanceId FROM ECDbMeta.ECClassDef where ECInstanceId IS (BisCore.ElementDrivesElement)\"\n )) {\n relationshipECClassIdsToSkip.add(row.ECInstanceId);\n }\n const relationshipECClassIds = new Set<string>();\n for await (const row of this.sourceDb.createQueryReader(\n \"SELECT ECInstanceId FROM ECDbMeta.ECClassDef where ECInstanceId IS (BisCore.ElementRefersToElements)\"\n )) {\n relationshipECClassIds.add(row.ECInstanceId);\n }\n\n // For later use when processing deletes.\n const alreadyImportedElementInserts = new Set<Id64String>();\n const alreadyImportedModelInserts = new Set<Id64String>();\n this.exporter.sourceDbChanges?.element.insertIds.forEach(\n (insertedSourceElementId) => {\n const targetElementId = this.context.findTargetElementId(\n insertedSourceElementId\n );\n if (Id64.isValid(targetElementId))\n alreadyImportedElementInserts.add(targetElementId);\n }\n );\n this.exporter.sourceDbChanges?.model.insertIds.forEach(\n (insertedSourceModelId) => {\n const targetModelId = this.context.findTargetElementId(\n insertedSourceModelId\n );\n if (Id64.isValid(targetModelId))\n alreadyImportedModelInserts.add(targetModelId);\n }\n );\n\n this._deletedSourceRelationshipData = new Map();\n\n for (const csFile of this._csFileProps ?? []) {\n const csReader = SqliteChangesetReader.openFile({\n fileName: csFile.pathname,\n db: this.sourceDb,\n disableSchemaCheck: true,\n });\n const csAdaptor = new ChangesetECAdaptor(csReader);\n const ecChangeUnifier = new PartialECChangeUnifier(this.sourceDb);\n while (csAdaptor.step()) {\n ecChangeUnifier.appendFrom(csAdaptor);\n }\n const changes: ChangedECInstance[] = [...ecChangeUnifier.instances];\n\n /** a map of element ids to this transformation scope's ESA data for that element, in case the ESA is deleted in the target */\n const elemIdToScopeEsa = new Map<Id64String, ChangedECInstance>();\n for (const change of changes) {\n if (\n change.ECClassId !== undefined &&\n relationshipECClassIdsToSkip.has(change.ECClassId)\n )\n continue;\n const changeType: SqliteChangeOp | undefined = change.$meta?.op;\n if (\n changeType === \"Deleted\" &&\n change?.$meta?.classFullName === ExternalSourceAspect.classFullName &&\n change.Scope.Id === this.targetScopeElementId &&\n change.Kind === ExternalSourceAspect.Kind.Element\n ) {\n elemIdToScopeEsa.set(change.Element.Id, change);\n }\n }\n // Loop to process deletes.\n for (const change of changes) {\n const changeType: SqliteChangeOp | undefined = change.$meta?.op;\n const ecClassId = change.ECClassId ?? change.$meta?.fallbackClassId;\n if (ecClassId === undefined)\n throw new Error(\n `ECClassId was not found for id: ${change.ECInstanceId}! Table is : ${change?.$meta?.tables}`\n );\n if (changeType === undefined)\n throw new Error(\n `ChangeType was undefined for id: ${change.ECInstanceId}.`\n );\n if (\n changeType !== \"Deleted\" ||\n relationshipECClassIdsToSkip.has(ecClassId)\n )\n continue;\n await this.processDeletedOp(\n change,\n elemIdToScopeEsa,\n relationshipECClassIds.has(ecClassId ?? \"\"),\n alreadyImportedElementInserts,\n alreadyImportedModelInserts\n );\n }\n\n csReader.close();\n }\n return;\n }\n\n /**\n * This will be called when transformer is called with [[IModelTransformOptions.argsForProcessChanges]] to process changes.\n * It will be executed after changes in changesets are populated into `sourceDbChanges` and before data processing begins.\n * Remap table between the source and target iModels will be built at that time, meaning that functions like [[IModelTransformer.context.findTargetElementId]] will return meaningful results.\n * This function should be used to modify the `sourceDbChanges`, if necessary, using `add custom change` methods in [[ChangedInstanceIds]], such as [[ChangedInstanceIds.addCustomElementChange]], [[ChangedInstanceIds.addCustomModelChange]] and other.\n * @param sourceDbChanges the ChangedInstanceIds already populated by the exporter with the changes in source changesets, if any, passed to the transformer.\n * @note Its expected that this function be overridden by a subclass of transformer if it needs to modify sourceDbChanges.\n */\n protected async addCustomChanges(\n _sourceDbChanges: ChangedInstanceIds\n ): Promise<void> {}\n\n /**\n * Helper function for processChangesets. Remaps the id of element deleted found in the 'change' to an element in the targetDb.\n * @param change the change to process, must be of changeType \"Deleted\"\n * @param mapOfDeletedElemIdToScopeEsas a map of elementIds to changedECInstances (which are ESAs). the elementId is not the id of the esa itself, but the elementid that the esa was stored on before the esa's deletion.\n * All ESAs in this map are part of the transformer's scope / ESA data and are tracked in case the ESA is deleted in the target.\n * @param isRelationship is relationship or not\n * @param alreadyImportedElementInserts used to handle entity recreation and not delete already handled element inserts.\n * @param alreadyImportedModelInserts used to handle entity recreation and not delete already handled model inserts.\n * @returns void\n */\n private async processDeletedOp(\n change: ChangedECInstance,\n mapOfDeletedElemIdToScopeEsas: Map<string, ChangedECInstance>,\n isRelationship: boolean,\n alreadyImportedElementInserts: Set<Id64String>,\n alreadyImportedModelInserts: Set<Id64String>\n ) {\n // we need a connected iModel with changes to remap elements with deletions\n const notConnectedModel = this.sourceDb.iTwinId === undefined;\n const noChanges =\n this.synchronizationVersion.index === this.sourceDb.changeset.index &&\n (this.exporter.sourceDbChanges === undefined ||\n !this.exporter.sourceDbChanges.hasChanges);\n if (notConnectedModel || noChanges) return;\n\n /**\n * if our ChangedECInstance is in the provenanceDb, then we can use the ids we find in the ChangedECInstance to query for ESAs.\n * This is because the ESAs are stored on an element Id thats present in the provenanceDb.\n */\n const changeDataInProvenanceDb = this.sourceDb === this.provenanceDb;\n\n const getTargetIdFromSourceId = async (id: Id64String) => {\n let identifierValue: string | undefined;\n let element;\n if (isRelationship) {\n element = this.sourceDb.elements.tryGetElement(id);\n }\n const fedGuid = isRelationship\n ? element?.federationGuid\n : change.FederationGuid;\n if (changeDataInProvenanceDb) {\n // TODO: clarify what happens if there are multiple (e.g. elements were merged)\n for await (const row of this.sourceDb.createQueryReader(\n \"SELECT esa.Identifier FROM bis.ExternalSourceAspect esa WHERE Scope.Id=:scopeId AND Kind=:kind AND Element.Id=:relatedElementId LIMIT 1\",\n QueryBinder.from([\n this.targetScopeElementId,\n ExternalSourceAspect.Kind.Element,\n id,\n ])\n )) {\n identifierValue = row.Identifier;\n }\n identifierValue =\n identifierValue ?? mapOfDeletedElemIdToScopeEsas.get(id)?.Identifier;\n }\n\n // Check for targetId by an esa first\n if (changeDataInProvenanceDb && identifierValue) {\n const targetId = identifierValue;\n return targetId;\n }\n\n // Check for targetId using sourceId's fedguid if we didn't find an esa.\n if (fedGuid) {\n const targetId = this._queryElemIdByFedGuid(this.targetDb, fedGuid);\n return targetId;\n }\n return undefined;\n };\n\n const changedInstanceId = change.ECInstanceId;\n if (isRelationship) {\n const sourceIdOfRelationshipInSource = change.SourceECInstanceId;\n const targetIdOfRelationshipInSource = change.TargetECInstanceId;\n const classFullName = change.$meta?.classFullName;\n\n const sourceIdOfRelationshipInTarget = await getTargetIdFromSourceId(\n sourceIdOfRelationshipInSource\n );\n const targetIdOfRelationshipInTarget = await getTargetIdFromSourceId(\n targetIdOfRelationshipInSource\n );\n if (sourceIdOfRelationshipInTarget && targetIdOfRelationshipInTarget) {\n this._deletedSourceRelationshipData?.set(changedInstanceId, {\n classFullName: classFullName ?? \"\",\n sourceIdInTarget: sourceIdOfRelationshipInTarget,\n targetIdInTarget: targetIdOfRelationshipInTarget,\n });\n } else if (this.sourceDb === this.provenanceSourceDb) {\n const relProvenance = this._queryProvenanceForRelationship(\n changedInstanceId,\n {\n classFullName: classFullName ?? \"\",\n sourceId: sourceIdOfRelationshipInSource,\n targetId: targetIdOfRelationshipInSource,\n }\n );\n if (relProvenance && relProvenance.relationshipId)\n this._deletedSourceRelationshipData?.set(changedInstanceId, {\n classFullName: classFullName ?? \"\",\n relId: relProvenance.relationshipId,\n provenanceAspectId: relProvenance.aspectId,\n });\n }\n } else {\n let targetId = await getTargetIdFromSourceId(changedInstanceId);\n if (targetId === undefined && this.sourceDb === this.provenanceSourceDb) {\n targetId = this._queryProvenanceForElement(changedInstanceId);\n }\n // since we are processing one changeset at a time, we can see local source deletes\n // of entities that were never synced and can be safely ignored\n const deletionNotInTarget = !targetId;\n if (deletionNotInTarget) return;\n\n if (targetId === undefined) {\n throw new IModelError(\n IModelStatus.BadElement,\n \"targetId should aquired from source id or element provenance\"\n );\n }\n\n this.context.remapElement(changedInstanceId, targetId);\n // If an entity insert and an entity delete both point to the same entity in target iModel, that means that entity was recreated.\n // In such case an entity update will be triggered and we no longer need to delete the entity.\n if (alreadyImportedElementInserts.has(targetId)) {\n this.exporter.sourceDbChanges?.element.deleteIds.delete(\n changedInstanceId\n );\n }\n if (alreadyImportedModelInserts.has(targetId)) {\n this.exporter.sourceDbChanges?.model.deleteIds.delete(\n changedInstanceId\n );\n }\n }\n }\n\n private async _tryInitChangesetData(args?: ProcessChangesOptions) {\n if (\n !args ||\n this.sourceDb.iTwinId === undefined ||\n this.sourceDb.changeset.index === undefined\n ) {\n this._sourceChangeDataState = \"unconnected\";\n return;\n }\n\n const noChanges =\n this.synchronizationVersion.index === this.sourceDb.changeset.index;\n if (noChanges) {\n this._sourceChangeDataState = \"no-changes\";\n this._csFileProps = [];\n return;\n }\n const startChangeset =\n \"startChangeset\" in args ? args.startChangeset : undefined;\n\n // NOTE: that we do NOT download the changesummary for the last transformed version, we want\n // to ignore those already processed changes\n const startChangesetIndexOrId =\n startChangeset?.index ??\n startChangeset?.id ??\n this.synchronizationVersion.index + 1;\n const endChangesetId = this.sourceDb.changeset.id;\n\n const [startChangesetIndex, endChangesetIndex] = await Promise.all(\n [startChangesetIndexOrId, endChangesetId].map(async (indexOrId) =>\n typeof indexOrId === \"number\"\n ? indexOrId\n : BriefcaseManager.queryChangeset({\n iModelId: this.sourceDb.iModelId,\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n changeset: { id: indexOrId },\n }).then((changeset) => changeset.index)\n )\n );\n\n const missingChangesets =\n startChangesetIndex > this.synchronizationVersion.index + 1;\n if (\n !this._options.argsForProcessChanges\n ?.ignoreMissingChangesetsInSynchronizations &&\n startChangesetIndex !== this.synchronizationVersion.index + 1 &&\n this.synchronizationVersion.index !== -1\n ) {\n throw Error(\n `synchronization is ${missingChangesets ? \"missing changesets\" : \"\"},` +\n \" startChangesetId should be\" +\n \" exactly the first changeset *after* the previous synchronization to not miss data.\" +\n ` You specified '${startChangesetIndexOrId}' which is changeset #${startChangesetIndex}` +\n ` but the previous synchronization for this targetScopeElement was '${this.synchronizationVersion.id}'` +\n ` which is changeset #${this.synchronizationVersion.index}. The transformer expected` +\n ` #${this.synchronizationVersion.index + 1}.`\n );\n }\n\n nodeAssert(\n this._targetScopeProvenanceProps,\n \"_targetScopeProvenanceProps should be set by now\"\n );\n\n const changesetsToSkip = this.isReverseSynchronization\n ? this._targetScopeProvenanceProps.jsonProperties\n .pendingReverseSyncChangesetIndices\n : this._targetScopeProvenanceProps.jsonProperties\n .pendingSyncChangesetIndices;\n\n Logger.logTrace(loggerCategory, `changesets to skip: ${changesetsToSkip}`);\n this._changesetRanges = rangesFromRangeAndSkipped(\n startChangesetIndex,\n endChangesetIndex,\n changesetsToSkip\n );\n Logger.logTrace(loggerCategory, `ranges: ${this._changesetRanges}`);\n\n const csFileProps: ChangesetFileProps[] = [];\n for (const [first, end] of this._changesetRanges) {\n // TODO: should the first changeset in a reverse sync really be included even though its 'initialized branch provenance'? The answer is no, its a bug that needs to be fixed.\n const fileProps = await BriefcaseManager.downloadChangesets({\n iModelId: this.sourceDb.iModelId,\n targetDir: BriefcaseManager.getChangeSetsPath(this.sourceDb.iModelId),\n range: { first, end },\n });\n csFileProps.push(...fileProps);\n }\n this._csFileProps = csFileProps;\n\n /** Theres a possibility that our csFileProps length is still 0 here, since we skip cs indices found in the pendingSync and pendingReverseSync indices arrays. */\n this._sourceChangeDataState =\n this._csFileProps.length === 0 ? \"no-changes\" : \"has-changes\";\n }\n\n /**\n * The behavior of process is influenced by [[IModelTransformOptions.argsForProcessChanges]] being defined or not defined during construction passed of the IModelTransformer.\n * @section When argsForProcessChanges are defined:\n *\n * Export changes from the source iModel and import the transformed entities into the target iModel.\n * Inserts, updates, and deletes are determined by inspecting the changeset(s).\n *\n * Notes:\n * - the transformer assumes that you saveChanges after processing changes. You should not modify the iModel after processChanges until saveChanges,\n * failure to do so may result in corrupted\n * data loss in future branch operations\n * - if no startChangesetId or startChangeset option is provided as part of the ProcessChangesOptions, the next unsynchronized changeset\n * will automatically be determined and used\n * - To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n *\n * @section When argsForProcessChanges are undefined:\n *\n * Export everything from the source iModel and import the transformed entities into the target iModel.\n *\n * Notes:\n * - [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.\n *\n */\n public async process(): Promise<void> {\n await this.initialize();\n\n this.logSettings();\n\n return this._options.argsForProcessChanges !== undefined\n ? this.processChanges(this._options.argsForProcessChanges)\n : this.processAll();\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 private async processAll(): Promise<void> {\n await this.exporter.exportCodeSpecs();\n await this.exporter.exportFonts();\n\n if (this._options.skipPropagateChangesToRootElements) {\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(\n IModel.repositoryModelId,\n Element.classFullName,\n true\n ); // after the Subject hierarchy, process the other elements of the RepositoryModel\n await this.exporter.exportSubModels(IModel.repositoryModelId); // start below the RepositoryModel\n } else {\n await this.exporter.exportModel(IModel.repositoryModelId);\n }\n this.completePartiallyCommittedElements();\n await this.exporter[\"exportAllAspects\"](); // eslint-disable-line @typescript-eslint/dot-notation\n this.completePartiallyCommittedAspects();\n await this.exporter.exportRelationships(\n ElementRefersToElements.classFullName\n );\n if (\n this._options.forceExternalSourceAspectProvenance &&\n this.shouldDetectDeletes()\n ) {\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n await this.detectElementDeletes();\n // eslint-disable-next-line @typescript-eslint/no-deprecated\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 /** previous provenance, either a federation guid, a `${sourceFedGuid}/${targetFedGuid}` pair, or required aspect props */\n private _lastProvenanceEntityInfo: string | LastProvenanceEntityInfo =\n nullLastProvenanceEntityInfo;\n\n private markLastProvenance(\n sourceAspect: string | MarkRequired<ExternalSourceAspectProps, \"id\">,\n { isRelationship = false }\n ) {\n this._lastProvenanceEntityInfo =\n typeof sourceAspect === \"string\"\n ? sourceAspect\n : {\n entityId: sourceAspect.element.id,\n aspectId: sourceAspect.id,\n aspectVersion: sourceAspect.version ?? \"\",\n aspectKind: isRelationship\n ? ExternalSourceAspect.Kind.Relationship\n : ExternalSourceAspect.Kind.Element,\n };\n }\n\n /** Export changes from the source iModel and import the transformed entities into the target iModel.\n * Inserts, updates, and deletes are determined by inspecting the changeset(s).\n * @note the transformer assumes that you saveChanges after processing changes. You should not\n * modify the iModel after processChanges until saveChanges, failure to do so may result in corrupted\n * data loss in future branch operations\n * @note if no startChangesetId or startChangeset option is provided as part of the ProcessChangesOptions, the next unsynchronized changeset\n * will automatically be determined and used\n * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n */\n private async processChanges(options: ProcessChangesOptions): Promise<void> {\n // must wait for initialization of synchronization provenance data\n await this.exporter.exportChanges(this.getExportInitOpts(options));\n this.completePartiallyCommittedElements();\n this.completePartiallyCommittedAspects();\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n\n const defaultSaveTargetChanges = () => {\n this.targetDb.saveChanges();\n };\n\n await (options.saveTargetChanges ?? defaultSaveTargetChanges)(this);\n }\n\n /** Changeset data must be initialized in order to build correct changeOptions.\n * Call [[IModelTransformer.initialize]] for initialization of synchronization provenance data\n */\n private getExportInitOpts(opts: ExportChangesOptions): ExporterInitOptions {\n if (!this._options.argsForProcessChanges) return {};\n const startChangeset =\n \"startChangeset\" in opts ? opts.startChangeset : undefined;\n return {\n skipPropagateChangesToRootElements:\n this._options.skipPropagateChangesToRootElements,\n ...(this._csFileProps\n ? { csFileProps: this._csFileProps }\n : this._changesetRanges\n ? { changesetRanges: this._changesetRanges }\n : startChangeset\n ? { startChangeset }\n : {\n startChangeset: {\n index: this.synchronizationVersion.index + 1,\n },\n }),\n };\n }\n\n /** Combine an array of source elements into a single target element.\n * All source and target elements must be created before calling this method.\n * The \"combine\" operation is a remap and no properties from the source elements will be exported into the target\n * and provenance will be explicitly tracked by ExternalSourceAspects\n */\n public combineElements(\n sourceElementIds: Id64Array,\n targetElementId: Id64String\n ) {\n for (const elementId of sourceElementIds) {\n this.context.remapElement(elementId, targetElementId);\n this._elementsWithExplicitlyTrackedProvenance.add(elementId);\n }\n }\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(\n sourceTemplateModelId: Id64String,\n targetModelId: Id64String,\n placement: Placement3d\n ): Promise<Map<Id64String, Id64String>> {\n await this.initialize();\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(\n placement.origin,\n placement.angles.toMatrix3d()\n );\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(\n sourceTemplateModelId: Id64String,\n targetModelId: Id64String,\n placement: Placement2d\n ): Promise<Map<Id64String, Id64String>> {\n await this.initialize();\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(\n Point3d.createFrom(placement.origin),\n placement.rotation\n );\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 const referenceIds = sourceElement.getReferenceIds();\n referenceIds.forEach((referenceId) => {\n // TODO: consider going through all definition elements at once and remapping them to themselves\n if (\n !EntityReferences.isValid(this.context.findTargetEntityId(referenceId))\n ) {\n if (this.context.isBetweenIModels) {\n throw new IModelError(\n IModelStatus.BadRequest,\n `Remapping for source dependency ${referenceId} not found for target iModel`\n );\n } else {\n const definitionElement =\n this.sourceDb.elements.tryGetElement<DefinitionElement>(\n referenceId,\n DefinitionElement\n );\n if (\n definitionElement &&\n !(definitionElement instanceof RecipeDefinitionElement)\n ) {\n this.context.remapElement(referenceId, referenceId); // when in the same iModel, can use existing DefinitionElements without remapping\n } else {\n throw new IModelError(\n IModelStatus.BadRequest,\n `Remapping for dependency ${referenceId} not found`\n );\n }\n }\n }\n });\n\n const targetElementProps: ElementProps = super.onTransformElement(\n sourceElement\n );\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 GeometricElement) {\n const is3d = sourceElement instanceof GeometricElement3d;\n const placementClass = is3d ? Placement3d : Placement2d;\n const placement = placementClass.fromJSON(\n (targetElementProps as GeometricElementProps).placement as any\n );\n if (placement.isValid) {\n nodeAssert(this._transform3d);\n placement.multiplyTransform(this._transform3d);\n (targetElementProps as GeometricElementProps).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\nfunction queryElemFedGuid(db: IModelDb, elemId: Id64String) {\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return db.withPreparedStatement(\n `\n SELECT FederationGuid\n FROM bis.Element\n WHERE ECInstanceId=?\n `,\n (stmt) => {\n stmt.bindId(1, elemId);\n assert(stmt.step() === DbResult.BE_SQLITE_ROW);\n const result = stmt.getValue(0).getGuid();\n assert(stmt.step() === DbResult.BE_SQLITE_DONE);\n return result;\n }\n );\n}\n"]}