@itwin/core-backend 5.0.0-dev.5 → 5.0.0-dev.7

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.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,27 @@
1
1
  # Change Log - @itwin/core-backend
2
2
 
3
- This log was last generated on Wed, 06 Nov 2024 19:24:30 GMT and should not be manually modified.
3
+ This log was last generated on Thu, 14 Nov 2024 18:13:56 GMT and should not be manually modified.
4
+
5
+ ## 4.10.1
6
+ Thu, 14 Nov 2024 18:11:00 GMT
7
+
8
+ _Version update only_
9
+
10
+ ## 4.10.0
11
+ Wed, 13 Nov 2024 15:23:38 GMT
12
+
13
+ ### Updates
14
+
15
+ - Added basic TS implementation for Sheet Indexes
16
+ - Comply with 4.8.x ECSql row format
17
+ - fix regression related to classid
18
+ - Allow revert timeline changes
19
+ - Add support for Node 22
20
+ - `Object` methods are now prohibited through IPC.
21
+ - Deprecate `IModelHost.snapshotFileNameResolver` and `FileNameResolver`
22
+ - Require db in `SqliteChangesetReaderArgs`
23
+ - omit baseuri from RequestTokenProps interface
24
+ - Removed added tests for boolean exps in select statement
4
25
 
5
26
  ## 4.9.7
6
27
  Wed, 06 Nov 2024 19:23:04 GMT
@@ -394,7 +394,7 @@ var CloudSqlite;
394
394
  if (undefined === auth)
395
395
  throw new Error("no authorization client available");
396
396
  const userToken = await auth.getAccessToken();
397
- const cloudContainer = await service.create({ scope: args.scope, metadata: { ...args.metadata, containerType: "property-store" }, userToken });
397
+ const cloudContainer = await service.create({ scope: args.scope, metadata: args.metadata, userToken });
398
398
  return { baseUri: cloudContainer.baseUri, containerId: cloudContainer.containerId, storageType: cloudContainer.provider };
399
399
  }
400
400
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"CloudSqlite.js","sourceRoot":"","sources":["../../src/CloudSqlite.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,2BAA2C;AAC3C,+BAAqC;AACrC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AAE,GAAG,IAAW,EAAE,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,kBAAQ,CAAC,eAAe,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;gBACnJ,CAAC;aACF,CAAmC,CAAC;QACvC,CAAC;QAED;;;WAGG;QACH,IAAW,MAAM;YACf,OAAO,IAAI,CAAC,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE;gBAC3C,GAAG,CAAC,MAAM,EAAE,UAAkB;oBAC5B,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;oBAC1C,OAAO,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;gBACpE,CAAC;aACF,CAA6B,CAAC;QACjC,CAAC;;IA1NgB,mBAAU,GAAG,aAAa,AAAhB,CAAiB;IATjC,oBAAQ,WAoOpB,CAAA;AACH,CAAC,EA7+BgB,WAAW,2BAAX,WAAW,QA6+B3B","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module SQLiteDb\r\n */\r\n\r\nimport { mkdirSync, unlinkSync } from \"fs\";\r\nimport { dirname, join } from \"path\";\r\nimport { NativeLibrary } from \"@bentley/imodeljs-native\";\r\nimport {\r\n AccessToken, BeDuration, BriefcaseStatus, Constructor, GuidString, Logger, LogLevel, OpenMode, Optional, PickAsyncMethods, PickMethods, StopWatch,\r\n} from \"@itwin/core-bentley\";\r\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\r\nimport { BlobContainer } from \"./BlobContainerService\";\r\nimport { IModelHost, KnownLocations } from \"./IModelHost\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\nimport { RpcTrace } from \"./rpc/tracing\";\r\n\r\nimport type { SQLiteDb, VersionedSqliteDb } from \"./SQLiteDb\";\r\n\r\n// spell:ignore logmsg httpcode daemonless cachefile cacheslots ddthh\r\n\r\n/**\r\n * Types for accessing SQLite databases stored in cloud containers.\r\n * @beta\r\n */\r\nexport namespace CloudSqlite {\r\n\r\n const logInfo = (msg: string) => Logger.logInfo(\"CloudSqlite\", msg);\r\n const logError = (msg: string) => Logger.logError(\"CloudSqlite\", msg);\r\n\r\n export type RequestTokenArgs = Optional<BlobContainer.RequestTokenProps, \"userToken\">;\r\n /**\r\n * Request a new AccessToken for a cloud container using the [[BlobContainer]] service.\r\n * If the service is unavailable or returns an error, an empty token is returned.\r\n */\r\n export async function requestToken(args: RequestTokenArgs): Promise<AccessToken> {\r\n // allow the userToken to be supplied via args. If not supplied, or blank, use the backend's accessToken. If that fails, use the value from the current RPC request\r\n let userToken = args.userToken ? args.userToken : await IModelHost.getAccessToken();\r\n if (userToken === \"\")\r\n userToken = RpcTrace.currentActivity?.accessToken ?? \"\";\r\n if (BlobContainer.service === undefined) {\r\n throw new Error(`BlobContainer.service is not defined`);\r\n }\r\n const response = await BlobContainer.service.requestToken({ ...args, userToken });\r\n return response?.token ?? \"\";\r\n }\r\n\r\n interface CloudContainerInternal extends CloudContainer {\r\n timer?: NodeJS.Timeout;\r\n refreshPromise?: Promise<void>;\r\n lockExpireSeconds: number;\r\n writeLockHeldBy?: string;\r\n }\r\n\r\n /**\r\n * Create a new CloudContainer from a ContainerAccessProps. For non-public containers, a valid accessToken must be provided before the container\r\n * can be used (e.g. via [[CloudSqlite.requestToken]]).\r\n * @note After the container is successfully connected to a CloudCache, it will begin auto-refreshing its accessToken every `tokenRefreshSeconds` seconds (default is 1 hour)\r\n * until it is disconnected. However, if the container is public, or if `tokenRefreshSeconds` is <=0, auto-refresh is not enabled.\r\n */\r\n export function createCloudContainer(args: ContainerAccessProps & { accessLevel?: BlobContainer.RequestAccessLevel, tokenFn?: (args: RequestTokenArgs) => Promise<AccessToken> }): CloudContainer {\r\n const container = new NativeLibrary.nativeLib.CloudContainer(args) as CloudContainerInternal;\r\n const refreshSeconds = (undefined !== args.tokenRefreshSeconds) ? args.tokenRefreshSeconds : 60 * 60; // default is 1 hour\r\n container.lockExpireSeconds = args.lockExpireSeconds ?? 60 * 60; // default is 1 hour\r\n\r\n // don't refresh tokens for public containers or if refreshSeconds<=0\r\n if (!args.isPublic && refreshSeconds > 0) {\r\n const tokenProps = { baseUri: args.baseUri, containerId: args.containerId, accessLevel: args.accessLevel };\r\n const doRefresh = async () => {\r\n let newToken: AccessToken | undefined;\r\n const url = `[${tokenProps.baseUri}/${tokenProps.containerId}]`;\r\n try {\r\n newToken = await (args.tokenFn ?? CloudSqlite.requestToken)(tokenProps);\r\n logInfo(`Refreshed token for container ${url}`);\r\n } catch (err: any) {\r\n logError(`Error refreshing token for container ${url}: ${err.message}`);\r\n }\r\n container.accessToken = newToken ?? \"\";\r\n };\r\n const tokenRefreshFn = () => {\r\n container.timer = setTimeout(async () => {\r\n container.refreshPromise = doRefresh(); // this promise is stored on the container so it can be awaited in tests\r\n await container.refreshPromise;\r\n container.refreshPromise = undefined;\r\n tokenRefreshFn(); // schedule next refresh\r\n }, refreshSeconds * 1000);\r\n };\r\n container.onConnected = tokenRefreshFn; // schedule the first refresh when the container is connected\r\n container.onDisconnect = () => { // clear the refresh timer when the container is disconnected\r\n if (container.timer !== undefined) {\r\n clearTimeout(container.timer);\r\n container.timer = undefined;\r\n }\r\n };\r\n }\r\n return container;\r\n }\r\n\r\n /** Begin prefetching all blocks for a database in a CloudContainer in the background. */\r\n export function startCloudPrefetch(container: CloudContainer, dbName: string, args?: PrefetchProps): CloudPrefetch {\r\n return new NativeLibrary.nativeLib.CloudPrefetch(container, dbName, args);\r\n }\r\n export interface ContainerProps {\r\n /** The type of storage provider. */\r\n readonly storageType: \"azure\" | \"google\";\r\n /** The base URI for the container. */\r\n readonly baseUri: string;\r\n /** The name of the container. */\r\n readonly containerId: string;\r\n /** true if the container is public (doesn't require authorization) */\r\n readonly isPublic?: boolean;\r\n /** access token for container. If not present uses `CloudSqlite.requestToken` */\r\n accessToken?: string;\r\n }\r\n\r\n /** Properties to access a CloudContainer. */\r\n export interface ContainerAccessProps extends ContainerProps {\r\n /** an alias for the container. Defaults to `containerId` */\r\n readonly alias?: string;\r\n /** SAS token that grants access to the container. */\r\n accessToken: string;\r\n /** if true, container is allowed to request the write lock. */\r\n readonly writeable?: boolean;\r\n /** if true, container is attached in \"secure\" mode (blocks are encrypted). Only supported in daemon mode. */\r\n readonly secure?: boolean;\r\n /** string attached to log messages from CloudSQLite. This is most useful for identifying usage from daemon mode. */\r\n readonly logId?: string;\r\n /** Duration for holding write lock, in seconds. After this time the write lock expires if not refreshed. Default is one hour. */\r\n readonly lockExpireSeconds?: number;\r\n /** number of seconds between auto-refresh of access token. If <=0 no auto-refresh. Default is 1 hour (60*60) */\r\n readonly tokenRefreshSeconds?: number;\r\n }\r\n\r\n /** Returned from `CloudContainer.queryDatabase` describing one database in the container */\r\n export interface CachedDbProps {\r\n /** The total number of blocks in the database. */\r\n readonly totalBlocks: number;\r\n /** the number of blocks of the database that have been downloaded into the CloudCache */\r\n readonly localBlocks: number;\r\n /** the number of blocks from this database that have been modified in the CloudCache and need to be uploaded. */\r\n readonly dirtyBlocks: number;\r\n /** If true, the database currently has transactions in the WAL file and may not be uploaded until they have been checkPointed. */\r\n readonly transactions: boolean;\r\n /** the state of this database. Indicates whether the database is new or deleted since last upload */\r\n readonly state: \"\" | \"copied\" | \"deleted\";\r\n /** current number of clients that have this database open. */\r\n readonly nClient: number;\r\n /** current number of ongoing prefetches on this database. */\r\n readonly nPrefetch: number;\r\n }\r\n\r\n /** Filter options passed to CloudContainer.queryHttpLog\r\n * @internal\r\n */\r\n export interface BcvHttpLogFilterOptions {\r\n /** only return rows whose ID is >= the provided id */\r\n startFromId?: number;\r\n /** only return rows whose endTime is null OR >= the provided endTime. */\r\n finishedAtOrAfterTime?: string;\r\n /** only return rows with a non-null end_time. */\r\n showOnlyFinished?: boolean;\r\n }\r\n\r\n /** Returned from 'CloudContainer.queryHttpLog' describing a row in the bcv_http_log table.\r\n * @internal\r\n */\r\n export interface BcvHttpLog {\r\n /** Unique, monotonically increasing id value */\r\n readonly id: number;\r\n /** Time request was made, as iso-8601 */\r\n readonly startTime: string;\r\n /** Time reply received, as iso-8601 (may be undefined) */\r\n readonly endTime: string | undefined;\r\n /** \"PUT\", \"GET\", etc. */\r\n readonly method: string;\r\n /** LogId of client that caused this request. Will be \"prefetch\" for prefetch requests. */\r\n readonly logId: string;\r\n /** Log message associated with request */\r\n readonly logmsg: string;\r\n /** URI of request */\r\n readonly uri: string;\r\n /** HTTP response code (e.g. 200) */\r\n readonly httpcode: number;\r\n }\r\n\r\n /** Filter options passed to 'CloudContainer.queryBcvStats'\r\n * @internal\r\n */\r\n interface BcvStatsFilterOptions {\r\n /** if true, adds activeClients, totalClients, ongoingPrefetches, and attachedContainers to the result. */\r\n addClientInformation?: boolean;\r\n }\r\n\r\n /** Returned from 'CloudContainer.queryBcvStats' describing the rows in the bcv_stat table.\r\n * Also gathers additional statistics using the other virtual tables bcv_container, bcv_database such as totalClients, ongoingPrefetches, activeClients and attachedContainers.\r\n * @internal\r\n */\r\n export interface BcvStats {\r\n /** The total number of cache slots that are currently in use or 'locked' by ongoing client read transactions. In daemonless mode, this value is always 0.\r\n * A locked cache slot implies that it is not eligible for eviction in the event of a full cachefile.\r\n */\r\n readonly lockedCacheslots: number;\r\n /** The current number of slots with data in them in the cache. */\r\n readonly populatedCacheslots: number;\r\n /** The configured size of the cache, in number of slots. */\r\n readonly totalCacheslots: number;\r\n /** The total number of clients opened on this cache */\r\n readonly totalClients?: number;\r\n /** The total number of ongoing prefetches on this cache */\r\n readonly ongoingPrefetches?: number;\r\n /** The total number of active clients on this cache. An active client is one which has an open read txn. */\r\n readonly activeClients?: number;\r\n /** The total number of attached containers on this cache. */\r\n readonly attachedContainers?: number;\r\n }\r\n\r\n /** The name of a CloudSqlite database within a CloudContainer. */\r\n export interface DbNameProp {\r\n /** the name of the database within the CloudContainer.\r\n * @note names of databases within a CloudContainer are always **case sensitive** on all platforms.*/\r\n dbName: string;\r\n }\r\n\r\n /** Properties for accessing a database within a CloudContainer */\r\n export interface DbProps extends DbNameProp {\r\n /** the name of the local file to access the database. */\r\n localFileName: LocalFileName;\r\n }\r\n\r\n export type TransferDirection = \"upload\" | \"download\";\r\n export interface TransferProgress {\r\n /** a user-supplied progress function called during the transfer operation. Return a non-0 value to abort the transfer. */\r\n onProgress?: (loaded: number, total: number) => number;\r\n }\r\n\r\n export interface CloudHttpProps {\r\n /** The number of simultaneous HTTP requests. Default is 6. */\r\n nRequests?: number;\r\n }\r\n\r\n export interface PrefetchProps extends CloudHttpProps {\r\n /** timeout between requests, in milliseconds. Default is 100. */\r\n timeout?: number;\r\n /** The number of prefetch requests to issue while there is foreground activity. Default is 3. */\r\n minRequests?: number;\r\n }\r\n\r\n export type TransferDbProps = DbProps & TransferProgress & CloudHttpProps;\r\n\r\n /** Properties for creating a CloudCache. */\r\n export interface CacheProps extends CloudHttpProps {\r\n /** full path of directory for cache to store its files. Must be on a (preferably fast) local drive, and must be empty when the cache is first created. */\r\n rootDir: string;\r\n /** name of this cache. It is possible to have more than one CloudCache in the same session, but each must have a unique name. */\r\n name: string;\r\n /** maximum cache Size. Must be a number followed by either M (for megabytes) or G (for gigabytes.) Default is 1G */\r\n cacheSize?: string;\r\n /** turn on diagnostics for `curl` (outputs to stderr) */\r\n curlDiagnostics?: boolean;\r\n }\r\n\r\n /** Parameters used to obtain the write lock on a cloud container */\r\n export interface ObtainLockParams {\r\n /** a string that identifies me to others if I hold the lock while they attempt to acquire it. */\r\n user?: string;\r\n /** number of times to retry in the event the lock currently held by someone else.\r\n * After this number of attempts, `onFailure` is called. Default is 20.\r\n */\r\n nRetries: number;\r\n /** Delay between retries, in milliseconds. Default is 100. */\r\n retryDelayMs: number;\r\n /** function called if lock cannot be obtained after all retries. It is called with the name of the user currently holding the lock and\r\n * generally is expected that the user will be consulted whether to wait further.\r\n * If this function returns \"stop\", an exception will be thrown. Otherwise the retry cycle is restarted.\r\n */\r\n onFailure?: WriteLockBusyHandler;\r\n }\r\n\r\n /** @internal */\r\n export interface LockAndOpenArgs extends SQLiteDb.WithOpenDbArgs {\r\n /** a string that identifies me to others if I hold the lock while they attempt to acquire it. */\r\n user: string;\r\n /** the name of the database within the container */\r\n dbName: string;\r\n /** the CloudContainer on which the operation will be performed */\r\n container: CloudContainer;\r\n /** if present, function called when the write lock is currently held by another user. */\r\n busyHandler?: WriteLockBusyHandler;\r\n /** if present, open mode for Db. Default is ReadWrite */\r\n openMode?: OpenMode;\r\n }\r\n\r\n /** Logging categories for `CloudCache.setLogMask` */\r\n export enum LoggingMask {\r\n /** log all HTTP requests and responses */\r\n HTTP = 0x01,\r\n /** log as blocks become dirty and must be uploaded */\r\n DirtyBlocks = 0x02,\r\n /** log as blocks are added to the delete list */\r\n AddToDelete = 0x04,\r\n /** log container lifecycle events (e.g. authorization requests, disconnects, and state transitions) */\r\n LifecycleEvents = 0x08,\r\n /** Turn on all logging categories */\r\n All = 0xff,\r\n /** Disable logging */\r\n None = 0,\r\n }\r\n\r\n /**\r\n * A local cache for storing data downloaded from many CloudSqlite databases. This object refers to a directory on the local filesystem\r\n * and is used to **connect** CloudContainers so they may be accessed. It maintains the state of the local copy of\r\n * the downloaded data from SQLiteDbs in CloudContainers across sessions.\r\n *\r\n * Notes:\r\n * - CloudCaches have a name, used internally by CloudSqlite, that must be unique. CloudCaches are created and maintained via [[CloudCaches.getCache]].\r\n * - All CloudContainers connected to a given CloudCache must have the same block size, as determined by the first CloudContainer connected.\r\n * - they have a maximum size that limits the amount of disk space they can consume. When the maximum size of a CloudCache is reached,\r\n * the least recently used blocks are removed to make room for new blocks.\r\n * - CloudCaches may only be used by a single process at a time. An exception is thrown if you attempt to access a CloudCache from a\r\n * second process if it is already in use by another process. Note: for a readonly CloudCache, a \"daemon\" process can be used to\r\n * share a CloudCache across processes. See its documentation for details.\r\n * - Generally, it is expected that there only be a few CloudCaches and they be shared by all applications. Each CloudCache can consume\r\n * its maximum disk space, so controlling system-wide disk usage is complicated. The only reason to make a new CloudCache is either\r\n * for containers with a different block size, or to purposely control local disk space usage for a specific set of containers.\r\n * - The contents of the cache directory are entirely controlled by CloudSqlite and should be empty when the cache is\r\n * first created and never modified directly thereafter.\r\n */\r\n export interface CloudCache {\r\n /** `true` if this CloudCache is connected to a daemon process */\r\n get isDaemon(): boolean;\r\n /** The name for this CloudCache. */\r\n get name(): string;\r\n /** The root directory of this CloudCache on a local drive. */\r\n get rootDir(): LocalDirName;\r\n /** A guid for this CloudCache. It is assigned when the CloudCache is first created and used for acquiring write locks. */\r\n get guid(): GuidString;\r\n /** Configure logging for this CloudCache.\r\n * @param mask A bitmask of `LoggingMask` values\r\n * @note this method does nothing if [[isDaemon]] is true. Daemon logging is configured when the daemon is started.\r\n * @note HTTP logging can be happen on multiple threads and may be buffered. To see buffered log messages, periodically call\r\n * `[[IModelHost.flushLog]]\r\n */\r\n setLogMask(mask: number): void;\r\n /**\r\n * destroy this CloudCache to end this session. All currently connected CloudContainers are disconnected first.\r\n * @note this does *not* delete the local directory. Its contents are maintained so it can be used in future sessions.\r\n * @note this function is automatically called on [[IModelHost.shutdown]], so it is only called directly for tests.\r\n * @internal\r\n */\r\n destroy(): void;\r\n }\r\n\r\n export interface CleanDeletedBlocksOptions {\r\n /**\r\n * Any block that was marked as unused before this number of seconds ago will be deleted. Specifying a non-zero\r\n * value gives a period of time for other clients to refresh their manifests and stop using the now-garbage blocks. Otherwise they may get\r\n * a 404 error. Default is 1 hour.\r\n */\r\n nSeconds?: number;\r\n /** if enabled, outputs verbose logs about the cleanup process. Output includes blocks determined eligible for deletion.\r\n * @default false\r\n */\r\n debugLogging?: boolean;\r\n /** If true, iterates over all blobs in the cloud container to add blocks that are 'orphaned' to the delete list in the manifest.\r\n * Orphaned blocks are created when a client abruptly halts, is disconnected, or encounters an error while uploading a change.\r\n * If false, the search for 'orphaned' blocks is skipped and only any blocks which are already on the delete list are deleted.\r\n * @default true\r\n */\r\n findOrphanedBlocks?: boolean;\r\n /**\r\n * a user-supplied progress function called during the cleanup operation. While the search for orphaned blocks occurs, nDeleted will be 0 and nTotalToDelete will be 1.\r\n * Once the search is complete and orphaned blocks begin being deleted, nDeleted will be the number of blocks deleted and nTotalToDelete will be the total number of blocks to delete.\r\n * If the return value is 1, the job will be cancelled and progress will be saved. If one or more blocks have already been deleted, then a new manifest file is uploaded saving the progress of the delete job.\r\n * Return any other non-0 value to cancel the job without saving progress.\r\n */\r\n onProgress?: (nDeleted: number, nTotalToDelete: number) => Promise<number>;\r\n }\r\n\r\n /**\r\n * A CloudSqlite container that may be connected to a CloudCache. A CloudContainer maps a container in a cloud blob-storage\r\n * account to a local cache, so that the contents of a database in the container may be accessed as if it were a local file.\r\n *\r\n * Notes:\r\n * - all methods and accessors of this interface (other than `initializeContainer`) require that the `connect` method be successfully called first.\r\n * Otherwise they will throw an exception or return meaningless values.\r\n * - before a SQLiteDb in a container may be opened for write access, the container's write lock must be held (see [[acquireWriteLock]].)\r\n * - a single CloudContainer may hold more than one SQLiteDb, but often they are 1:1.\r\n * - the write lock is per-Container, not per-SQLiteDb (which is the reason they are often 1:1)\r\n * - the accessToken (a SAS key) member provides time limited, restricted, access to the container. It must be refreshed before it expires.\r\n * - when a CloudContainer is created, it may either be readonly or writeable. If a container is never meant to be used for writes,\r\n * it is slightly more efficient to indicate that by passing `writeable: false`\r\n */\r\n export interface CloudContainer {\r\n onConnect?: (container: CloudContainer, cache: CloudCache) => void;\r\n onConnected?: (container: CloudContainer) => void;\r\n onDisconnect?: (container: CloudContainer, detach: boolean) => void;\r\n onDisconnected?: (container: CloudContainer, detach: boolean) => void;\r\n\r\n readonly cache?: CloudCache;\r\n /** the baseUri of this container */\r\n get baseUri(): string;\r\n /** the storageType of this container */\r\n get storageType(): string;\r\n /** The ContainerId within a storage account. */\r\n get containerId(): string;\r\n /** The *alias* to identify this CloudContainer in a CloudCache. Usually just the ContainerId. */\r\n get alias(): string;\r\n /** The logId. */\r\n get logId(): string;\r\n /** The time that the write lock expires. Of the form 'YYYY-MM-DDTHH:MM:SS.000Z' in UTC.\r\n * Returns empty string if write lock is not held.\r\n */\r\n get writeLockExpires(): string;\r\n /** true if this CloudContainer is currently connected to a CloudCache via the `connect` method. */\r\n get isConnected(): boolean;\r\n /** true if this CloudContainer was created with the `writeable` flag (and its `accessToken` supplies write access). */\r\n get isWriteable(): boolean;\r\n /** true if this container is public (doesn't require authorization ). */\r\n get isPublic(): boolean;\r\n /** true if this CloudContainer currently holds the write lock for its container in the cloud. */\r\n get hasWriteLock(): boolean;\r\n /** true if this CloudContainer has local changes that have not be uploaded to its container in the cloud. */\r\n get hasLocalChanges(): boolean;\r\n /** The current accessToken providing access to the cloud container */\r\n get accessToken(): string;\r\n set accessToken(val: string);\r\n /** Get the number of garbage blocks in this container that can be purged. */\r\n get garbageBlocks(): number;\r\n /** The block size for this CloudContainer. */\r\n get blockSize(): number;\r\n\r\n /**\r\n * initialize a cloud blob-store container to be used as a new CloudContainer. This creates the container's manifest of its contents, and should be\r\n * performed on an empty container. If an existing manifest is present, it is destroyed and a new one is created (essentially emptying the container.)\r\n */\r\n initializeContainer(args: { checksumBlockNames?: boolean, blockSize: number }): void;\r\n\r\n /**\r\n * Connect this CloudContainer to a CloudCache for accessing and/or modifying its contents.\r\n * @note A CloudCache is a local directory holding copies of information from the cloud. It is persistent across sessions,\r\n * but this method must be called each session to (re)establish the connection to the CloudCache. If the CloudCache was previously populated,\r\n * this method may be called and will succeed *even when offline* or without a valid `accessToken`.\r\n */\r\n connect(cache: CloudCache): void;\r\n\r\n /**\r\n * Attempt to acquire the write lock for this CloudContainer. For this to succeed:\r\n * 1. it must be connected to a `CloudCache`\r\n * 2. this CloudContainer must have been constructed with `writeable: true`\r\n * 3. the `accessToken` must authorize write access\r\n * 4. no other process may be holding an unexpired write lock\r\n * @throws if any of the above conditions fail\r\n * @note Write locks *expire* after the duration specified in the `durationSeconds` property of the constructor argument, in case a process\r\n * crashes or otherwise fails to release the lock. Calling `acquireWriteLock` with the lock already held resets the lock duration from the current time,\r\n * so long running processes should call this method periodically to ensure their lock doesn't expire (they should also make sure their accessToken is refreshed\r\n * before it expires.)\r\n * @note on success, the container is synchronized with its contents in the cloud before the promise resolves.\r\n * @param user An identifier of the process/user locking the CloudContainer. In the event of a write lock\r\n * collision, this string will be included in the exception string of the *other* process attempting to obtain a write lock so that users may identify who currently holds\r\n * the lock.\r\n */\r\n acquireWriteLock(user: string): void;\r\n\r\n /**\r\n * Release the write lock if it is currently held.\r\n *\r\n * Notes:\r\n * - if there are local changes that have not been uploaded, they are automatically uploaded before the write lock is released.\r\n * - if the write lock is not held, this method does nothing.\r\n */\r\n releaseWriteLock(): void;\r\n\r\n /**\r\n * Destroy any currently valid write lock from this or any other process. This is obviously very dangerous and defeats the purpose of write locking.\r\n * This method exists only for administrator tools to clear a failed process without waiting for the expiration period. It can also be useful for tests.\r\n * For this to succeed, all of the conditions of `acquireWriteLock` must be true other than #4.\r\n */\r\n clearWriteLock(): void;\r\n\r\n /**\r\n * Abandon any local changes in this container. If the write lock is currently held, it is released.\r\n * This function fails with BE_SQLITE_BUSY if there are any open read or write transactions on *any* database in the container.\r\n */\r\n abandonChanges(): void;\r\n\r\n /**\r\n * Disconnect this CloudContainer from its CloudCache. There must be no open databases from this container. Leaves the container's contents in the\r\n * CloudCache so it is available for future sessions.\r\n * @note This function does nothing (and does not throw) if the CloudContainer is not connected to a CloudCache.\r\n */\r\n disconnect(args?: {\r\n /** if true removes the container from the CloudCache, otherwise Leaves the container in the CloudCache so it is available for future sessions. */\r\n detach?: boolean;\r\n }): void;\r\n\r\n /**\r\n * Poll cloud storage for changes from other processes.\r\n *\r\n * Notes:\r\n * - no changes made by other processes are visible to this CloudContainer unless/until this method is called.\r\n * - note this is automatically called whenever the write lock is obtained to ensure all changes are against the latest version.\r\n */\r\n checkForChanges(): void;\r\n\r\n /**\r\n * Upload any changed blocks from the databases in this CloudContainer.\r\n * @note this is called automatically from `releaseWriteLock` before the write lock is released. It is only necessary to call this directly if you\r\n * wish to upload changes while the write lock is still held.\r\n * @see hasLocalChanges\r\n */\r\n uploadChanges(): Promise<void>;\r\n\r\n /**\r\n * Create a copy of an existing database within this CloudContainer with a new name.\r\n * @note CloudSqlite uses copy-on-write semantics for this operation. That is, this method merely makes a\r\n * new entry in the manifest with the new name that *shares* all of its blocks with the original database.\r\n * If either database subsequently changes, the only modified blocks are not shared.\r\n */\r\n copyDatabase(dbName: string, toAlias: string): Promise<void>;\r\n\r\n /** Remove a database from this CloudContainer. Unused blocks are moved to the delete list in the manifest.\r\n * @see [[CloudSqlite.cleanDeletedBlocks]] to actually delete the blocks from the delete list.\r\n */\r\n deleteDatabase(dbName: string): Promise<void>;\r\n\r\n /** Get the list of database names in this CloudContainer.\r\n * @param globArg if present, filter the results with SQLite [GLOB](https://www.sqlite.org/lang_expr.html#glob) operator.\r\n */\r\n queryDatabases(globArg?: string): string[];\r\n\r\n /**\r\n * Get the status of a specific database in this CloudContainer.\r\n * @param dbName the name of the database of interest\r\n */\r\n queryDatabase(dbName: string): CachedDbProps | undefined;\r\n\r\n /**\r\n * query the bcv_http_log table\r\n * @note the bcv_http_log table contains one row for each HTTP request made by the VFS or connected daemon.\r\n * @note Entries are automatically removed from the table on a FIFO basis. By default entries which are 1 hr old will be removed.\r\n * @internal\r\n */\r\n queryHttpLog(filterOptions?: BcvHttpLogFilterOptions): CloudSqlite.BcvHttpLog[];\r\n\r\n /**\r\n * query the bcv_stat table.\r\n * @internal\r\n */\r\n queryBcvStats(filterOptions?: BcvStatsFilterOptions): CloudSqlite.BcvStats;\r\n\r\n /**\r\n * Get the SHA1 hash of the content of a database.\r\n * @param dbName the name of the database of interest\r\n * @note the hash will be empty if the database does not exist\r\n */\r\n queryDatabaseHash(dbName: string): string;\r\n }\r\n\r\n /**\r\n * Object returned by [[CloudSqlite.startCloudPrefetch]].\r\n * It holds a promise that is fulfilled when a Prefetch is completed. May also be used to cancel an in-progress prefetch.\r\n */\r\n export interface CloudPrefetch {\r\n readonly cloudContainer: CloudContainer;\r\n readonly dbName: string;\r\n\r\n /** Cancel a currently pending prefetch. The promise will be resolved immediately after this call. */\r\n cancel(): void;\r\n\r\n /**\r\n * Promise that is resolved when the prefetch completes or is cancelled. Await this promise to ensure that the\r\n * database has been fully downloaded before going offline, for example.\r\n *\r\n * Notes:\r\n * - resolves to `true` if the prefetch completed and the entire database is local, or `false` if it was aborted or failed.\r\n * - it is *not* rejected on `cancel`. Some progress may (or may not) have been made by the request.\r\n * - To monitor the progress being made during prefetch, call `CloudContainer.queryDatabase` periodically.\r\n */\r\n promise: Promise<boolean>;\r\n }\r\n\r\n /**\r\n * Clean any unused deleted blocks from cloud storage. Unused deleted blocks can accumulate in cloud storage in a couple of ways:\r\n * 1) When a database is updated, a subset of its blocks are replaced by new versions, sometimes leaving the originals unused.\r\n * 2) A database is deleted with [[CloudContainer.deleteDatabase]]\r\n * In both cases, the blocks are not deleted immediately. Instead, they are scheduled for deletion at some later time.\r\n * Calling this method deletes all blocks in the cloud container for which the scheduled deletion time has passed.\r\n * @param container the CloudContainer to be cleaned. Must be connected and hold the write lock.\r\n * @param options options for the cleanup operation. @see CloudSqlite.CleanDeletedBlocksOptions\r\n */\r\n export async function cleanDeletedBlocks(container: CloudContainer, options: CleanDeletedBlocksOptions): Promise<void> {\r\n let timer: NodeJS.Timeout | undefined;\r\n try {\r\n const cleanJob = new NativeLibrary.nativeLib.CancellableCloudSqliteJob(\"cleanup\", container, options);\r\n let total = 0;\r\n const onProgress = options?.onProgress;\r\n if (onProgress) {\r\n timer = setInterval(async () => { // set an interval timer to show progress every 250ms\r\n const progress = cleanJob.getProgress();\r\n total = progress.total;\r\n const result = await onProgress(progress.loaded, progress.total);\r\n if (result === 1)\r\n cleanJob.stopAndSaveProgress();\r\n else if (result !== 0)\r\n cleanJob.cancelTransfer();\r\n }, 250);\r\n }\r\n await cleanJob.promise;\r\n await onProgress?.(total, total); // make sure we call progress func one last time when download completes\r\n container.checkForChanges(); // re-read the manifest so the number of garbage blocks is updated.\r\n } catch (err: any) {\r\n if (err.message === \"cancelled\")\r\n err.errorNumber = BriefcaseStatus.DownloadCancelled;\r\n\r\n throw err;\r\n } finally {\r\n if (timer)\r\n clearInterval(timer);\r\n }\r\n }\r\n\r\n /** @internal */\r\n export async function transferDb(direction: TransferDirection, container: CloudContainer, props: TransferDbProps) {\r\n if (direction === \"download\")\r\n mkdirSync(dirname(props.localFileName), { recursive: true }); // make sure the directory exists before starting download\r\n\r\n let timer: NodeJS.Timeout | undefined;\r\n try {\r\n const transfer = new NativeLibrary.nativeLib.CancellableCloudSqliteJob(direction, container, props);\r\n let total = 0;\r\n const onProgress = props.onProgress;\r\n if (onProgress) {\r\n timer = setInterval(async () => { // set an interval timer to show progress every 250ms\r\n const progress = transfer.getProgress();\r\n total = progress.total;\r\n if (onProgress(progress.loaded, progress.total))\r\n transfer.cancelTransfer();\r\n }, 250);\r\n }\r\n await transfer.promise;\r\n onProgress?.(total, total); // make sure we call progress func one last time when download completes\r\n } catch (err: any) {\r\n if (err.message === \"cancelled\")\r\n err.errorNumber = BriefcaseStatus.DownloadCancelled;\r\n\r\n throw err;\r\n } finally {\r\n if (timer)\r\n clearInterval(timer);\r\n\r\n }\r\n }\r\n\r\n /** Upload a local SQLite database file into a CloudContainer.\r\n * @param container the CloudContainer holding the database. Must be connected.\r\n * @param props the properties that describe the database to be downloaded, plus optionally an `onProgress` function.\r\n * @note this function requires that the write lock be held on the container\r\n */\r\n export async function uploadDb(container: CloudContainer, props: TransferDbProps): Promise<void> {\r\n await transferDb(\"upload\", container, props);\r\n container.checkForChanges(); // re-read the manifest so the database is available locally.\r\n }\r\n\r\n /** Download a database from a CloudContainer.\r\n * @param container the CloudContainer holding the database. Must be connected.\r\n * @param props the properties that describe the database to be downloaded, plus optionally an `onProgress` function.\r\n * @returns a Promise that is resolved when the download completes.\r\n * @note the download is \"restartable.\" If the transfer is aborted and then re-requested, it will continue from where\r\n * it left off rather than re-downloading the entire file.\r\n */\r\n export async function downloadDb(container: CloudContainer, props: TransferDbProps): Promise<void> {\r\n await transferDb(\"download\", container, props);\r\n }\r\n\r\n /** Optional method to be called when an attempt to acquire the write lock fails because another user currently holds it.\r\n * @param lockedBy The identifier supplied by the application/user that currently holds the lock.\r\n * @param expires a stringified Date (in local time) indicating when the lock will expire.\r\n * @return \"stop\" to give up and stop retrying. Generally, it's a good idea to wait for some time before returning.\r\n */\r\n export type WriteLockBusyHandler = (lockedBy: string, expires: string) => Promise<void | \"stop\">;\r\n\r\n /**\r\n * Attempt to acquire the write lock for a container, with retries.\r\n * If write lock is held by another user, call busyHandler if supplied. If no busyHandler, or handler returns \"stop\", throw. Otherwise try again.\r\n * @note if write lock is already held by the same user, this function will refresh the write lock's expiry time.\r\n * @param user the name to be displayed to other users in the event they attempt to obtain the lock while it is held by us\r\n * @param container the CloudContainer for which the lock is to be acquired\r\n * @param busyHandler if present, function called when the write lock is currently held by another user.\r\n * @throws if [[container]] is not connected to a CloudCache.\r\n */\r\n export async function acquireWriteLock(args: { user: string, container: CloudContainer, busyHandler?: WriteLockBusyHandler }) {\r\n const container = args.container as CloudContainerInternal;\r\n while (true) {\r\n try {\r\n if (container.hasWriteLock) {\r\n if (container.writeLockHeldBy === args.user) {\r\n return container.acquireWriteLock(args.user); // refresh the write lock's expiry time.\r\n }\r\n const err = new Error() as any; // lock held by another user within this process\r\n err.errorNumber = 5;\r\n err.lockedBy = container.writeLockHeldBy;\r\n err.expires = container.writeLockExpires;\r\n throw err;\r\n }\r\n return container.acquireWriteLock(args.user);\r\n\r\n } catch (e: any) {\r\n if (e.errorNumber === 5 && args.busyHandler && \"stop\" !== await args.busyHandler(e.lockedBy, e.expires)) // 5 === BE_SQLITE_BUSY\r\n continue; // busy handler wants to try again\r\n throw e;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Perform an asynchronous write operation on a CloudContainer with the write lock held.\r\n * 1. if write lock is already held by the current user, refresh write lock's expiry time, call operation and return.\r\n * 2. attempt to acquire the write lock, with retries. Throw if unable to obtain write lock.\r\n * 3. perform the operation\r\n * 3.a if the operation throws, abandon all changes and re-throw\r\n * 4. release the write lock.\r\n * 5. return value from operation\r\n * @param user the name to be displayed to other users in the event they attempt to obtain the lock while it is held by us\r\n * @param container the CloudContainer for which the lock is to be acquired\r\n * @param operation an asynchronous operation performed with the write lock held.\r\n * @param busyHandler if present, function called when the write lock is currently held by another user.\r\n * @returns a Promise with the result of `operation`\r\n */\r\n export async function withWriteLock<T>(args: { user: string, container: CloudContainer, busyHandler?: WriteLockBusyHandler }, operation: () => Promise<T>): Promise<T> {\r\n await acquireWriteLock(args);\r\n const containerInternal = args.container as CloudContainerInternal;\r\n try {\r\n if (containerInternal.writeLockHeldBy === args.user) // If the user already had the write lock, then don't release it.\r\n return await operation();\r\n containerInternal.writeLockHeldBy = args.user;\r\n const val = await operation(); // wait for work to finish or fail\r\n containerInternal.releaseWriteLock();\r\n containerInternal.writeLockHeldBy = undefined;\r\n return val;\r\n } catch (e) {\r\n args.container.abandonChanges(); // if operation threw, abandon all changes\r\n containerInternal.writeLockHeldBy = undefined;\r\n throw e;\r\n }\r\n }\r\n\r\n /** Arguments to create or find a CloudCache */\r\n export interface CreateCloudCacheArg {\r\n /** The name of the CloudCache. CloudCache names must be unique. */\r\n cacheName: string;\r\n /** A string that specifies the maximum size of the CloudCache. It should be a number followed by \"K\",\r\n * \"M\" \"G\", or \"T\". Default is \"10G\". */\r\n cacheSize?: string;\r\n /** A local directory in temporary storage for the CloudCache. If not supplied, it is a subdirectory called `cacheName`\r\n * in the `CloudCaches` temporary directory.\r\n * If the directory does not exist, it is created. */\r\n cacheDir?: string;\r\n }\r\n\r\n /** The collection of currently extant `CloudCache`s, by name. */\r\n export class CloudCaches {\r\n private static readonly cloudCaches = new Map<string, CloudCache>();\r\n\r\n /** create a new CloudCache */\r\n private static makeCache(args: CreateCloudCacheArg): CloudCache {\r\n const cacheName = args.cacheName;\r\n const rootDir = args.cacheDir ?? join(IModelHost.profileDir, \"CloudCaches\", cacheName);\r\n IModelJsFs.recursiveMkDirSync(rootDir);\r\n const cache = new NativeLibrary.nativeLib.CloudCache({ rootDir, name: cacheName, cacheSize: args.cacheSize ?? \"10G\" });\r\n if (Logger.getLevel(\"CloudSqlite\") === LogLevel.Trace) {\r\n cache.setLogMask(CloudSqlite.LoggingMask.All);\r\n }\r\n this.cloudCaches.set(cacheName, cache);\r\n return cache;\r\n }\r\n\r\n /** find a CloudCache by name, if it exists */\r\n public static findCache(cacheName: string): CloudCache | undefined {\r\n return this.cloudCaches.get(cacheName);\r\n }\r\n /** @internal */\r\n public static dropCache(cacheName: string): CloudCache | undefined {\r\n const cache = this.cloudCaches.get(cacheName);\r\n this.cloudCaches.delete(cacheName);\r\n return cache;\r\n }\r\n /** called by IModelHost after shutdown.\r\n * @internal\r\n */\r\n public static destroy() {\r\n this.cloudCaches.forEach((cache) => cache.destroy());\r\n this.cloudCaches.clear();\r\n }\r\n\r\n /** Get a CloudCache by name. If the CloudCache doesn't yet exist, it is created. */\r\n public static getCache(args: CreateCloudCacheArg): CloudCache {\r\n return this.cloudCaches.get(args.cacheName) ?? this.makeCache(args);\r\n }\r\n }\r\n\r\n /** Class that provides convenient local access to a SQLite database in a CloudContainer. */\r\n export class DbAccess<DbType extends VersionedSqliteDb, ReadMethods = DbType, WriteMethods = DbType> {\r\n /** The name of the database within the cloud container. */\r\n public readonly dbName: string;\r\n /** Parameters for obtaining the write lock for this container. */\r\n public readonly lockParams: ObtainLockParams = {\r\n user: \"\",\r\n nRetries: 20,\r\n retryDelayMs: 100,\r\n };\r\n protected static _cacheName = \"default-64k\";\r\n protected _container: CloudContainer;\r\n protected _cloudDb: DbType;\r\n private _writeLockProxy?: PickAsyncMethods<WriteMethods>;\r\n private _readerProxy?: PickMethods<ReadMethods>;\r\n private get _ctor() { return this.constructor as typeof DbAccess; }\r\n\r\n /** @internal */\r\n public static getCacheForClass() {\r\n return CloudCaches.getCache({ cacheName: this._cacheName });\r\n }\r\n private _cache?: CloudCache;\r\n /** only for tests\r\n * @internal\r\n */\r\n public setCache(cache: CloudCache) {\r\n this._cache = cache;\r\n }\r\n /** @internal */\r\n public getCache(): CloudCache {\r\n return this._cache ??= this._ctor.getCacheForClass();\r\n }\r\n /** @internal */\r\n public getCloudDb(): DbType {\r\n return this._cloudDb;\r\n }\r\n\r\n /**\r\n * The token that grants access to the cloud container for this DbAccess. If it does not grant write permissions, all\r\n * write operations will fail. It should be refreshed (via a timer) before it expires.\r\n */\r\n public get sasToken() { return this._container.accessToken; }\r\n public set sasToken(token: AccessToken) { this._container.accessToken = token; }\r\n\r\n /** the container for this DbAccess. It is automatically connected to the CloudCache whenever it is accessed. */\r\n public get container(): CloudContainer {\r\n const container = this._container;\r\n if (!container.isConnected)\r\n container.connect(this.getCache());\r\n return container;\r\n }\r\n\r\n /** Start a prefetch operation to download all the blocks for the VersionedSqliteDb */\r\n public startPrefetch(): CloudPrefetch {\r\n return startCloudPrefetch(this.container, this.dbName);\r\n }\r\n\r\n /** Create a new DbAccess for a database stored in a cloud container. */\r\n public constructor(args: {\r\n /** The Constructor for DbType. */\r\n dbType: Constructor<DbType>;\r\n /** The properties of the cloud container holding the database. */\r\n props: ContainerAccessProps;\r\n /** The name of the database within the container. */\r\n dbName: string;\r\n }) {\r\n this._container = createCloudContainer({ writeable: true, ...args.props });\r\n this._cloudDb = new args.dbType(args.props);\r\n this.dbName = args.dbName;\r\n this.lockParams.user = IModelHost.userMoniker;\r\n }\r\n\r\n /** Close the database for this DbAccess, if it is open */\r\n public closeDb() {\r\n if (this._cloudDb.isOpen)\r\n this._cloudDb.closeDb();\r\n }\r\n\r\n /** Close the database for this DbAccess if it is opened, and disconnect this `DbAccess from its CloudContainer. */\r\n public close() {\r\n this.closeDb();\r\n this._container.disconnect();\r\n }\r\n\r\n /**\r\n * Initialize a cloud container to hold VersionedSqliteDbs. The container must first be created by [[createBlobContainer]].\r\n * This function creates and uploads an empty database into the container.\r\n * @note this deletes any existing content in the container.\r\n */\r\n protected static async _initializeDb(args: { dbType: typeof VersionedSqliteDb, props: ContainerProps, dbName: string, blockSize?: \"64K\" | \"4M\" }) {\r\n const container = createCloudContainer({ ...args.props, writeable: true, accessToken: args.props.accessToken ?? await CloudSqlite.requestToken(args.props) });\r\n container.initializeContainer({ blockSize: args.blockSize === \"4M\" ? 4 * 1024 * 1024 : 64 * 1024 });\r\n container.connect(CloudCaches.getCache({ cacheName: this._cacheName }));\r\n await withWriteLock({ user: \"initialize\", container }, async () => {\r\n const localFileName = join(KnownLocations.tmpdir, \"blank.db\");\r\n args.dbType.createNewDb(localFileName, args);\r\n await transferDb(\"upload\", container, { dbName: args.dbName, localFileName });\r\n unlinkSync(localFileName);\r\n });\r\n container.disconnect({ detach: true });\r\n }\r\n\r\n /**\r\n * Create a new BlobContainer from the BlobContainer service to hold one or more VersionedSqliteDbs.\r\n * @returns A ContainerProps that describes the newly created container.\r\n * @note the current user must have administrator rights to create containers.\r\n */\r\n protected static async createBlobContainer(args: Omit<BlobContainer.CreateNewContainerProps, \"userToken\">): Promise<CloudSqlite.ContainerProps> {\r\n const service = BlobContainer.service;\r\n if (undefined === service)\r\n throw new Error(\"no BlobContainer service available\");\r\n const auth = IModelHost.authorizationClient;\r\n if (undefined === auth)\r\n throw new Error(\"no authorization client available\");\r\n\r\n const userToken = await auth.getAccessToken();\r\n const cloudContainer = await service.create({ scope: args.scope, metadata: { ...args.metadata, containerType: \"property-store\" }, userToken });\r\n return { baseUri: cloudContainer.baseUri, containerId: cloudContainer.containerId, storageType: cloudContainer.provider };\r\n }\r\n\r\n /**\r\n * Synchronize the local cache of this database with any changes by made by others.\r\n * @note This is called automatically whenever any write operation is performed on this DbAccess. It is only necessary to\r\n * call this directly if you have not changed the database recently, but wish to perform a readonly operation and want to\r\n * ensure it is up-to-date as of now.\r\n * @note There is no guarantee that the database is up-to-date even immediately after calling this method, since others\r\n * may be modifying it at any time.\r\n */\r\n public synchronizeWithCloud() {\r\n this.closeDb();\r\n this.container.checkForChanges();\r\n }\r\n\r\n /**\r\n * Ensure that the database controlled by this `DbAccess` is open for read access and return the database object.\r\n * @note if the database is already open (either for read or write), this method merely returns the database object.\r\n */\r\n public openForRead(): DbType {\r\n if (!this._cloudDb.isOpen)\r\n this._cloudDb.openDb(this.dbName, OpenMode.Readonly, this.container);\r\n return this._cloudDb;\r\n }\r\n\r\n /**\r\n * Perform an operation on this database with the lock held and the database opened for write\r\n * @param operationName the name of the operation. Only used for logging.\r\n * @param operation a function called with the lock held and the database open for write.\r\n * @returns A promise that resolves to the the return value of `operation`.\r\n * @see `SQLiteDb.withLockedContainer`\r\n * @note Most uses of `CloudSqliteDbAccess` require that the lock not be held by any operation for long. Make sure you don't\r\n * do any avoidable or time consuming work in your operation function.\r\n */\r\n public async withLockedDb<T>(args: { operationName: string, openMode?: OpenMode, user?: string }, operation: () => Promise<T>): Promise<T> {\r\n let nRetries = this.lockParams.nRetries;\r\n const cacheGuid = this.container.cache!.guid; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n const user = args.user ?? this.lockParams.user ?? cacheGuid;\r\n const timer = new StopWatch(undefined, true);\r\n const showMs = () => `(${timer.elapsed.milliseconds}ms)`;\r\n\r\n const busyHandler = async (lockedBy: string, expires: string): Promise<void | \"stop\"> => {\r\n if (--nRetries <= 0) {\r\n if (\"stop\" === await this.lockParams.onFailure?.(lockedBy, expires))\r\n return \"stop\";\r\n nRetries = this.lockParams.nRetries;\r\n }\r\n const delay = this.lockParams.retryDelayMs;\r\n logInfo(`lock retry for ${cacheGuid} after ${showMs()}, waiting ${delay}`);\r\n await BeDuration.fromMilliseconds(delay).wait();\r\n };\r\n\r\n this.closeDb(); // in case it is currently open for read.\r\n let lockObtained = false;\r\n const operationName = args.operationName;\r\n try {\r\n return await this._cloudDb.withLockedContainer({ user, dbName: this.dbName, container: this.container, busyHandler, openMode: args.openMode }, async () => {\r\n lockObtained = true;\r\n logInfo(`lock acquired by ${cacheGuid} for ${operationName} ${showMs()}`);\r\n return operation();\r\n });\r\n } finally {\r\n if (lockObtained)\r\n logInfo(`lock released by ${cacheGuid} after ${operationName} ${showMs()} `);\r\n else\r\n logError(`could not obtain lock for ${cacheGuid} to perform ${operationName} ${showMs()} `);\r\n }\r\n }\r\n\r\n /** get a method member, by name, from the database object. Throws if not a Function. */\r\n private getDbMethod(methodName: string): (...args: any[]) => any {\r\n const fn = (this._cloudDb as any)[methodName];\r\n if (typeof fn !== \"function\")\r\n throw new Error(`illegal method name ${methodName}`);\r\n return fn;\r\n }\r\n\r\n /**\r\n * A Proxy Object to call a writeable async method on the cloud database controlled by this `DbAccess`.\r\n *\r\n * Whenever a method is called through this Proxy, it will:\r\n * - attempt to acquire the write lock on the container\r\n * - open the database for write\r\n * - call the method\r\n * - close the database\r\n * - upload changes\r\n * - release the write lock.\r\n *\r\n * @see [[withLockedDb]]\r\n */\r\n public get writeLocker() {\r\n return this._writeLockProxy ??= new Proxy(this, {\r\n get(access, operationName: string) {\r\n const fn = access.getDbMethod(operationName);\r\n return async (...args: any[]) => access.withLockedDb({ operationName, user: RpcTrace.currentActivity?.user }, fn.bind(access._cloudDb, ...args));\r\n },\r\n }) as PickAsyncMethods<WriteMethods>;\r\n }\r\n\r\n /**\r\n * A Proxy Object to call a synchronous readonly method on the database controlled by this `DbAccess`.\r\n * Whenever a method is called through this Proxy, it will first ensure that the database is opened for at least read access.\r\n */\r\n public get reader() {\r\n return this._readerProxy ??= new Proxy(this, {\r\n get(access, methodName: string) {\r\n const fn = access.getDbMethod(methodName);\r\n return (...args: any[]) => fn.call(access.openForRead(), ...args);\r\n },\r\n }) as PickMethods<ReadMethods>;\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3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BAC/B,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;oBAC7C,OAAO,KAAK,EAAE,GAAG,IAAW,EAAE,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,kBAAQ,CAAC,eAAe,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;gBACnJ,CAAC;aACF,CAAmC,CAAC;QACvC,CAAC;QAED;;;WAGG;QACH,IAAW,MAAM;YACf,OAAO,IAAI,CAAC,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE;gBAC3C,GAAG,CAAC,MAAM,EAAE,UAAkB;oBAC5B,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;oBAC1C,OAAO,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;gBACpE,CAAC;aACF,CAA6B,CAAC;QACjC,CAAC;;IA1NgB,mBAAU,GAAG,aAAa,AAAhB,CAAiB;IATjC,oBAAQ,WAoOpB,CAAA;AACH,CAAC,EA7+BgB,WAAW,2BAAX,WAAW,QA6+B3B","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module SQLiteDb\r\n */\r\n\r\nimport { mkdirSync, unlinkSync } from \"fs\";\r\nimport { dirname, join } from \"path\";\r\nimport { NativeLibrary } from \"@bentley/imodeljs-native\";\r\nimport {\r\n AccessToken, BeDuration, BriefcaseStatus, Constructor, GuidString, Logger, LogLevel, OpenMode, Optional, PickAsyncMethods, PickMethods, StopWatch,\r\n} from \"@itwin/core-bentley\";\r\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\r\nimport { BlobContainer } from \"./BlobContainerService\";\r\nimport { IModelHost, KnownLocations } from \"./IModelHost\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\nimport { RpcTrace } from \"./rpc/tracing\";\r\n\r\nimport type { SQLiteDb, VersionedSqliteDb } from \"./SQLiteDb\";\r\n\r\n// spell:ignore logmsg httpcode daemonless cachefile cacheslots ddthh\r\n\r\n/**\r\n * Types for accessing SQLite databases stored in cloud containers.\r\n * @beta\r\n */\r\nexport namespace CloudSqlite {\r\n\r\n const logInfo = (msg: string) => Logger.logInfo(\"CloudSqlite\", msg);\r\n const logError = (msg: string) => Logger.logError(\"CloudSqlite\", msg);\r\n\r\n export type RequestTokenArgs = Optional<BlobContainer.RequestTokenProps, \"userToken\">;\r\n /**\r\n * Request a new AccessToken for a cloud container using the [[BlobContainer]] service.\r\n * If the service is unavailable or returns an error, an empty token is returned.\r\n */\r\n export async function requestToken(args: RequestTokenArgs): Promise<AccessToken> {\r\n // allow the userToken to be supplied via args. If not supplied, or blank, use the backend's accessToken. If that fails, use the value from the current RPC request\r\n let userToken = args.userToken ? args.userToken : await IModelHost.getAccessToken();\r\n if (userToken === \"\")\r\n userToken = RpcTrace.currentActivity?.accessToken ?? \"\";\r\n if (BlobContainer.service === undefined) {\r\n throw new Error(`BlobContainer.service is not defined`);\r\n }\r\n const response = await BlobContainer.service.requestToken({ ...args, userToken });\r\n return response?.token ?? \"\";\r\n }\r\n\r\n interface CloudContainerInternal extends CloudContainer {\r\n timer?: NodeJS.Timeout;\r\n refreshPromise?: Promise<void>;\r\n lockExpireSeconds: number;\r\n writeLockHeldBy?: string;\r\n }\r\n\r\n /**\r\n * Create a new CloudContainer from a ContainerAccessProps. For non-public containers, a valid accessToken must be provided before the container\r\n * can be used (e.g. via [[CloudSqlite.requestToken]]).\r\n * @note After the container is successfully connected to a CloudCache, it will begin auto-refreshing its accessToken every `tokenRefreshSeconds` seconds (default is 1 hour)\r\n * until it is disconnected. However, if the container is public, or if `tokenRefreshSeconds` is <=0, auto-refresh is not enabled.\r\n */\r\n export function createCloudContainer(args: ContainerAccessProps & { accessLevel?: BlobContainer.RequestAccessLevel, tokenFn?: (args: RequestTokenArgs) => Promise<AccessToken> }): CloudContainer {\r\n const container = new NativeLibrary.nativeLib.CloudContainer(args) as CloudContainerInternal;\r\n const refreshSeconds = (undefined !== args.tokenRefreshSeconds) ? args.tokenRefreshSeconds : 60 * 60; // default is 1 hour\r\n container.lockExpireSeconds = args.lockExpireSeconds ?? 60 * 60; // default is 1 hour\r\n\r\n // don't refresh tokens for public containers or if refreshSeconds<=0\r\n if (!args.isPublic && refreshSeconds > 0) {\r\n const tokenProps = { baseUri: args.baseUri, containerId: args.containerId, accessLevel: args.accessLevel };\r\n const doRefresh = async () => {\r\n let newToken: AccessToken | undefined;\r\n const url = `[${tokenProps.baseUri}/${tokenProps.containerId}]`;\r\n try {\r\n newToken = await (args.tokenFn ?? CloudSqlite.requestToken)(tokenProps);\r\n logInfo(`Refreshed token for container ${url}`);\r\n } catch (err: any) {\r\n logError(`Error refreshing token for container ${url}: ${err.message}`);\r\n }\r\n container.accessToken = newToken ?? \"\";\r\n };\r\n const tokenRefreshFn = () => {\r\n container.timer = setTimeout(async () => {\r\n container.refreshPromise = doRefresh(); // this promise is stored on the container so it can be awaited in tests\r\n await container.refreshPromise;\r\n container.refreshPromise = undefined;\r\n tokenRefreshFn(); // schedule next refresh\r\n }, refreshSeconds * 1000);\r\n };\r\n container.onConnected = tokenRefreshFn; // schedule the first refresh when the container is connected\r\n container.onDisconnect = () => { // clear the refresh timer when the container is disconnected\r\n if (container.timer !== undefined) {\r\n clearTimeout(container.timer);\r\n container.timer = undefined;\r\n }\r\n };\r\n }\r\n return container;\r\n }\r\n\r\n /** Begin prefetching all blocks for a database in a CloudContainer in the background. */\r\n export function startCloudPrefetch(container: CloudContainer, dbName: string, args?: PrefetchProps): CloudPrefetch {\r\n return new NativeLibrary.nativeLib.CloudPrefetch(container, dbName, args);\r\n }\r\n export interface ContainerProps {\r\n /** The type of storage provider. */\r\n readonly storageType: \"azure\" | \"google\";\r\n /** The base URI for the container. */\r\n readonly baseUri: string;\r\n /** The name of the container. */\r\n readonly containerId: string;\r\n /** true if the container is public (doesn't require authorization) */\r\n readonly isPublic?: boolean;\r\n /** access token for container. If not present uses `CloudSqlite.requestToken` */\r\n accessToken?: string;\r\n }\r\n\r\n /** Properties to access a CloudContainer. */\r\n export interface ContainerAccessProps extends ContainerProps {\r\n /** an alias for the container. Defaults to `containerId` */\r\n readonly alias?: string;\r\n /** SAS token that grants access to the container. */\r\n accessToken: string;\r\n /** if true, container is allowed to request the write lock. */\r\n readonly writeable?: boolean;\r\n /** if true, container is attached in \"secure\" mode (blocks are encrypted). Only supported in daemon mode. */\r\n readonly secure?: boolean;\r\n /** string attached to log messages from CloudSQLite. This is most useful for identifying usage from daemon mode. */\r\n readonly logId?: string;\r\n /** Duration for holding write lock, in seconds. After this time the write lock expires if not refreshed. Default is one hour. */\r\n readonly lockExpireSeconds?: number;\r\n /** number of seconds between auto-refresh of access token. If <=0 no auto-refresh. Default is 1 hour (60*60) */\r\n readonly tokenRefreshSeconds?: number;\r\n }\r\n\r\n /** Returned from `CloudContainer.queryDatabase` describing one database in the container */\r\n export interface CachedDbProps {\r\n /** The total number of blocks in the database. */\r\n readonly totalBlocks: number;\r\n /** the number of blocks of the database that have been downloaded into the CloudCache */\r\n readonly localBlocks: number;\r\n /** the number of blocks from this database that have been modified in the CloudCache and need to be uploaded. */\r\n readonly dirtyBlocks: number;\r\n /** If true, the database currently has transactions in the WAL file and may not be uploaded until they have been checkPointed. */\r\n readonly transactions: boolean;\r\n /** the state of this database. Indicates whether the database is new or deleted since last upload */\r\n readonly state: \"\" | \"copied\" | \"deleted\";\r\n /** current number of clients that have this database open. */\r\n readonly nClient: number;\r\n /** current number of ongoing prefetches on this database. */\r\n readonly nPrefetch: number;\r\n }\r\n\r\n /** Filter options passed to CloudContainer.queryHttpLog\r\n * @internal\r\n */\r\n export interface BcvHttpLogFilterOptions {\r\n /** only return rows whose ID is >= the provided id */\r\n startFromId?: number;\r\n /** only return rows whose endTime is null OR >= the provided endTime. */\r\n finishedAtOrAfterTime?: string;\r\n /** only return rows with a non-null end_time. */\r\n showOnlyFinished?: boolean;\r\n }\r\n\r\n /** Returned from 'CloudContainer.queryHttpLog' describing a row in the bcv_http_log table.\r\n * @internal\r\n */\r\n export interface BcvHttpLog {\r\n /** Unique, monotonically increasing id value */\r\n readonly id: number;\r\n /** Time request was made, as iso-8601 */\r\n readonly startTime: string;\r\n /** Time reply received, as iso-8601 (may be undefined) */\r\n readonly endTime: string | undefined;\r\n /** \"PUT\", \"GET\", etc. */\r\n readonly method: string;\r\n /** LogId of client that caused this request. Will be \"prefetch\" for prefetch requests. */\r\n readonly logId: string;\r\n /** Log message associated with request */\r\n readonly logmsg: string;\r\n /** URI of request */\r\n readonly uri: string;\r\n /** HTTP response code (e.g. 200) */\r\n readonly httpcode: number;\r\n }\r\n\r\n /** Filter options passed to 'CloudContainer.queryBcvStats'\r\n * @internal\r\n */\r\n interface BcvStatsFilterOptions {\r\n /** if true, adds activeClients, totalClients, ongoingPrefetches, and attachedContainers to the result. */\r\n addClientInformation?: boolean;\r\n }\r\n\r\n /** Returned from 'CloudContainer.queryBcvStats' describing the rows in the bcv_stat table.\r\n * Also gathers additional statistics using the other virtual tables bcv_container, bcv_database such as totalClients, ongoingPrefetches, activeClients and attachedContainers.\r\n * @internal\r\n */\r\n export interface BcvStats {\r\n /** The total number of cache slots that are currently in use or 'locked' by ongoing client read transactions. In daemonless mode, this value is always 0.\r\n * A locked cache slot implies that it is not eligible for eviction in the event of a full cachefile.\r\n */\r\n readonly lockedCacheslots: number;\r\n /** The current number of slots with data in them in the cache. */\r\n readonly populatedCacheslots: number;\r\n /** The configured size of the cache, in number of slots. */\r\n readonly totalCacheslots: number;\r\n /** The total number of clients opened on this cache */\r\n readonly totalClients?: number;\r\n /** The total number of ongoing prefetches on this cache */\r\n readonly ongoingPrefetches?: number;\r\n /** The total number of active clients on this cache. An active client is one which has an open read txn. */\r\n readonly activeClients?: number;\r\n /** The total number of attached containers on this cache. */\r\n readonly attachedContainers?: number;\r\n }\r\n\r\n /** The name of a CloudSqlite database within a CloudContainer. */\r\n export interface DbNameProp {\r\n /** the name of the database within the CloudContainer.\r\n * @note names of databases within a CloudContainer are always **case sensitive** on all platforms.*/\r\n dbName: string;\r\n }\r\n\r\n /** Properties for accessing a database within a CloudContainer */\r\n export interface DbProps extends DbNameProp {\r\n /** the name of the local file to access the database. */\r\n localFileName: LocalFileName;\r\n }\r\n\r\n export type TransferDirection = \"upload\" | \"download\";\r\n export interface TransferProgress {\r\n /** a user-supplied progress function called during the transfer operation. Return a non-0 value to abort the transfer. */\r\n onProgress?: (loaded: number, total: number) => number;\r\n }\r\n\r\n export interface CloudHttpProps {\r\n /** The number of simultaneous HTTP requests. Default is 6. */\r\n nRequests?: number;\r\n }\r\n\r\n export interface PrefetchProps extends CloudHttpProps {\r\n /** timeout between requests, in milliseconds. Default is 100. */\r\n timeout?: number;\r\n /** The number of prefetch requests to issue while there is foreground activity. Default is 3. */\r\n minRequests?: number;\r\n }\r\n\r\n export type TransferDbProps = DbProps & TransferProgress & CloudHttpProps;\r\n\r\n /** Properties for creating a CloudCache. */\r\n export interface CacheProps extends CloudHttpProps {\r\n /** full path of directory for cache to store its files. Must be on a (preferably fast) local drive, and must be empty when the cache is first created. */\r\n rootDir: string;\r\n /** name of this cache. It is possible to have more than one CloudCache in the same session, but each must have a unique name. */\r\n name: string;\r\n /** maximum cache Size. Must be a number followed by either M (for megabytes) or G (for gigabytes.) Default is 1G */\r\n cacheSize?: string;\r\n /** turn on diagnostics for `curl` (outputs to stderr) */\r\n curlDiagnostics?: boolean;\r\n }\r\n\r\n /** Parameters used to obtain the write lock on a cloud container */\r\n export interface ObtainLockParams {\r\n /** a string that identifies me to others if I hold the lock while they attempt to acquire it. */\r\n user?: string;\r\n /** number of times to retry in the event the lock currently held by someone else.\r\n * After this number of attempts, `onFailure` is called. Default is 20.\r\n */\r\n nRetries: number;\r\n /** Delay between retries, in milliseconds. Default is 100. */\r\n retryDelayMs: number;\r\n /** function called if lock cannot be obtained after all retries. It is called with the name of the user currently holding the lock and\r\n * generally is expected that the user will be consulted whether to wait further.\r\n * If this function returns \"stop\", an exception will be thrown. Otherwise the retry cycle is restarted.\r\n */\r\n onFailure?: WriteLockBusyHandler;\r\n }\r\n\r\n /** @internal */\r\n export interface LockAndOpenArgs extends SQLiteDb.WithOpenDbArgs {\r\n /** a string that identifies me to others if I hold the lock while they attempt to acquire it. */\r\n user: string;\r\n /** the name of the database within the container */\r\n dbName: string;\r\n /** the CloudContainer on which the operation will be performed */\r\n container: CloudContainer;\r\n /** if present, function called when the write lock is currently held by another user. */\r\n busyHandler?: WriteLockBusyHandler;\r\n /** if present, open mode for Db. Default is ReadWrite */\r\n openMode?: OpenMode;\r\n }\r\n\r\n /** Logging categories for `CloudCache.setLogMask` */\r\n export enum LoggingMask {\r\n /** log all HTTP requests and responses */\r\n HTTP = 0x01,\r\n /** log as blocks become dirty and must be uploaded */\r\n DirtyBlocks = 0x02,\r\n /** log as blocks are added to the delete list */\r\n AddToDelete = 0x04,\r\n /** log container lifecycle events (e.g. authorization requests, disconnects, and state transitions) */\r\n LifecycleEvents = 0x08,\r\n /** Turn on all logging categories */\r\n All = 0xff,\r\n /** Disable logging */\r\n None = 0,\r\n }\r\n\r\n /**\r\n * A local cache for storing data downloaded from many CloudSqlite databases. This object refers to a directory on the local filesystem\r\n * and is used to **connect** CloudContainers so they may be accessed. It maintains the state of the local copy of\r\n * the downloaded data from SQLiteDbs in CloudContainers across sessions.\r\n *\r\n * Notes:\r\n * - CloudCaches have a name, used internally by CloudSqlite, that must be unique. CloudCaches are created and maintained via [[CloudCaches.getCache]].\r\n * - All CloudContainers connected to a given CloudCache must have the same block size, as determined by the first CloudContainer connected.\r\n * - they have a maximum size that limits the amount of disk space they can consume. When the maximum size of a CloudCache is reached,\r\n * the least recently used blocks are removed to make room for new blocks.\r\n * - CloudCaches may only be used by a single process at a time. An exception is thrown if you attempt to access a CloudCache from a\r\n * second process if it is already in use by another process. Note: for a readonly CloudCache, a \"daemon\" process can be used to\r\n * share a CloudCache across processes. See its documentation for details.\r\n * - Generally, it is expected that there only be a few CloudCaches and they be shared by all applications. Each CloudCache can consume\r\n * its maximum disk space, so controlling system-wide disk usage is complicated. The only reason to make a new CloudCache is either\r\n * for containers with a different block size, or to purposely control local disk space usage for a specific set of containers.\r\n * - The contents of the cache directory are entirely controlled by CloudSqlite and should be empty when the cache is\r\n * first created and never modified directly thereafter.\r\n */\r\n export interface CloudCache {\r\n /** `true` if this CloudCache is connected to a daemon process */\r\n get isDaemon(): boolean;\r\n /** The name for this CloudCache. */\r\n get name(): string;\r\n /** The root directory of this CloudCache on a local drive. */\r\n get rootDir(): LocalDirName;\r\n /** A guid for this CloudCache. It is assigned when the CloudCache is first created and used for acquiring write locks. */\r\n get guid(): GuidString;\r\n /** Configure logging for this CloudCache.\r\n * @param mask A bitmask of `LoggingMask` values\r\n * @note this method does nothing if [[isDaemon]] is true. Daemon logging is configured when the daemon is started.\r\n * @note HTTP logging can be happen on multiple threads and may be buffered. To see buffered log messages, periodically call\r\n * `[[IModelHost.flushLog]]\r\n */\r\n setLogMask(mask: number): void;\r\n /**\r\n * destroy this CloudCache to end this session. All currently connected CloudContainers are disconnected first.\r\n * @note this does *not* delete the local directory. Its contents are maintained so it can be used in future sessions.\r\n * @note this function is automatically called on [[IModelHost.shutdown]], so it is only called directly for tests.\r\n * @internal\r\n */\r\n destroy(): void;\r\n }\r\n\r\n export interface CleanDeletedBlocksOptions {\r\n /**\r\n * Any block that was marked as unused before this number of seconds ago will be deleted. Specifying a non-zero\r\n * value gives a period of time for other clients to refresh their manifests and stop using the now-garbage blocks. Otherwise they may get\r\n * a 404 error. Default is 1 hour.\r\n */\r\n nSeconds?: number;\r\n /** if enabled, outputs verbose logs about the cleanup process. Output includes blocks determined eligible for deletion.\r\n * @default false\r\n */\r\n debugLogging?: boolean;\r\n /** If true, iterates over all blobs in the cloud container to add blocks that are 'orphaned' to the delete list in the manifest.\r\n * Orphaned blocks are created when a client abruptly halts, is disconnected, or encounters an error while uploading a change.\r\n * If false, the search for 'orphaned' blocks is skipped and only any blocks which are already on the delete list are deleted.\r\n * @default true\r\n */\r\n findOrphanedBlocks?: boolean;\r\n /**\r\n * a user-supplied progress function called during the cleanup operation. While the search for orphaned blocks occurs, nDeleted will be 0 and nTotalToDelete will be 1.\r\n * Once the search is complete and orphaned blocks begin being deleted, nDeleted will be the number of blocks deleted and nTotalToDelete will be the total number of blocks to delete.\r\n * If the return value is 1, the job will be cancelled and progress will be saved. If one or more blocks have already been deleted, then a new manifest file is uploaded saving the progress of the delete job.\r\n * Return any other non-0 value to cancel the job without saving progress.\r\n */\r\n onProgress?: (nDeleted: number, nTotalToDelete: number) => Promise<number>;\r\n }\r\n\r\n /**\r\n * A CloudSqlite container that may be connected to a CloudCache. A CloudContainer maps a container in a cloud blob-storage\r\n * account to a local cache, so that the contents of a database in the container may be accessed as if it were a local file.\r\n *\r\n * Notes:\r\n * - all methods and accessors of this interface (other than `initializeContainer`) require that the `connect` method be successfully called first.\r\n * Otherwise they will throw an exception or return meaningless values.\r\n * - before a SQLiteDb in a container may be opened for write access, the container's write lock must be held (see [[acquireWriteLock]].)\r\n * - a single CloudContainer may hold more than one SQLiteDb, but often they are 1:1.\r\n * - the write lock is per-Container, not per-SQLiteDb (which is the reason they are often 1:1)\r\n * - the accessToken (a SAS key) member provides time limited, restricted, access to the container. It must be refreshed before it expires.\r\n * - when a CloudContainer is created, it may either be readonly or writeable. If a container is never meant to be used for writes,\r\n * it is slightly more efficient to indicate that by passing `writeable: false`\r\n */\r\n export interface CloudContainer {\r\n onConnect?: (container: CloudContainer, cache: CloudCache) => void;\r\n onConnected?: (container: CloudContainer) => void;\r\n onDisconnect?: (container: CloudContainer, detach: boolean) => void;\r\n onDisconnected?: (container: CloudContainer, detach: boolean) => void;\r\n\r\n readonly cache?: CloudCache;\r\n /** the baseUri of this container */\r\n get baseUri(): string;\r\n /** the storageType of this container */\r\n get storageType(): string;\r\n /** The ContainerId within a storage account. */\r\n get containerId(): string;\r\n /** The *alias* to identify this CloudContainer in a CloudCache. Usually just the ContainerId. */\r\n get alias(): string;\r\n /** The logId. */\r\n get logId(): string;\r\n /** The time that the write lock expires. Of the form 'YYYY-MM-DDTHH:MM:SS.000Z' in UTC.\r\n * Returns empty string if write lock is not held.\r\n */\r\n get writeLockExpires(): string;\r\n /** true if this CloudContainer is currently connected to a CloudCache via the `connect` method. */\r\n get isConnected(): boolean;\r\n /** true if this CloudContainer was created with the `writeable` flag (and its `accessToken` supplies write access). */\r\n get isWriteable(): boolean;\r\n /** true if this container is public (doesn't require authorization ). */\r\n get isPublic(): boolean;\r\n /** true if this CloudContainer currently holds the write lock for its container in the cloud. */\r\n get hasWriteLock(): boolean;\r\n /** true if this CloudContainer has local changes that have not be uploaded to its container in the cloud. */\r\n get hasLocalChanges(): boolean;\r\n /** The current accessToken providing access to the cloud container */\r\n get accessToken(): string;\r\n set accessToken(val: string);\r\n /** Get the number of garbage blocks in this container that can be purged. */\r\n get garbageBlocks(): number;\r\n /** The block size for this CloudContainer. */\r\n get blockSize(): number;\r\n\r\n /**\r\n * initialize a cloud blob-store container to be used as a new CloudContainer. This creates the container's manifest of its contents, and should be\r\n * performed on an empty container. If an existing manifest is present, it is destroyed and a new one is created (essentially emptying the container.)\r\n */\r\n initializeContainer(args: { checksumBlockNames?: boolean, blockSize: number }): void;\r\n\r\n /**\r\n * Connect this CloudContainer to a CloudCache for accessing and/or modifying its contents.\r\n * @note A CloudCache is a local directory holding copies of information from the cloud. It is persistent across sessions,\r\n * but this method must be called each session to (re)establish the connection to the CloudCache. If the CloudCache was previously populated,\r\n * this method may be called and will succeed *even when offline* or without a valid `accessToken`.\r\n */\r\n connect(cache: CloudCache): void;\r\n\r\n /**\r\n * Attempt to acquire the write lock for this CloudContainer. For this to succeed:\r\n * 1. it must be connected to a `CloudCache`\r\n * 2. this CloudContainer must have been constructed with `writeable: true`\r\n * 3. the `accessToken` must authorize write access\r\n * 4. no other process may be holding an unexpired write lock\r\n * @throws if any of the above conditions fail\r\n * @note Write locks *expire* after the duration specified in the `durationSeconds` property of the constructor argument, in case a process\r\n * crashes or otherwise fails to release the lock. Calling `acquireWriteLock` with the lock already held resets the lock duration from the current time,\r\n * so long running processes should call this method periodically to ensure their lock doesn't expire (they should also make sure their accessToken is refreshed\r\n * before it expires.)\r\n * @note on success, the container is synchronized with its contents in the cloud before the promise resolves.\r\n * @param user An identifier of the process/user locking the CloudContainer. In the event of a write lock\r\n * collision, this string will be included in the exception string of the *other* process attempting to obtain a write lock so that users may identify who currently holds\r\n * the lock.\r\n */\r\n acquireWriteLock(user: string): void;\r\n\r\n /**\r\n * Release the write lock if it is currently held.\r\n *\r\n * Notes:\r\n * - if there are local changes that have not been uploaded, they are automatically uploaded before the write lock is released.\r\n * - if the write lock is not held, this method does nothing.\r\n */\r\n releaseWriteLock(): void;\r\n\r\n /**\r\n * Destroy any currently valid write lock from this or any other process. This is obviously very dangerous and defeats the purpose of write locking.\r\n * This method exists only for administrator tools to clear a failed process without waiting for the expiration period. It can also be useful for tests.\r\n * For this to succeed, all of the conditions of `acquireWriteLock` must be true other than #4.\r\n */\r\n clearWriteLock(): void;\r\n\r\n /**\r\n * Abandon any local changes in this container. If the write lock is currently held, it is released.\r\n * This function fails with BE_SQLITE_BUSY if there are any open read or write transactions on *any* database in the container.\r\n */\r\n abandonChanges(): void;\r\n\r\n /**\r\n * Disconnect this CloudContainer from its CloudCache. There must be no open databases from this container. Leaves the container's contents in the\r\n * CloudCache so it is available for future sessions.\r\n * @note This function does nothing (and does not throw) if the CloudContainer is not connected to a CloudCache.\r\n */\r\n disconnect(args?: {\r\n /** if true removes the container from the CloudCache, otherwise Leaves the container in the CloudCache so it is available for future sessions. */\r\n detach?: boolean;\r\n }): void;\r\n\r\n /**\r\n * Poll cloud storage for changes from other processes.\r\n *\r\n * Notes:\r\n * - no changes made by other processes are visible to this CloudContainer unless/until this method is called.\r\n * - note this is automatically called whenever the write lock is obtained to ensure all changes are against the latest version.\r\n */\r\n checkForChanges(): void;\r\n\r\n /**\r\n * Upload any changed blocks from the databases in this CloudContainer.\r\n * @note this is called automatically from `releaseWriteLock` before the write lock is released. It is only necessary to call this directly if you\r\n * wish to upload changes while the write lock is still held.\r\n * @see hasLocalChanges\r\n */\r\n uploadChanges(): Promise<void>;\r\n\r\n /**\r\n * Create a copy of an existing database within this CloudContainer with a new name.\r\n * @note CloudSqlite uses copy-on-write semantics for this operation. That is, this method merely makes a\r\n * new entry in the manifest with the new name that *shares* all of its blocks with the original database.\r\n * If either database subsequently changes, the only modified blocks are not shared.\r\n */\r\n copyDatabase(dbName: string, toAlias: string): Promise<void>;\r\n\r\n /** Remove a database from this CloudContainer. Unused blocks are moved to the delete list in the manifest.\r\n * @see [[CloudSqlite.cleanDeletedBlocks]] to actually delete the blocks from the delete list.\r\n */\r\n deleteDatabase(dbName: string): Promise<void>;\r\n\r\n /** Get the list of database names in this CloudContainer.\r\n * @param globArg if present, filter the results with SQLite [GLOB](https://www.sqlite.org/lang_expr.html#glob) operator.\r\n */\r\n queryDatabases(globArg?: string): string[];\r\n\r\n /**\r\n * Get the status of a specific database in this CloudContainer.\r\n * @param dbName the name of the database of interest\r\n */\r\n queryDatabase(dbName: string): CachedDbProps | undefined;\r\n\r\n /**\r\n * query the bcv_http_log table\r\n * @note the bcv_http_log table contains one row for each HTTP request made by the VFS or connected daemon.\r\n * @note Entries are automatically removed from the table on a FIFO basis. By default entries which are 1 hr old will be removed.\r\n * @internal\r\n */\r\n queryHttpLog(filterOptions?: BcvHttpLogFilterOptions): CloudSqlite.BcvHttpLog[];\r\n\r\n /**\r\n * query the bcv_stat table.\r\n * @internal\r\n */\r\n queryBcvStats(filterOptions?: BcvStatsFilterOptions): CloudSqlite.BcvStats;\r\n\r\n /**\r\n * Get the SHA1 hash of the content of a database.\r\n * @param dbName the name of the database of interest\r\n * @note the hash will be empty if the database does not exist\r\n */\r\n queryDatabaseHash(dbName: string): string;\r\n }\r\n\r\n /**\r\n * Object returned by [[CloudSqlite.startCloudPrefetch]].\r\n * It holds a promise that is fulfilled when a Prefetch is completed. May also be used to cancel an in-progress prefetch.\r\n */\r\n export interface CloudPrefetch {\r\n readonly cloudContainer: CloudContainer;\r\n readonly dbName: string;\r\n\r\n /** Cancel a currently pending prefetch. The promise will be resolved immediately after this call. */\r\n cancel(): void;\r\n\r\n /**\r\n * Promise that is resolved when the prefetch completes or is cancelled. Await this promise to ensure that the\r\n * database has been fully downloaded before going offline, for example.\r\n *\r\n * Notes:\r\n * - resolves to `true` if the prefetch completed and the entire database is local, or `false` if it was aborted or failed.\r\n * - it is *not* rejected on `cancel`. Some progress may (or may not) have been made by the request.\r\n * - To monitor the progress being made during prefetch, call `CloudContainer.queryDatabase` periodically.\r\n */\r\n promise: Promise<boolean>;\r\n }\r\n\r\n /**\r\n * Clean any unused deleted blocks from cloud storage. Unused deleted blocks can accumulate in cloud storage in a couple of ways:\r\n * 1) When a database is updated, a subset of its blocks are replaced by new versions, sometimes leaving the originals unused.\r\n * 2) A database is deleted with [[CloudContainer.deleteDatabase]]\r\n * In both cases, the blocks are not deleted immediately. Instead, they are scheduled for deletion at some later time.\r\n * Calling this method deletes all blocks in the cloud container for which the scheduled deletion time has passed.\r\n * @param container the CloudContainer to be cleaned. Must be connected and hold the write lock.\r\n * @param options options for the cleanup operation. @see CloudSqlite.CleanDeletedBlocksOptions\r\n */\r\n export async function cleanDeletedBlocks(container: CloudContainer, options: CleanDeletedBlocksOptions): Promise<void> {\r\n let timer: NodeJS.Timeout | undefined;\r\n try {\r\n const cleanJob = new NativeLibrary.nativeLib.CancellableCloudSqliteJob(\"cleanup\", container, options);\r\n let total = 0;\r\n const onProgress = options?.onProgress;\r\n if (onProgress) {\r\n timer = setInterval(async () => { // set an interval timer to show progress every 250ms\r\n const progress = cleanJob.getProgress();\r\n total = progress.total;\r\n const result = await onProgress(progress.loaded, progress.total);\r\n if (result === 1)\r\n cleanJob.stopAndSaveProgress();\r\n else if (result !== 0)\r\n cleanJob.cancelTransfer();\r\n }, 250);\r\n }\r\n await cleanJob.promise;\r\n await onProgress?.(total, total); // make sure we call progress func one last time when download completes\r\n container.checkForChanges(); // re-read the manifest so the number of garbage blocks is updated.\r\n } catch (err: any) {\r\n if (err.message === \"cancelled\")\r\n err.errorNumber = BriefcaseStatus.DownloadCancelled;\r\n\r\n throw err;\r\n } finally {\r\n if (timer)\r\n clearInterval(timer);\r\n }\r\n }\r\n\r\n /** @internal */\r\n export async function transferDb(direction: TransferDirection, container: CloudContainer, props: TransferDbProps) {\r\n if (direction === \"download\")\r\n mkdirSync(dirname(props.localFileName), { recursive: true }); // make sure the directory exists before starting download\r\n\r\n let timer: NodeJS.Timeout | undefined;\r\n try {\r\n const transfer = new NativeLibrary.nativeLib.CancellableCloudSqliteJob(direction, container, props);\r\n let total = 0;\r\n const onProgress = props.onProgress;\r\n if (onProgress) {\r\n timer = setInterval(async () => { // set an interval timer to show progress every 250ms\r\n const progress = transfer.getProgress();\r\n total = progress.total;\r\n if (onProgress(progress.loaded, progress.total))\r\n transfer.cancelTransfer();\r\n }, 250);\r\n }\r\n await transfer.promise;\r\n onProgress?.(total, total); // make sure we call progress func one last time when download completes\r\n } catch (err: any) {\r\n if (err.message === \"cancelled\")\r\n err.errorNumber = BriefcaseStatus.DownloadCancelled;\r\n\r\n throw err;\r\n } finally {\r\n if (timer)\r\n clearInterval(timer);\r\n\r\n }\r\n }\r\n\r\n /** Upload a local SQLite database file into a CloudContainer.\r\n * @param container the CloudContainer holding the database. Must be connected.\r\n * @param props the properties that describe the database to be downloaded, plus optionally an `onProgress` function.\r\n * @note this function requires that the write lock be held on the container\r\n */\r\n export async function uploadDb(container: CloudContainer, props: TransferDbProps): Promise<void> {\r\n await transferDb(\"upload\", container, props);\r\n container.checkForChanges(); // re-read the manifest so the database is available locally.\r\n }\r\n\r\n /** Download a database from a CloudContainer.\r\n * @param container the CloudContainer holding the database. Must be connected.\r\n * @param props the properties that describe the database to be downloaded, plus optionally an `onProgress` function.\r\n * @returns a Promise that is resolved when the download completes.\r\n * @note the download is \"restartable.\" If the transfer is aborted and then re-requested, it will continue from where\r\n * it left off rather than re-downloading the entire file.\r\n */\r\n export async function downloadDb(container: CloudContainer, props: TransferDbProps): Promise<void> {\r\n await transferDb(\"download\", container, props);\r\n }\r\n\r\n /** Optional method to be called when an attempt to acquire the write lock fails because another user currently holds it.\r\n * @param lockedBy The identifier supplied by the application/user that currently holds the lock.\r\n * @param expires a stringified Date (in local time) indicating when the lock will expire.\r\n * @return \"stop\" to give up and stop retrying. Generally, it's a good idea to wait for some time before returning.\r\n */\r\n export type WriteLockBusyHandler = (lockedBy: string, expires: string) => Promise<void | \"stop\">;\r\n\r\n /**\r\n * Attempt to acquire the write lock for a container, with retries.\r\n * If write lock is held by another user, call busyHandler if supplied. If no busyHandler, or handler returns \"stop\", throw. Otherwise try again.\r\n * @note if write lock is already held by the same user, this function will refresh the write lock's expiry time.\r\n * @param user the name to be displayed to other users in the event they attempt to obtain the lock while it is held by us\r\n * @param container the CloudContainer for which the lock is to be acquired\r\n * @param busyHandler if present, function called when the write lock is currently held by another user.\r\n * @throws if [[container]] is not connected to a CloudCache.\r\n */\r\n export async function acquireWriteLock(args: { user: string, container: CloudContainer, busyHandler?: WriteLockBusyHandler }) {\r\n const container = args.container as CloudContainerInternal;\r\n while (true) {\r\n try {\r\n if (container.hasWriteLock) {\r\n if (container.writeLockHeldBy === args.user) {\r\n return container.acquireWriteLock(args.user); // refresh the write lock's expiry time.\r\n }\r\n const err = new Error() as any; // lock held by another user within this process\r\n err.errorNumber = 5;\r\n err.lockedBy = container.writeLockHeldBy;\r\n err.expires = container.writeLockExpires;\r\n throw err;\r\n }\r\n return container.acquireWriteLock(args.user);\r\n\r\n } catch (e: any) {\r\n if (e.errorNumber === 5 && args.busyHandler && \"stop\" !== await args.busyHandler(e.lockedBy, e.expires)) // 5 === BE_SQLITE_BUSY\r\n continue; // busy handler wants to try again\r\n throw e;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Perform an asynchronous write operation on a CloudContainer with the write lock held.\r\n * 1. if write lock is already held by the current user, refresh write lock's expiry time, call operation and return.\r\n * 2. attempt to acquire the write lock, with retries. Throw if unable to obtain write lock.\r\n * 3. perform the operation\r\n * 3.a if the operation throws, abandon all changes and re-throw\r\n * 4. release the write lock.\r\n * 5. return value from operation\r\n * @param user the name to be displayed to other users in the event they attempt to obtain the lock while it is held by us\r\n * @param container the CloudContainer for which the lock is to be acquired\r\n * @param operation an asynchronous operation performed with the write lock held.\r\n * @param busyHandler if present, function called when the write lock is currently held by another user.\r\n * @returns a Promise with the result of `operation`\r\n */\r\n export async function withWriteLock<T>(args: { user: string, container: CloudContainer, busyHandler?: WriteLockBusyHandler }, operation: () => Promise<T>): Promise<T> {\r\n await acquireWriteLock(args);\r\n const containerInternal = args.container as CloudContainerInternal;\r\n try {\r\n if (containerInternal.writeLockHeldBy === args.user) // If the user already had the write lock, then don't release it.\r\n return await operation();\r\n containerInternal.writeLockHeldBy = args.user;\r\n const val = await operation(); // wait for work to finish or fail\r\n containerInternal.releaseWriteLock();\r\n containerInternal.writeLockHeldBy = undefined;\r\n return val;\r\n } catch (e) {\r\n args.container.abandonChanges(); // if operation threw, abandon all changes\r\n containerInternal.writeLockHeldBy = undefined;\r\n throw e;\r\n }\r\n }\r\n\r\n /** Arguments to create or find a CloudCache */\r\n export interface CreateCloudCacheArg {\r\n /** The name of the CloudCache. CloudCache names must be unique. */\r\n cacheName: string;\r\n /** A string that specifies the maximum size of the CloudCache. It should be a number followed by \"K\",\r\n * \"M\" \"G\", or \"T\". Default is \"10G\". */\r\n cacheSize?: string;\r\n /** A local directory in temporary storage for the CloudCache. If not supplied, it is a subdirectory called `cacheName`\r\n * in the `CloudCaches` temporary directory.\r\n * If the directory does not exist, it is created. */\r\n cacheDir?: string;\r\n }\r\n\r\n /** The collection of currently extant `CloudCache`s, by name. */\r\n export class CloudCaches {\r\n private static readonly cloudCaches = new Map<string, CloudCache>();\r\n\r\n /** create a new CloudCache */\r\n private static makeCache(args: CreateCloudCacheArg): CloudCache {\r\n const cacheName = args.cacheName;\r\n const rootDir = args.cacheDir ?? join(IModelHost.profileDir, \"CloudCaches\", cacheName);\r\n IModelJsFs.recursiveMkDirSync(rootDir);\r\n const cache = new NativeLibrary.nativeLib.CloudCache({ rootDir, name: cacheName, cacheSize: args.cacheSize ?? \"10G\" });\r\n if (Logger.getLevel(\"CloudSqlite\") === LogLevel.Trace) {\r\n cache.setLogMask(CloudSqlite.LoggingMask.All);\r\n }\r\n this.cloudCaches.set(cacheName, cache);\r\n return cache;\r\n }\r\n\r\n /** find a CloudCache by name, if it exists */\r\n public static findCache(cacheName: string): CloudCache | undefined {\r\n return this.cloudCaches.get(cacheName);\r\n }\r\n /** @internal */\r\n public static dropCache(cacheName: string): CloudCache | undefined {\r\n const cache = this.cloudCaches.get(cacheName);\r\n this.cloudCaches.delete(cacheName);\r\n return cache;\r\n }\r\n /** called by IModelHost after shutdown.\r\n * @internal\r\n */\r\n public static destroy() {\r\n this.cloudCaches.forEach((cache) => cache.destroy());\r\n this.cloudCaches.clear();\r\n }\r\n\r\n /** Get a CloudCache by name. If the CloudCache doesn't yet exist, it is created. */\r\n public static getCache(args: CreateCloudCacheArg): CloudCache {\r\n return this.cloudCaches.get(args.cacheName) ?? this.makeCache(args);\r\n }\r\n }\r\n\r\n /** Class that provides convenient local access to a SQLite database in a CloudContainer. */\r\n export class DbAccess<DbType extends VersionedSqliteDb, ReadMethods = DbType, WriteMethods = DbType> {\r\n /** The name of the database within the cloud container. */\r\n public readonly dbName: string;\r\n /** Parameters for obtaining the write lock for this container. */\r\n public readonly lockParams: ObtainLockParams = {\r\n user: \"\",\r\n nRetries: 20,\r\n retryDelayMs: 100,\r\n };\r\n protected static _cacheName = \"default-64k\";\r\n protected _container: CloudContainer;\r\n protected _cloudDb: DbType;\r\n private _writeLockProxy?: PickAsyncMethods<WriteMethods>;\r\n private _readerProxy?: PickMethods<ReadMethods>;\r\n private get _ctor() { return this.constructor as typeof DbAccess; }\r\n\r\n /** @internal */\r\n public static getCacheForClass() {\r\n return CloudCaches.getCache({ cacheName: this._cacheName });\r\n }\r\n private _cache?: CloudCache;\r\n /** only for tests\r\n * @internal\r\n */\r\n public setCache(cache: CloudCache) {\r\n this._cache = cache;\r\n }\r\n /** @internal */\r\n public getCache(): CloudCache {\r\n return this._cache ??= this._ctor.getCacheForClass();\r\n }\r\n /** @internal */\r\n public getCloudDb(): DbType {\r\n return this._cloudDb;\r\n }\r\n\r\n /**\r\n * The token that grants access to the cloud container for this DbAccess. If it does not grant write permissions, all\r\n * write operations will fail. It should be refreshed (via a timer) before it expires.\r\n */\r\n public get sasToken() { return this._container.accessToken; }\r\n public set sasToken(token: AccessToken) { this._container.accessToken = token; }\r\n\r\n /** the container for this DbAccess. It is automatically connected to the CloudCache whenever it is accessed. */\r\n public get container(): CloudContainer {\r\n const container = this._container;\r\n if (!container.isConnected)\r\n container.connect(this.getCache());\r\n return container;\r\n }\r\n\r\n /** Start a prefetch operation to download all the blocks for the VersionedSqliteDb */\r\n public startPrefetch(): CloudPrefetch {\r\n return startCloudPrefetch(this.container, this.dbName);\r\n }\r\n\r\n /** Create a new DbAccess for a database stored in a cloud container. */\r\n public constructor(args: {\r\n /** The Constructor for DbType. */\r\n dbType: Constructor<DbType>;\r\n /** The properties of the cloud container holding the database. */\r\n props: ContainerAccessProps;\r\n /** The name of the database within the container. */\r\n dbName: string;\r\n }) {\r\n this._container = createCloudContainer({ writeable: true, ...args.props });\r\n this._cloudDb = new args.dbType(args.props);\r\n this.dbName = args.dbName;\r\n this.lockParams.user = IModelHost.userMoniker;\r\n }\r\n\r\n /** Close the database for this DbAccess, if it is open */\r\n public closeDb() {\r\n if (this._cloudDb.isOpen)\r\n this._cloudDb.closeDb();\r\n }\r\n\r\n /** Close the database for this DbAccess if it is opened, and disconnect this `DbAccess from its CloudContainer. */\r\n public close() {\r\n this.closeDb();\r\n this._container.disconnect();\r\n }\r\n\r\n /**\r\n * Initialize a cloud container to hold VersionedSqliteDbs. The container must first be created by [[createBlobContainer]].\r\n * This function creates and uploads an empty database into the container.\r\n * @note this deletes any existing content in the container.\r\n */\r\n protected static async _initializeDb(args: { dbType: typeof VersionedSqliteDb, props: ContainerProps, dbName: string, blockSize?: \"64K\" | \"4M\" }) {\r\n const container = createCloudContainer({ ...args.props, writeable: true, accessToken: args.props.accessToken ?? await CloudSqlite.requestToken(args.props) });\r\n container.initializeContainer({ blockSize: args.blockSize === \"4M\" ? 4 * 1024 * 1024 : 64 * 1024 });\r\n container.connect(CloudCaches.getCache({ cacheName: this._cacheName }));\r\n await withWriteLock({ user: \"initialize\", container }, async () => {\r\n const localFileName = join(KnownLocations.tmpdir, \"blank.db\");\r\n args.dbType.createNewDb(localFileName, args);\r\n await transferDb(\"upload\", container, { dbName: args.dbName, localFileName });\r\n unlinkSync(localFileName);\r\n });\r\n container.disconnect({ detach: true });\r\n }\r\n\r\n /**\r\n * Create a new BlobContainer from the BlobContainer service to hold one or more VersionedSqliteDbs.\r\n * @returns A ContainerProps that describes the newly created container.\r\n * @note the current user must have administrator rights to create containers.\r\n */\r\n protected static async createBlobContainer(args: Omit<BlobContainer.CreateNewContainerProps, \"userToken\">): Promise<CloudSqlite.ContainerProps> {\r\n const service = BlobContainer.service;\r\n if (undefined === service)\r\n throw new Error(\"no BlobContainer service available\");\r\n const auth = IModelHost.authorizationClient;\r\n if (undefined === auth)\r\n throw new Error(\"no authorization client available\");\r\n\r\n const userToken = await auth.getAccessToken();\r\n const cloudContainer = await service.create({ scope: args.scope, metadata: args.metadata, userToken });\r\n return { baseUri: cloudContainer.baseUri, containerId: cloudContainer.containerId, storageType: cloudContainer.provider };\r\n }\r\n\r\n /**\r\n * Synchronize the local cache of this database with any changes by made by others.\r\n * @note This is called automatically whenever any write operation is performed on this DbAccess. It is only necessary to\r\n * call this directly if you have not changed the database recently, but wish to perform a readonly operation and want to\r\n * ensure it is up-to-date as of now.\r\n * @note There is no guarantee that the database is up-to-date even immediately after calling this method, since others\r\n * may be modifying it at any time.\r\n */\r\n public synchronizeWithCloud() {\r\n this.closeDb();\r\n this.container.checkForChanges();\r\n }\r\n\r\n /**\r\n * Ensure that the database controlled by this `DbAccess` is open for read access and return the database object.\r\n * @note if the database is already open (either for read or write), this method merely returns the database object.\r\n */\r\n public openForRead(): DbType {\r\n if (!this._cloudDb.isOpen)\r\n this._cloudDb.openDb(this.dbName, OpenMode.Readonly, this.container);\r\n return this._cloudDb;\r\n }\r\n\r\n /**\r\n * Perform an operation on this database with the lock held and the database opened for write\r\n * @param operationName the name of the operation. Only used for logging.\r\n * @param operation a function called with the lock held and the database open for write.\r\n * @returns A promise that resolves to the the return value of `operation`.\r\n * @see `SQLiteDb.withLockedContainer`\r\n * @note Most uses of `CloudSqliteDbAccess` require that the lock not be held by any operation for long. Make sure you don't\r\n * do any avoidable or time consuming work in your operation function.\r\n */\r\n public async withLockedDb<T>(args: { operationName: string, openMode?: OpenMode, user?: string }, operation: () => Promise<T>): Promise<T> {\r\n let nRetries = this.lockParams.nRetries;\r\n const cacheGuid = this.container.cache!.guid; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n const user = args.user ?? this.lockParams.user ?? cacheGuid;\r\n const timer = new StopWatch(undefined, true);\r\n const showMs = () => `(${timer.elapsed.milliseconds}ms)`;\r\n\r\n const busyHandler = async (lockedBy: string, expires: string): Promise<void | \"stop\"> => {\r\n if (--nRetries <= 0) {\r\n if (\"stop\" === await this.lockParams.onFailure?.(lockedBy, expires))\r\n return \"stop\";\r\n nRetries = this.lockParams.nRetries;\r\n }\r\n const delay = this.lockParams.retryDelayMs;\r\n logInfo(`lock retry for ${cacheGuid} after ${showMs()}, waiting ${delay}`);\r\n await BeDuration.fromMilliseconds(delay).wait();\r\n };\r\n\r\n this.closeDb(); // in case it is currently open for read.\r\n let lockObtained = false;\r\n const operationName = args.operationName;\r\n try {\r\n return await this._cloudDb.withLockedContainer({ user, dbName: this.dbName, container: this.container, busyHandler, openMode: args.openMode }, async () => {\r\n lockObtained = true;\r\n logInfo(`lock acquired by ${cacheGuid} for ${operationName} ${showMs()}`);\r\n return operation();\r\n });\r\n } finally {\r\n if (lockObtained)\r\n logInfo(`lock released by ${cacheGuid} after ${operationName} ${showMs()} `);\r\n else\r\n logError(`could not obtain lock for ${cacheGuid} to perform ${operationName} ${showMs()} `);\r\n }\r\n }\r\n\r\n /** get a method member, by name, from the database object. Throws if not a Function. */\r\n private getDbMethod(methodName: string): (...args: any[]) => any {\r\n const fn = (this._cloudDb as any)[methodName];\r\n if (typeof fn !== \"function\")\r\n throw new Error(`illegal method name ${methodName}`);\r\n return fn;\r\n }\r\n\r\n /**\r\n * A Proxy Object to call a writeable async method on the cloud database controlled by this `DbAccess`.\r\n *\r\n * Whenever a method is called through this Proxy, it will:\r\n * - attempt to acquire the write lock on the container\r\n * - open the database for write\r\n * - call the method\r\n * - close the database\r\n * - upload changes\r\n * - release the write lock.\r\n *\r\n * @see [[withLockedDb]]\r\n */\r\n public get writeLocker() {\r\n return this._writeLockProxy ??= new Proxy(this, {\r\n get(access, operationName: string) {\r\n const fn = access.getDbMethod(operationName);\r\n return async (...args: any[]) => access.withLockedDb({ operationName, user: RpcTrace.currentActivity?.user }, fn.bind(access._cloudDb, ...args));\r\n },\r\n }) as PickAsyncMethods<WriteMethods>;\r\n }\r\n\r\n /**\r\n * A Proxy Object to call a synchronous readonly method on the database controlled by this `DbAccess`.\r\n * Whenever a method is called through this Proxy, it will first ensure that the database is opened for at least read access.\r\n */\r\n public get reader() {\r\n return this._readerProxy ??= new Proxy(this, {\r\n get(access, methodName: string) {\r\n const fn = access.getDbMethod(methodName);\r\n return (...args: any[]) => fn.call(access.openForRead(), ...args);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AOnD"}
@@ -31,7 +31,6 @@ const DevToolsRpcImpl_1 = require("./rpc-impl/DevToolsRpcImpl");
31
31
  const IModelReadRpcImpl_1 = require("./rpc-impl/IModelReadRpcImpl");
32
32
  const IModelTileRpcImpl_1 = require("./rpc-impl/IModelTileRpcImpl");
33
33
  const SnapshotIModelRpcImpl_1 = require("./rpc-impl/SnapshotIModelRpcImpl");
34
- const WipRpcImpl_1 = require("./rpc-impl/WipRpcImpl");
35
34
  const RpcBackend_1 = require("./RpcBackend");
36
35
  const TileStorage_1 = require("./TileStorage");
37
36
  const Settings_1 = require("./workspace/Settings");
@@ -250,7 +249,6 @@ class IModelHost {
250
249
  IModelReadRpcImpl_1.IModelReadRpcImpl,
251
250
  IModelTileRpcImpl_1.IModelTileRpcImpl,
252
251
  SnapshotIModelRpcImpl_1.SnapshotIModelRpcImpl, // eslint-disable-line @typescript-eslint/no-deprecated
253
- WipRpcImpl_1.WipRpcImpl, // eslint-disable-line @typescript-eslint/no-deprecated
254
252
  DevToolsRpcImpl_1.DevToolsRpcImpl,
255
253
  ].forEach((rpc) => rpc.register()); // register all of the RPC implementations
256
254
  [
@@ -1 +1 @@
1
- {"version":3,"file":"IModelHost.js","sourceRoot":"","sources":["../../src/IModelHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,yFAAyF;AACzF,sBAAoB,CAAC,mCAAmC;AAExD,8DAA6E;AAC7E,yBAAyB;AACzB,4BAA0B,CAAC,yJAAyJ;AACpL,8DAAyE;AACzE,oEAAyF;AACzF,sDAA+I;AAC/I,oDAAiH;AACjH,sEAAyE;AACzE,oEAA2D;AAE3D,mEAAgE;AAChE,mDAAgD;AAChD,yDAAsD;AACtD,+CAA4C;AAC5C,iEAA8D;AAC9D,2DAAwD;AACxD,qDAAkD;AAClD,6CAA0C;AAC1C,gEAA6D;AAC7D,oEAAiE;AACjE,oEAAiE;AACjE,4EAAyE;AACzE,sDAAmD;AACnD,6CAAoD;AACpD,+CA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AAQ,CAAC,CAAC;IACnC,CAAC;IAED,+BAA+B;IACxB,MAAM,KAAK,MAAM;QACtB,OAAO,EAAE,CAAC,MAAM,EAAE,CAAC;IACrB,CAAC;CACF;AAhBD,wCAgBC;AAED;;;;;GAKG;AACH,MAAsB,gBAAgB;IACpC;;;OAGG;IACI,aAAa,CAAC,QAAgB,IAAwB,OAAO,SAAS,CAAC,CAAC,CAAC;IAChF;;;;OAIG;IACI,UAAU,CAAC,OAAe;QAC/B,MAAM,gBAAgB,GAAuB,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QACzE,IAAI,SAAS,KAAK,gBAAgB,EAAE,CAAC;YACnC,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,QAAQ,EAAE,GAAG,OAAO,eAAe,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IACD;;;OAGG;IACI,kBAAkB,CAAC,UAAkB,IAAwB,OAAO,UAAU,CAAC,CAAC,CAAC;IACxF;;;;OAIG;IACI,eAAe,CAAC,UAAkB;QACvC,MAAM,gBAAgB,GAAuB,IAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,CAAC;QACjF,IAAI,SAAS,KAAK,gBAAgB,EAAE,CAAC;YACnC,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,QAAQ,EAAE,GAAG,UAAU,eAAe,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AAnCD,4CAmCC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module IModelHost\r\n */\r\n\r\n// To avoid circular load errors, the \"Element\" classes must be loaded before IModelHost.\r\nimport \"./IModelDb\"; // DO NOT REMOVE OR MOVE THIS LINE!\r\n\r\nimport { IModelNative, loadNativePlatform } from \"./internal/NativePlatform\";\r\nimport * as os from \"os\";\r\nimport \"reflect-metadata\"; // this has to be before @itwin/object-storage-* and @itwin/cloud-agnostic-core imports because those packages contain decorators that use this polyfill.\r\nimport { IModelJsNative, NativeLibrary } from \"@bentley/imodeljs-native\";\r\nimport { DependenciesConfig, Types as ExtensionTypes } from \"@itwin/cloud-agnostic-core\";\r\nimport { AccessToken, assert, BeEvent, DbResult, Guid, GuidString, IModelStatus, Logger, Mutable, ProcessDetector } from \"@itwin/core-bentley\";\r\nimport { AuthorizationClient, BentleyStatus, IModelError, LocalDirName, SessionProps } from \"@itwin/core-common\";\r\nimport { AzureServerStorageBindings } from \"@itwin/object-storage-azure\";\r\nimport { ServerStorage } from \"@itwin/object-storage-core\";\r\nimport { BackendHubAccess } from \"./BackendHubAccess\";\r\nimport { BackendLoggerCategory } from \"./BackendLoggerCategory\";\r\nimport { BisCoreSchema } from \"./BisCoreSchema\";\r\nimport { BriefcaseManager } from \"./BriefcaseManager\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { FunctionalSchema } from \"./domains/FunctionalSchema\";\r\nimport { GenericSchema } from \"./domains/GenericSchema\";\r\nimport { GeoCoordConfig } from \"./GeoCoordConfig\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\nimport { DevToolsRpcImpl } from \"./rpc-impl/DevToolsRpcImpl\";\r\nimport { IModelReadRpcImpl } from \"./rpc-impl/IModelReadRpcImpl\";\r\nimport { IModelTileRpcImpl } from \"./rpc-impl/IModelTileRpcImpl\";\r\nimport { SnapshotIModelRpcImpl } from \"./rpc-impl/SnapshotIModelRpcImpl\";\r\nimport { WipRpcImpl } from \"./rpc-impl/WipRpcImpl\";\r\nimport { initializeRpcBackend } from \"./RpcBackend\";\r\nimport { TileStorage } from \"./TileStorage\";\r\nimport { SettingsContainer, SettingsPriority } from \"./workspace/Settings\";\r\nimport { SettingsSchemas } from \"./workspace/SettingsSchemas\";\r\nimport { Workspace, WorkspaceOpts } from \"./workspace/Workspace\";\r\nimport { Container } from \"inversify\";\r\nimport { join, normalize as normalizeDir } from \"path\";\r\nimport { constructWorkspace, OwnedWorkspace } from \"./internal/workspace/WorkspaceImpl\";\r\nimport { SettingsImpl } from \"./internal/workspace/SettingsImpl\";\r\nimport { constructSettingsSchemas } from \"./internal/workspace/SettingsSchemasImpl\";\r\n\r\nconst loggerCategory = BackendLoggerCategory.IModelHost;\r\n\r\n// cspell:ignore nodereport fatalerror apicall alicloud rpcs inversify\r\n\r\n/** @internal */\r\nexport interface CrashReportingConfigNameValuePair {\r\n name: string;\r\n value: string;\r\n}\r\n\r\n/** Configuration of the crash-reporting system.\r\n * @internal\r\n */\r\nexport interface CrashReportingConfig {\r\n /** The directory to which *.dmp and/or iModelJsNativeCrash*.properties.txt files are written. This directory will be created if it does not already exist. */\r\n crashDir: string;\r\n /** max # .dmp files that may exist in crashDir. The default is 50. */\r\n maxDumpsInDir?: number;\r\n /** Enable crash-dumps? If so, .dmp and .properties.txt files will be generated and written to crashDir in the event of an unhandled native-code exception. If not, only .properties.txt files will be written. The default is false. */\r\n enableCrashDumps?: boolean;\r\n /** If enableCrashDumps is true, do you want a full-memory dump? Defaults to false. */\r\n wantFullMemoryDumps?: boolean;\r\n /** Enable Node.js crash reporting? If so, report files will be generated in the event of an unhandled exception or fatal error and written to crashDir. The default is false. */\r\n enableNodeReport?: boolean;\r\n /** Additional name, value pairs to write to iModelJsNativeCrash*.properties.txt file in the event of a crash. */\r\n params?: CrashReportingConfigNameValuePair[];\r\n /** Run this .js file to process .dmp and Node.js crash reporting .json files in the event of a crash.\r\n * This script will be executed with a single command-line parameter: the name of the dump or Node.js report file.\r\n * In the case of a dump file, there will be a second file with the same basename and the extension \".properties.txt\".\r\n * Since it runs in a separate process, this script will have no access to the Javascript\r\n * context of the exiting backend. No default.\r\n */\r\n dumpProcessorScriptFileName?: string;\r\n /** Upload crash dump and node-reports to Bentley's crash-reporting service? Defaults to false */\r\n uploadToBentley?: boolean;\r\n}\r\n\r\n/** @beta */\r\nexport interface AzureBlobStorageCredentials {\r\n account: string;\r\n accessKey: string;\r\n baseUrl?: string;\r\n}\r\n\r\n/**\r\n * Options for [[IModelHost.startup]]\r\n * @public\r\n */\r\nexport interface IModelHostOptions {\r\n /**\r\n * The name of the *Profile* subdirectory of [[cacheDir]] for this process. If not present, \"default\" is used.\r\n * @see [[IModelHost.profileName]]\r\n * @beta\r\n */\r\n profileName?: string;\r\n\r\n /**\r\n * Root of the directory holding all the files that iTwin.js caches\r\n * - If not specified at startup a platform specific default is used -\r\n * - Windows: $(HOMEDIR)/AppData/Local/iModelJs/\r\n * - Mac/iOS: $(HOMEDIR)/Library/Caches/iModelJs/\r\n * - Linux: $(HOMEDIR)/.cache/iModelJs/\r\n * where $(HOMEDIR) is documented [here](https://nodejs.org/api/os.html#os_os_homedir)\r\n * - if specified, ensure it is set to a folder with read/write access.\r\n * @see [[IModelHost.cacheDir]] for the value it's set to after startup\r\n */\r\n cacheDir?: LocalDirName;\r\n\r\n /** The directory where application assets are found. */\r\n appAssetsDir?: LocalDirName;\r\n\r\n /**\r\n * Options for creating the [[IModelHost.appWorkspace]]\r\n * @beta\r\n */\r\n workspace?: WorkspaceOpts;\r\n\r\n /**\r\n * The kind of iModel hub server to use.\r\n * @internal\r\n */\r\n hubAccess?: BackendHubAccess;\r\n\r\n /** The Azure blob storage credentials to use for the tile cache service. If omitted and no external service implementation is provided, a local cache will be used.\r\n * @beta\r\n */\r\n tileCacheAzureCredentials?: AzureBlobStorageCredentials;\r\n\r\n /**\r\n * @beta\r\n * @note A reference implementation is set for AzureServerStorage from @itwin/object-storage-azure if [[tileCacheAzureCredentials]] property is set. To supply a different implementation for any service provider (such as AWS),\r\n * set this property with a custom ServerStorage.\r\n */\r\n tileCacheStorage?: ServerStorage;\r\n\r\n /** The maximum size in bytes to which a local sqlite database used for caching tiles can grow before it is purged of least-recently-used tiles.\r\n * The local cache is used only if an external cache has not been configured via [[tileCacheStorage]], and [[tileCacheAzureCredentials]].\r\n * Defaults to 1 GB. Must be an unsigned integer. A value of zero disables the local cache entirely.\r\n * @beta\r\n */\r\n maxTileCacheDbSize?: number;\r\n\r\n /** Whether to restrict tile cache URLs by client IP address (if available).\r\n * @beta\r\n */\r\n restrictTileUrlsByClientIp?: boolean;\r\n\r\n /** Whether to enable OpenTelemetry tracing.\r\n * Defaults to `false`.\r\n */\r\n enableOpenTelemetry?: boolean;\r\n\r\n /** Whether to compress cached tiles.\r\n * Defaults to `true`.\r\n */\r\n compressCachedTiles?: boolean;\r\n\r\n /** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileTreeProps]($common) should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n tileTreeRequestTimeout?: number;\r\n\r\n /** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileContent]($common) should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n tileContentRequestTimeout?: number;\r\n\r\n /** The backend will log when a tile took longer to load than this threshold in seconds.\r\n * @internal\r\n */\r\n logTileLoadTimeThreshold?: number;\r\n\r\n /** The backend will log when a tile is loaded with a size in bytes above this threshold.\r\n * @internal\r\n */\r\n logTileSizeThreshold?: number;\r\n\r\n /** Crash-reporting configuration\r\n * @internal\r\n */\r\n crashReportingConfig?: CrashReportingConfig;\r\n\r\n /** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */\r\n authorizationClient?: AuthorizationClient;\r\n\r\n /**\r\n * Automatically enable shared channel when opening iModels for read/write (see [Working With Channels]($docs/learning/backend/Channel.md)).\r\n * If not present, defaults to `true` for backwards compatibility. This means that the shared channel may be edited by default. Generally\r\n * that is undesirable because it allows applications to \"accidentally\" modify data it shouldn't be allowed to modify. Unfortunately the\r\n * previous versions of iTwin.js allowed it so this is necessary so they won't break.\r\n * Will be changed to default to `false` in 5.0.\r\n */\r\n allowSharedChannel?: boolean;\r\n}\r\n\r\n/** Configuration of core-backend.\r\n * @public\r\n */\r\nexport class IModelHostConfiguration implements IModelHostOptions {\r\n public static defaultTileRequestTimeout = 20 * 1000;\r\n public static defaultLogTileLoadTimeThreshold = 40;\r\n public static defaultLogTileSizeThreshold = 20 * 1000000;\r\n /** @internal */\r\n public static defaultMaxTileCacheDbSize = 1024 * 1024 * 1024;\r\n\r\n public appAssetsDir?: LocalDirName;\r\n public cacheDir?: LocalDirName;\r\n\r\n /** @beta */\r\n public workspace?: WorkspaceOpts;\r\n /** @internal */\r\n public hubAccess?: BackendHubAccess;\r\n /** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */\r\n public authorizationClient?: AuthorizationClient;\r\n /** @beta */\r\n public restrictTileUrlsByClientIp?: boolean;\r\n public compressCachedTiles?: boolean;\r\n /** @beta */\r\n public tileCacheAzureCredentials?: AzureBlobStorageCredentials;\r\n /** @internal */\r\n public tileTreeRequestTimeout = IModelHostConfiguration.defaultTileRequestTimeout;\r\n /** @internal */\r\n public tileContentRequestTimeout = IModelHostConfiguration.defaultTileRequestTimeout;\r\n /** @internal */\r\n public logTileLoadTimeThreshold = IModelHostConfiguration.defaultLogTileLoadTimeThreshold;\r\n /** @internal */\r\n public logTileSizeThreshold = IModelHostConfiguration.defaultLogTileSizeThreshold;\r\n /** @internal */\r\n public crashReportingConfig?: CrashReportingConfig;\r\n}\r\n\r\n/**\r\n * Settings for `IModelHost.appWorkspace`.\r\n * @note this includes the default dictionary from the SettingsSpecRegistry\r\n */\r\nclass ApplicationSettings extends SettingsImpl {\r\n private _remove?: VoidFunction;\r\n protected override verifyPriority(priority: SettingsPriority) {\r\n if (priority > SettingsPriority.application) // only application or lower may appear in ApplicationSettings\r\n throw new Error(\"Use IModelSettings\");\r\n }\r\n private updateDefaults() {\r\n const defaults: SettingsContainer = {};\r\n for (const [schemaName, val] of IModelHost.settingsSchemas.settingDefs) {\r\n if (val.default)\r\n defaults[schemaName] = val.default;\r\n }\r\n this.addDictionary({ name: \"_default_\", priority: 0 }, defaults);\r\n }\r\n\r\n public constructor() {\r\n super();\r\n this._remove = IModelHost.settingsSchemas.onSchemaChanged.addListener(() => this.updateDefaults());\r\n this.updateDefaults();\r\n }\r\n\r\n public override close() {\r\n if (this._remove) {\r\n this._remove();\r\n this._remove = undefined;\r\n }\r\n }\r\n}\r\n\r\nconst definedInStartup = <T>(obj: T | undefined): T => {\r\n if (obj === undefined)\r\n throw new Error(\"IModelHost.startup must be called first\");\r\n return obj;\r\n};\r\n\r\n/** IModelHost initializes ($backend) and captures its configuration. A backend must call [[IModelHost.startup]] before using any backend classes.\r\n * See [the learning article]($docs/learning/backend/IModelHost.md)\r\n * @public\r\n */\r\nexport class IModelHost {\r\n private constructor() { }\r\n\r\n /** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */\r\n public static authorizationClient?: AuthorizationClient;\r\n\r\n public static backendVersion = \"\";\r\n private static _profileName: string;\r\n private static _cacheDir = \"\";\r\n private static _settingsSchemas?: SettingsSchemas;\r\n private static _appWorkspace?: OwnedWorkspace;\r\n\r\n /** Provides access to the entirely internal, low-level, unstable APIs provided by @bentley/imodel-native.\r\n * Should not be used outside of @itwin/core-backend, and certainly not outside of the itwinjs-core repository\r\n * @deprecated in 4.8. This internal API will be removed in 5.0. Use IModelHost's public API instead.\r\n * @internal\r\n */\r\n public static get platform(): typeof IModelJsNative { return IModelNative.platform; }\r\n\r\n public static configuration?: IModelHostOptions;\r\n\r\n /**\r\n * The name of the *Profile* directory (a subdirectory of \"[[cacheDir]]/profiles/\") for this process.\r\n *\r\n * The *Profile* directory is used to cache data that is specific to a type-of-usage of the iTwin.js library.\r\n * It is important that information in the profile cache be consistent but isolated across sessions (i.e.\r\n * data for a profile is maintained between runs, but each profile is completely independent and\r\n * unaffected by the presence ot use of others.)\r\n * @note **Only one process at a time may be using a given profile**, and an exception will be thrown by [[startup]]\r\n * if a second process attempts to use the same profile.\r\n * @beta\r\n */\r\n public static get profileName(): string {\r\n return this._profileName;\r\n }\r\n\r\n /** The full path of the Profile directory.\r\n * @see [[profileName]]\r\n * @beta\r\n */\r\n public static get profileDir(): LocalDirName {\r\n return join(this._cacheDir, \"profiles\", this._profileName);\r\n }\r\n\r\n /** Event raised during startup to allow loading settings data */\r\n public static readonly onWorkspaceStartup = new BeEvent<() => void>();\r\n\r\n /** Event raised just after the backend IModelHost was started */\r\n public static readonly onAfterStartup = new BeEvent<() => void>();\r\n\r\n /** Event raised just before the backend IModelHost is to be shut down */\r\n public static readonly onBeforeShutdown = new BeEvent<() => void>();\r\n\r\n /** @internal */\r\n public static readonly session: Mutable<SessionProps> = { applicationId: \"2686\", applicationVersion: \"1.0.0\", sessionId: \"\" };\r\n\r\n /** A uniqueId for this session */\r\n public static get sessionId() { return this.session.sessionId; }\r\n public static set sessionId(id: GuidString) { this.session.sessionId = id; }\r\n\r\n /** The Id of this application - needs to be set only if it is an agent application. The applicationId will otherwise originate at the frontend. */\r\n public static get applicationId() { return this.session.applicationId; }\r\n public static set applicationId(id: string) { this.session.applicationId = id; }\r\n\r\n /** The version of this application - needs to be set if is an agent application. The applicationVersion will otherwise originate at the frontend. */\r\n public static get applicationVersion() { return this.session.applicationVersion; }\r\n public static set applicationVersion(version: string) { this.session.applicationVersion = version; }\r\n\r\n /** A string that can identify the current user to other users when collaborating. */\r\n public static userMoniker = \"unknown\";\r\n\r\n /** Root directory holding files that iTwin.js caches */\r\n public static get cacheDir(): LocalDirName { return this._cacheDir; }\r\n\r\n /** The application [[Workspace]] for this `IModelHost`\r\n * @note this `Workspace` only holds [[WorkspaceContainer]]s and [[Settings]] scoped to the currently loaded application(s).\r\n * All organization, iTwin, and iModel based containers or settings must be accessed through [[IModelDb.workspace]] and\r\n * attempting to add them to this Workspace will fail.\r\n * @beta\r\n */\r\n public static get appWorkspace(): Workspace { return definedInStartup(this._appWorkspace); }\r\n\r\n /** The registry of schemas describing the [[Setting]]s for the application session.\r\n * Applications should register their schemas via methods like [[SettingsSchemas.addGroup]].\r\n * @beta\r\n */\r\n public static get settingsSchemas(): SettingsSchemas { return definedInStartup(this._settingsSchemas); }\r\n\r\n /** The optional [[FileNameResolver]] that resolves keys and partial file names for snapshot iModels.\r\n * @deprecated in 4.10. When opening a snapshot by file name, ensure to pass already resolved path. Using a key to open a snapshot is now deprecated.\r\n */\r\n public static snapshotFileNameResolver?: FileNameResolver; // eslint-disable-line @typescript-eslint/no-deprecated\r\n\r\n /** Get the current access token for this IModelHost, or a blank string if none is available.\r\n * @note for web backends, this will *always* return a blank string because the backend itself has no token (but never needs one either.)\r\n * For all IpcHosts, where this backend is servicing a single frontend, this will be the user's token. For ElectronHost, the backend\r\n * obtains the token and forwards it to the frontend.\r\n * @note accessTokens expire periodically and are automatically refreshed, if possible. Therefore tokens should not be saved, and the value\r\n * returned by this method may change over time throughout the course of a session.\r\n */\r\n public static async getAccessToken(): Promise<AccessToken> {\r\n try {\r\n return (await IModelHost.authorizationClient?.getAccessToken()) ?? \"\";\r\n } catch {\r\n return \"\";\r\n }\r\n }\r\n\r\n private static loadNative(options: IModelHostOptions) {\r\n loadNativePlatform();\r\n\r\n if (options.crashReportingConfig && options.crashReportingConfig.crashDir && !ProcessDetector.isElectronAppBackend && !ProcessDetector.isMobileAppBackend) {\r\n IModelNative.platform.setCrashReporting(options.crashReportingConfig);\r\n\r\n Logger.logTrace(loggerCategory, \"Configured crash reporting\", {\r\n enableCrashDumps: options.crashReportingConfig?.enableCrashDumps,\r\n wantFullMemoryDumps: options.crashReportingConfig?.wantFullMemoryDumps,\r\n enableNodeReport: options.crashReportingConfig?.enableNodeReport,\r\n uploadToBentley: options.crashReportingConfig?.uploadToBentley,\r\n });\r\n\r\n if (options.crashReportingConfig.enableNodeReport) {\r\n if (process.report !== undefined) {\r\n process.report.reportOnFatalError = true;\r\n process.report.reportOnUncaughtException = true;\r\n process.report.directory = options.crashReportingConfig.crashDir;\r\n Logger.logTrace(loggerCategory, \"Configured Node.js crash reporting\");\r\n } else {\r\n Logger.logWarning(loggerCategory, \"Unable to configure Node.js crash reporting\");\r\n }\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n public static tileStorage?: TileStorage;\r\n\r\n private static _hubAccess?: BackendHubAccess;\r\n /** @internal */\r\n public static setHubAccess(hubAccess: BackendHubAccess | undefined) { this._hubAccess = hubAccess; }\r\n\r\n /** get the current hubAccess, if present.\r\n * @internal\r\n */\r\n public static getHubAccess(): BackendHubAccess | undefined { return this._hubAccess; }\r\n\r\n /** Provides access to the IModelHub for this IModelHost\r\n * @internal\r\n * @note If [[IModelHostOptions.hubAccess]] was undefined when initializing this class, accessing this property will throw an error.\r\n * To determine whether one is present, use [[getHubAccess]].\r\n */\r\n public static get hubAccess(): BackendHubAccess {\r\n if (IModelHost._hubAccess === undefined)\r\n throw new IModelError(IModelStatus.BadRequest, \"No BackendHubAccess supplied in IModelHostOptions\");\r\n return IModelHost._hubAccess;\r\n }\r\n\r\n private static initializeWorkspace(configuration: IModelHostOptions) {\r\n const settingAssets = join(KnownLocations.packageAssetsDir, \"Settings\");\r\n this._settingsSchemas = constructSettingsSchemas();\r\n this._settingsSchemas.addDirectory(join(settingAssets, \"Schemas\"));\r\n this._appWorkspace = constructWorkspace(new ApplicationSettings(), configuration.workspace);\r\n\r\n // Create the CloudCache for Workspaces. This will fail if another process is already using the same profile.\r\n try {\r\n this.appWorkspace.getCloudCache();\r\n } catch (e: any) {\r\n throw (e.errorNumber === DbResult.BE_SQLITE_BUSY) ? new IModelError(DbResult.BE_SQLITE_BUSY, `Profile [${this.profileDir}] is already in use by another process`) : e;\r\n }\r\n\r\n this.appWorkspace.settings.addDirectory(settingAssets, SettingsPriority.defaults);\r\n\r\n GeoCoordConfig.onStartup();\r\n // allow applications to load their default settings\r\n this.onWorkspaceStartup.raiseEvent();\r\n }\r\n\r\n private static _isValid = false;\r\n\r\n /** true between a successful call to [[startup]] and before [[shutdown]] */\r\n public static get isValid() {\r\n return IModelHost._isValid;\r\n }\r\n\r\n /** This method must be called before any iTwin.js services are used.\r\n * @param options Host configuration data.\r\n * Raises [[onAfterStartup]].\r\n * @see [[shutdown]].\r\n */\r\n public static async startup(options?: IModelHostOptions): Promise<void> {\r\n if (this._isValid)\r\n return; // we're already initialized\r\n this._isValid = true;\r\n\r\n options = options ?? {};\r\n if (this.sessionId === \"\")\r\n this.sessionId = Guid.createValue();\r\n\r\n this.authorizationClient = options.authorizationClient;\r\n\r\n this.backendVersion = require(\"../../package.json\").version; // eslint-disable-line @typescript-eslint/no-require-imports\r\n initializeRpcBackend(options.enableOpenTelemetry);\r\n\r\n this.loadNative(options);\r\n this.setupCacheDir(options);\r\n this.initializeWorkspace(options);\r\n\r\n BriefcaseManager.initialize(join(this._cacheDir, \"imodels\"));\r\n\r\n [\r\n IModelReadRpcImpl,\r\n IModelTileRpcImpl,\r\n SnapshotIModelRpcImpl, // eslint-disable-line @typescript-eslint/no-deprecated\r\n WipRpcImpl, // eslint-disable-line @typescript-eslint/no-deprecated\r\n DevToolsRpcImpl,\r\n ].forEach((rpc) => rpc.register()); // register all of the RPC implementations\r\n\r\n [\r\n BisCoreSchema,\r\n GenericSchema,\r\n FunctionalSchema,\r\n ].forEach((schema) => schema.registerSchema()); // register all of the schemas\r\n\r\n if (undefined !== options.hubAccess)\r\n this._hubAccess = options.hubAccess;\r\n\r\n this.configuration = options;\r\n this.setupTileCache();\r\n\r\n process.once(\"beforeExit\", IModelHost.shutdown);\r\n this.onAfterStartup.raiseEvent();\r\n }\r\n\r\n private static setupCacheDir(configuration: IModelHostOptions) {\r\n this._cacheDir = normalizeDir(configuration.cacheDir ?? NativeLibrary.defaultCacheDir);\r\n IModelJsFs.recursiveMkDirSync(this._cacheDir);\r\n\r\n this._profileName = configuration.profileName ?? \"default\";\r\n Logger.logInfo(loggerCategory, `cacheDir: [${this.cacheDir}], profileDir: [${this.profileDir}]`);\r\n }\r\n\r\n /** This method must be called when an iTwin.js host is shut down. Raises [[onBeforeShutdown]] */\r\n public static async shutdown(this: void): Promise<void> {\r\n // Note: This method is set as a node listener where `this` is unbound. Call private method to\r\n // ensure `this` is correct. Don't combine these methods.\r\n return IModelHost.doShutdown();\r\n }\r\n\r\n private static async doShutdown() {\r\n if (!this._isValid)\r\n return;\r\n\r\n this._isValid = false;\r\n this.onBeforeShutdown.raiseEvent();\r\n\r\n this.configuration = undefined;\r\n this.tileStorage = undefined;\r\n\r\n this._appWorkspace?.close();\r\n this._appWorkspace = undefined;\r\n this._settingsSchemas = undefined;\r\n\r\n CloudSqlite.CloudCaches.destroy();\r\n process.removeListener(\"beforeExit\", IModelHost.shutdown);\r\n }\r\n\r\n /**\r\n * Add or update a property that should be included in a crash report.\r\n * @internal\r\n */\r\n public static setCrashReportProperty(name: string, value: string): void {\r\n IModelNative.platform.setCrashReportProperty(name, value);\r\n }\r\n\r\n /**\r\n * Remove a previously defined property so that will not be included in a crash report.\r\n * @internal\r\n */\r\n public static removeCrashReportProperty(name: string): void {\r\n IModelNative.platform.setCrashReportProperty(name, undefined);\r\n }\r\n\r\n /**\r\n * Get all properties that will be included in a crash report.\r\n * @internal\r\n */\r\n public static getCrashReportProperties(): CrashReportingConfigNameValuePair[] {\r\n return IModelNative.platform.getCrashReportProperties();\r\n }\r\n\r\n /** The directory where application assets may be found */\r\n public static get appAssetsDir(): string | undefined {\r\n return undefined !== IModelHost.configuration ? IModelHost.configuration.appAssetsDir : undefined;\r\n }\r\n\r\n /** The time, in milliseconds, for which IModelTileRpcInterface.requestTileTreeProps should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n public static get tileTreeRequestTimeout(): number {\r\n return IModelHost.configuration?.tileTreeRequestTimeout ?? IModelHostConfiguration.defaultTileRequestTimeout;\r\n }\r\n /** The time, in milliseconds, for which IModelTileRpcInterface.requestTileContent should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n public static get tileContentRequestTimeout(): number {\r\n return IModelHost.configuration?.tileContentRequestTimeout ?? IModelHostConfiguration.defaultTileRequestTimeout;\r\n }\r\n\r\n /** The backend will log when a tile took longer to load than this threshold in seconds. */\r\n public static get logTileLoadTimeThreshold(): number {\r\n return IModelHost.configuration?.logTileLoadTimeThreshold ?? IModelHostConfiguration.defaultLogTileLoadTimeThreshold;\r\n }\r\n /** The backend will log when a tile is loaded with a size in bytes above this threshold. */\r\n public static get logTileSizeThreshold(): number {\r\n return IModelHost.configuration?.logTileSizeThreshold ?? IModelHostConfiguration.defaultLogTileSizeThreshold;\r\n }\r\n\r\n /** Whether external tile caching is active.\r\n * @internal\r\n */\r\n public static get usingExternalTileCache(): boolean {\r\n return undefined !== IModelHost.tileStorage;\r\n }\r\n\r\n /** Whether to restrict tile cache URLs by client IP address.\r\n * @internal\r\n */\r\n public static get restrictTileUrlsByClientIp(): boolean {\r\n return undefined !== IModelHost.configuration && (IModelHost.configuration.restrictTileUrlsByClientIp ? true : false);\r\n }\r\n\r\n /** Whether to compress cached tiles.\r\n * @internal\r\n */\r\n public static get compressCachedTiles(): boolean {\r\n return false !== IModelHost.configuration?.compressCachedTiles;\r\n }\r\n\r\n private static setupTileCache() {\r\n assert(undefined !== IModelHost.configuration);\r\n const config = IModelHost.configuration;\r\n const storage = config.tileCacheStorage;\r\n const credentials = config.tileCacheAzureCredentials;\r\n\r\n if (!storage && !credentials) {\r\n IModelNative.platform.setMaxTileCacheSize(config.maxTileCacheDbSize ?? IModelHostConfiguration.defaultMaxTileCacheDbSize);\r\n return;\r\n }\r\n\r\n IModelNative.platform.setMaxTileCacheSize(0);\r\n if (credentials) {\r\n if (storage)\r\n throw new IModelError(BentleyStatus.ERROR, \"Cannot use both Azure and custom cloud storage providers for tile cache.\");\r\n this.setupAzureTileCache(credentials);\r\n }\r\n if (storage)\r\n IModelHost.tileStorage = new TileStorage(storage);\r\n }\r\n\r\n private static setupAzureTileCache(credentials: AzureBlobStorageCredentials) {\r\n const config = {\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n ServerSideStorage: {\r\n dependencyName: \"azure\",\r\n accountName: credentials.account,\r\n accountKey: credentials.accessKey,\r\n baseUrl: credentials.baseUrl ?? `https://${credentials.account}.blob.core.windows.net`,\r\n },\r\n };\r\n const ioc: Container = new Container();\r\n ioc.bind<DependenciesConfig>(ExtensionTypes.dependenciesConfig).toConstantValue(config);\r\n new AzureServerStorageBindings().register(ioc, config.ServerSideStorage);\r\n IModelHost.tileStorage = new TileStorage(ioc.get(ServerStorage));\r\n }\r\n\r\n /** @internal */\r\n public static computeSchemaChecksum(arg: { schemaXmlPath: string, referencePaths: string[], exactMatch?: boolean }): string {\r\n return IModelNative.platform.computeSchemaChecksum(arg);\r\n }\r\n}\r\n\r\n/** Information about the platform on which the app is running.\r\n * @public\r\n */\r\nexport class Platform {\r\n /** Get the name of the platform. */\r\n public static get platformName(): \"win32\" | \"linux\" | \"darwin\" | \"ios\" | \"android\" | \"uwp\" {\r\n return process.platform as any;\r\n }\r\n}\r\n\r\n/** Well known directories that may be used by the application.\r\n * @public\r\n */\r\nexport class KnownLocations {\r\n\r\n /** The directory where the imodeljs-native assets are stored. */\r\n public static get nativeAssetsDir(): LocalDirName {\r\n return IModelNative.platform.DgnDb.getAssetsDir();\r\n }\r\n\r\n /** The directory where the core-backend assets are stored. */\r\n public static get packageAssetsDir(): LocalDirName {\r\n return join(__dirname, \"assets\");\r\n }\r\n\r\n /** The temporary directory. */\r\n public static get tmpdir(): LocalDirName {\r\n return os.tmpdir();\r\n }\r\n}\r\n\r\n/** Extend this class to provide custom file name resolution behavior.\r\n * @note Only `tryResolveKey` and/or `tryResolveFileName` need to be overridden as the implementations of `resolveKey` and `resolveFileName` work for most purposes.\r\n * @see [[IModelHost.snapshotFileNameResolver]]\r\n * @public\r\n * @deprecated in 4.10. When opening a snapshot by file name, ensure to pass already resolved path. Using a key to open a snapshot is now deprecated.\r\n */\r\nexport abstract class FileNameResolver {\r\n /** Resolve a file name from the specified key.\r\n * @param _fileKey The key that identifies the file name in a `Map` or other similar data structure.\r\n * @returns The resolved file name or `undefined` if not found.\r\n */\r\n public tryResolveKey(_fileKey: string): string | undefined { return undefined; }\r\n /** Resolve a file name from the specified key.\r\n * @param fileKey The key that identifies the file name in a `Map` or other similar data structure.\r\n * @returns The resolved file name.\r\n * @throws [[IModelError]] if not found.\r\n */\r\n public resolveKey(fileKey: string): string {\r\n const resolvedFileName: string | undefined = this.tryResolveKey(fileKey);\r\n if (undefined === resolvedFileName) {\r\n throw new IModelError(IModelStatus.NotFound, `${fileKey} not resolved`);\r\n }\r\n return resolvedFileName;\r\n }\r\n /** Resolve the input file name, which may be a partial name, into a full path file name.\r\n * @param inFileName The partial file name.\r\n * @returns The resolved full path file name or `undefined` if not found.\r\n */\r\n public tryResolveFileName(inFileName: string): string | undefined { return inFileName; }\r\n /** Resolve the input file name, which may be a partial name, into a full path file name.\r\n * @param inFileName The partial file name.\r\n * @returns The resolved full path file name.\r\n * @throws [[IModelError]] if not found.\r\n */\r\n public resolveFileName(inFileName: string): string {\r\n const resolvedFileName: string | undefined = this.tryResolveFileName(inFileName);\r\n if (undefined === resolvedFileName) {\r\n throw new IModelError(IModelStatus.NotFound, `${inFileName} not resolved`);\r\n }\r\n return resolvedFileName;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"IModelHost.js","sourceRoot":"","sources":["../../src/IModelHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,yFAAyF;AACzF,sBAAoB,CAAC,mCAAmC;AAExD,8DAA6E;AAC7E,yBAAyB;AACzB,4BAA0B,CAAC,yJAAyJ;AACpL,8DAAyE;AACzE,oEAAyF;AACzF,sDAA+I;AAC/I,oDAAiH;AACjH,sEAAyE;AACzE,oEAA2D;AAE3D,mEAAgE;AAChE,mDAAgD;AAChD,yDAAsD;AACtD,+CAA4C;AAC5C,iEAA8D;AAC9D,2DAAwD;AACxD,qDAAkD;AAClD,6CAA0C;AAC1C,gEAA6D;AAC7D,oEAAiE;AACjE,oEAAiE;AACjE,4EAAyE;AACzE,6CAAoD;AACpD,+CAA4C;AAC5C,mDAA2E;AAG3E,yCAAsC;AACtC,+BAAuD;AACvD,sEAAwF;AACxF,oEAAiE;AACjE,kFAAoF;AAEpF,MAAM,cAAc,GAAG,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;;;;GAKG;AACH,MAAsB,gBAAgB;IACpC;;;OAGG;IACI,aAAa,CAAC,QAAgB,IAAwB,OAAO,SAAS,CAAC,CAAC,CAAC;IAChF;;;;OAIG;IACI,UAAU,CAAC,OAAe;QAC/B,MAAM,gBAAgB,GAAuB,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QACzE,IAAI,SAAS,KAAK,gBAAgB,EAAE,CAAC;YACnC,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,QAAQ,EAAE,GAAG,OAAO,eAAe,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IACD;;;OAGG;IACI,kBAAkB,CAAC,UAAkB,IAAwB,OAAO,UAAU,CAAC,CAAC,CAAC;IACxF;;;;OAIG;IACI,eAAe,CAAC,UAAkB;QACvC,MAAM,gBAAgB,GAAuB,IAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,CAAC;QACjF,IAAI,SAAS,KAAK,gBAAgB,EAAE,CAAC;YACnC,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,QAAQ,EAAE,GAAG,UAAU,eAAe,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AAnCD,4CAmCC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module IModelHost\r\n */\r\n\r\n// To avoid circular load errors, the \"Element\" classes must be loaded before IModelHost.\r\nimport \"./IModelDb\"; // DO NOT REMOVE OR MOVE THIS LINE!\r\n\r\nimport { IModelNative, loadNativePlatform } from \"./internal/NativePlatform\";\r\nimport * as os from \"os\";\r\nimport \"reflect-metadata\"; // this has to be before @itwin/object-storage-* and @itwin/cloud-agnostic-core imports because those packages contain decorators that use this polyfill.\r\nimport { IModelJsNative, NativeLibrary } from \"@bentley/imodeljs-native\";\r\nimport { DependenciesConfig, Types as ExtensionTypes } from \"@itwin/cloud-agnostic-core\";\r\nimport { AccessToken, assert, BeEvent, DbResult, Guid, GuidString, IModelStatus, Logger, Mutable, ProcessDetector } from \"@itwin/core-bentley\";\r\nimport { AuthorizationClient, BentleyStatus, IModelError, LocalDirName, SessionProps } from \"@itwin/core-common\";\r\nimport { AzureServerStorageBindings } from \"@itwin/object-storage-azure\";\r\nimport { ServerStorage } from \"@itwin/object-storage-core\";\r\nimport { BackendHubAccess } from \"./BackendHubAccess\";\r\nimport { BackendLoggerCategory } from \"./BackendLoggerCategory\";\r\nimport { BisCoreSchema } from \"./BisCoreSchema\";\r\nimport { BriefcaseManager } from \"./BriefcaseManager\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { FunctionalSchema } from \"./domains/FunctionalSchema\";\r\nimport { GenericSchema } from \"./domains/GenericSchema\";\r\nimport { GeoCoordConfig } from \"./GeoCoordConfig\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\nimport { DevToolsRpcImpl } from \"./rpc-impl/DevToolsRpcImpl\";\r\nimport { IModelReadRpcImpl } from \"./rpc-impl/IModelReadRpcImpl\";\r\nimport { IModelTileRpcImpl } from \"./rpc-impl/IModelTileRpcImpl\";\r\nimport { SnapshotIModelRpcImpl } from \"./rpc-impl/SnapshotIModelRpcImpl\";\r\nimport { initializeRpcBackend } from \"./RpcBackend\";\r\nimport { TileStorage } from \"./TileStorage\";\r\nimport { SettingsContainer, SettingsPriority } from \"./workspace/Settings\";\r\nimport { SettingsSchemas } from \"./workspace/SettingsSchemas\";\r\nimport { Workspace, WorkspaceOpts } from \"./workspace/Workspace\";\r\nimport { Container } from \"inversify\";\r\nimport { join, normalize as normalizeDir } from \"path\";\r\nimport { constructWorkspace, OwnedWorkspace } from \"./internal/workspace/WorkspaceImpl\";\r\nimport { SettingsImpl } from \"./internal/workspace/SettingsImpl\";\r\nimport { constructSettingsSchemas } from \"./internal/workspace/SettingsSchemasImpl\";\r\n\r\nconst loggerCategory = BackendLoggerCategory.IModelHost;\r\n\r\n// cspell:ignore nodereport fatalerror apicall alicloud rpcs inversify\r\n\r\n/** @internal */\r\nexport interface CrashReportingConfigNameValuePair {\r\n name: string;\r\n value: string;\r\n}\r\n\r\n/** Configuration of the crash-reporting system.\r\n * @internal\r\n */\r\nexport interface CrashReportingConfig {\r\n /** The directory to which *.dmp and/or iModelJsNativeCrash*.properties.txt files are written. This directory will be created if it does not already exist. */\r\n crashDir: string;\r\n /** max # .dmp files that may exist in crashDir. The default is 50. */\r\n maxDumpsInDir?: number;\r\n /** Enable crash-dumps? If so, .dmp and .properties.txt files will be generated and written to crashDir in the event of an unhandled native-code exception. If not, only .properties.txt files will be written. The default is false. */\r\n enableCrashDumps?: boolean;\r\n /** If enableCrashDumps is true, do you want a full-memory dump? Defaults to false. */\r\n wantFullMemoryDumps?: boolean;\r\n /** Enable Node.js crash reporting? If so, report files will be generated in the event of an unhandled exception or fatal error and written to crashDir. The default is false. */\r\n enableNodeReport?: boolean;\r\n /** Additional name, value pairs to write to iModelJsNativeCrash*.properties.txt file in the event of a crash. */\r\n params?: CrashReportingConfigNameValuePair[];\r\n /** Run this .js file to process .dmp and Node.js crash reporting .json files in the event of a crash.\r\n * This script will be executed with a single command-line parameter: the name of the dump or Node.js report file.\r\n * In the case of a dump file, there will be a second file with the same basename and the extension \".properties.txt\".\r\n * Since it runs in a separate process, this script will have no access to the Javascript\r\n * context of the exiting backend. No default.\r\n */\r\n dumpProcessorScriptFileName?: string;\r\n /** Upload crash dump and node-reports to Bentley's crash-reporting service? Defaults to false */\r\n uploadToBentley?: boolean;\r\n}\r\n\r\n/** @beta */\r\nexport interface AzureBlobStorageCredentials {\r\n account: string;\r\n accessKey: string;\r\n baseUrl?: string;\r\n}\r\n\r\n/**\r\n * Options for [[IModelHost.startup]]\r\n * @public\r\n */\r\nexport interface IModelHostOptions {\r\n /**\r\n * The name of the *Profile* subdirectory of [[cacheDir]] for this process. If not present, \"default\" is used.\r\n * @see [[IModelHost.profileName]]\r\n * @beta\r\n */\r\n profileName?: string;\r\n\r\n /**\r\n * Root of the directory holding all the files that iTwin.js caches\r\n * - If not specified at startup a platform specific default is used -\r\n * - Windows: $(HOMEDIR)/AppData/Local/iModelJs/\r\n * - Mac/iOS: $(HOMEDIR)/Library/Caches/iModelJs/\r\n * - Linux: $(HOMEDIR)/.cache/iModelJs/\r\n * where $(HOMEDIR) is documented [here](https://nodejs.org/api/os.html#os_os_homedir)\r\n * - if specified, ensure it is set to a folder with read/write access.\r\n * @see [[IModelHost.cacheDir]] for the value it's set to after startup\r\n */\r\n cacheDir?: LocalDirName;\r\n\r\n /** The directory where application assets are found. */\r\n appAssetsDir?: LocalDirName;\r\n\r\n /**\r\n * Options for creating the [[IModelHost.appWorkspace]]\r\n * @beta\r\n */\r\n workspace?: WorkspaceOpts;\r\n\r\n /**\r\n * The kind of iModel hub server to use.\r\n * @internal\r\n */\r\n hubAccess?: BackendHubAccess;\r\n\r\n /** The Azure blob storage credentials to use for the tile cache service. If omitted and no external service implementation is provided, a local cache will be used.\r\n * @beta\r\n */\r\n tileCacheAzureCredentials?: AzureBlobStorageCredentials;\r\n\r\n /**\r\n * @beta\r\n * @note A reference implementation is set for AzureServerStorage from @itwin/object-storage-azure if [[tileCacheAzureCredentials]] property is set. To supply a different implementation for any service provider (such as AWS),\r\n * set this property with a custom ServerStorage.\r\n */\r\n tileCacheStorage?: ServerStorage;\r\n\r\n /** The maximum size in bytes to which a local sqlite database used for caching tiles can grow before it is purged of least-recently-used tiles.\r\n * The local cache is used only if an external cache has not been configured via [[tileCacheStorage]], and [[tileCacheAzureCredentials]].\r\n * Defaults to 1 GB. Must be an unsigned integer. A value of zero disables the local cache entirely.\r\n * @beta\r\n */\r\n maxTileCacheDbSize?: number;\r\n\r\n /** Whether to restrict tile cache URLs by client IP address (if available).\r\n * @beta\r\n */\r\n restrictTileUrlsByClientIp?: boolean;\r\n\r\n /** Whether to enable OpenTelemetry tracing.\r\n * Defaults to `false`.\r\n */\r\n enableOpenTelemetry?: boolean;\r\n\r\n /** Whether to compress cached tiles.\r\n * Defaults to `true`.\r\n */\r\n compressCachedTiles?: boolean;\r\n\r\n /** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileTreeProps]($common) should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n tileTreeRequestTimeout?: number;\r\n\r\n /** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileContent]($common) should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n tileContentRequestTimeout?: number;\r\n\r\n /** The backend will log when a tile took longer to load than this threshold in seconds.\r\n * @internal\r\n */\r\n logTileLoadTimeThreshold?: number;\r\n\r\n /** The backend will log when a tile is loaded with a size in bytes above this threshold.\r\n * @internal\r\n */\r\n logTileSizeThreshold?: number;\r\n\r\n /** Crash-reporting configuration\r\n * @internal\r\n */\r\n crashReportingConfig?: CrashReportingConfig;\r\n\r\n /** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */\r\n authorizationClient?: AuthorizationClient;\r\n\r\n /**\r\n * Automatically enable shared channel when opening iModels for read/write (see [Working With Channels]($docs/learning/backend/Channel.md)).\r\n * If not present, defaults to `true` for backwards compatibility. This means that the shared channel may be edited by default. Generally\r\n * that is undesirable because it allows applications to \"accidentally\" modify data it shouldn't be allowed to modify. Unfortunately the\r\n * previous versions of iTwin.js allowed it so this is necessary so they won't break.\r\n * Will be changed to default to `false` in 5.0.\r\n */\r\n allowSharedChannel?: boolean;\r\n}\r\n\r\n/** Configuration of core-backend.\r\n * @public\r\n */\r\nexport class IModelHostConfiguration implements IModelHostOptions {\r\n public static defaultTileRequestTimeout = 20 * 1000;\r\n public static defaultLogTileLoadTimeThreshold = 40;\r\n public static defaultLogTileSizeThreshold = 20 * 1000000;\r\n /** @internal */\r\n public static defaultMaxTileCacheDbSize = 1024 * 1024 * 1024;\r\n\r\n public appAssetsDir?: LocalDirName;\r\n public cacheDir?: LocalDirName;\r\n\r\n /** @beta */\r\n public workspace?: WorkspaceOpts;\r\n /** @internal */\r\n public hubAccess?: BackendHubAccess;\r\n /** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */\r\n public authorizationClient?: AuthorizationClient;\r\n /** @beta */\r\n public restrictTileUrlsByClientIp?: boolean;\r\n public compressCachedTiles?: boolean;\r\n /** @beta */\r\n public tileCacheAzureCredentials?: AzureBlobStorageCredentials;\r\n /** @internal */\r\n public tileTreeRequestTimeout = IModelHostConfiguration.defaultTileRequestTimeout;\r\n /** @internal */\r\n public tileContentRequestTimeout = IModelHostConfiguration.defaultTileRequestTimeout;\r\n /** @internal */\r\n public logTileLoadTimeThreshold = IModelHostConfiguration.defaultLogTileLoadTimeThreshold;\r\n /** @internal */\r\n public logTileSizeThreshold = IModelHostConfiguration.defaultLogTileSizeThreshold;\r\n /** @internal */\r\n public crashReportingConfig?: CrashReportingConfig;\r\n}\r\n\r\n/**\r\n * Settings for `IModelHost.appWorkspace`.\r\n * @note this includes the default dictionary from the SettingsSpecRegistry\r\n */\r\nclass ApplicationSettings extends SettingsImpl {\r\n private _remove?: VoidFunction;\r\n protected override verifyPriority(priority: SettingsPriority) {\r\n if (priority > SettingsPriority.application) // only application or lower may appear in ApplicationSettings\r\n throw new Error(\"Use IModelSettings\");\r\n }\r\n private updateDefaults() {\r\n const defaults: SettingsContainer = {};\r\n for (const [schemaName, val] of IModelHost.settingsSchemas.settingDefs) {\r\n if (val.default)\r\n defaults[schemaName] = val.default;\r\n }\r\n this.addDictionary({ name: \"_default_\", priority: 0 }, defaults);\r\n }\r\n\r\n public constructor() {\r\n super();\r\n this._remove = IModelHost.settingsSchemas.onSchemaChanged.addListener(() => this.updateDefaults());\r\n this.updateDefaults();\r\n }\r\n\r\n public override close() {\r\n if (this._remove) {\r\n this._remove();\r\n this._remove = undefined;\r\n }\r\n }\r\n}\r\n\r\nconst definedInStartup = <T>(obj: T | undefined): T => {\r\n if (obj === undefined)\r\n throw new Error(\"IModelHost.startup must be called first\");\r\n return obj;\r\n};\r\n\r\n/** IModelHost initializes ($backend) and captures its configuration. A backend must call [[IModelHost.startup]] before using any backend classes.\r\n * See [the learning article]($docs/learning/backend/IModelHost.md)\r\n * @public\r\n */\r\nexport class IModelHost {\r\n private constructor() { }\r\n\r\n /** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */\r\n public static authorizationClient?: AuthorizationClient;\r\n\r\n public static backendVersion = \"\";\r\n private static _profileName: string;\r\n private static _cacheDir = \"\";\r\n private static _settingsSchemas?: SettingsSchemas;\r\n private static _appWorkspace?: OwnedWorkspace;\r\n\r\n /** Provides access to the entirely internal, low-level, unstable APIs provided by @bentley/imodel-native.\r\n * Should not be used outside of @itwin/core-backend, and certainly not outside of the itwinjs-core repository\r\n * @deprecated in 4.8. This internal API will be removed in 5.0. Use IModelHost's public API instead.\r\n * @internal\r\n */\r\n public static get platform(): typeof IModelJsNative { return IModelNative.platform; }\r\n\r\n public static configuration?: IModelHostOptions;\r\n\r\n /**\r\n * The name of the *Profile* directory (a subdirectory of \"[[cacheDir]]/profiles/\") for this process.\r\n *\r\n * The *Profile* directory is used to cache data that is specific to a type-of-usage of the iTwin.js library.\r\n * It is important that information in the profile cache be consistent but isolated across sessions (i.e.\r\n * data for a profile is maintained between runs, but each profile is completely independent and\r\n * unaffected by the presence ot use of others.)\r\n * @note **Only one process at a time may be using a given profile**, and an exception will be thrown by [[startup]]\r\n * if a second process attempts to use the same profile.\r\n * @beta\r\n */\r\n public static get profileName(): string {\r\n return this._profileName;\r\n }\r\n\r\n /** The full path of the Profile directory.\r\n * @see [[profileName]]\r\n * @beta\r\n */\r\n public static get profileDir(): LocalDirName {\r\n return join(this._cacheDir, \"profiles\", this._profileName);\r\n }\r\n\r\n /** Event raised during startup to allow loading settings data */\r\n public static readonly onWorkspaceStartup = new BeEvent<() => void>();\r\n\r\n /** Event raised just after the backend IModelHost was started */\r\n public static readonly onAfterStartup = new BeEvent<() => void>();\r\n\r\n /** Event raised just before the backend IModelHost is to be shut down */\r\n public static readonly onBeforeShutdown = new BeEvent<() => void>();\r\n\r\n /** @internal */\r\n public static readonly session: Mutable<SessionProps> = { applicationId: \"2686\", applicationVersion: \"1.0.0\", sessionId: \"\" };\r\n\r\n /** A uniqueId for this session */\r\n public static get sessionId() { return this.session.sessionId; }\r\n public static set sessionId(id: GuidString) { this.session.sessionId = id; }\r\n\r\n /** The Id of this application - needs to be set only if it is an agent application. The applicationId will otherwise originate at the frontend. */\r\n public static get applicationId() { return this.session.applicationId; }\r\n public static set applicationId(id: string) { this.session.applicationId = id; }\r\n\r\n /** The version of this application - needs to be set if is an agent application. The applicationVersion will otherwise originate at the frontend. */\r\n public static get applicationVersion() { return this.session.applicationVersion; }\r\n public static set applicationVersion(version: string) { this.session.applicationVersion = version; }\r\n\r\n /** A string that can identify the current user to other users when collaborating. */\r\n public static userMoniker = \"unknown\";\r\n\r\n /** Root directory holding files that iTwin.js caches */\r\n public static get cacheDir(): LocalDirName { return this._cacheDir; }\r\n\r\n /** The application [[Workspace]] for this `IModelHost`\r\n * @note this `Workspace` only holds [[WorkspaceContainer]]s and [[Settings]] scoped to the currently loaded application(s).\r\n * All organization, iTwin, and iModel based containers or settings must be accessed through [[IModelDb.workspace]] and\r\n * attempting to add them to this Workspace will fail.\r\n * @beta\r\n */\r\n public static get appWorkspace(): Workspace { return definedInStartup(this._appWorkspace); }\r\n\r\n /** The registry of schemas describing the [[Setting]]s for the application session.\r\n * Applications should register their schemas via methods like [[SettingsSchemas.addGroup]].\r\n * @beta\r\n */\r\n public static get settingsSchemas(): SettingsSchemas { return definedInStartup(this._settingsSchemas); }\r\n\r\n /** The optional [[FileNameResolver]] that resolves keys and partial file names for snapshot iModels.\r\n * @deprecated in 4.10. When opening a snapshot by file name, ensure to pass already resolved path. Using a key to open a snapshot is now deprecated.\r\n */\r\n public static snapshotFileNameResolver?: FileNameResolver; // eslint-disable-line @typescript-eslint/no-deprecated\r\n\r\n /** Get the current access token for this IModelHost, or a blank string if none is available.\r\n * @note for web backends, this will *always* return a blank string because the backend itself has no token (but never needs one either.)\r\n * For all IpcHosts, where this backend is servicing a single frontend, this will be the user's token. For ElectronHost, the backend\r\n * obtains the token and forwards it to the frontend.\r\n * @note accessTokens expire periodically and are automatically refreshed, if possible. Therefore tokens should not be saved, and the value\r\n * returned by this method may change over time throughout the course of a session.\r\n */\r\n public static async getAccessToken(): Promise<AccessToken> {\r\n try {\r\n return (await IModelHost.authorizationClient?.getAccessToken()) ?? \"\";\r\n } catch {\r\n return \"\";\r\n }\r\n }\r\n\r\n private static loadNative(options: IModelHostOptions) {\r\n loadNativePlatform();\r\n\r\n if (options.crashReportingConfig && options.crashReportingConfig.crashDir && !ProcessDetector.isElectronAppBackend && !ProcessDetector.isMobileAppBackend) {\r\n IModelNative.platform.setCrashReporting(options.crashReportingConfig);\r\n\r\n Logger.logTrace(loggerCategory, \"Configured crash reporting\", {\r\n enableCrashDumps: options.crashReportingConfig?.enableCrashDumps,\r\n wantFullMemoryDumps: options.crashReportingConfig?.wantFullMemoryDumps,\r\n enableNodeReport: options.crashReportingConfig?.enableNodeReport,\r\n uploadToBentley: options.crashReportingConfig?.uploadToBentley,\r\n });\r\n\r\n if (options.crashReportingConfig.enableNodeReport) {\r\n if (process.report !== undefined) {\r\n process.report.reportOnFatalError = true;\r\n process.report.reportOnUncaughtException = true;\r\n process.report.directory = options.crashReportingConfig.crashDir;\r\n Logger.logTrace(loggerCategory, \"Configured Node.js crash reporting\");\r\n } else {\r\n Logger.logWarning(loggerCategory, \"Unable to configure Node.js crash reporting\");\r\n }\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n public static tileStorage?: TileStorage;\r\n\r\n private static _hubAccess?: BackendHubAccess;\r\n /** @internal */\r\n public static setHubAccess(hubAccess: BackendHubAccess | undefined) { this._hubAccess = hubAccess; }\r\n\r\n /** get the current hubAccess, if present.\r\n * @internal\r\n */\r\n public static getHubAccess(): BackendHubAccess | undefined { return this._hubAccess; }\r\n\r\n /** Provides access to the IModelHub for this IModelHost\r\n * @internal\r\n * @note If [[IModelHostOptions.hubAccess]] was undefined when initializing this class, accessing this property will throw an error.\r\n * To determine whether one is present, use [[getHubAccess]].\r\n */\r\n public static get hubAccess(): BackendHubAccess {\r\n if (IModelHost._hubAccess === undefined)\r\n throw new IModelError(IModelStatus.BadRequest, \"No BackendHubAccess supplied in IModelHostOptions\");\r\n return IModelHost._hubAccess;\r\n }\r\n\r\n private static initializeWorkspace(configuration: IModelHostOptions) {\r\n const settingAssets = join(KnownLocations.packageAssetsDir, \"Settings\");\r\n this._settingsSchemas = constructSettingsSchemas();\r\n this._settingsSchemas.addDirectory(join(settingAssets, \"Schemas\"));\r\n this._appWorkspace = constructWorkspace(new ApplicationSettings(), configuration.workspace);\r\n\r\n // Create the CloudCache for Workspaces. This will fail if another process is already using the same profile.\r\n try {\r\n this.appWorkspace.getCloudCache();\r\n } catch (e: any) {\r\n throw (e.errorNumber === DbResult.BE_SQLITE_BUSY) ? new IModelError(DbResult.BE_SQLITE_BUSY, `Profile [${this.profileDir}] is already in use by another process`) : e;\r\n }\r\n\r\n this.appWorkspace.settings.addDirectory(settingAssets, SettingsPriority.defaults);\r\n\r\n GeoCoordConfig.onStartup();\r\n // allow applications to load their default settings\r\n this.onWorkspaceStartup.raiseEvent();\r\n }\r\n\r\n private static _isValid = false;\r\n\r\n /** true between a successful call to [[startup]] and before [[shutdown]] */\r\n public static get isValid() {\r\n return IModelHost._isValid;\r\n }\r\n\r\n /** This method must be called before any iTwin.js services are used.\r\n * @param options Host configuration data.\r\n * Raises [[onAfterStartup]].\r\n * @see [[shutdown]].\r\n */\r\n public static async startup(options?: IModelHostOptions): Promise<void> {\r\n if (this._isValid)\r\n return; // we're already initialized\r\n this._isValid = true;\r\n\r\n options = options ?? {};\r\n if (this.sessionId === \"\")\r\n this.sessionId = Guid.createValue();\r\n\r\n this.authorizationClient = options.authorizationClient;\r\n\r\n this.backendVersion = require(\"../../package.json\").version; // eslint-disable-line @typescript-eslint/no-require-imports\r\n initializeRpcBackend(options.enableOpenTelemetry);\r\n\r\n this.loadNative(options);\r\n this.setupCacheDir(options);\r\n this.initializeWorkspace(options);\r\n\r\n BriefcaseManager.initialize(join(this._cacheDir, \"imodels\"));\r\n\r\n [\r\n IModelReadRpcImpl,\r\n IModelTileRpcImpl,\r\n SnapshotIModelRpcImpl, // eslint-disable-line @typescript-eslint/no-deprecated\r\n DevToolsRpcImpl,\r\n ].forEach((rpc) => rpc.register()); // register all of the RPC implementations\r\n\r\n [\r\n BisCoreSchema,\r\n GenericSchema,\r\n FunctionalSchema,\r\n ].forEach((schema) => schema.registerSchema()); // register all of the schemas\r\n\r\n if (undefined !== options.hubAccess)\r\n this._hubAccess = options.hubAccess;\r\n\r\n this.configuration = options;\r\n this.setupTileCache();\r\n\r\n process.once(\"beforeExit\", IModelHost.shutdown);\r\n this.onAfterStartup.raiseEvent();\r\n }\r\n\r\n private static setupCacheDir(configuration: IModelHostOptions) {\r\n this._cacheDir = normalizeDir(configuration.cacheDir ?? NativeLibrary.defaultCacheDir);\r\n IModelJsFs.recursiveMkDirSync(this._cacheDir);\r\n\r\n this._profileName = configuration.profileName ?? \"default\";\r\n Logger.logInfo(loggerCategory, `cacheDir: [${this.cacheDir}], profileDir: [${this.profileDir}]`);\r\n }\r\n\r\n /** This method must be called when an iTwin.js host is shut down. Raises [[onBeforeShutdown]] */\r\n public static async shutdown(this: void): Promise<void> {\r\n // Note: This method is set as a node listener where `this` is unbound. Call private method to\r\n // ensure `this` is correct. Don't combine these methods.\r\n return IModelHost.doShutdown();\r\n }\r\n\r\n private static async doShutdown() {\r\n if (!this._isValid)\r\n return;\r\n\r\n this._isValid = false;\r\n this.onBeforeShutdown.raiseEvent();\r\n\r\n this.configuration = undefined;\r\n this.tileStorage = undefined;\r\n\r\n this._appWorkspace?.close();\r\n this._appWorkspace = undefined;\r\n this._settingsSchemas = undefined;\r\n\r\n CloudSqlite.CloudCaches.destroy();\r\n process.removeListener(\"beforeExit\", IModelHost.shutdown);\r\n }\r\n\r\n /**\r\n * Add or update a property that should be included in a crash report.\r\n * @internal\r\n */\r\n public static setCrashReportProperty(name: string, value: string): void {\r\n IModelNative.platform.setCrashReportProperty(name, value);\r\n }\r\n\r\n /**\r\n * Remove a previously defined property so that will not be included in a crash report.\r\n * @internal\r\n */\r\n public static removeCrashReportProperty(name: string): void {\r\n IModelNative.platform.setCrashReportProperty(name, undefined);\r\n }\r\n\r\n /**\r\n * Get all properties that will be included in a crash report.\r\n * @internal\r\n */\r\n public static getCrashReportProperties(): CrashReportingConfigNameValuePair[] {\r\n return IModelNative.platform.getCrashReportProperties();\r\n }\r\n\r\n /** The directory where application assets may be found */\r\n public static get appAssetsDir(): string | undefined {\r\n return undefined !== IModelHost.configuration ? IModelHost.configuration.appAssetsDir : undefined;\r\n }\r\n\r\n /** The time, in milliseconds, for which IModelTileRpcInterface.requestTileTreeProps should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n public static get tileTreeRequestTimeout(): number {\r\n return IModelHost.configuration?.tileTreeRequestTimeout ?? IModelHostConfiguration.defaultTileRequestTimeout;\r\n }\r\n /** The time, in milliseconds, for which IModelTileRpcInterface.requestTileContent should wait before returning a \"pending\" status.\r\n * @internal\r\n */\r\n public static get tileContentRequestTimeout(): number {\r\n return IModelHost.configuration?.tileContentRequestTimeout ?? IModelHostConfiguration.defaultTileRequestTimeout;\r\n }\r\n\r\n /** The backend will log when a tile took longer to load than this threshold in seconds. */\r\n public static get logTileLoadTimeThreshold(): number {\r\n return IModelHost.configuration?.logTileLoadTimeThreshold ?? IModelHostConfiguration.defaultLogTileLoadTimeThreshold;\r\n }\r\n /** The backend will log when a tile is loaded with a size in bytes above this threshold. */\r\n public static get logTileSizeThreshold(): number {\r\n return IModelHost.configuration?.logTileSizeThreshold ?? IModelHostConfiguration.defaultLogTileSizeThreshold;\r\n }\r\n\r\n /** Whether external tile caching is active.\r\n * @internal\r\n */\r\n public static get usingExternalTileCache(): boolean {\r\n return undefined !== IModelHost.tileStorage;\r\n }\r\n\r\n /** Whether to restrict tile cache URLs by client IP address.\r\n * @internal\r\n */\r\n public static get restrictTileUrlsByClientIp(): boolean {\r\n return undefined !== IModelHost.configuration && (IModelHost.configuration.restrictTileUrlsByClientIp ? true : false);\r\n }\r\n\r\n /** Whether to compress cached tiles.\r\n * @internal\r\n */\r\n public static get compressCachedTiles(): boolean {\r\n return false !== IModelHost.configuration?.compressCachedTiles;\r\n }\r\n\r\n private static setupTileCache() {\r\n assert(undefined !== IModelHost.configuration);\r\n const config = IModelHost.configuration;\r\n const storage = config.tileCacheStorage;\r\n const credentials = config.tileCacheAzureCredentials;\r\n\r\n if (!storage && !credentials) {\r\n IModelNative.platform.setMaxTileCacheSize(config.maxTileCacheDbSize ?? IModelHostConfiguration.defaultMaxTileCacheDbSize);\r\n return;\r\n }\r\n\r\n IModelNative.platform.setMaxTileCacheSize(0);\r\n if (credentials) {\r\n if (storage)\r\n throw new IModelError(BentleyStatus.ERROR, \"Cannot use both Azure and custom cloud storage providers for tile cache.\");\r\n this.setupAzureTileCache(credentials);\r\n }\r\n if (storage)\r\n IModelHost.tileStorage = new TileStorage(storage);\r\n }\r\n\r\n private static setupAzureTileCache(credentials: AzureBlobStorageCredentials) {\r\n const config = {\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n ServerSideStorage: {\r\n dependencyName: \"azure\",\r\n accountName: credentials.account,\r\n accountKey: credentials.accessKey,\r\n baseUrl: credentials.baseUrl ?? `https://${credentials.account}.blob.core.windows.net`,\r\n },\r\n };\r\n const ioc: Container = new Container();\r\n ioc.bind<DependenciesConfig>(ExtensionTypes.dependenciesConfig).toConstantValue(config);\r\n new AzureServerStorageBindings().register(ioc, config.ServerSideStorage);\r\n IModelHost.tileStorage = new TileStorage(ioc.get(ServerStorage));\r\n }\r\n\r\n /** @internal */\r\n public static computeSchemaChecksum(arg: { schemaXmlPath: string, referencePaths: string[], exactMatch?: boolean }): string {\r\n return IModelNative.platform.computeSchemaChecksum(arg);\r\n }\r\n}\r\n\r\n/** Information about the platform on which the app is running.\r\n * @public\r\n */\r\nexport class Platform {\r\n /** Get the name of the platform. */\r\n public static get platformName(): \"win32\" | \"linux\" | \"darwin\" | \"ios\" | \"android\" | \"uwp\" {\r\n return process.platform as any;\r\n }\r\n}\r\n\r\n/** Well known directories that may be used by the application.\r\n * @public\r\n */\r\nexport class KnownLocations {\r\n\r\n /** The directory where the imodeljs-native assets are stored. */\r\n public static get nativeAssetsDir(): LocalDirName {\r\n return IModelNative.platform.DgnDb.getAssetsDir();\r\n }\r\n\r\n /** The directory where the core-backend assets are stored. */\r\n public static get packageAssetsDir(): LocalDirName {\r\n return join(__dirname, \"assets\");\r\n }\r\n\r\n /** The temporary directory. */\r\n public static get tmpdir(): LocalDirName {\r\n return os.tmpdir();\r\n }\r\n}\r\n\r\n/** Extend this class to provide custom file name resolution behavior.\r\n * @note Only `tryResolveKey` and/or `tryResolveFileName` need to be overridden as the implementations of `resolveKey` and `resolveFileName` work for most purposes.\r\n * @see [[IModelHost.snapshotFileNameResolver]]\r\n * @public\r\n * @deprecated in 4.10. When opening a snapshot by file name, ensure to pass already resolved path. Using a key to open a snapshot is now deprecated.\r\n */\r\nexport abstract class FileNameResolver {\r\n /** Resolve a file name from the specified key.\r\n * @param _fileKey The key that identifies the file name in a `Map` or other similar data structure.\r\n * @returns The resolved file name or `undefined` if not found.\r\n */\r\n public tryResolveKey(_fileKey: string): string | undefined { return undefined; }\r\n /** Resolve a file name from the specified key.\r\n * @param fileKey The key that identifies the file name in a `Map` or other similar data structure.\r\n * @returns The resolved file name.\r\n * @throws [[IModelError]] if not found.\r\n */\r\n public resolveKey(fileKey: string): string {\r\n const resolvedFileName: string | undefined = this.tryResolveKey(fileKey);\r\n if (undefined === resolvedFileName) {\r\n throw new IModelError(IModelStatus.NotFound, `${fileKey} not resolved`);\r\n }\r\n return resolvedFileName;\r\n }\r\n /** Resolve the input file name, which may be a partial name, into a full path file name.\r\n * @param inFileName The partial file name.\r\n * @returns The resolved full path file name or `undefined` if not found.\r\n */\r\n public tryResolveFileName(inFileName: string): string | undefined { return inFileName; }\r\n /** Resolve the input file name, which may be a partial name, into a full path file name.\r\n * @param inFileName The partial file name.\r\n * @returns The resolved full path file name.\r\n * @throws [[IModelError]] if not found.\r\n */\r\n public resolveFileName(inFileName: string): string {\r\n const resolvedFileName: string | undefined = this.tryResolveFileName(inFileName);\r\n if (undefined === resolvedFileName) {\r\n throw new IModelError(IModelStatus.NotFound, `${inFileName} not resolved`);\r\n }\r\n return resolvedFileName;\r\n }\r\n}\r\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"TextAnnotationLayout.d.ts","sourceRoot":"","sources":["../../src/TextAnnotationLayout.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,GAAG,EAAE,eAAe,EAAE,SAAS,EAAE,qBAAqB,EAAE,OAAO,EAAE,iBAAiB,EAA0B,MAAM,oBAAoB,CAAC;AACjN,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAItC,gBAAgB;AAChB,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,EAAE,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC7C,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,EAAE,aAAa,CAAC;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,CAAC,IAAI,EAAE,8BAA8B,KAAK,gBAAgB,CAAC;AAEpG,gB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CAAC,aAAa;IA0Bd,QAAQ,CAAC,SAAS,EAAE,SAAS,GAAG,gBAAgB;CASxD;AAED;;;GAGG;AACH,qBAAa,eAAe;IACnB,MAAM,EAAE,SAAS,CAAC;IAClB,KAAK,UAAiB;IACtB,KAAK,EAAE,UAAU,EAAE,CAAM;IAChC,OAAO,CAAC,QAAQ,CAAgB;gBAEb,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,aAAa;IAarD,QAAQ,IAAI,qBAAqB;IAOxC,yEAAyE;IAClE,SAAS,IAAI,MAAM;IAI1B,OAAO,KAAK,KAAK,GAGhB;IAED,OAAO,CAAC,aAAa;IAqDrB,OAAO,CAAC,YAAY;IA4BpB,OAAO,CAAC,SAAS;CAoClB"}
@@ -411,7 +411,7 @@ class TextBlockLayout {
411
411
  }
412
412
  const runWidth = run.range.xLength();
413
413
  const lineWidth = curLine.range.xLength();
414
- if (runWidth + lineWidth <= doc.width) {
414
+ if (runWidth + lineWidth < doc.width || core_geometry_1.Geometry.isAlmostEqualNumber(runWidth + lineWidth, doc.width, core_geometry_1.Geometry.smallMetricDistance)) {
415
415
  curLine.append(run);
416
416
  continue;
417
417
  }
@@ -1 +1 @@
1
- {"version":3,"file":"TextAnnotationLayout.js","sourceRoot":"","sources":["../../src/TextAnnotationLayout.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAgEH,0CAQC;AAQD,oEAGC;AAsBD,wDAqBC;AA5HD,oDAAiN;AACjN,wDAA+C;AAE/C,sDAAsE;AACtE,yCAAyC;AAiDzC;;;;;;;;GAQG;AACH,SAAgB,eAAe,CAAC,IAAyB;IACvD,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC;IAC7F,MAAM,gBAAgB,GAAG,IAAI,CAAC,gBA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AAC,CAAC;QACtB,OAAO,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC;IACvC,CAAC;CACF;AAzJD,0CAyJC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module ElementGeometry\r\n */\r\n\r\nimport { BaselineShift, FontId, FractionRun, LineLayoutResult, Paragraph, Run, RunLayoutResult, TextBlock, TextBlockLayoutResult, TextRun, TextStyleSettings, TextStyleSettingsProps } from \"@itwin/core-common\";\r\nimport { Range2d } from \"@itwin/core-geometry\";\r\nimport { IModelDb } from \"./IModelDb\";\r\nimport { assert, NonFunctionPropertiesOf } from \"@itwin/core-bentley\";\r\nimport * as LineBreaker from \"linebreak\";\r\n\r\n/** @internal */\r\nexport interface TextLayoutRanges {\r\n layout: Range2d;\r\n justification: Range2d;\r\n}\r\n\r\n/** Arguments to [[ComputeRangesForTextLayout]].\r\n * @internal\r\n */\r\nexport interface ComputeRangesForTextLayoutArgs {\r\n chars: string;\r\n bold: boolean;\r\n italic: boolean;\r\n baselineShift: BaselineShift;\r\n fontId: FontId;\r\n widthFactor: number;\r\n lineHeight: number;\r\n}\r\n\r\n/** A function that uses a font to compute the layout and justification ranges of a string of text.\r\n * @internal\r\n */\r\nexport type ComputeRangesForTextLayout = (args: ComputeRangesForTextLayoutArgs) => TextLayoutRanges;\r\n\r\n/** @internal */\r\nexport type FindFontId = (name: string) => FontId;\r\n\r\n/** @internal */\r\nexport type FindTextStyle = (name: string) => TextStyleSettings;\r\n\r\n/**\r\n * Arguments supplied to [[computeLayoutTextBlockResult]].\r\n * @beta\r\n */\r\nexport interface LayoutTextBlockArgs {\r\n /** The text block whose extents are to be computed. */\r\n textBlock: TextBlock;\r\n /** The iModel from which to obtain fonts and [TextStyle]($common)s when laying out glyphs. */\r\n iModel: IModelDb;\r\n /** @internal chiefly for tests, by default uses IModelJsNative.DgnDb.computeRangesForText. */\r\n computeTextRange?: ComputeRangesForTextLayout;\r\n /** @internal chiefly for tests, by default looks up styles from a workspace. */\r\n findTextStyle?: FindTextStyle;\r\n /** @internal chiefly for tests, by default uses IModelDb.fontMap. */\r\n findFontId?: FindFontId;\r\n}\r\n\r\n/**\r\n * Lays out the contents of a TextBlock into a series of lines containing runs.\r\n * Each paragraph is decomposed into a series of lines.\r\n * Each series of consecutive non-linebreak runs within a paragraph is concatenated into one line.\r\n * If the document specifies a width > 0, individual lines are split to try to avoid exceeding that width.\r\n * Individual TextRuns can be split onto multiple lines at word boundaries if necessary. Individual FractionRuns are never split.\r\n * @see [[computeLayoutTextBlockResult]]\r\n * @internal\r\n */\r\nexport function layoutTextBlock(args: LayoutTextBlockArgs): TextBlockLayout {\r\n const findFontId = args.findFontId ?? ((name) => args.iModel.fontMap.getFont(name)?.id ?? 0);\r\n const computeTextRange = args.computeTextRange ?? ((x) => args.iModel.computeRangesForText(x));\r\n\r\n // ###TODO finding text styles in workspaces.\r\n const findTextStyle = args.findTextStyle ?? (() => TextStyleSettings.fromJSON());\r\n\r\n return new TextBlockLayout(args.textBlock, new LayoutContext(args.textBlock, computeTextRange, findTextStyle, findFontId));\r\n}\r\n\r\n/**\r\n * Gets the result of laying out the the contents of a TextBlock into a series of lines containing runs.\r\n * The visual layout accounts for the [TextStyle]($common)s, fonts, and [TextBlock.width]($common). It applies word-wrapping if needed.\r\n * The layout returned matches the visual layout of the geometry produced by [[produceTextAnnotationGeometry]].\r\n * @beta\r\n */\r\nexport function computeLayoutTextBlockResult(args: LayoutTextBlockArgs): TextBlockLayoutResult {\r\n const layout = layoutTextBlock(args);\r\n return layout.toResult();\r\n}\r\n\r\n/**\r\n * Arguments supplied to [[computeGraphemeOffsets]].\r\n * @beta\r\n */\r\nexport interface ComputeGraphemeOffsetsArgs extends LayoutTextBlockArgs {\r\n /** The index of the [Paragraph]($common) in the text block that contains the run layout result text. */\r\n paragraphIndex: number;\r\n /** The run layout result for which grapheme ranges will be computed. */\r\n runLayoutResult: RunLayoutResult;\r\n /** An array of starting character indexes for each grapheme. Each entry represents the index of the first character in a grapheme. */\r\n graphemeCharIndexes: number[];\r\n};\r\n\r\n/**\r\n * Computes the range from the start of a [RunLayoutResult]($common) to the trailing edge of each grapheme.\r\n * It is the responsibility of the caller to determine the number and character indexes of the graphemes.\r\n * @returns If the [RunLayoutResult]($common)'s source is a [TextRun]($common), it returns an array containing the range of each grapheme.\r\n * Otherwise, it returns and empty array.\r\n * @beta\r\n */\r\nexport function computeGraphemeOffsets(args: ComputeGraphemeOffsetsArgs): Range2d[] {\r\n const { textBlock, paragraphIndex, runLayoutResult, graphemeCharIndexes, iModel } = args;\r\n const findFontId = args.findFontId ?? ((name) => iModel.fontMap.getFont(name)?.id ?? 0);\r\n const computeTextRange = args.computeTextRange ?? ((x) => iModel.computeRangesForText(x));\r\n const findTextStyle = args.findTextStyle ?? (() => TextStyleSettings.fromJSON());\r\n const source = textBlock.paragraphs[paragraphIndex].runs[runLayoutResult.sourceRunIndex];\r\n\r\n if (source.type !== \"text\" || runLayoutResult.characterCount === 0) {\r\n return [];\r\n }\r\n\r\n const style = TextStyleSettings.fromJSON(runLayoutResult.textStyle);\r\n\r\n const layoutContext = new LayoutContext(textBlock, computeTextRange, findTextStyle, findFontId);\r\n const graphemeRanges: Range2d[] = [];\r\n\r\n graphemeCharIndexes.forEach((_, index) => {\r\n const nextGraphemeCharIndex = graphemeCharIndexes[index + 1] ?? runLayoutResult.characterCount;\r\n graphemeRanges.push(layoutContext.computeRangeForTextRun(style, source, runLayoutResult.characterOffset, nextGraphemeCharIndex).layout);\r\n });\r\n return graphemeRanges;\r\n}\r\n\r\nfunction scaleRange(range: Range2d, scale: number): void {\r\n range.low.scaleInPlace(scale);\r\n range.high.scaleInPlace(scale);\r\n}\r\n\r\nfunction applyBlockSettings(target: TextStyleSettings, source: TextStyleSettings | TextStyleSettingsProps): TextStyleSettings {\r\n if (source === target) {\r\n return target;\r\n }\r\n\r\n const lineSpacingFactor = source.lineSpacingFactor ?? target.lineSpacingFactor;\r\n const lineHeight = source.lineHeight ?? target.lineHeight;\r\n const widthFactor = source.widthFactor ?? target.widthFactor;\r\n\r\n if (lineSpacingFactor !== target.lineSpacingFactor || lineHeight !== target.lineHeight || widthFactor !== target.widthFactor) {\r\n target = target.clone({ lineSpacingFactor, lineHeight, widthFactor });\r\n }\r\n\r\n return target;\r\n}\r\n\r\nclass LayoutContext {\r\n private readonly _textStyles = new Map<string, TextStyleSettings>();\r\n private readonly _fontIds = new Map<string, FontId>();\r\n public readonly blockSettings: TextStyleSettings;\r\n\r\n public constructor(block: TextBlock, private readonly _computeTextRange: ComputeRangesForTextLayout, private readonly _findTextStyle: FindTextStyle, private readonly _findFontId: FindFontId) {\r\n const settings = this.findTextStyle(block.styleName);\r\n this.blockSettings = applyBlockSettings(settings, block.styleOverrides);\r\n }\r\n\r\n public findFontId(name: string): FontId {\r\n let fontId = this._fontIds.get(name);\r\n if (undefined === fontId) {\r\n this._fontIds.set(name, fontId = this._findFontId(name));\r\n }\r\n\r\n return fontId;\r\n }\r\n\r\n public findTextStyle(name: string): TextStyleSettings {\r\n let style = this._textStyles.get(name);\r\n if (undefined === style) {\r\n this._textStyles.set(name, style = this._findTextStyle(name));\r\n }\r\n\r\n return style;\r\n }\r\n\r\n public createRunSettings(run: Run): TextStyleSettings {\r\n let settings = this.findTextStyle(run.styleName);\r\n if (run.overridesStyle) {\r\n settings = settings.clone(run.styleOverrides);\r\n }\r\n\r\n return applyBlockSettings(settings, this.blockSettings);\r\n }\r\n\r\n public computeRangeForText(chars: string, style: TextStyleSettings, baselineShift: BaselineShift): TextLayoutRanges {\r\n if (chars.length === 0) {\r\n return {\r\n layout: new Range2d(0, 0, 0, style.lineHeight),\r\n justification: new Range2d(),\r\n };\r\n }\r\n\r\n const fontId = this.findFontId(style.fontName);\r\n const { layout, justification } = this._computeTextRange({\r\n chars,\r\n fontId,\r\n baselineShift,\r\n bold: style.isBold,\r\n italic: style.isItalic,\r\n lineHeight: this.blockSettings.lineHeight,\r\n widthFactor: this.blockSettings.widthFactor,\r\n });\r\n\r\n if (\"none\" !== baselineShift) {\r\n const isSub = \"subscript\" === baselineShift;\r\n const scale = isSub ? style.subScriptScale : style.superScriptScale;\r\n const offsetFactor = isSub ? style.subScriptOffsetFactor : style.superScriptOffsetFactor;\r\n const offset = { x: 0, y: style.lineHeight * offsetFactor };\r\n\r\n scaleRange(layout, scale);\r\n layout.cloneTranslated(offset, layout);\r\n\r\n scaleRange(justification, scale);\r\n justification.cloneTranslated(offset, justification);\r\n }\r\n\r\n return { layout, justification };\r\n }\r\n\r\n public computeRangeForTextRun(style: TextStyleSettings, run: TextRun, charOffset: number, numChars: number): TextLayoutRanges {\r\n return this.computeRangeForText(run.content.substring(charOffset, charOffset + numChars), style, run.baselineShift);\r\n }\r\n\r\n public computeRangeForFractionRun(style: TextStyleSettings, source: FractionRun): { layout: Range2d, numerator: Range2d, denominator: Range2d } {\r\n const numerator = this.computeRangeForText(source.numerator, style, \"none\").layout;\r\n scaleRange(numerator, style.stackedFractionScale);\r\n\r\n const denominator = this.computeRangeForText(source.denominator, style, \"none\").layout;\r\n scaleRange(denominator, style.stackedFractionScale);\r\n\r\n const numLen = numerator.xLength();\r\n const denomLen = denominator.xLength();\r\n switch (style.stackedFractionType) {\r\n case \"horizontal\": {\r\n if (numLen > denomLen) {\r\n denominator.cloneTranslated({ x: (numLen - denomLen) / 2, y: 0 }, denominator);\r\n } else {\r\n numerator.cloneTranslated({ x: (denomLen - numLen) / 2, y: 0 }, numerator);\r\n }\r\n\r\n numerator.cloneTranslated({ x: 0, y: 1.5 * denominator.yLength() }, numerator);\r\n break;\r\n }\r\n case \"diagonal\": {\r\n numerator.cloneTranslated({ x: 0, y: denominator.yLength() }, numerator);\r\n denominator.cloneTranslated({ x: numLen, y: 0 }, denominator);\r\n break;\r\n }\r\n }\r\n\r\n const layout = numerator.clone();\r\n layout.extendRange(denominator);\r\n return { layout, numerator, denominator };\r\n }\r\n}\r\n\r\ninterface Segment {\r\n segment: string;\r\n index: number;\r\n}\r\n\r\nfunction split(source: string): Segment[] {\r\n if (source.length === 0) {\r\n return [];\r\n }\r\n\r\n let index = 0;\r\n const segments: Segment[] = [];\r\n const breaker = new LineBreaker(source);\r\n for (let brk = breaker.nextBreak(); brk; brk = breaker.nextBreak()) {\r\n segments.push({\r\n segment: source.slice(index, brk.position),\r\n index,\r\n });\r\n\r\n index = brk.position;\r\n }\r\n\r\n return segments;\r\n}\r\n\r\n/** @internal */\r\nexport class RunLayout {\r\n public source: Run;\r\n public charOffset: number;\r\n public numChars: number;\r\n public range: Range2d;\r\n public justificationRange?: Range2d;\r\n public denominatorRange?: Range2d;\r\n public numeratorRange?: Range2d;\r\n public offsetFromLine: { x: number, y: number };\r\n public style: TextStyleSettings;\r\n public fontId: FontId;\r\n\r\n private constructor(props: NonFunctionPropertiesOf<RunLayout>) {\r\n this.source = props.source;\r\n this.charOffset = props.charOffset;\r\n this.numChars = props.numChars;\r\n this.range = props.range;\r\n this.justificationRange = props.justificationRange;\r\n this.denominatorRange = props.denominatorRange;\r\n this.numeratorRange = props.numeratorRange;\r\n this.offsetFromLine = props.offsetFromLine;\r\n this.style = props.style;\r\n this.fontId = props.fontId;\r\n }\r\n\r\n public static create(source: Run, context: LayoutContext): RunLayout {\r\n const style = context.createRunSettings(source);\r\n const fontId = context.findFontId(style.fontName);\r\n const charOffset = 0;\r\n const offsetFromLine = { x: 0, y: 0 };\r\n let numChars = 0;\r\n\r\n let range, justificationRange, numeratorRange, denominatorRange;\r\n\r\n switch (source.type) {\r\n case \"text\": {\r\n numChars = source.content.length;\r\n const ranges = context.computeRangeForTextRun(style, source, charOffset, numChars);\r\n range = ranges.layout;\r\n justificationRange = ranges.justification;\r\n break;\r\n }\r\n case \"fraction\": {\r\n numChars = 1;\r\n const ranges = context.computeRangeForFractionRun(style, source);\r\n range = ranges.layout;\r\n numeratorRange = ranges.numerator;\r\n denominatorRange = ranges.denominator;\r\n break;\r\n }\r\n default: {\r\n // We do this so that blank lines space correctly without special casing later.\r\n range = new Range2d(0, 0, 0, style.lineHeight);\r\n break;\r\n }\r\n }\r\n\r\n return new RunLayout({ source, charOffset, numChars, range, justificationRange, denominatorRange, numeratorRange, offsetFromLine, style, fontId });\r\n }\r\n\r\n /** Compute a string representation, primarily for debugging purposes. */\r\n public stringify(): string {\r\n return this.source.type === \"text\" ? this.source.content.substring(this.charOffset, this.charOffset + this.numChars) : this.source.stringify();\r\n }\r\n\r\n public canWrap(): this is { source: TextRun } {\r\n return this.source.type === \"text\";\r\n }\r\n\r\n private cloneForWrap(args: { ranges: TextLayoutRanges, charOffset: number, numChars: number}): RunLayout {\r\n assert(this.canWrap());\r\n\r\n return new RunLayout({\r\n ...this,\r\n charOffset: args.charOffset,\r\n numChars: args.numChars,\r\n range: args.ranges.layout,\r\n justificationRange: args.ranges.justification,\r\n offsetFromLine: { ...this.offsetFromLine },\r\n });\r\n }\r\n\r\n public split(context: LayoutContext): RunLayout[] {\r\n assert(this.charOffset === 0, \"cannot re-split a run\");\r\n if (!this.canWrap() || this.charOffset > 0) {\r\n return [this];\r\n }\r\n\r\n const myText = this.source.content.substring(this.charOffset, this.charOffset + this.numChars);\r\n const segments = split(myText);\r\n\r\n if (segments.length <= 1) {\r\n return [this];\r\n }\r\n\r\n return segments.map((segment: any) => {\r\n return this.cloneForWrap({\r\n ranges: context.computeRangeForText(segment.segment, this.style, this.source.baselineShift),\r\n charOffset: segment.index,\r\n numChars: segment.segment.length,\r\n });\r\n });\r\n }\r\n\r\n public toResult(paragraph: Paragraph): RunLayoutResult {\r\n const result: RunLayoutResult = {\r\n sourceRunIndex: paragraph.runs.indexOf(this.source),\r\n fontId: this.fontId,\r\n characterOffset: this.charOffset,\r\n characterCount: this.numChars,\r\n range: this.range.toJSON(),\r\n offsetFromLine: this.offsetFromLine,\r\n textStyle: this.style.toJSON(),\r\n };\r\n\r\n if (this.justificationRange) {\r\n result.justificationRange = this.justificationRange.toJSON();\r\n }\r\n\r\n if (this.numeratorRange) {\r\n result.numeratorRange = this.numeratorRange.toJSON();\r\n }\r\n\r\n if (this.denominatorRange) {\r\n result.denominatorRange = this.denominatorRange.toJSON();\r\n }\r\n\r\n return result;\r\n }\r\n}\r\n\r\n/** @internal */\r\nexport class LineLayout {\r\n public source: Paragraph;\r\n public range = new Range2d(0, 0, 0, 0);\r\n public justificationRange = new Range2d(0, 0, 0, 0);\r\n public offsetFromDocument = { x: 0, y: 0 };\r\n private _runs: RunLayout[] = [];\r\n\r\n public constructor(source: Paragraph) {\r\n this.source = source;\r\n }\r\n\r\n /** Compute a string representation, primarily for debugging purposes. */\r\n public stringify(): string {\r\n const runs = this._runs.map((run) => run.stringify());\r\n return `${runs.join(\"\")}`;\r\n }\r\n\r\n public get runs(): ReadonlyArray<RunLayout> { return this._runs; }\r\n public get isEmpty() { return this._runs.length === 0; }\r\n public get back(): RunLayout {\r\n assert(!this.isEmpty);\r\n return this._runs[this._runs.length - 1];\r\n }\r\n\r\n public append(run: RunLayout): void {\r\n this._runs.push(run);\r\n this.computeRanges();\r\n }\r\n\r\n /** Invoked every time a run is appended,. */\r\n private computeRanges(): void {\r\n this.range.low.setZero();\r\n this.range.high.setZero();\r\n\r\n // Some runs (fractions) are taller than others.\r\n // We want to center each run vertically inside the line.\r\n let lineHeight = 0;\r\n for (const run of this._runs) {\r\n lineHeight = Math.max(lineHeight, run.range.yLength());\r\n }\r\n\r\n for (const run of this._runs) {\r\n const runHeight = run.range.yLength();\r\n const runOffset = { x: this.range.high.x, y: (lineHeight - runHeight) / 2 };\r\n run.offsetFromLine = runOffset;\r\n\r\n const runLayoutRange = run.range.cloneTranslated(runOffset);\r\n this.range.extendRange(runLayoutRange);\r\n\r\n if (\"linebreak\" !== run.source.type) {\r\n const runJustificationRange = run.justificationRange?.cloneTranslated(runOffset);\r\n this.justificationRange.extendRange(runJustificationRange ?? runLayoutRange);\r\n }\r\n }\r\n }\r\n\r\n public toResult(textBlock: TextBlock): LineLayoutResult {\r\n return {\r\n sourceParagraphIndex: textBlock.paragraphs.indexOf(this.source),\r\n runs: this.runs.map((x) => x.toResult(this.source)),\r\n range: this.range.toJSON(),\r\n justificationRange: this.justificationRange.toJSON(),\r\n offsetFromDocument: this.offsetFromDocument,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Describes the layout of a text block as a collection of lines containing runs.\r\n * @internal\r\n */\r\nexport class TextBlockLayout {\r\n public source: TextBlock;\r\n public range = new Range2d();\r\n public lines: LineLayout[] = [];\r\n private _context: LayoutContext;\r\n\r\n public constructor(source: TextBlock, context: LayoutContext) {\r\n this._context = context;\r\n this.source = source;\r\n\r\n if (source.width > 0) {\r\n this.range.low.x = 0;\r\n this.range.high.x = source.width;\r\n }\r\n\r\n this.populateLines(context);\r\n this.justifyLines();\r\n }\r\n\r\n public toResult(): TextBlockLayoutResult {\r\n return {\r\n lines: this.lines.map((x) => x.toResult(this.source)),\r\n range: this.range.toJSON(),\r\n };\r\n }\r\n\r\n /** Compute a string representation, primarily for debugging purposes. */\r\n public stringify(): string {\r\n return this.lines.map((line) => line.stringify()).join(\"\\n\");\r\n }\r\n\r\n private get _back(): LineLayout {\r\n assert(this.lines.length > 0);\r\n return this.lines[this.lines.length - 1];\r\n }\r\n\r\n private populateLines(context: LayoutContext): void {\r\n const doc = this.source;\r\n if (doc.paragraphs.length === 0) {\r\n return;\r\n }\r\n\r\n const doWrap = doc.width > 0;\r\n let curLine = new LineLayout(doc.paragraphs[0]);\r\n for (let i = 0; i < doc.paragraphs.length; i++) {\r\n const paragraph = doc.paragraphs[i];\r\n if (i > 0) {\r\n curLine = this.flushLine(context, curLine, paragraph);\r\n }\r\n\r\n let runs = paragraph.runs.map((run) => RunLayout.create(run, context));\r\n if (doWrap) {\r\n runs = runs.map((run) => run.split(context)).flat();\r\n }\r\n\r\n for (const run of runs) {\r\n if (\"linebreak\" === run.source.type) {\r\n curLine.append(run);\r\n curLine = this.flushLine(context, curLine);\r\n continue;\r\n }\r\n\r\n if (!doWrap) {\r\n curLine.append(run);\r\n continue;\r\n }\r\n\r\n const runWidth = run.range.xLength();\r\n const lineWidth = curLine.range.xLength();\r\n if (runWidth + lineWidth <= doc.width) {\r\n curLine.append(run);\r\n continue;\r\n }\r\n\r\n if (curLine.runs.length === 0) {\r\n curLine.append(run);\r\n curLine = this.flushLine(context, curLine);\r\n } else {\r\n curLine = this.flushLine(context, curLine);\r\n curLine.append(run);\r\n }\r\n }\r\n }\r\n\r\n if (curLine.runs.length > 0) {\r\n this.flushLine(context, curLine);\r\n }\r\n }\r\n\r\n private justifyLines(): void {\r\n if (this.lines.length <= 1 || \"left\" === this.source.justification) {\r\n return;\r\n }\r\n\r\n // This is the minimum width of the document's bounding box.\r\n const docWidth = this.source.width;\r\n\r\n let minOffset = Number.MAX_VALUE;\r\n for (const line of this.lines) {\r\n const lineWidth = line.justificationRange.xLength();\r\n\r\n let offset = docWidth - lineWidth;\r\n if (\"center\" === this.source.justification) {\r\n offset = offset / 2;\r\n }\r\n\r\n line.offsetFromDocument.x += offset;\r\n minOffset = Math.min(offset, minOffset);\r\n }\r\n\r\n if (minOffset < 0) {\r\n // Shift left to accomodate lines that exceeded the document's minimum width.\r\n this.range.low.x += minOffset;\r\n this.range.high.x += minOffset;\r\n }\r\n }\r\n\r\n private flushLine(context: LayoutContext, line: LineLayout, nextParagraph?: Paragraph): LineLayout {\r\n nextParagraph = nextParagraph ?? line.source;\r\n\r\n // We want to guarantee that each layout line has at least one run.\r\n if (line.runs.length === 0) {\r\n // If we're empty, there should always be a preceding run, and it should be a line break.\r\n if (this.lines.length === 0 || this._back.runs.length === 0) {\r\n return new LineLayout(nextParagraph);\r\n }\r\n\r\n const prevRun = this._back.back.source;\r\n assert(prevRun.type === \"linebreak\");\r\n if (prevRun.type !== \"linebreak\") {\r\n return new LineLayout(nextParagraph);\r\n }\r\n\r\n line.append(RunLayout.create(prevRun.clone(), context));\r\n }\r\n\r\n // Line origin is its baseline.\r\n const lineOffset = { x: 0, y: -line.range.yLength() };\r\n\r\n // Place it below any existing lines\r\n if (this.lines.length > 0) {\r\n lineOffset.y += this._back.offsetFromDocument.y;\r\n lineOffset.y -= context.blockSettings.lineSpacingFactor * context.blockSettings.lineHeight;\r\n }\r\n\r\n line.offsetFromDocument = lineOffset;\r\n\r\n // Update document range from computed line range and position\r\n this.range.extendRange(line.range.cloneTranslated(lineOffset));\r\n\r\n this.lines.push(line);\r\n return new LineLayout(nextParagraph);\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"TextAnnotationLayout.js","sourceRoot":"","sources":["../../src/TextAnnotationLayout.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAgEH,0CAQC;AAQD,oEAGC;AAsBD,wDAqBC;AA5HD,oDAAiN;AACjN,wDAAyD;AAEzD,sDAAsE;AACtE,yCAAyC;AAiDzC;;;;;;;;GAQG;AACH,SAAgB,eAAe,CAAC,IAAyB;IACvD,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC;IAC7F,MAAM,gBAAgB,GAAG,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC;IAE/F,6CAA6C;IAC7C,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,IAAI,CAAC,GAAG,EAAE,CAAC,+BAAiB,CAAC,QAAQ,EAAE,CAAC,CAAC;IAEjF,OAAO,IAAI,eAAe,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,aAAa,CAAC,IAAI,CAAC,SAAS,EAAE,gBAAgB,EAAE,aAAa,EAAE,UAAU,CAAC,CAAC,CAAC;AA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,IAAI,CAAC,MAAM,CAAC;YACvC,IAAA,qBAAM,EAAC,OAAO,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;YACrC,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;gBACjC,OAAO,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC;YACvC,CAAC;YAED,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;QAC1D,CAAC;QAED,+BAA+B;QAC/B,MAAM,UAAU,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;QAEtD,oCAAoC;QACpC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC1B,UAAU,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC,CAAC;YAChD,UAAU,CAAC,CAAC,IAAI,OAAO,CAAC,aAAa,CAAC,iBAAiB,GAAG,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC;QAC7F,CAAC;QAED,IAAI,CAAC,kBAAkB,GAAG,UAAU,CAAC;QAErC,8DAA8D;QAC9D,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC;QAE/D,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC;IACvC,CAAC;CACF;AAzJD,0CAyJC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module ElementGeometry\r\n */\r\n\r\nimport { BaselineShift, FontId, FractionRun, LineLayoutResult, Paragraph, Run, RunLayoutResult, TextBlock, TextBlockLayoutResult, TextRun, TextStyleSettings, TextStyleSettingsProps } from \"@itwin/core-common\";\r\nimport { Geometry, Range2d } from \"@itwin/core-geometry\";\r\nimport { IModelDb } from \"./IModelDb\";\r\nimport { assert, NonFunctionPropertiesOf } from \"@itwin/core-bentley\";\r\nimport * as LineBreaker from \"linebreak\";\r\n\r\n/** @internal */\r\nexport interface TextLayoutRanges {\r\n layout: Range2d;\r\n justification: Range2d;\r\n}\r\n\r\n/** Arguments to [[ComputeRangesForTextLayout]].\r\n * @internal\r\n */\r\nexport interface ComputeRangesForTextLayoutArgs {\r\n chars: string;\r\n bold: boolean;\r\n italic: boolean;\r\n baselineShift: BaselineShift;\r\n fontId: FontId;\r\n widthFactor: number;\r\n lineHeight: number;\r\n}\r\n\r\n/** A function that uses a font to compute the layout and justification ranges of a string of text.\r\n * @internal\r\n */\r\nexport type ComputeRangesForTextLayout = (args: ComputeRangesForTextLayoutArgs) => TextLayoutRanges;\r\n\r\n/** @internal */\r\nexport type FindFontId = (name: string) => FontId;\r\n\r\n/** @internal */\r\nexport type FindTextStyle = (name: string) => TextStyleSettings;\r\n\r\n/**\r\n * Arguments supplied to [[computeLayoutTextBlockResult]].\r\n * @beta\r\n */\r\nexport interface LayoutTextBlockArgs {\r\n /** The text block whose extents are to be computed. */\r\n textBlock: TextBlock;\r\n /** The iModel from which to obtain fonts and [TextStyle]($common)s when laying out glyphs. */\r\n iModel: IModelDb;\r\n /** @internal chiefly for tests, by default uses IModelJsNative.DgnDb.computeRangesForText. */\r\n computeTextRange?: ComputeRangesForTextLayout;\r\n /** @internal chiefly for tests, by default looks up styles from a workspace. */\r\n findTextStyle?: FindTextStyle;\r\n /** @internal chiefly for tests, by default uses IModelDb.fontMap. */\r\n findFontId?: FindFontId;\r\n}\r\n\r\n/**\r\n * Lays out the contents of a TextBlock into a series of lines containing runs.\r\n * Each paragraph is decomposed into a series of lines.\r\n * Each series of consecutive non-linebreak runs within a paragraph is concatenated into one line.\r\n * If the document specifies a width > 0, individual lines are split to try to avoid exceeding that width.\r\n * Individual TextRuns can be split onto multiple lines at word boundaries if necessary. Individual FractionRuns are never split.\r\n * @see [[computeLayoutTextBlockResult]]\r\n * @internal\r\n */\r\nexport function layoutTextBlock(args: LayoutTextBlockArgs): TextBlockLayout {\r\n const findFontId = args.findFontId ?? ((name) => args.iModel.fontMap.getFont(name)?.id ?? 0);\r\n const computeTextRange = args.computeTextRange ?? ((x) => args.iModel.computeRangesForText(x));\r\n\r\n // ###TODO finding text styles in workspaces.\r\n const findTextStyle = args.findTextStyle ?? (() => TextStyleSettings.fromJSON());\r\n\r\n return new TextBlockLayout(args.textBlock, new LayoutContext(args.textBlock, computeTextRange, findTextStyle, findFontId));\r\n}\r\n\r\n/**\r\n * Gets the result of laying out the the contents of a TextBlock into a series of lines containing runs.\r\n * The visual layout accounts for the [TextStyle]($common)s, fonts, and [TextBlock.width]($common). It applies word-wrapping if needed.\r\n * The layout returned matches the visual layout of the geometry produced by [[produceTextAnnotationGeometry]].\r\n * @beta\r\n */\r\nexport function computeLayoutTextBlockResult(args: LayoutTextBlockArgs): TextBlockLayoutResult {\r\n const layout = layoutTextBlock(args);\r\n return layout.toResult();\r\n}\r\n\r\n/**\r\n * Arguments supplied to [[computeGraphemeOffsets]].\r\n * @beta\r\n */\r\nexport interface ComputeGraphemeOffsetsArgs extends LayoutTextBlockArgs {\r\n /** The index of the [Paragraph]($common) in the text block that contains the run layout result text. */\r\n paragraphIndex: number;\r\n /** The run layout result for which grapheme ranges will be computed. */\r\n runLayoutResult: RunLayoutResult;\r\n /** An array of starting character indexes for each grapheme. Each entry represents the index of the first character in a grapheme. */\r\n graphemeCharIndexes: number[];\r\n};\r\n\r\n/**\r\n * Computes the range from the start of a [RunLayoutResult]($common) to the trailing edge of each grapheme.\r\n * It is the responsibility of the caller to determine the number and character indexes of the graphemes.\r\n * @returns If the [RunLayoutResult]($common)'s source is a [TextRun]($common), it returns an array containing the range of each grapheme.\r\n * Otherwise, it returns and empty array.\r\n * @beta\r\n */\r\nexport function computeGraphemeOffsets(args: ComputeGraphemeOffsetsArgs): Range2d[] {\r\n const { textBlock, paragraphIndex, runLayoutResult, graphemeCharIndexes, iModel } = args;\r\n const findFontId = args.findFontId ?? ((name) => iModel.fontMap.getFont(name)?.id ?? 0);\r\n const computeTextRange = args.computeTextRange ?? ((x) => iModel.computeRangesForText(x));\r\n const findTextStyle = args.findTextStyle ?? (() => TextStyleSettings.fromJSON());\r\n const source = textBlock.paragraphs[paragraphIndex].runs[runLayoutResult.sourceRunIndex];\r\n\r\n if (source.type !== \"text\" || runLayoutResult.characterCount === 0) {\r\n return [];\r\n }\r\n\r\n const style = TextStyleSettings.fromJSON(runLayoutResult.textStyle);\r\n\r\n const layoutContext = new LayoutContext(textBlock, computeTextRange, findTextStyle, findFontId);\r\n const graphemeRanges: Range2d[] = [];\r\n\r\n graphemeCharIndexes.forEach((_, index) => {\r\n const nextGraphemeCharIndex = graphemeCharIndexes[index + 1] ?? runLayoutResult.characterCount;\r\n graphemeRanges.push(layoutContext.computeRangeForTextRun(style, source, runLayoutResult.characterOffset, nextGraphemeCharIndex).layout);\r\n });\r\n return graphemeRanges;\r\n}\r\n\r\nfunction scaleRange(range: Range2d, scale: number): void {\r\n range.low.scaleInPlace(scale);\r\n range.high.scaleInPlace(scale);\r\n}\r\n\r\nfunction applyBlockSettings(target: TextStyleSettings, source: TextStyleSettings | TextStyleSettingsProps): TextStyleSettings {\r\n if (source === target) {\r\n return target;\r\n }\r\n\r\n const lineSpacingFactor = source.lineSpacingFactor ?? target.lineSpacingFactor;\r\n const lineHeight = source.lineHeight ?? target.lineHeight;\r\n const widthFactor = source.widthFactor ?? target.widthFactor;\r\n\r\n if (lineSpacingFactor !== target.lineSpacingFactor || lineHeight !== target.lineHeight || widthFactor !== target.widthFactor) {\r\n target = target.clone({ lineSpacingFactor, lineHeight, widthFactor });\r\n }\r\n\r\n return target;\r\n}\r\n\r\nclass LayoutContext {\r\n private readonly _textStyles = new Map<string, TextStyleSettings>();\r\n private readonly _fontIds = new Map<string, FontId>();\r\n public readonly blockSettings: TextStyleSettings;\r\n\r\n public constructor(block: TextBlock, private readonly _computeTextRange: ComputeRangesForTextLayout, private readonly _findTextStyle: FindTextStyle, private readonly _findFontId: FindFontId) {\r\n const settings = this.findTextStyle(block.styleName);\r\n this.blockSettings = applyBlockSettings(settings, block.styleOverrides);\r\n }\r\n\r\n public findFontId(name: string): FontId {\r\n let fontId = this._fontIds.get(name);\r\n if (undefined === fontId) {\r\n this._fontIds.set(name, fontId = this._findFontId(name));\r\n }\r\n\r\n return fontId;\r\n }\r\n\r\n public findTextStyle(name: string): TextStyleSettings {\r\n let style = this._textStyles.get(name);\r\n if (undefined === style) {\r\n this._textStyles.set(name, style = this._findTextStyle(name));\r\n }\r\n\r\n return style;\r\n }\r\n\r\n public createRunSettings(run: Run): TextStyleSettings {\r\n let settings = this.findTextStyle(run.styleName);\r\n if (run.overridesStyle) {\r\n settings = settings.clone(run.styleOverrides);\r\n }\r\n\r\n return applyBlockSettings(settings, this.blockSettings);\r\n }\r\n\r\n public computeRangeForText(chars: string, style: TextStyleSettings, baselineShift: BaselineShift): TextLayoutRanges {\r\n if (chars.length === 0) {\r\n return {\r\n layout: new Range2d(0, 0, 0, style.lineHeight),\r\n justification: new Range2d(),\r\n };\r\n }\r\n\r\n const fontId = this.findFontId(style.fontName);\r\n const { layout, justification } = this._computeTextRange({\r\n chars,\r\n fontId,\r\n baselineShift,\r\n bold: style.isBold,\r\n italic: style.isItalic,\r\n lineHeight: this.blockSettings.lineHeight,\r\n widthFactor: this.blockSettings.widthFactor,\r\n });\r\n\r\n if (\"none\" !== baselineShift) {\r\n const isSub = \"subscript\" === baselineShift;\r\n const scale = isSub ? style.subScriptScale : style.superScriptScale;\r\n const offsetFactor = isSub ? style.subScriptOffsetFactor : style.superScriptOffsetFactor;\r\n const offset = { x: 0, y: style.lineHeight * offsetFactor };\r\n\r\n scaleRange(layout, scale);\r\n layout.cloneTranslated(offset, layout);\r\n\r\n scaleRange(justification, scale);\r\n justification.cloneTranslated(offset, justification);\r\n }\r\n\r\n return { layout, justification };\r\n }\r\n\r\n public computeRangeForTextRun(style: TextStyleSettings, run: TextRun, charOffset: number, numChars: number): TextLayoutRanges {\r\n return this.computeRangeForText(run.content.substring(charOffset, charOffset + numChars), style, run.baselineShift);\r\n }\r\n\r\n public computeRangeForFractionRun(style: TextStyleSettings, source: FractionRun): { layout: Range2d, numerator: Range2d, denominator: Range2d } {\r\n const numerator = this.computeRangeForText(source.numerator, style, \"none\").layout;\r\n scaleRange(numerator, style.stackedFractionScale);\r\n\r\n const denominator = this.computeRangeForText(source.denominator, style, \"none\").layout;\r\n scaleRange(denominator, style.stackedFractionScale);\r\n\r\n const numLen = numerator.xLength();\r\n const denomLen = denominator.xLength();\r\n switch (style.stackedFractionType) {\r\n case \"horizontal\": {\r\n if (numLen > denomLen) {\r\n denominator.cloneTranslated({ x: (numLen - denomLen) / 2, y: 0 }, denominator);\r\n } else {\r\n numerator.cloneTranslated({ x: (denomLen - numLen) / 2, y: 0 }, numerator);\r\n }\r\n\r\n numerator.cloneTranslated({ x: 0, y: 1.5 * denominator.yLength() }, numerator);\r\n break;\r\n }\r\n case \"diagonal\": {\r\n numerator.cloneTranslated({ x: 0, y: denominator.yLength() }, numerator);\r\n denominator.cloneTranslated({ x: numLen, y: 0 }, denominator);\r\n break;\r\n }\r\n }\r\n\r\n const layout = numerator.clone();\r\n layout.extendRange(denominator);\r\n return { layout, numerator, denominator };\r\n }\r\n}\r\n\r\ninterface Segment {\r\n segment: string;\r\n index: number;\r\n}\r\n\r\nfunction split(source: string): Segment[] {\r\n if (source.length === 0) {\r\n return [];\r\n }\r\n\r\n let index = 0;\r\n const segments: Segment[] = [];\r\n const breaker = new LineBreaker(source);\r\n for (let brk = breaker.nextBreak(); brk; brk = breaker.nextBreak()) {\r\n segments.push({\r\n segment: source.slice(index, brk.position),\r\n index,\r\n });\r\n\r\n index = brk.position;\r\n }\r\n\r\n return segments;\r\n}\r\n\r\n/** @internal */\r\nexport class RunLayout {\r\n public source: Run;\r\n public charOffset: number;\r\n public numChars: number;\r\n public range: Range2d;\r\n public justificationRange?: Range2d;\r\n public denominatorRange?: Range2d;\r\n public numeratorRange?: Range2d;\r\n public offsetFromLine: { x: number, y: number };\r\n public style: TextStyleSettings;\r\n public fontId: FontId;\r\n\r\n private constructor(props: NonFunctionPropertiesOf<RunLayout>) {\r\n this.source = props.source;\r\n this.charOffset = props.charOffset;\r\n this.numChars = props.numChars;\r\n this.range = props.range;\r\n this.justificationRange = props.justificationRange;\r\n this.denominatorRange = props.denominatorRange;\r\n this.numeratorRange = props.numeratorRange;\r\n this.offsetFromLine = props.offsetFromLine;\r\n this.style = props.style;\r\n this.fontId = props.fontId;\r\n }\r\n\r\n public static create(source: Run, context: LayoutContext): RunLayout {\r\n const style = context.createRunSettings(source);\r\n const fontId = context.findFontId(style.fontName);\r\n const charOffset = 0;\r\n const offsetFromLine = { x: 0, y: 0 };\r\n let numChars = 0;\r\n\r\n let range, justificationRange, numeratorRange, denominatorRange;\r\n\r\n switch (source.type) {\r\n case \"text\": {\r\n numChars = source.content.length;\r\n const ranges = context.computeRangeForTextRun(style, source, charOffset, numChars);\r\n range = ranges.layout;\r\n justificationRange = ranges.justification;\r\n break;\r\n }\r\n case \"fraction\": {\r\n numChars = 1;\r\n const ranges = context.computeRangeForFractionRun(style, source);\r\n range = ranges.layout;\r\n numeratorRange = ranges.numerator;\r\n denominatorRange = ranges.denominator;\r\n break;\r\n }\r\n default: {\r\n // We do this so that blank lines space correctly without special casing later.\r\n range = new Range2d(0, 0, 0, style.lineHeight);\r\n break;\r\n }\r\n }\r\n\r\n return new RunLayout({ source, charOffset, numChars, range, justificationRange, denominatorRange, numeratorRange, offsetFromLine, style, fontId });\r\n }\r\n\r\n /** Compute a string representation, primarily for debugging purposes. */\r\n public stringify(): string {\r\n return this.source.type === \"text\" ? this.source.content.substring(this.charOffset, this.charOffset + this.numChars) : this.source.stringify();\r\n }\r\n\r\n public canWrap(): this is { source: TextRun } {\r\n return this.source.type === \"text\";\r\n }\r\n\r\n private cloneForWrap(args: { ranges: TextLayoutRanges, charOffset: number, numChars: number }): RunLayout {\r\n assert(this.canWrap());\r\n\r\n return new RunLayout({\r\n ...this,\r\n charOffset: args.charOffset,\r\n numChars: args.numChars,\r\n range: args.ranges.layout,\r\n justificationRange: args.ranges.justification,\r\n offsetFromLine: { ...this.offsetFromLine },\r\n });\r\n }\r\n\r\n public split(context: LayoutContext): RunLayout[] {\r\n assert(this.charOffset === 0, \"cannot re-split a run\");\r\n if (!this.canWrap() || this.charOffset > 0) {\r\n return [this];\r\n }\r\n\r\n const myText = this.source.content.substring(this.charOffset, this.charOffset + this.numChars);\r\n const segments = split(myText);\r\n\r\n if (segments.length <= 1) {\r\n return [this];\r\n }\r\n\r\n return segments.map((segment: any) => {\r\n return this.cloneForWrap({\r\n ranges: context.computeRangeForText(segment.segment, this.style, this.source.baselineShift),\r\n charOffset: segment.index,\r\n numChars: segment.segment.length,\r\n });\r\n });\r\n }\r\n\r\n public toResult(paragraph: Paragraph): RunLayoutResult {\r\n const result: RunLayoutResult = {\r\n sourceRunIndex: paragraph.runs.indexOf(this.source),\r\n fontId: this.fontId,\r\n characterOffset: this.charOffset,\r\n characterCount: this.numChars,\r\n range: this.range.toJSON(),\r\n offsetFromLine: this.offsetFromLine,\r\n textStyle: this.style.toJSON(),\r\n };\r\n\r\n if (this.justificationRange) {\r\n result.justificationRange = this.justificationRange.toJSON();\r\n }\r\n\r\n if (this.numeratorRange) {\r\n result.numeratorRange = this.numeratorRange.toJSON();\r\n }\r\n\r\n if (this.denominatorRange) {\r\n result.denominatorRange = this.denominatorRange.toJSON();\r\n }\r\n\r\n return result;\r\n }\r\n}\r\n\r\n/** @internal */\r\nexport class LineLayout {\r\n public source: Paragraph;\r\n public range = new Range2d(0, 0, 0, 0);\r\n public justificationRange = new Range2d(0, 0, 0, 0);\r\n public offsetFromDocument = { x: 0, y: 0 };\r\n private _runs: RunLayout[] = [];\r\n\r\n public constructor(source: Paragraph) {\r\n this.source = source;\r\n }\r\n\r\n /** Compute a string representation, primarily for debugging purposes. */\r\n public stringify(): string {\r\n const runs = this._runs.map((run) => run.stringify());\r\n return `${runs.join(\"\")}`;\r\n }\r\n\r\n public get runs(): ReadonlyArray<RunLayout> { return this._runs; }\r\n public get isEmpty() { return this._runs.length === 0; }\r\n public get back(): RunLayout {\r\n assert(!this.isEmpty);\r\n return this._runs[this._runs.length - 1];\r\n }\r\n\r\n public append(run: RunLayout): void {\r\n this._runs.push(run);\r\n this.computeRanges();\r\n }\r\n\r\n /** Invoked every time a run is appended,. */\r\n private computeRanges(): void {\r\n this.range.low.setZero();\r\n this.range.high.setZero();\r\n\r\n // Some runs (fractions) are taller than others.\r\n // We want to center each run vertically inside the line.\r\n let lineHeight = 0;\r\n for (const run of this._runs) {\r\n lineHeight = Math.max(lineHeight, run.range.yLength());\r\n }\r\n\r\n for (const run of this._runs) {\r\n const runHeight = run.range.yLength();\r\n const runOffset = { x: this.range.high.x, y: (lineHeight - runHeight) / 2 };\r\n run.offsetFromLine = runOffset;\r\n\r\n const runLayoutRange = run.range.cloneTranslated(runOffset);\r\n this.range.extendRange(runLayoutRange);\r\n\r\n if (\"linebreak\" !== run.source.type) {\r\n const runJustificationRange = run.justificationRange?.cloneTranslated(runOffset);\r\n this.justificationRange.extendRange(runJustificationRange ?? runLayoutRange);\r\n }\r\n }\r\n }\r\n\r\n public toResult(textBlock: TextBlock): LineLayoutResult {\r\n return {\r\n sourceParagraphIndex: textBlock.paragraphs.indexOf(this.source),\r\n runs: this.runs.map((x) => x.toResult(this.source)),\r\n range: this.range.toJSON(),\r\n justificationRange: this.justificationRange.toJSON(),\r\n offsetFromDocument: this.offsetFromDocument,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Describes the layout of a text block as a collection of lines containing runs.\r\n * @internal\r\n */\r\nexport class TextBlockLayout {\r\n public source: TextBlock;\r\n public range = new Range2d();\r\n public lines: LineLayout[] = [];\r\n private _context: LayoutContext;\r\n\r\n public constructor(source: TextBlock, context: LayoutContext) {\r\n this._context = context;\r\n this.source = source;\r\n\r\n if (source.width > 0) {\r\n this.range.low.x = 0;\r\n this.range.high.x = source.width;\r\n }\r\n\r\n this.populateLines(context);\r\n this.justifyLines();\r\n }\r\n\r\n public toResult(): TextBlockLayoutResult {\r\n return {\r\n lines: this.lines.map((x) => x.toResult(this.source)),\r\n range: this.range.toJSON(),\r\n };\r\n }\r\n\r\n /** Compute a string representation, primarily for debugging purposes. */\r\n public stringify(): string {\r\n return this.lines.map((line) => line.stringify()).join(\"\\n\");\r\n }\r\n\r\n private get _back(): LineLayout {\r\n assert(this.lines.length > 0);\r\n return this.lines[this.lines.length - 1];\r\n }\r\n\r\n private populateLines(context: LayoutContext): void {\r\n const doc = this.source;\r\n if (doc.paragraphs.length === 0) {\r\n return;\r\n }\r\n\r\n const doWrap = doc.width > 0;\r\n let curLine = new LineLayout(doc.paragraphs[0]);\r\n for (let i = 0; i < doc.paragraphs.length; i++) {\r\n const paragraph = doc.paragraphs[i];\r\n if (i > 0) {\r\n curLine = this.flushLine(context, curLine, paragraph);\r\n }\r\n\r\n let runs = paragraph.runs.map((run) => RunLayout.create(run, context));\r\n if (doWrap) {\r\n runs = runs.map((run) => run.split(context)).flat();\r\n }\r\n\r\n for (const run of runs) {\r\n if (\"linebreak\" === run.source.type) {\r\n curLine.append(run);\r\n curLine = this.flushLine(context, curLine);\r\n continue;\r\n }\r\n\r\n if (!doWrap) {\r\n curLine.append(run);\r\n continue;\r\n }\r\n\r\n const runWidth = run.range.xLength();\r\n const lineWidth = curLine.range.xLength();\r\n if (runWidth + lineWidth < doc.width || Geometry.isAlmostEqualNumber(runWidth + lineWidth, doc.width, Geometry.smallMetricDistance)) {\r\n curLine.append(run);\r\n continue;\r\n }\r\n\r\n if (curLine.runs.length === 0) {\r\n curLine.append(run);\r\n curLine = this.flushLine(context, curLine);\r\n } else {\r\n curLine = this.flushLine(context, curLine);\r\n curLine.append(run);\r\n }\r\n }\r\n }\r\n\r\n if (curLine.runs.length > 0) {\r\n this.flushLine(context, curLine);\r\n }\r\n }\r\n\r\n private justifyLines(): void {\r\n if (this.lines.length <= 1 || \"left\" === this.source.justification) {\r\n return;\r\n }\r\n\r\n // This is the minimum width of the document's bounding box.\r\n const docWidth = this.source.width;\r\n\r\n let minOffset = Number.MAX_VALUE;\r\n for (const line of this.lines) {\r\n const lineWidth = line.justificationRange.xLength();\r\n\r\n let offset = docWidth - lineWidth;\r\n if (\"center\" === this.source.justification) {\r\n offset = offset / 2;\r\n }\r\n\r\n line.offsetFromDocument.x += offset;\r\n minOffset = Math.min(offset, minOffset);\r\n }\r\n\r\n if (minOffset < 0) {\r\n // Shift left to accomodate lines that exceeded the document's minimum width.\r\n this.range.low.x += minOffset;\r\n this.range.high.x += minOffset;\r\n }\r\n }\r\n\r\n private flushLine(context: LayoutContext, line: LineLayout, nextParagraph?: Paragraph): LineLayout {\r\n nextParagraph = nextParagraph ?? line.source;\r\n\r\n // We want to guarantee that each layout line has at least one run.\r\n if (line.runs.length === 0) {\r\n // If we're empty, there should always be a preceding run, and it should be a line break.\r\n if (this.lines.length === 0 || this._back.runs.length === 0) {\r\n return new LineLayout(nextParagraph);\r\n }\r\n\r\n const prevRun = this._back.back.source;\r\n assert(prevRun.type === \"linebreak\");\r\n if (prevRun.type !== \"linebreak\") {\r\n return new LineLayout(nextParagraph);\r\n }\r\n\r\n line.append(RunLayout.create(prevRun.clone(), context));\r\n }\r\n\r\n // Line origin is its baseline.\r\n const lineOffset = { x: 0, y: -line.range.yLength() };\r\n\r\n // Place it below any existing lines\r\n if (this.lines.length > 0) {\r\n lineOffset.y += this._back.offsetFromDocument.y;\r\n lineOffset.y -= context.blockSettings.lineSpacingFactor * context.blockSettings.lineHeight;\r\n }\r\n\r\n line.offsetFromDocument = lineOffset;\r\n\r\n // Update document range from computed line range and position\r\n this.range.extendRange(line.range.cloneTranslated(lineOffset));\r\n\r\n this.lines.push(line);\r\n return new LineLayout(nextParagraph);\r\n }\r\n}\r\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@itwin/core-backend",
3
- "version": "5.0.0-dev.5",
3
+ "version": "5.0.0-dev.7",
4
4
  "description": "iTwin.js backend components",
5
5
  "main": "lib/cjs/core-backend.js",
6
6
  "typings": "lib/cjs/core-backend",
@@ -25,9 +25,9 @@
25
25
  "url": "http://www.bentley.com"
26
26
  },
27
27
  "peerDependencies": {
28
- "@itwin/core-bentley": "^5.0.0-dev.5",
29
- "@itwin/core-common": "^5.0.0-dev.5",
30
- "@itwin/core-geometry": "^5.0.0-dev.5",
28
+ "@itwin/core-bentley": "^5.0.0-dev.7",
29
+ "@itwin/core-common": "^5.0.0-dev.7",
30
+ "@itwin/core-geometry": "^5.0.0-dev.7",
31
31
  "@opentelemetry/api": "^1.0.4"
32
32
  },
33
33
  "peerDependenciesMeta": {
@@ -68,16 +68,16 @@
68
68
  "source-map-loader": "^4.0.0",
69
69
  "typescript": "~5.6.2",
70
70
  "webpack": "^5.76.0",
71
- "@itwin/build-tools": "5.0.0-dev.5",
72
- "@itwin/core-common": "5.0.0-dev.5",
73
- "@itwin/core-bentley": "5.0.0-dev.5",
74
- "@itwin/core-geometry": "5.0.0-dev.5",
75
- "@itwin/core-webpack-tools": "5.0.0-dev.5",
76
- "@itwin/ecsql-common": "5.0.0-dev.5",
77
- "internal-tools": "3.0.0-dev.69"
71
+ "@itwin/build-tools": "5.0.0-dev.7",
72
+ "@itwin/core-bentley": "5.0.0-dev.7",
73
+ "@itwin/core-geometry": "5.0.0-dev.7",
74
+ "@itwin/core-common": "5.0.0-dev.7",
75
+ "internal-tools": "3.0.0-dev.69",
76
+ "@itwin/core-webpack-tools": "5.0.0-dev.7",
77
+ "@itwin/ecsql-common": "5.0.0-dev.7"
78
78
  },
79
79
  "dependencies": {
80
- "@bentley/imodeljs-native": "5.0.2",
80
+ "@bentley/imodeljs-native": "5.0.3",
81
81
  "@itwin/cloud-agnostic-core": "^2.2.4",
82
82
  "@itwin/object-storage-azure": "^2.2.5",
83
83
  "@itwin/object-storage-core": "^2.2.5",
@@ -91,7 +91,7 @@
91
91
  "semver": "^7.5.2",
92
92
  "touch": "^3.1.0",
93
93
  "ws": "^7.5.10",
94
- "@itwin/core-telemetry": "5.0.0-dev.5"
94
+ "@itwin/core-telemetry": "5.0.0-dev.7"
95
95
  },
96
96
  "nyc": {
97
97
  "extends": "./node_modules/@itwin/build-tools/.nycrc"
@@ -100,7 +100,7 @@
100
100
  "build": "npm run -s build:cjs && npm run -s copy:assets && npm run -s copy:test-assets",
101
101
  "build:cjs": "tsc 1>&2 --outDir lib/cjs",
102
102
  "clean": "rimraf lib .rush/temp/package-deps*.json ../../tools/internal/ios/core-test-runner/build ../../tools/internal/lib",
103
- "docs": "betools docs --includes=../../generated-docs/extract --json=../../generated-docs/core/core-backend/file.json --tsIndexFile=./core-backend.ts --onlyJson --excludeGlob=**/*.d.ts",
103
+ "docs": "betools docs --json=../../generated-docs/core/core-backend/file.json --tsIndexFile=./core-backend.ts --onlyJson --excludeGlob=**/*.d.ts",
104
104
  "copy:assets": "cpx \"./src/assets/**/*\" ./lib/cjs/assets",
105
105
  "copy:config": "internal-tools copy-config",
106
106
  "copy:test-assets": "cpx \"./src/test/assets/**/*\" ./lib/cjs/test/assets",
@@ -1,42 +0,0 @@
1
- import { GuidString } from "@itwin/core-bentley";
2
- import { ChangeData, ChangedElements, ChangedModels } from "@itwin/core-common";
3
- /** Utilities for querying changed elements caches
4
- * @internal
5
- * @deprecated in 4.10. Call methods on [[IModelDb]] instance directly.
6
- */
7
- export declare class ChangedElementsManager {
8
- /** Maintains a single entry since we will only have a cache per iModel, which means a ChangedElementsDb per backend instance */
9
- private static _entry;
10
- static getChangedElementsPathName(iModelId: GuidString): string;
11
- /** Get changed elements Db */
12
- private static getChangedElementsDb;
13
- static cleanUp(): void;
14
- /** Gets the changed elements from the cache if found
15
- * @param iModelId Id of the iModel
16
- * @param startChangesetId Start changeset Id
17
- * @param endChangesetId End changeset Id
18
- * @returns Changed elements if found
19
- */
20
- static getChangedElements(iModelId: GuidString, startChangesetId: string, endChangesetId: string): ChangedElements | undefined;
21
- /** Gets the changed models from the cache if found
22
- * @param iModelId Id of the iModel
23
- * @param startChangesetId Start changeset Id
24
- * @param endChangesetId End changeset Id
25
- * @returns Changed models if found
26
- */
27
- static getChangedModels(iModelId: GuidString, startChangesetId: string, endChangesetId: string): ChangedModels | undefined;
28
- /** Gets the change data (models and elements) from the cache if found
29
- * @param iModelId Id of the iModel
30
- * @param startChangesetId Start changeset Id
31
- * @param endChangesetId End changeset Id
32
- * @returns Changed models if found
33
- */
34
- static getChangeData(iModelId: GuidString, startChangesetId: string, endChangesetId: string): ChangeData | undefined;
35
- /** Checks if the cache contains information about the changeset
36
- * @param iModelId Id of the iModel
37
- * @param changesetId Changeset to check for
38
- * @returns true if the changeset has been processed and exists in the cache
39
- */
40
- static isProcessed(iModelId: GuidString, changesetId: string): boolean;
41
- }
42
- //# sourceMappingURL=ChangedElementsManager.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChangedElementsManager.d.ts","sourceRoot":"","sources":["../../src/ChangedElementsManager.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAahF;;;GAGG;AACH,qBAAa,sBAAsB;IACjC,gIAAgI;IAChI,OAAO,CAAC,MAAM,CAAC,MAAM,CAA0C;WAEjD,0BAA0B,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM;IAEtE,8BAA8B;IAC9B,OAAO,CAAC,MAAM,CAAC,oBAAoB;WAyBrB,OAAO;IAQrB;;;;;OAKG;WACW,kBAAkB,CAAC,QAAQ,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS;IAQrI;;;;;OAKG;WACW,gBAAgB,CAAC,QAAQ,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS;IAQjI;;;;;OAKG;WACW,aAAa,CAAC,QAAQ,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS;IAQ3H;;;;OAIG;WACW,WAAW,CAAC,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO;CAO9E"}
@@ -1,91 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ChangedElementsManager = void 0;
4
- const BriefcaseManager_1 = require("./BriefcaseManager");
5
- const ChangedElementsDb_1 = require("./ChangedElementsDb");
6
- const IModelJsFs_1 = require("./IModelJsFs");
7
- /** Utilities for querying changed elements caches
8
- * @internal
9
- * @deprecated in 4.10. Call methods on [[IModelDb]] instance directly.
10
- */
11
- class ChangedElementsManager {
12
- static getChangedElementsPathName(iModelId) { return BriefcaseManager_1.BriefcaseManager.getChangedElementsPathName(iModelId); }
13
- /** Get changed elements Db */
14
- static getChangedElementsDb(iModelId) {
15
- if (this._entry && this._entry.iModelId === iModelId)
16
- return this._entry.db;
17
- if (this._entry && this._entry.iModelId !== iModelId) {
18
- this._entry.db.closeDb();
19
- this._entry.db.cleanCaches();
20
- this._entry = undefined;
21
- }
22
- if (!this._entry) {
23
- const path = ChangedElementsManager.getChangedElementsPathName(iModelId);
24
- if (!IModelJsFs_1.IModelJsFs.existsSync(path))
25
- return undefined;
26
- const db = ChangedElementsDb_1.ChangedElementsDb.openDb(path);
27
- this._entry = {
28
- iModelId,
29
- db,
30
- };
31
- return db;
32
- }
33
- return undefined;
34
- }
35
- static cleanUp() {
36
- if (this._entry) {
37
- this._entry.db.closeDb();
38
- this._entry.db.cleanCaches();
39
- this._entry = undefined;
40
- }
41
- }
42
- /** Gets the changed elements from the cache if found
43
- * @param iModelId Id of the iModel
44
- * @param startChangesetId Start changeset Id
45
- * @param endChangesetId End changeset Id
46
- * @returns Changed elements if found
47
- */
48
- static getChangedElements(iModelId, startChangesetId, endChangesetId) {
49
- const db = ChangedElementsManager.getChangedElementsDb(iModelId);
50
- if (!db)
51
- return undefined;
52
- return db.getChangedElements(startChangesetId, endChangesetId);
53
- }
54
- /** Gets the changed models from the cache if found
55
- * @param iModelId Id of the iModel
56
- * @param startChangesetId Start changeset Id
57
- * @param endChangesetId End changeset Id
58
- * @returns Changed models if found
59
- */
60
- static getChangedModels(iModelId, startChangesetId, endChangesetId) {
61
- const db = ChangedElementsManager.getChangedElementsDb(iModelId);
62
- if (!db)
63
- return undefined;
64
- return db.getChangedModels(startChangesetId, endChangesetId);
65
- }
66
- /** Gets the change data (models and elements) from the cache if found
67
- * @param iModelId Id of the iModel
68
- * @param startChangesetId Start changeset Id
69
- * @param endChangesetId End changeset Id
70
- * @returns Changed models if found
71
- */
72
- static getChangeData(iModelId, startChangesetId, endChangesetId) {
73
- const db = ChangedElementsManager.getChangedElementsDb(iModelId);
74
- if (!db)
75
- return undefined;
76
- return db.getChangeData(startChangesetId, endChangesetId);
77
- }
78
- /** Checks if the cache contains information about the changeset
79
- * @param iModelId Id of the iModel
80
- * @param changesetId Changeset to check for
81
- * @returns true if the changeset has been processed and exists in the cache
82
- */
83
- static isProcessed(iModelId, changesetId) {
84
- const db = ChangedElementsManager.getChangedElementsDb(iModelId);
85
- if (!db)
86
- return false;
87
- return db.isProcessed(changesetId);
88
- }
89
- }
90
- exports.ChangedElementsManager = ChangedElementsManager;
91
- //# sourceMappingURL=ChangedElementsManager.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChangedElementsManager.js","sourceRoot":"","sources":["../../src/ChangedElementsManager.ts"],"names":[],"m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------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\nimport { GuidString } from \"@itwin/core-bentley\";\r\nimport { ChangeData, ChangedElements, ChangedModels } from \"@itwin/core-common\";\r\nimport { BriefcaseManager } from \"./BriefcaseManager\";\r\nimport { ChangedElementsDb } from \"./ChangedElementsDb\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\n\r\n/* eslint-disable @typescript-eslint/no-deprecated */\r\n\r\n/** @internal */\r\ninterface ChangedElementsDbCacheEntry {\r\n iModelId: GuidString;\r\n db: ChangedElementsDb;\r\n}\r\n\r\n/** Utilities for querying changed elements caches\r\n * @internal\r\n * @deprecated in 4.10. Call methods on [[IModelDb]] instance directly.\r\n */\r\nexport class ChangedElementsManager {\r\n /** Maintains a single entry since we will only have a cache per iModel, which means a ChangedElementsDb per backend instance */\r\n private static _entry: ChangedElementsDbCacheEntry | undefined;\r\n\r\n public static getChangedElementsPathName(iModelId: GuidString): string { return BriefcaseManager.getChangedElementsPathName(iModelId); }\r\n\r\n /** Get changed elements Db */\r\n private static getChangedElementsDb(iModelId: GuidString): ChangedElementsDb | undefined {\r\n if (this._entry && this._entry.iModelId === iModelId)\r\n return this._entry.db;\r\n if (this._entry && this._entry.iModelId !== iModelId) {\r\n this._entry.db.closeDb();\r\n this._entry.db.cleanCaches();\r\n this._entry = undefined;\r\n }\r\n if (!this._entry) {\r\n const path = ChangedElementsManager.getChangedElementsPathName(iModelId);\r\n if (!IModelJsFs.existsSync(path))\r\n return undefined;\r\n\r\n const db: ChangedElementsDb = ChangedElementsDb.openDb(path);\r\n this._entry = {\r\n iModelId,\r\n db,\r\n };\r\n\r\n return db;\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n public static cleanUp() {\r\n if (this._entry) {\r\n this._entry.db.closeDb();\r\n this._entry.db.cleanCaches();\r\n this._entry = undefined;\r\n }\r\n }\r\n\r\n /** Gets the changed elements from the cache if found\r\n * @param iModelId Id of the iModel\r\n * @param startChangesetId Start changeset Id\r\n * @param endChangesetId End changeset Id\r\n * @returns Changed elements if found\r\n */\r\n public static getChangedElements(iModelId: GuidString, startChangesetId: string, endChangesetId: string): ChangedElements | undefined {\r\n const db: ChangedElementsDb | undefined = ChangedElementsManager.getChangedElementsDb(iModelId);\r\n if (!db)\r\n return undefined;\r\n\r\n return db.getChangedElements(startChangesetId, endChangesetId);\r\n }\r\n\r\n /** Gets the changed models from the cache if found\r\n * @param iModelId Id of the iModel\r\n * @param startChangesetId Start changeset Id\r\n * @param endChangesetId End changeset Id\r\n * @returns Changed models if found\r\n */\r\n public static getChangedModels(iModelId: GuidString, startChangesetId: string, endChangesetId: string): ChangedModels | undefined {\r\n const db: ChangedElementsDb | undefined = ChangedElementsManager.getChangedElementsDb(iModelId);\r\n if (!db)\r\n return undefined;\r\n\r\n return db.getChangedModels(startChangesetId, endChangesetId);\r\n }\r\n\r\n /** Gets the change data (models and elements) from the cache if found\r\n * @param iModelId Id of the iModel\r\n * @param startChangesetId Start changeset Id\r\n * @param endChangesetId End changeset Id\r\n * @returns Changed models if found\r\n */\r\n public static getChangeData(iModelId: GuidString, startChangesetId: string, endChangesetId: string): ChangeData | undefined {\r\n const db: ChangedElementsDb | undefined = ChangedElementsManager.getChangedElementsDb(iModelId);\r\n if (!db)\r\n return undefined;\r\n\r\n return db.getChangeData(startChangesetId, endChangesetId);\r\n }\r\n\r\n /** Checks if the cache contains information about the changeset\r\n * @param iModelId Id of the iModel\r\n * @param changesetId Changeset to check for\r\n * @returns true if the changeset has been processed and exists in the cache\r\n */\r\n public static isProcessed(iModelId: GuidString, changesetId: string): boolean {\r\n const db: ChangedElementsDb | undefined = ChangedElementsManager.getChangedElementsDb(iModelId);\r\n if (!db)\r\n return false;\r\n\r\n return db.isProcessed(changesetId);\r\n }\r\n}\r\n"]}
@@ -1,17 +0,0 @@
1
- /** @packageDocumentation
2
- * @module RpcInterface
3
- */
4
- import { ChangedElements, IModelRpcProps, RpcInterface, WipRpcInterface } from "@itwin/core-common";
5
- /** The backend implementation of WipRpcInterface.
6
- * @internal
7
- * @deprecated in 4.10. If any of these methods are needed in the frontend, they should be rewritten using IPC or HTTP protocol.
8
- */
9
- export declare class WipRpcImpl extends RpcInterface implements WipRpcInterface {
10
- static register(): void;
11
- placeholder(_tokenProps: IModelRpcProps): Promise<string>;
12
- isChangeCacheAttached(tokenProps: IModelRpcProps): Promise<boolean>;
13
- attachChangeCache(tokenProps: IModelRpcProps): Promise<void>;
14
- getChangedElements(tokenProps: IModelRpcProps, startChangesetId: string, endChangesetId: string): Promise<ChangedElements | undefined>;
15
- isChangesetProcessed(tokenProps: IModelRpcProps, changesetId: string): Promise<boolean>;
16
- }
17
- //# sourceMappingURL=WipRpcImpl.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"WipRpcImpl.d.ts","sourceRoot":"","sources":["../../../src/rpc-impl/WipRpcImpl.ts"],"names":[],"mappings":"AAIA;;GAEG;AAKH,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,YAAY,EAAc,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAKhH;;;GAGG;AACH,qBAAa,UAAW,SAAQ,YAAa,YAAW,eAAe;WAEvD,QAAQ;IACT,WAAW,CAAC,WAAW,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAEzD,qBAAqB,CAAC,UAAU,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC;IAInE,iBAAiB,CAAC,UAAU,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAI5D,kBAAkB,CAAC,UAAU,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC;IAKtI,oBAAoB,CAAC,UAAU,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;CAIrG"}
@@ -1,40 +0,0 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
- * See LICENSE.md in the project root for license terms and full copyright notice.
5
- *--------------------------------------------------------------------------------------------*/
6
- /** @packageDocumentation
7
- * @module RpcInterface
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.WipRpcImpl = void 0;
11
- /* eslint-disable @typescript-eslint/no-deprecated */
12
- const core_bentley_1 = require("@itwin/core-bentley");
13
- const core_common_1 = require("@itwin/core-common");
14
- const ChangedElementsManager_1 = require("../ChangedElementsManager");
15
- const ChangeSummaryManager_1 = require("../ChangeSummaryManager");
16
- const IModelDb_1 = require("../IModelDb");
17
- /** The backend implementation of WipRpcInterface.
18
- * @internal
19
- * @deprecated in 4.10. If any of these methods are needed in the frontend, they should be rewritten using IPC or HTTP protocol.
20
- */
21
- class WipRpcImpl extends core_common_1.RpcInterface {
22
- static register() { core_common_1.RpcManager.registerImpl(core_common_1.WipRpcInterface, WipRpcImpl); }
23
- async placeholder(_tokenProps) { return "placeholder"; }
24
- async isChangeCacheAttached(tokenProps) {
25
- return ChangeSummaryManager_1.ChangeSummaryManager.isChangeCacheAttached(IModelDb_1.BriefcaseDb.findByKey(tokenProps.key));
26
- }
27
- async attachChangeCache(tokenProps) {
28
- ChangeSummaryManager_1.ChangeSummaryManager.attachChangeCache(IModelDb_1.BriefcaseDb.findByKey(tokenProps.key));
29
- }
30
- async getChangedElements(tokenProps, startChangesetId, endChangesetId) {
31
- (0, core_bentley_1.assert)(undefined !== tokenProps.iModelId);
32
- return ChangedElementsManager_1.ChangedElementsManager.getChangedElements(tokenProps.iModelId, startChangesetId, endChangesetId);
33
- }
34
- async isChangesetProcessed(tokenProps, changesetId) {
35
- (0, core_bentley_1.assert)(undefined !== tokenProps.iModelId);
36
- return ChangedElementsManager_1.ChangedElementsManager.isProcessed(tokenProps.iModelId, changesetId);
37
- }
38
- }
39
- exports.WipR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,QAAQ,EAAE,WAAW,CAAC,CAAC;IAC9E,CAAC;CACF;AAtBD,gCAsBC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module RpcInterface\r\n */\r\n\r\n/* eslint-disable @typescript-eslint/no-deprecated */\r\n\r\nimport { assert } from \"@itwin/core-bentley\";\r\nimport { ChangedElements, IModelRpcProps, RpcInterface, RpcManager, WipRpcInterface } from \"@itwin/core-common\";\r\nimport { ChangedElementsManager } from \"../ChangedElementsManager\";\r\nimport { ChangeSummaryManager } from \"../ChangeSummaryManager\";\r\nimport { BriefcaseDb } from \"../IModelDb\";\r\n\r\n/** The backend implementation of WipRpcInterface.\r\n * @internal\r\n * @deprecated in 4.10. If any of these methods are needed in the frontend, they should be rewritten using IPC or HTTP protocol.\r\n */\r\nexport class WipRpcImpl extends RpcInterface implements WipRpcInterface {\r\n\r\n public static register() { RpcManager.registerImpl(WipRpcInterface, WipRpcImpl); }\r\n public async placeholder(_tokenProps: IModelRpcProps): Promise<string> { return \"placeholder\"; }\r\n\r\n public async isChangeCacheAttached(tokenProps: IModelRpcProps): Promise<boolean> {\r\n return ChangeSummaryManager.isChangeCacheAttached(BriefcaseDb.findByKey(tokenProps.key));\r\n }\r\n\r\n public async attachChangeCache(tokenProps: IModelRpcProps): Promise<void> {\r\n ChangeSummaryManager.attachChangeCache(BriefcaseDb.findByKey(tokenProps.key));\r\n }\r\n\r\n public async getChangedElements(tokenProps: IModelRpcProps, startChangesetId: string, endChangesetId: string): Promise<ChangedElements | undefined> {\r\n assert(undefined !== tokenProps.iModelId);\r\n return ChangedElementsManager.getChangedElements(tokenProps.iModelId, startChangesetId, endChangesetId);\r\n }\r\n\r\n public async isChangesetProcessed(tokenProps: IModelRpcProps, changesetId: string): Promise<boolean> {\r\n assert(undefined !== tokenProps.iModelId);\r\n return ChangedElementsManager.isProcessed(tokenProps.iModelId, changesetId);\r\n }\r\n}\r\n"]}