@itwin/core-backend 4.0.0-dev.23 → 4.0.0-dev.28
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 +71 -66
- package/lib/cjs/BriefcaseManager.js +13 -19
- package/lib/cjs/BriefcaseManager.js.map +1 -1
- package/lib/cjs/ChangeSummaryManager.js +6 -7
- package/lib/cjs/ChangeSummaryManager.js.map +1 -1
- package/lib/cjs/CheckpointManager.js +3 -4
- package/lib/cjs/CheckpointManager.js.map +1 -1
- package/lib/cjs/ClassRegistry.js +1 -2
- package/lib/cjs/ClassRegistry.js.map +1 -1
- package/lib/cjs/CloudSqlite.js +1 -1
- package/lib/cjs/CloudSqlite.js.map +1 -1
- package/lib/cjs/CloudStorageBackend.js +5 -8
- package/lib/cjs/CloudStorageBackend.js.map +1 -1
- package/lib/cjs/CustomViewState3dCreator.js +2 -2
- package/lib/cjs/CustomViewState3dCreator.js.map +1 -1
- package/lib/cjs/DisplayStyle.js +8 -11
- package/lib/cjs/DisplayStyle.js.map +1 -1
- package/lib/cjs/ECDb.js +2 -4
- package/lib/cjs/ECDb.js.map +1 -1
- package/lib/cjs/Element.js +13 -21
- package/lib/cjs/Element.js.map +1 -1
- package/lib/cjs/ElementTreeWalker.js +2 -2
- package/lib/cjs/ElementTreeWalker.js.map +1 -1
- package/lib/cjs/GeoCoordConfig.js +1 -1
- package/lib/cjs/GeoCoordConfig.js.map +1 -1
- package/lib/cjs/HubMock.js +3 -5
- package/lib/cjs/HubMock.js.map +1 -1
- package/lib/cjs/IModelDb.d.ts +15 -1
- package/lib/cjs/IModelDb.d.ts.map +1 -1
- package/lib/cjs/IModelDb.js +44 -59
- package/lib/cjs/IModelDb.js.map +1 -1
- package/lib/cjs/IModelHost.js +15 -23
- package/lib/cjs/IModelHost.js.map +1 -1
- package/lib/cjs/IModelJsFs.js +2 -3
- package/lib/cjs/IModelJsFs.js.map +1 -1
- package/lib/cjs/IpcHost.js +11 -13
- package/lib/cjs/IpcHost.js.map +1 -1
- package/lib/cjs/LocalHub.js +11 -16
- package/lib/cjs/LocalHub.js.map +1 -1
- package/lib/cjs/LocalhostIpcHost.js +3 -5
- package/lib/cjs/LocalhostIpcHost.js.map +1 -1
- package/lib/cjs/Material.js +1 -2
- package/lib/cjs/Material.js.map +1 -1
- package/lib/cjs/NativeHost.js +3 -6
- package/lib/cjs/NativeHost.js.map +1 -1
- package/lib/cjs/SQLiteDb.js +2 -4
- package/lib/cjs/SQLiteDb.js.map +1 -1
- package/lib/cjs/TileStorage.js +4 -7
- package/lib/cjs/TileStorage.js.map +1 -1
- package/lib/cjs/rpc/tracing.js +1 -2
- package/lib/cjs/rpc/tracing.js.map +1 -1
- package/lib/cjs/rpc/web/request.js +1 -2
- package/lib/cjs/rpc/web/request.js.map +1 -1
- package/lib/cjs/rpc/web/response.js +1 -2
- package/lib/cjs/rpc/web/response.js.map +1 -1
- package/lib/cjs/rpc-impl/IModelReadRpcImpl.js +1 -2
- package/lib/cjs/rpc-impl/IModelReadRpcImpl.js.map +1 -1
- package/lib/cjs/rpc-impl/IModelTileRpcImpl.js +4 -7
- package/lib/cjs/rpc-impl/IModelTileRpcImpl.js.map +1 -1
- package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js +6 -8
- package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js.map +1 -1
- package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js +1 -2
- package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js.map +1 -1
- package/lib/cjs/workspace/Settings.js +1 -2
- package/lib/cjs/workspace/Settings.js.map +1 -1
- package/lib/cjs/workspace/SettingsSchemas.js +3 -4
- package/lib/cjs/workspace/SettingsSchemas.js.map +1 -1
- package/lib/cjs/workspace/Workspace.js +15 -21
- package/lib/cjs/workspace/Workspace.js.map +1 -1
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IModelTileRpcImpl.js","sourceRoot":"","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AAC,KAAK,CAAC,CAAC;SAC3D;QAED,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;KAC3E;AACH,CAAC;AAbD,8DAaC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module RpcInterface\n */\n\nimport type { TransferConfig } from \"@itwin/object-storage-core\";\nimport { AccessToken, assert, BeDuration, Id64Array, Logger } from \"@itwin/core-bentley\";\nimport {\n CloudStorageContainerDescriptor, CloudStorageContainerUrl, CloudStorageTileCache, ElementGraphicsRequestProps, IModelRpcProps,\n IModelTileRpcInterface, IModelTileTreeProps, RpcInterface, RpcInvocation, RpcManager, RpcPendingResponse, TileContentIdentifier,\n TileContentSource, TileTreeContentIds, TileVersionInfo,\n} from \"@itwin/core-common\";\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\nimport { IModelDb } from \"../IModelDb\";\nimport { IModelHost } from \"../IModelHost\";\nimport { PromiseMemoizer, QueryablePromise } from \"../PromiseMemoizer\";\nimport { RpcTrace } from \"../rpc/tracing\";\nimport { RpcBriefcaseUtility } from \"./RpcBriefcaseUtility\";\n\ninterface TileRequestProps {\n accessToken?: AccessToken;\n tokenProps: IModelRpcProps;\n treeId: string;\n}\n\nfunction generateTileRequestKey(props: TileRequestProps): string {\n const token = props.tokenProps;\n return `${JSON.stringify({\n key: token.key,\n iTwinId: token.iTwinId,\n iModelId: token.iModelId,\n changesetId: token.changeset?.id,\n })}:${props.treeId}`;\n}\n\nabstract class TileRequestMemoizer<Result, Props extends TileRequestProps> extends PromiseMemoizer<Result> {\n private readonly _loggerCategory = BackendLoggerCategory.IModelTileRequestRpc;\n protected abstract get _operationName(): string;\n protected abstract addMetadata(metadata: any, props: Props): void;\n protected abstract stringify(props: Props): string;\n protected abstract get _timeoutMilliseconds(): number;\n\n private makeMetadata(props: Props): any {\n const meta = { ...props.tokenProps };\n this.addMetadata(meta, props);\n return meta;\n }\n\n protected constructor(memoizeFn: (props: Props) => Promise<Result>, generateKeyFn: (props: Props) => string) {\n super(memoizeFn, generateKeyFn);\n }\n\n public override memoize(props: Props): QueryablePromise<Result> {\n return super.memoize(props);\n }\n\n public override deleteMemoized(props: Props) {\n super.deleteMemoized(props);\n }\n\n private log(status: string, props: Props): void {\n const descr = `${this._operationName}(${this.stringify(props)})`;\n Logger.logTrace(this._loggerCategory, `Backend ${status} ${descr}`, () => this.makeMetadata(props));\n }\n\n protected async perform(props: Props): Promise<Result> {\n this.log(\"received\", props);\n\n const tileQP = this.memoize(props);\n\n await BeDuration.race(this._timeoutMilliseconds, tileQP.promise).catch(() => { });\n // Note: Rejections must be caught so that the memoization entry can be deleted\n\n if (tileQP.isPending) {\n this.log(\"issuing pending status for\", props);\n throw new RpcPendingResponse(); // eslint-disable-line deprecation/deprecation\n }\n\n this.deleteMemoized(props);\n\n if (tileQP.isFulfilled) {\n this.log(\"completed\", props);\n assert(undefined !== tileQP.result);\n return tileQP.result;\n }\n\n assert(tileQP.isRejected);\n this.log(\"rejected\", props);\n throw tileQP.error; // eslint-disable-line no-throw-literal\n }\n}\n\nasync function getTileTreeProps(props: TileRequestProps): Promise<IModelTileTreeProps> {\n assert(undefined !== props.accessToken);\n const db = await RpcBriefcaseUtility.findOpenIModel(props.accessToken, props.tokenProps);\n return db.tiles.requestTileTreeProps(props.treeId);\n}\n\nclass RequestTileTreePropsMemoizer extends TileRequestMemoizer<IModelTileTreeProps, TileRequestProps> {\n protected get _timeoutMilliseconds() { return IModelHost.tileTreeRequestTimeout; }\n protected get _operationName() { return \"requestTileTreeProps\"; }\n protected stringify(props: TileRequestProps): string { return props.treeId; }\n protected addMetadata(meta: any, props: TileRequestProps): void {\n meta.treeId = props.treeId;\n }\n\n private static _instance?: RequestTileTreePropsMemoizer;\n\n private constructor() {\n super(getTileTreeProps, generateTileRequestKey);\n IModelHost.onBeforeShutdown.addOnce(() => {\n this.dispose();\n RequestTileTreePropsMemoizer._instance = undefined;\n });\n }\n\n public static async perform(props: TileRequestProps): Promise<IModelTileTreeProps> {\n if (undefined === this._instance)\n this._instance = new RequestTileTreePropsMemoizer();\n\n return this._instance.perform(props);\n }\n}\n\ninterface TileContentRequestProps extends TileRequestProps {\n contentId: string;\n guid?: string;\n}\n\nasync function getTileContent(props: TileContentRequestProps): Promise<TileContentSource> {\n assert(undefined !== props.accessToken);\n const db = await RpcBriefcaseUtility.findOpenIModel(props.accessToken, props.tokenProps);\n const tile = await db.tiles.requestTileContent(props.treeId, props.contentId);\n\n // ###TODO: Verify the guid supplied by the front-end matches the guid stored in the model?\n if (IModelHost.usingExternalTileCache) {\n await IModelHost.tileStorage?.uploadTile(db.iModelId, db.changeset.id, props.treeId, props.contentId, tile.content, props.guid, {\n backendName: IModelHost.applicationId,\n tileGenerationTime: tile.elapsedSeconds.toString(),\n tileSize: tile.content.byteLength.toString(),\n });\n\n return TileContentSource.ExternalCache;\n }\n\n return TileContentSource.Backend;\n}\n\nfunction generateTileContentKey(props: TileContentRequestProps): string {\n return `${generateTileRequestKey(props)}:${props.contentId}`;\n}\n\nclass RequestTileContentMemoizer extends TileRequestMemoizer<TileContentSource, TileContentRequestProps> {\n protected get _timeoutMilliseconds() { return IModelHost.tileContentRequestTimeout; }\n protected get _operationName() { return \"requestTileContent\"; }\n protected stringify(props: TileContentRequestProps): string { return `${props.treeId}:${props.contentId}`; }\n protected addMetadata(meta: any, props: TileContentRequestProps): void {\n meta.treeId = props.treeId;\n meta.contentId = props.contentId;\n }\n\n private static _instance?: RequestTileContentMemoizer;\n\n private constructor() {\n super(getTileContent, generateTileContentKey);\n IModelHost.onBeforeShutdown.addOnce(() => {\n this.dispose();\n RequestTileContentMemoizer._instance = undefined;\n });\n }\n\n public static get instance() {\n if (undefined === this._instance)\n this._instance = new RequestTileContentMemoizer();\n\n return this._instance;\n }\n\n public static async perform(props: TileContentRequestProps): Promise<TileContentSource> {\n return this.instance.perform(props);\n }\n}\n\nfunction currentActivity() {\n return RpcTrace.expectCurrentActivity; // eslint-disable-line deprecation/deprecation\n}\n\n/** @internal */\nexport class IModelTileRpcImpl extends RpcInterface implements IModelTileRpcInterface { // eslint-disable-line deprecation/deprecation\n public static register() { RpcManager.registerImpl(IModelTileRpcInterface, IModelTileRpcImpl); }\n\n public async requestTileTreeProps(tokenProps: IModelRpcProps, treeId: string): Promise<IModelTileTreeProps> {\n return RequestTileTreePropsMemoizer.perform({ accessToken: currentActivity().accessToken, tokenProps, treeId });\n }\n\n public async purgeTileTrees(tokenProps: IModelRpcProps, modelIds: Id64Array | undefined): Promise<void> {\n // `undefined` gets forwarded as `null`...\n if (null === modelIds)\n modelIds = undefined;\n\n const db = await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, tokenProps);\n return db.nativeDb.purgeTileTrees(modelIds);\n }\n\n public async generateTileContent(tokenProps: IModelRpcProps, treeId: string, contentId: string, guid: string | undefined): Promise<TileContentSource> {\n return RequestTileContentMemoizer.perform({ accessToken: currentActivity().accessToken, tokenProps, treeId, contentId, guid });\n }\n\n public async retrieveTileContent(tokenProps: IModelRpcProps, key: TileContentIdentifier): Promise<Uint8Array> {\n const db = await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, tokenProps);\n return db.tiles.getTileContent(key.treeId, key.contentId);\n }\n\n public async getTileCacheConfig(tokenProps: IModelRpcProps): Promise<TransferConfig | undefined> {\n if (IModelHost.tileStorage === undefined)\n return undefined;\n const iModelId = tokenProps.iModelId ?? (await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, tokenProps)).iModelId;\n return IModelHost.tileStorage.getDownloadConfig(iModelId);\n }\n\n /* eslint-disable deprecation/deprecation */\n public async getTileCacheContainerUrl(_tokenProps: IModelRpcProps, id: CloudStorageContainerDescriptor): Promise<CloudStorageContainerUrl> {\n const invocation = RpcInvocation.current(this);\n\n if (!IModelHost.usingExternalTileCache) {\n return CloudStorageContainerUrl.empty();\n }\n\n const expiry = CloudStorageTileCache.getCache().supplyExpiryForContainerUrl(id);\n const clientIp = (IModelHost.restrictTileUrlsByClientIp && invocation.request.ip) ? invocation.request.ip : undefined;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return IModelHost.tileCacheService!.obtainContainerUrl(id, expiry, clientIp);\n }\n\n public async isUsingExternalTileCache(): Promise<boolean> { // eslint-disable-line @itwin/prefer-get\n return IModelHost.tileCacheService !== undefined;\n }\n /* eslint-enable deprecation/deprecation */\n\n public async queryVersionInfo(): Promise<TileVersionInfo> {\n return IModelHost.platform.getTileVersionInfo();\n }\n\n /** @internal */\n public async requestElementGraphics(rpcProps: IModelRpcProps, request: ElementGraphicsRequestProps): Promise<Uint8Array | undefined> {\n const iModel = await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, rpcProps);\n return iModel.generateElementGraphics(request);\n }\n}\n\n/** @internal */\nexport async function cancelTileContentRequests(tokenProps: IModelRpcProps, contentIds: TileTreeContentIds[]): Promise<void> {\n const iModel = IModelDb.findByKey(tokenProps.key);\n const props: TileContentRequestProps = { tokenProps, treeId: \"\", contentId: \"\" };\n\n for (const entry of contentIds) {\n props.treeId = entry.treeId;\n for (const contentId of entry.contentIds) {\n props.contentId = contentId;\n RequestTileContentMemoizer.instance.deleteMemoized(props);\n }\n\n iModel.nativeDb.cancelTileContentRequests(entry.treeId, entry.contentIds);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"IModelTileRpcImpl.js","sourceRoot":"","sources":["../../../src/rpc-impl/IModelTileRpcImpl.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAGH,sDAAyF;AACzF,oDAI4B;AAC5B,oEAAiE;AACjE,0CAAuC;AACvC,8CAA2C;AAC3C,wDAAuE;AACvE,4CAA0C;AAC1C,+DAA4D;AAQ5D,SAAS,sBAAsB,CAAC,KAAuB;IACrD,M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;IAEM,KAAK,CAAC,wBAAwB;QACnC,OAAO,uBAAU,CAAC,gBAAgB,KAAK,SAAS,CAAC;IACnD,CAAC;IACD,2CAA2C;IAEpC,KAAK,CAAC,gBAAgB;QAC3B,OAAO,uBAAU,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC;IAClD,CAAC;IAED,gBAAgB;IACT,KAAK,CAAC,sBAAsB,CAAC,QAAwB,EAAE,OAAoC;QAChG,MAAM,MAAM,GAAG,MAAM,yCAAmB,CAAC,cAAc,CAAC,eAAe,EAAE,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;QACjG,OAAO,MAAM,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC;CACF;AA5DD,8CA4DC;AAED,gBAAgB;AACT,KAAK,UAAU,yBAAyB,CAAC,UAA0B,EAAE,UAAgC;IAC1G,MAAM,MAAM,GAAG,mBAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAClD,MAAM,KAAK,GAA4B,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;IAEjF,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE;QAC9B,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;QAC5B,KAAK,MAAM,SAAS,IAAI,KAAK,CAAC,UAAU,EAAE;YACxC,KAAK,CAAC,SAAS,GAAG,SAAS,CAAC;YAC5B,0BAA0B,CAAC,QAAQ,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;SAC3D;QAED,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;KAC3E;AACH,CAAC;AAbD,8DAaC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module RpcInterface\n */\n\nimport type { TransferConfig } from \"@itwin/object-storage-core\";\nimport { AccessToken, assert, BeDuration, Id64Array, Logger } from \"@itwin/core-bentley\";\nimport {\n CloudStorageContainerDescriptor, CloudStorageContainerUrl, CloudStorageTileCache, ElementGraphicsRequestProps, IModelRpcProps,\n IModelTileRpcInterface, IModelTileTreeProps, RpcInterface, RpcInvocation, RpcManager, RpcPendingResponse, TileContentIdentifier,\n TileContentSource, TileTreeContentIds, TileVersionInfo,\n} from \"@itwin/core-common\";\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\nimport { IModelDb } from \"../IModelDb\";\nimport { IModelHost } from \"../IModelHost\";\nimport { PromiseMemoizer, QueryablePromise } from \"../PromiseMemoizer\";\nimport { RpcTrace } from \"../rpc/tracing\";\nimport { RpcBriefcaseUtility } from \"./RpcBriefcaseUtility\";\n\ninterface TileRequestProps {\n accessToken?: AccessToken;\n tokenProps: IModelRpcProps;\n treeId: string;\n}\n\nfunction generateTileRequestKey(props: TileRequestProps): string {\n const token = props.tokenProps;\n return `${JSON.stringify({\n key: token.key,\n iTwinId: token.iTwinId,\n iModelId: token.iModelId,\n changesetId: token.changeset?.id,\n })}:${props.treeId}`;\n}\n\nabstract class TileRequestMemoizer<Result, Props extends TileRequestProps> extends PromiseMemoizer<Result> {\n private readonly _loggerCategory = BackendLoggerCategory.IModelTileRequestRpc;\n protected abstract get _operationName(): string;\n protected abstract addMetadata(metadata: any, props: Props): void;\n protected abstract stringify(props: Props): string;\n protected abstract get _timeoutMilliseconds(): number;\n\n private makeMetadata(props: Props): any {\n const meta = { ...props.tokenProps };\n this.addMetadata(meta, props);\n return meta;\n }\n\n protected constructor(memoizeFn: (props: Props) => Promise<Result>, generateKeyFn: (props: Props) => string) {\n super(memoizeFn, generateKeyFn);\n }\n\n public override memoize(props: Props): QueryablePromise<Result> {\n return super.memoize(props);\n }\n\n public override deleteMemoized(props: Props) {\n super.deleteMemoized(props);\n }\n\n private log(status: string, props: Props): void {\n const descr = `${this._operationName}(${this.stringify(props)})`;\n Logger.logTrace(this._loggerCategory, `Backend ${status} ${descr}`, () => this.makeMetadata(props));\n }\n\n protected async perform(props: Props): Promise<Result> {\n this.log(\"received\", props);\n\n const tileQP = this.memoize(props);\n\n await BeDuration.race(this._timeoutMilliseconds, tileQP.promise).catch(() => { });\n // Note: Rejections must be caught so that the memoization entry can be deleted\n\n if (tileQP.isPending) {\n this.log(\"issuing pending status for\", props);\n throw new RpcPendingResponse(); // eslint-disable-line deprecation/deprecation\n }\n\n this.deleteMemoized(props);\n\n if (tileQP.isFulfilled) {\n this.log(\"completed\", props);\n assert(undefined !== tileQP.result);\n return tileQP.result;\n }\n\n assert(tileQP.isRejected);\n this.log(\"rejected\", props);\n throw tileQP.error; // eslint-disable-line no-throw-literal\n }\n}\n\nasync function getTileTreeProps(props: TileRequestProps): Promise<IModelTileTreeProps> {\n assert(undefined !== props.accessToken);\n const db = await RpcBriefcaseUtility.findOpenIModel(props.accessToken, props.tokenProps);\n return db.tiles.requestTileTreeProps(props.treeId);\n}\n\nclass RequestTileTreePropsMemoizer extends TileRequestMemoizer<IModelTileTreeProps, TileRequestProps> {\n protected get _timeoutMilliseconds() { return IModelHost.tileTreeRequestTimeout; }\n protected get _operationName() { return \"requestTileTreeProps\"; }\n protected stringify(props: TileRequestProps): string { return props.treeId; }\n protected addMetadata(meta: any, props: TileRequestProps): void {\n meta.treeId = props.treeId;\n }\n\n private static _instance?: RequestTileTreePropsMemoizer;\n\n private constructor() {\n super(getTileTreeProps, generateTileRequestKey);\n IModelHost.onBeforeShutdown.addOnce(() => {\n this.dispose();\n RequestTileTreePropsMemoizer._instance = undefined;\n });\n }\n\n public static async perform(props: TileRequestProps): Promise<IModelTileTreeProps> {\n if (undefined === this._instance)\n this._instance = new RequestTileTreePropsMemoizer();\n\n return this._instance.perform(props);\n }\n}\n\ninterface TileContentRequestProps extends TileRequestProps {\n contentId: string;\n guid?: string;\n}\n\nasync function getTileContent(props: TileContentRequestProps): Promise<TileContentSource> {\n assert(undefined !== props.accessToken);\n const db = await RpcBriefcaseUtility.findOpenIModel(props.accessToken, props.tokenProps);\n const tile = await db.tiles.requestTileContent(props.treeId, props.contentId);\n\n // ###TODO: Verify the guid supplied by the front-end matches the guid stored in the model?\n if (IModelHost.usingExternalTileCache) {\n await IModelHost.tileStorage?.uploadTile(db.iModelId, db.changeset.id, props.treeId, props.contentId, tile.content, props.guid, {\n backendName: IModelHost.applicationId,\n tileGenerationTime: tile.elapsedSeconds.toString(),\n tileSize: tile.content.byteLength.toString(),\n });\n\n return TileContentSource.ExternalCache;\n }\n\n return TileContentSource.Backend;\n}\n\nfunction generateTileContentKey(props: TileContentRequestProps): string {\n return `${generateTileRequestKey(props)}:${props.contentId}`;\n}\n\nclass RequestTileContentMemoizer extends TileRequestMemoizer<TileContentSource, TileContentRequestProps> {\n protected get _timeoutMilliseconds() { return IModelHost.tileContentRequestTimeout; }\n protected get _operationName() { return \"requestTileContent\"; }\n protected stringify(props: TileContentRequestProps): string { return `${props.treeId}:${props.contentId}`; }\n protected addMetadata(meta: any, props: TileContentRequestProps): void {\n meta.treeId = props.treeId;\n meta.contentId = props.contentId;\n }\n\n private static _instance?: RequestTileContentMemoizer;\n\n private constructor() {\n super(getTileContent, generateTileContentKey);\n IModelHost.onBeforeShutdown.addOnce(() => {\n this.dispose();\n RequestTileContentMemoizer._instance = undefined;\n });\n }\n\n public static get instance() {\n if (undefined === this._instance)\n this._instance = new RequestTileContentMemoizer();\n\n return this._instance;\n }\n\n public static async perform(props: TileContentRequestProps): Promise<TileContentSource> {\n return this.instance.perform(props);\n }\n}\n\nfunction currentActivity() {\n return RpcTrace.expectCurrentActivity; // eslint-disable-line deprecation/deprecation\n}\n\n/** @internal */\nexport class IModelTileRpcImpl extends RpcInterface implements IModelTileRpcInterface { // eslint-disable-line deprecation/deprecation\n public static register() { RpcManager.registerImpl(IModelTileRpcInterface, IModelTileRpcImpl); }\n\n public async requestTileTreeProps(tokenProps: IModelRpcProps, treeId: string): Promise<IModelTileTreeProps> {\n return RequestTileTreePropsMemoizer.perform({ accessToken: currentActivity().accessToken, tokenProps, treeId });\n }\n\n public async purgeTileTrees(tokenProps: IModelRpcProps, modelIds: Id64Array | undefined): Promise<void> {\n // `undefined` gets forwarded as `null`...\n if (null === modelIds)\n modelIds = undefined;\n\n const db = await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, tokenProps);\n return db.nativeDb.purgeTileTrees(modelIds);\n }\n\n public async generateTileContent(tokenProps: IModelRpcProps, treeId: string, contentId: string, guid: string | undefined): Promise<TileContentSource> {\n return RequestTileContentMemoizer.perform({ accessToken: currentActivity().accessToken, tokenProps, treeId, contentId, guid });\n }\n\n public async retrieveTileContent(tokenProps: IModelRpcProps, key: TileContentIdentifier): Promise<Uint8Array> {\n const db = await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, tokenProps);\n return db.tiles.getTileContent(key.treeId, key.contentId);\n }\n\n public async getTileCacheConfig(tokenProps: IModelRpcProps): Promise<TransferConfig | undefined> {\n if (IModelHost.tileStorage === undefined)\n return undefined;\n const iModelId = tokenProps.iModelId ?? (await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, tokenProps)).iModelId;\n return IModelHost.tileStorage.getDownloadConfig(iModelId);\n }\n\n /* eslint-disable deprecation/deprecation */\n public async getTileCacheContainerUrl(_tokenProps: IModelRpcProps, id: CloudStorageContainerDescriptor): Promise<CloudStorageContainerUrl> {\n const invocation = RpcInvocation.current(this);\n\n if (!IModelHost.usingExternalTileCache) {\n return CloudStorageContainerUrl.empty();\n }\n\n const expiry = CloudStorageTileCache.getCache().supplyExpiryForContainerUrl(id);\n const clientIp = (IModelHost.restrictTileUrlsByClientIp && invocation.request.ip) ? invocation.request.ip : undefined;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return IModelHost.tileCacheService!.obtainContainerUrl(id, expiry, clientIp);\n }\n\n public async isUsingExternalTileCache(): Promise<boolean> { // eslint-disable-line @itwin/prefer-get\n return IModelHost.tileCacheService !== undefined;\n }\n /* eslint-enable deprecation/deprecation */\n\n public async queryVersionInfo(): Promise<TileVersionInfo> {\n return IModelHost.platform.getTileVersionInfo();\n }\n\n /** @internal */\n public async requestElementGraphics(rpcProps: IModelRpcProps, request: ElementGraphicsRequestProps): Promise<Uint8Array | undefined> {\n const iModel = await RpcBriefcaseUtility.findOpenIModel(currentActivity().accessToken, rpcProps);\n return iModel.generateElementGraphics(request);\n }\n}\n\n/** @internal */\nexport async function cancelTileContentRequests(tokenProps: IModelRpcProps, contentIds: TileTreeContentIds[]): Promise<void> {\n const iModel = IModelDb.findByKey(tokenProps.key);\n const props: TileContentRequestProps = { tokenProps, treeId: \"\", contentId: \"\" };\n\n for (const entry of contentIds) {\n props.treeId = entry.treeId;\n for (const contentId of entry.contentIds) {\n props.contentId = contentId;\n RequestTileContentMemoizer.instance.deleteMemoized(props);\n }\n\n iModel.nativeDb.cancelTileContentRequests(entry.treeId, entry.contentIds);\n }\n}\n"]}
|
|
@@ -23,7 +23,6 @@ const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
|
|
|
23
23
|
*/
|
|
24
24
|
class RpcBriefcaseUtility {
|
|
25
25
|
static async downloadAndOpen(args) {
|
|
26
|
-
var _a, _b, _c, _d;
|
|
27
26
|
const { activity, tokenProps } = args;
|
|
28
27
|
const accessToken = activity.accessToken;
|
|
29
28
|
(0, core_bentley_1.assert)(undefined !== tokenProps.iModelId);
|
|
@@ -36,7 +35,7 @@ class RpcBriefcaseUtility {
|
|
|
36
35
|
// check with iModelHub and see if we already have acquired any briefcaseIds
|
|
37
36
|
myBriefcaseIds = await IModelHost_1.IModelHost.hubAccess.getMyBriefcaseIds({ accessToken, iModelId });
|
|
38
37
|
}
|
|
39
|
-
const resolvers =
|
|
38
|
+
const resolvers = args.fileNameResolvers ?? [(arg) => BriefcaseManager_1.BriefcaseManager.getFileName(arg)];
|
|
40
39
|
// see if we can open any of the briefcaseIds we already acquired from iModelHub
|
|
41
40
|
if (resolvers) {
|
|
42
41
|
for (const resolver of resolvers) {
|
|
@@ -50,9 +49,10 @@ class RpcBriefcaseUtility {
|
|
|
50
49
|
if (args.forceDownload)
|
|
51
50
|
throw new Error(); // causes delete below
|
|
52
51
|
const db = await IModelDb_1.BriefcaseDb.open({ fileName });
|
|
53
|
-
if (db.changeset.id !==
|
|
52
|
+
if (db.changeset.id !== tokenProps.changeset?.id) {
|
|
54
53
|
(0, core_bentley_1.assert)(undefined !== tokenProps.changeset);
|
|
55
|
-
const toIndex =
|
|
54
|
+
const toIndex = tokenProps.changeset?.index ??
|
|
55
|
+
(await IModelHost_1.IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId, version: core_common_1.IModelVersion.asOfChangeSet(tokenProps.changeset.id) })).index;
|
|
56
56
|
await BriefcaseManager_1.BriefcaseManager.pullAndApplyChangesets(db, { accessToken, toIndex });
|
|
57
57
|
}
|
|
58
58
|
return db;
|
|
@@ -104,10 +104,9 @@ class RpcBriefcaseUtility {
|
|
|
104
104
|
* a RpcPendingResponse exception is thrown
|
|
105
105
|
*/
|
|
106
106
|
static async open(args) {
|
|
107
|
-
var _a;
|
|
108
107
|
const { activity, tokenProps, syncMode } = args;
|
|
109
108
|
core_bentley_1.Logger.logTrace(loggerCategory, "RpcBriefcaseUtility.open", () => ({ ...tokenProps }));
|
|
110
|
-
const timeout =
|
|
109
|
+
const timeout = args.timeout ?? 1000;
|
|
111
110
|
if (syncMode === core_common_1.SyncMode.PullOnly || syncMode === core_common_1.SyncMode.PullAndPush) {
|
|
112
111
|
const briefcaseDb = await core_bentley_1.BeDuration.race(timeout, this.openBriefcase(args));
|
|
113
112
|
if (briefcaseDb === undefined) {
|
|
@@ -159,9 +158,8 @@ class RpcBriefcaseUtility {
|
|
|
159
158
|
return db;
|
|
160
159
|
}
|
|
161
160
|
static async openWithTimeout(activity, tokenProps, syncMode, timeout = 1000) {
|
|
162
|
-
var _a;
|
|
163
161
|
if (tokenProps.iModelId)
|
|
164
|
-
await
|
|
162
|
+
await IModelHost_1.IModelHost.tileStorage?.initialize(tokenProps.iModelId);
|
|
165
163
|
return (await this.open({ activity, tokenProps, syncMode, timeout })).toJSON();
|
|
166
164
|
}
|
|
167
165
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RpcBriefcaseUtility.js","sourceRoot":"","sources":["../../../src/rpc-impl/RpcBriefcaseUtility.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA0G;AAC1G,oDAE4B;AAC5B,oEAAiE;AACjE,0DAA+E;AAC/E,4DAA+F;AAC/F,0CAAgE;AAChE,8CAA2C;AAC3C,8CAA2C;AAE3C,MAAM,cAAc,GAAW,6CAAqB,CAAC,QAAQ,CAAC;AAW9D;;;GAGG;AACH,MAAa,mBAAmB;IAEtB,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,IAAyB;;QAC5D,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;QACzC,IAAA,qBAAM,EAAC,SAAS,KAAK,UAAU,CAAC,QAAQ,CAAC,CAAC;QAE1C,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC;QACrC,IAAI,cAAwB,CAAC;QAC7B,IAAI,IAAI,CAAC,QAAQ,KAAK,sBAAQ,CAAC,QAAQ,EAAE;YACvC,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;SACtD;aAAM;YACL,4EAA4E;YAC5E,cAAc,GAAG,MAAM,uBAAU,CAAC,SAAS,CAAC,iBAAiB,CAAC,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,CAAC;SAC1F;QAED,MAAM,SAAS,GAAG,MAAA,IAAI,CAAC,iBAAiB,mCAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,mCAAgB,CAAC,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AAI,gCAAkB,EAAE,CAAC,CAAC,8CAA8C;aAC/E;YACD,qBAAM,CAAC,QAAQ,CAAC,cAAc,EAAE,sBAAsB,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC,CAAC;SACpF;QAED,mCAAgB,CAAC,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;QACxC,OAAO,EAAE,CAAC;IACZ,CAAC;IAEM,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,QAAqB,EAAE,UAA8B,EAAE,QAAkB,EAAE,UAAkB,IAAI;;QACnI,IAAI,UAAU,CAAC,QAAQ;YACrB,MAAM,CAAA,MAAA,uBAAU,CAAC,WAAW,0CAAE,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA,CAAC;QAChE,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjF,CAAC;CAEF;AAhKD,kDAgKC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module RpcInterface\n */\n\nimport { AccessToken, assert, BeDuration, BentleyError, IModelStatus, Logger } from \"@itwin/core-bentley\";\nimport {\n BriefcaseProps, IModelConnectionProps, IModelRpcOpenProps, IModelRpcProps, IModelVersion, RpcActivity, RpcPendingResponse, SyncMode,\n} from \"@itwin/core-common\";\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\nimport { BriefcaseManager, RequestNewBriefcaseArg } from \"../BriefcaseManager\";\nimport { CheckpointManager, CheckpointProps, V1CheckpointManager } from \"../CheckpointManager\";\nimport { BriefcaseDb, IModelDb, SnapshotDb } from \"../IModelDb\";\nimport { IModelHost } from \"../IModelHost\";\nimport { IModelJsFs } from \"../IModelJsFs\";\n\nconst loggerCategory: string = BackendLoggerCategory.IModelDb;\n\n/** @internal */\nexport interface DownloadAndOpenArgs {\n activity: RpcActivity; // eslint-disable-line deprecation/deprecation\n tokenProps: IModelRpcOpenProps;\n syncMode: SyncMode;\n fileNameResolvers?: ((arg: BriefcaseProps) => string)[];\n timeout?: number;\n forceDownload?: boolean;\n}\n/**\n * Utility to open the iModel for RPC interfaces\n * @internal\n */\nexport class RpcBriefcaseUtility {\n\n private static async downloadAndOpen(args: DownloadAndOpenArgs): Promise<BriefcaseDb> {\n const { activity, tokenProps } = args;\n const accessToken = activity.accessToken;\n assert(undefined !== tokenProps.iModelId);\n\n const iModelId = tokenProps.iModelId;\n let myBriefcaseIds: number[];\n if (args.syncMode === SyncMode.PullOnly) {\n myBriefcaseIds = [0]; // PullOnly means briefcaseId 0\n } else {\n // check with iModelHub and see if we already have acquired any briefcaseIds\n myBriefcaseIds = await IModelHost.hubAccess.getMyBriefcaseIds({ accessToken, iModelId });\n }\n\n const resolvers = args.fileNameResolvers ?? [(arg) => BriefcaseManager.getFileName(arg)];\n\n // see if we can open any of the briefcaseIds we already acquired from iModelHub\n if (resolvers) {\n for (const resolver of resolvers) {\n for (const briefcaseId of myBriefcaseIds) {\n const fileName = resolver({ briefcaseId, iModelId });\n if (IModelJsFs.existsSync(fileName)) {\n const briefcaseDb = BriefcaseDb.findByFilename(fileName);\n if (briefcaseDb !== undefined)\n return briefcaseDb as BriefcaseDb;\n try {\n if (args.forceDownload)\n throw new Error(); // causes delete below\n const db = await BriefcaseDb.open({ fileName });\n if (db.changeset.id !== tokenProps.changeset?.id) {\n assert(undefined !== tokenProps.changeset);\n const toIndex = tokenProps.changeset?.index ??\n (await IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId, version: IModelVersion.asOfChangeSet(tokenProps.changeset.id) })).index;\n await BriefcaseManager.pullAndApplyChangesets(db, { accessToken, toIndex });\n }\n return db;\n } catch (error: any) {\n if (!(error.errorNumber === IModelStatus.AlreadyOpen))\n // somehow we have this briefcaseId and the file exists, but we can't open it. Delete it.\n await BriefcaseManager.deleteBriefcaseFiles(fileName, accessToken);\n }\n }\n }\n }\n }\n\n // no local briefcase available. Download one and open it.\n assert(undefined !== tokenProps.iTwinId);\n const request: RequestNewBriefcaseArg = {\n accessToken,\n iTwinId: tokenProps.iTwinId,\n iModelId,\n briefcaseId: args.syncMode === SyncMode.PullOnly ? 0 : undefined, // if briefcaseId is undefined, we'll acquire a new one.\n };\n\n const props = await BriefcaseManager.downloadBriefcase(request);\n return BriefcaseDb.open(props);\n }\n\n private static _briefcasePromise: Promise<BriefcaseDb> | undefined;\n private static async openBriefcase(args: DownloadAndOpenArgs): Promise<BriefcaseDb> {\n if (this._briefcasePromise)\n return this._briefcasePromise;\n\n try {\n this._briefcasePromise = this.downloadAndOpen(args); // save the fact that we're working on downloading so if we timeout, we'll reuse this request.\n return await this._briefcasePromise;\n } finally {\n this._briefcasePromise = undefined; // the download and open is now done\n }\n }\n\n /** find a previously opened iModel for RPC.\n * @param accessToken necessary (only) for V2 checkpoints to refresh access token in daemon if it has expired. We use the accessToken of the current RPC request\n * to refresh the daemon, even though it will be used for all authorized users.\n * @param the IModelRpcProps to locate the opened iModel.\n */\n public static async findOpenIModel(accessToken: AccessToken, iModel: IModelRpcProps) {\n const iModelDb = IModelDb.findByKey(iModel.key);\n\n // call refreshContainerSas, just in case this is a V2 checkpoint whose sasToken is about to expire.\n await iModelDb.refreshContainerSas(accessToken);\n return iModelDb;\n }\n\n /**\n * Download and open a checkpoint or briefcase, ensuring the operation completes within a default timeout. If the time to open exceeds the timeout period,\n * a RpcPendingResponse exception is thrown\n */\n public static async open(args: DownloadAndOpenArgs): Promise<IModelDb> {\n const { activity, tokenProps, syncMode } = args;\n Logger.logTrace(loggerCategory, \"RpcBriefcaseUtility.open\", () => ({ ...tokenProps }));\n\n const timeout = args.timeout ?? 1000;\n if (syncMode === SyncMode.PullOnly || syncMode === SyncMode.PullAndPush) {\n const briefcaseDb = await BeDuration.race(timeout, this.openBriefcase(args));\n\n if (briefcaseDb === undefined) {\n Logger.logTrace(loggerCategory, \"Open briefcase - pending\", () => ({ ...tokenProps }));\n throw new RpcPendingResponse(); // eslint-disable-line deprecation/deprecation\n }\n // note: usage is logged in the function BriefcaseManager.downloadNewBriefcaseAndOpen\n return briefcaseDb;\n }\n\n assert(undefined !== tokenProps.iModelId);\n assert(undefined !== tokenProps.iTwinId);\n assert(undefined !== tokenProps.changeset);\n\n const checkpoint: CheckpointProps = {\n iModelId: tokenProps.iModelId,\n iTwinId: tokenProps.iTwinId,\n changeset: tokenProps.changeset,\n accessToken: activity.accessToken,\n };\n\n // opening a checkpoint, readonly.\n let db: SnapshotDb | void;\n // first check if it's already open\n db = SnapshotDb.tryFindByKey(CheckpointManager.getKey(checkpoint));\n if (db) {\n Logger.logTrace(loggerCategory, \"Checkpoint was already open\", () => ({ ...tokenProps }));\n BriefcaseManager.logUsage(db);\n return db;\n }\n\n try {\n // now try V2 checkpoint\n db = await SnapshotDb.openCheckpointV2(checkpoint);\n Logger.logTrace(loggerCategory, \"using V2 checkpoint briefcase\", () => ({ ...tokenProps }));\n } catch (e) {\n Logger.logTrace(loggerCategory, \"unable to open V2 checkpoint - falling back to V1 checkpoint\", () => ({ error: BentleyError.getErrorProps(e), ...tokenProps }));\n\n // this isn't a v2 checkpoint. Set up a race between the specified timeout period and the open. Throw an RpcPendingResponse exception if the timeout happens first.\n const request = {\n checkpoint,\n localFile: V1CheckpointManager.getFileName(checkpoint),\n aliasFiles: [],\n };\n db = await BeDuration.race(timeout, V1CheckpointManager.getCheckpointDb(request));\n\n if (db === undefined) {\n Logger.logTrace(loggerCategory, \"Open V1 checkpoint - pending\", () => ({ ...tokenProps }));\n throw new RpcPendingResponse(); // eslint-disable-line deprecation/deprecation\n }\n Logger.logTrace(loggerCategory, \"Opened V1 checkpoint\", () => ({ ...tokenProps }));\n }\n\n BriefcaseManager.logUsage(db, activity);\n return db;\n }\n\n public static async openWithTimeout(activity: RpcActivity, tokenProps: IModelRpcOpenProps, syncMode: SyncMode, timeout: number = 1000): Promise<IModelConnectionProps> { // eslint-disable-line deprecation/deprecation\n if (tokenProps.iModelId)\n await IModelHost.tileStorage?.initialize(tokenProps.iModelId);\n return (await this.open({ activity, tokenProps, syncMode, timeout })).toJSON();\n }\n\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RpcBriefcaseUtility.js","sourceRoot":"","sources":["../../../src/rpc-impl/RpcBriefcaseUtility.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA0G;AAC1G,oDAE4B;AAC5B,oEAAiE;AACjE,0DAA+E;AAC/E,4DAA+F;AAC/F,0CAAgE;AAChE,8CAA2C;AAC3C,8CAA2C;AAE3C,MAAM,cAAc,GAAW,6CAAqB,CAAC,QAAQ,CAAC;AAW9D;;;GAGG;AACH,MAAa,mBAAmB;IAEtB,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,IAAyB;QAC5D,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;QACzC,IAAA,qBAAM,EAAC,SAAS,KAAK,UAAU,CAAC,QAAQ,CAAC,CAAC;QAE1C,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC;QACrC,IAAI,cAAwB,CAAC;QAC7B,IAAI,IAAI,CAAC,QAAQ,KAAK,sBAAQ,CAAC,QAAQ,EAAE;YACvC,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B;SACtD;aAAM;YACL,4EAA4E;YAC5E,cAAc,GAAG,MAAM,uBAAU,CAAC,SAAS,CAAC,iBAAiB,CAAC,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,CAAC;SAC1F;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE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EAAE,CAAC,CAAC,8CAA8C;aAC/E;YACD,qBAAM,CAAC,QAAQ,CAAC,cAAc,EAAE,sBAAsB,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC,CAAC;SACpF;QAED,mCAAgB,CAAC,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;QACxC,OAAO,EAAE,CAAC;IACZ,CAAC;IAEM,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,QAAqB,EAAE,UAA8B,EAAE,QAAkB,EAAE,UAAkB,IAAI;QACnI,IAAI,UAAU,CAAC,QAAQ;YACrB,MAAM,uBAAU,CAAC,WAAW,EAAE,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QAChE,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjF,CAAC;CAEF;AAhKD,kDAgKC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module RpcInterface\n */\n\nimport { AccessToken, assert, BeDuration, BentleyError, IModelStatus, Logger } from \"@itwin/core-bentley\";\nimport {\n BriefcaseProps, IModelConnectionProps, IModelRpcOpenProps, IModelRpcProps, IModelVersion, RpcActivity, RpcPendingResponse, SyncMode,\n} from \"@itwin/core-common\";\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\nimport { BriefcaseManager, RequestNewBriefcaseArg } from \"../BriefcaseManager\";\nimport { CheckpointManager, CheckpointProps, V1CheckpointManager } from \"../CheckpointManager\";\nimport { BriefcaseDb, IModelDb, SnapshotDb } from \"../IModelDb\";\nimport { IModelHost } from \"../IModelHost\";\nimport { IModelJsFs } from \"../IModelJsFs\";\n\nconst loggerCategory: string = BackendLoggerCategory.IModelDb;\n\n/** @internal */\nexport interface DownloadAndOpenArgs {\n activity: RpcActivity; // eslint-disable-line deprecation/deprecation\n tokenProps: IModelRpcOpenProps;\n syncMode: SyncMode;\n fileNameResolvers?: ((arg: BriefcaseProps) => string)[];\n timeout?: number;\n forceDownload?: boolean;\n}\n/**\n * Utility to open the iModel for RPC interfaces\n * @internal\n */\nexport class RpcBriefcaseUtility {\n\n private static async downloadAndOpen(args: DownloadAndOpenArgs): Promise<BriefcaseDb> {\n const { activity, tokenProps } = args;\n const accessToken = activity.accessToken;\n assert(undefined !== tokenProps.iModelId);\n\n const iModelId = tokenProps.iModelId;\n let myBriefcaseIds: number[];\n if (args.syncMode === SyncMode.PullOnly) {\n myBriefcaseIds = [0]; // PullOnly means briefcaseId 0\n } else {\n // check with iModelHub and see if we already have acquired any briefcaseIds\n myBriefcaseIds = await IModelHost.hubAccess.getMyBriefcaseIds({ accessToken, iModelId });\n }\n\n const resolvers = args.fileNameResolvers ?? [(arg) => BriefcaseManager.getFileName(arg)];\n\n // see if we can open any of the briefcaseIds we already acquired from iModelHub\n if (resolvers) {\n for (const resolver of resolvers) {\n for (const briefcaseId of myBriefcaseIds) {\n const fileName = resolver({ briefcaseId, iModelId });\n if (IModelJsFs.existsSync(fileName)) {\n const briefcaseDb = BriefcaseDb.findByFilename(fileName);\n if (briefcaseDb !== undefined)\n return briefcaseDb as BriefcaseDb;\n try {\n if (args.forceDownload)\n throw new Error(); // causes delete below\n const db = await BriefcaseDb.open({ fileName });\n if (db.changeset.id !== tokenProps.changeset?.id) {\n assert(undefined !== tokenProps.changeset);\n const toIndex = tokenProps.changeset?.index ??\n (await IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId, version: IModelVersion.asOfChangeSet(tokenProps.changeset.id) })).index;\n await BriefcaseManager.pullAndApplyChangesets(db, { accessToken, toIndex });\n }\n return db;\n } catch (error: any) {\n if (!(error.errorNumber === IModelStatus.AlreadyOpen))\n // somehow we have this briefcaseId and the file exists, but we can't open it. Delete it.\n await BriefcaseManager.deleteBriefcaseFiles(fileName, accessToken);\n }\n }\n }\n }\n }\n\n // no local briefcase available. Download one and open it.\n assert(undefined !== tokenProps.iTwinId);\n const request: RequestNewBriefcaseArg = {\n accessToken,\n iTwinId: tokenProps.iTwinId,\n iModelId,\n briefcaseId: args.syncMode === SyncMode.PullOnly ? 0 : undefined, // if briefcaseId is undefined, we'll acquire a new one.\n };\n\n const props = await BriefcaseManager.downloadBriefcase(request);\n return BriefcaseDb.open(props);\n }\n\n private static _briefcasePromise: Promise<BriefcaseDb> | undefined;\n private static async openBriefcase(args: DownloadAndOpenArgs): Promise<BriefcaseDb> {\n if (this._briefcasePromise)\n return this._briefcasePromise;\n\n try {\n this._briefcasePromise = this.downloadAndOpen(args); // save the fact that we're working on downloading so if we timeout, we'll reuse this request.\n return await this._briefcasePromise;\n } finally {\n this._briefcasePromise = undefined; // the download and open is now done\n }\n }\n\n /** find a previously opened iModel for RPC.\n * @param accessToken necessary (only) for V2 checkpoints to refresh access token in daemon if it has expired. We use the accessToken of the current RPC request\n * to refresh the daemon, even though it will be used for all authorized users.\n * @param the IModelRpcProps to locate the opened iModel.\n */\n public static async findOpenIModel(accessToken: AccessToken, iModel: IModelRpcProps) {\n const iModelDb = IModelDb.findByKey(iModel.key);\n\n // call refreshContainerSas, just in case this is a V2 checkpoint whose sasToken is about to expire.\n await iModelDb.refreshContainerSas(accessToken);\n return iModelDb;\n }\n\n /**\n * Download and open a checkpoint or briefcase, ensuring the operation completes within a default timeout. If the time to open exceeds the timeout period,\n * a RpcPendingResponse exception is thrown\n */\n public static async open(args: DownloadAndOpenArgs): Promise<IModelDb> {\n const { activity, tokenProps, syncMode } = args;\n Logger.logTrace(loggerCategory, \"RpcBriefcaseUtility.open\", () => ({ ...tokenProps }));\n\n const timeout = args.timeout ?? 1000;\n if (syncMode === SyncMode.PullOnly || syncMode === SyncMode.PullAndPush) {\n const briefcaseDb = await BeDuration.race(timeout, this.openBriefcase(args));\n\n if (briefcaseDb === undefined) {\n Logger.logTrace(loggerCategory, \"Open briefcase - pending\", () => ({ ...tokenProps }));\n throw new RpcPendingResponse(); // eslint-disable-line deprecation/deprecation\n }\n // note: usage is logged in the function BriefcaseManager.downloadNewBriefcaseAndOpen\n return briefcaseDb;\n }\n\n assert(undefined !== tokenProps.iModelId);\n assert(undefined !== tokenProps.iTwinId);\n assert(undefined !== tokenProps.changeset);\n\n const checkpoint: CheckpointProps = {\n iModelId: tokenProps.iModelId,\n iTwinId: tokenProps.iTwinId,\n changeset: tokenProps.changeset,\n accessToken: activity.accessToken,\n };\n\n // opening a checkpoint, readonly.\n let db: SnapshotDb | void;\n // first check if it's already open\n db = SnapshotDb.tryFindByKey(CheckpointManager.getKey(checkpoint));\n if (db) {\n Logger.logTrace(loggerCategory, \"Checkpoint was already open\", () => ({ ...tokenProps }));\n BriefcaseManager.logUsage(db);\n return db;\n }\n\n try {\n // now try V2 checkpoint\n db = await SnapshotDb.openCheckpointV2(checkpoint);\n Logger.logTrace(loggerCategory, \"using V2 checkpoint briefcase\", () => ({ ...tokenProps }));\n } catch (e) {\n Logger.logTrace(loggerCategory, \"unable to open V2 checkpoint - falling back to V1 checkpoint\", () => ({ error: BentleyError.getErrorProps(e), ...tokenProps }));\n\n // this isn't a v2 checkpoint. Set up a race between the specified timeout period and the open. Throw an RpcPendingResponse exception if the timeout happens first.\n const request = {\n checkpoint,\n localFile: V1CheckpointManager.getFileName(checkpoint),\n aliasFiles: [],\n };\n db = await BeDuration.race(timeout, V1CheckpointManager.getCheckpointDb(request));\n\n if (db === undefined) {\n Logger.logTrace(loggerCategory, \"Open V1 checkpoint - pending\", () => ({ ...tokenProps }));\n throw new RpcPendingResponse(); // eslint-disable-line deprecation/deprecation\n }\n Logger.logTrace(loggerCategory, \"Opened V1 checkpoint\", () => ({ ...tokenProps }));\n }\n\n BriefcaseManager.logUsage(db, activity);\n return db;\n }\n\n public static async openWithTimeout(activity: RpcActivity, tokenProps: IModelRpcOpenProps, syncMode: SyncMode, timeout: number = 1000): Promise<IModelConnectionProps> { // eslint-disable-line deprecation/deprecation\n if (tokenProps.iModelId)\n await IModelHost.tileStorage?.initialize(tokenProps.iModelId);\n return (await this.open({ activity, tokenProps, syncMode, timeout })).toJSON();\n }\n\n}\n"]}
|
|
@@ -28,8 +28,7 @@ class SnapshotIModelRpcImpl extends core_common_1.RpcInterface {
|
|
|
28
28
|
}
|
|
29
29
|
/** Ask the backend to open a snapshot iModel from a key that is resolved by the backend. */
|
|
30
30
|
async openRemote(fileKey, opts) {
|
|
31
|
-
|
|
32
|
-
const resolvedFileName = (_a = IModelHost_1.IModelHost.snapshotFileNameResolver) === null || _a === void 0 ? void 0 : _a.resolveKey(fileKey);
|
|
31
|
+
const resolvedFileName = IModelHost_1.IModelHost.snapshotFileNameResolver?.resolveKey(fileKey);
|
|
33
32
|
if (undefined === resolvedFileName)
|
|
34
33
|
throw new core_common_1.IModelNotFoundResponse();
|
|
35
34
|
return IModelDb_1.SnapshotDb.openFile(resolvedFileName, { key: fileKey, ...opts }).getConnectionProps();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapshotIModelRpcImpl.js","sourceRoot":"","sources":["../../../src/rpc-impl/SnapshotIModelRpcImpl.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,oDAE4B;AAC5B,0CAAyC;AACzC,8CAA2C;AAE3C;;GAEG;AACH,MAAa,qBAAsB,SAAQ,0BAAY;IAC9C,MAAM,CAAC,QAAQ,KAAK,wBAAU,CAAC,YAAY,CAAC,wCAA0B,EAAE,qBAAqB,CAAC,CAAC,CAAC,CAAC;IAExG,kGAAkG;IAC3F,KAAK,CAAC,QAAQ,CAAC,QAAgB,EAAE,IAA0B;QAChE,IAAI,gBAAgB,GAAuB,QAAQ,CAAC;QACpD,IAAI,uBAAU,CAAC,wBAAwB,EAAE;YACvC,gBAAgB,GAAG,uBAAU,CAAC,wBA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,IAAI,oCAAsB,EAAE,CAAC;QAErC,OAAO,qBAAU,CAAC,QAAQ,CAAC,gBAAgB,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC,kBAAkB,EAAE,CAAC;IAC/F,CAAC;IAED,kDAAkD;IAC3C,KAAK,CAAC,KAAK,CAAC,UAA0B;QAC3C,qBAAU,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC;QAC7C,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA5BD,sDA4BC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module RpcInterface\n */\n\nimport {\n IModelConnectionProps, IModelNotFoundResponse, IModelRpcProps, RpcInterface, RpcManager, SnapshotIModelRpcInterface, SnapshotOpenOptions,\n} from \"@itwin/core-common\";\nimport { SnapshotDb } from \"../IModelDb\";\nimport { IModelHost } from \"../IModelHost\";\n\n/** The backend implementation of SnapshotIModelRpcInterface.\n * @internal\n */\nexport class SnapshotIModelRpcImpl extends RpcInterface implements SnapshotIModelRpcInterface { // eslint-disable-line deprecation/deprecation\n public static register() { RpcManager.registerImpl(SnapshotIModelRpcInterface, SnapshotIModelRpcImpl); }\n\n /** Ask the backend to open a snapshot iModel from a file name that is resolved by the backend. */\n public async openFile(filePath: string, opts?: SnapshotOpenOptions): Promise<IModelConnectionProps> {\n let resolvedFileName: string | undefined = filePath;\n if (IModelHost.snapshotFileNameResolver) {\n resolvedFileName = IModelHost.snapshotFileNameResolver.tryResolveFileName(filePath);\n if (undefined === resolvedFileName)\n throw new IModelNotFoundResponse();\n }\n return SnapshotDb.openFile(resolvedFileName, opts).getConnectionProps();\n }\n\n /** Ask the backend to open a snapshot iModel from a key that is resolved by the backend. */\n public async openRemote(fileKey: string, opts?: SnapshotOpenOptions): Promise<IModelConnectionProps> {\n const resolvedFileName = IModelHost.snapshotFileNameResolver?.resolveKey(fileKey);\n if (undefined === resolvedFileName)\n throw new IModelNotFoundResponse();\n\n return SnapshotDb.openFile(resolvedFileName, { key: fileKey, ...opts }).getConnectionProps();\n }\n\n /** Ask the backend to close a snapshot iModel. */\n public async close(tokenProps: IModelRpcProps): Promise<boolean> {\n SnapshotDb.findByKey(tokenProps.key).close();\n return true;\n }\n}\n"]}
|
|
@@ -117,8 +117,7 @@ class BaseSettings {
|
|
|
117
117
|
return defaultValue;
|
|
118
118
|
}
|
|
119
119
|
getSetting(name, defaultValue) {
|
|
120
|
-
|
|
121
|
-
return (_a = this.resolveSetting(name, (val) => deepClone(val))) !== null && _a !== void 0 ? _a : defaultValue;
|
|
120
|
+
return this.resolveSetting(name, (val) => deepClone(val)) ?? defaultValue;
|
|
122
121
|
}
|
|
123
122
|
/** for debugging. Returns an array of all values for a setting, sorted by priority.
|
|
124
123
|
* @note values are not cloned. Do not modify objects or arrays.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Settings.js","sourceRoot":"","sources":["../../../src/workspace/Settings.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,+BAA+B;AAC/B,iCAA8B;AAC9B,+BAAqC;AACrC,sDAA8D;AAE9D,8CAA2C;AAmD3C;;;EAGE;AACF,IAAY,gBAWX;AAXD,WAAY,gBAAgB;IAC1B,6CAA6C;IAC7C,iEAAc,CAAA;IACd,iDAAiD;IACjD,uEAAiB,CAAA;IACjB,2DAA2D;IAC3D,yEAAkB,CAAA;IAClB,oDAAoD;IACpD,2DAAW,CAAA;IACX,4CAA4C;IAC5C,6DAAY,CAAA;AACd,CAAC,EAXW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAW3B;AAyGD,gBAAgB;AAChB,SAAS,SAAS,CAAwB,GAAQ;IAChD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KA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------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Workspace\n */\n\nimport * as fs from \"fs-extra\";\nimport { parse } from \"json5\";\nimport { extname, join } from \"path\";\nimport { BeEvent, JSONSchemaType } from \"@itwin/core-bentley\";\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\nimport { IModelJsFs } from \"../IModelJsFs\";\n\n/** The type of a Setting, according to its schema\n * @beta\n */\nexport type SettingType = JSONSchemaType;\n\n/**\n * The name of a Setting. SettingNames must be valid JavaScript property names, defined in a [[SettingSchema]].\n * @see [SettingName]($docs/learning/backend/Workspace#settingnames)\n * @beta\n */\nexport type SettingName = string;\n\n/** The name of a [[SettingDictionary]]. `SettingDictionary`s are stored in [[Settings]] and may be removed by DictionaryName.\n * DictionaryNames must be valid JavaScript property names.\n * @beta\n */\nexport type DictionaryName = string;\n\n/**\n * A function called by [[Settings.resolveSetting]] for every SettingDictionary with a Setting that matches a name. The\n * SettingDictionaries are sorted by priority and this function is called in priority order with the highest priority first.\n * When this function returns a non-undefined value, the iteration is stopped and that value is returned. In this way,\n * applications can \"combine\" the prioritized Setting values as appropriate. The default implementation of this function\n * used by [[Settings.getSetting]] merely returns a clone of the value the first time it is called, so the highest priority\n * value is returned.\n * @beta\n */\nexport type SettingResolver<T> = (val: T, dict: DictionaryName, priority: SettingsPriority) => T | undefined;\n\n/** An entry in the array returned by [[Settings.inspectSetting]]\n * @beta\n *\n */\nexport interface SettingInspector<T> { value: T, dictionary: DictionaryName, priority: number }\n\n/** An object with string-named members (as opposed to an array object).\n * @beta\n */\nexport interface SettingObject {\n [name: string]: SettingType;\n}\n\n/**\n * An object with Settings as its members. A SettingDictionary also has a name and generally comes from a parsed JSON file, but\n * may also be created in memory by applications\n * @beta\n */\nexport type SettingDictionary = SettingObject;\n\n/**\n * Values for SettingsPriority determine the sort order for Settings. Higher values take precedence over lower values.\n * @beta\n*/\nexport enum SettingsPriority {\n /** values supplied default-settings files */\n defaults = 100,\n /** values supplied by applications at runtime */\n application = 200,\n /** values that apply to all iTwins for an organization. */\n organization = 300,\n /** values that apply to all iModels in an iTwin. */\n iTwin = 400,\n /** values that apply to a single iModel. */\n iModel = 500,\n}\n\n/** The current set of Settings for a Workspace.\n * @beta\n */\nexport interface Settings {\n /** @internal */\n close(): void;\n\n /** Event raised whenever a SettingsDictionary is added or removed. */\n readonly onSettingsChanged: BeEvent<() => void>;\n\n /** Add a SettingDictionary from a local settings file. The file should be in [JSON5](https://json5.org/) format. It is read\n * and parsed and the fileName is used as the DictionaryName.\n * @param fileName the name of a local settings file of the SettingDictionary. This becomes the DictionaryName.\n * @param priority the SettingsPriority for the SettingDictionary\n * @note If the SettingDictionary was previously added, the new content overrides the old content.\n */\n addFile(fileName: LocalFileName, priority: SettingsPriority): void;\n\n /** Add all files in the supplied directory with the extension \".json\" or \".json5\"\n * @param dirName the name of a local settings directory\n */\n addDirectory(dirName: LocalDirName, priority: SettingsPriority): void;\n\n /** Add a SettingDictionary from a JSON5 stringified string. The string is parsed and the resultant object is added as a SettingDictionary.\n * @param dictionaryName the name of the SettingDictionary\n * @param priority the SettingsPriority for the SettingDictionary\n * @param settingsJson the JSON5 stringified string to be parsed.\n * @note If the SettingDictionary was previously added, the new content overrides the old content.\n */\n addJson(dictionaryName: DictionaryName, priority: SettingsPriority, settingsJson: string): void;\n\n /** Add a SettingDictionary object.\n * @param dictionaryName the name of the SettingDictionary\n * @param priority the SettingsPriority for the SettingDictionary\n * @param settings the SettingDictionary object to be added.\n * @note If the SettingDictionary was previously added, the new content overrides the old content.\n */\n addDictionary(dictionaryName: DictionaryName, priority: SettingsPriority, settings: SettingDictionary): void;\n\n /** Remove a SettingDictionary by name. */\n dropDictionary(dictionaryName: DictionaryName): void;\n\n /**\n * Resolve a setting, by name, using a SettingResolver.\n * @param settingName The name of the setting to resolve\n * @param resolver function to be called for each SettingDictionary with a matching Setting. Iteration stops when it returns a non-undefined value.\n * @param defaultValue value returned if settingName is not present in any SettingDictionary or resolver never returned a value.\n * @returns the resolved setting value.\n */\n resolveSetting<T extends SettingType>(settingName: SettingName, resolver: SettingResolver<T>, defaultValue: T): T;\n resolveSetting<T extends SettingType>(settingName: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined;\n\n /** Get the highest priority setting for a SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary.\n * @note This method is generic on SettingType, but no type checking is actually performed at run time. So, if you\n * use this method to get a setting with an expected type, but its value is a different type, the return type of this method will be wrong.\n * You must always type check the result. Use the non-generic \"get\" methods (e.g. [[getString]]) if you only want the value\n * if its type is correct.\n */\n getSetting<T extends SettingType>(settingName: SettingName, defaultValue?: T): T | undefined;\n\n /** Get a string setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a string.\n */\n getString(settingName: SettingName, defaultValue: string): string;\n getString(settingName: SettingName, defaultValue?: string): string | undefined;\n\n /** Get a boolean setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a boolean.\n */\n getBoolean(settingName: SettingName, defaultValue: boolean): boolean;\n getBoolean(settingName: SettingName, defaultValue?: boolean): boolean | undefined;\n\n /** Get a number setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a number.\n */\n getNumber(settingName: SettingName, defaultValue: number): number;\n getNumber(settingName: SettingName): number | undefined;\n\n /** Get an object setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not an object.\n */\n getObject<T extends object>(settingName: SettingName, defaultValue: T): T;\n getObject<T extends object>(settingName: SettingName): T | undefined;\n\n /** Get an array setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not an array.\n */\n getArray<T extends SettingType>(settingName: SettingName, defaultValue: Array<T>): Array<T>;\n getArray<T extends SettingType>(settingName: SettingName): Array<T> | undefined;\n\n /** Get an array of [[SettingInspector] objects, sorted in priority order, for all Settings that match a SettingName.\n * @note this method is mainly for debugging and diagnostics.\n */\n inspectSetting<T extends SettingType>(name: SettingName): SettingInspector<T>[];\n}\n\n/** @internal */\nfunction deepClone<T extends SettingType>(obj: any): T {\n if (!obj || typeof obj !== \"object\")\n return obj;\n\n const result = Array.isArray(obj) ? [] : {} as any;\n Object.keys(obj).forEach((key: string) => {\n const val = obj[key];\n if (val && typeof val === \"object\") {\n result[key] = deepClone(val);\n } else {\n result[key] = val;\n }\n });\n return result;\n}\n\nclass SettingsDictionary {\n public constructor(public readonly name: string, public readonly priority: SettingsPriority, public readonly settings: SettingDictionary) { }\n public getSetting<T extends SettingType>(settingName: string): SettingType | undefined {\n return this.settings[settingName] as T | undefined;\n }\n}\n\n/**\n * Internal implementation of Settings interface.\n * @internal\n */\nexport class BaseSettings implements Settings {\n private _dictionaries: SettingsDictionary[] = [];\n protected verifyPriority(_priority: SettingsPriority) { }\n public close() { }\n public readonly onSettingsChanged = new BeEvent<() => void>();\n\n public addFile(fileName: LocalFileName, priority: SettingsPriority) {\n this.addJson(fileName, priority, fs.readFileSync(fileName, \"utf-8\"));\n }\n\n public addDirectory(dirName: LocalDirName, priority: SettingsPriority) {\n for (const fileName of IModelJsFs.readdirSync(dirName)) {\n const ext = extname(fileName);\n if (ext === \".json5\" || ext === \".json\")\n this.addFile(join(dirName, fileName), priority);\n }\n }\n\n public addJson(dictionaryName: string, priority: SettingsPriority, settingsJson: string) {\n this.addDictionary(dictionaryName, priority, parse(settingsJson));\n }\n\n public addDictionary(dictionaryName: string, priority: SettingsPriority, settings: SettingDictionary) {\n this.verifyPriority(priority);\n this.dropDictionary(dictionaryName, false); // make sure we don't have the same dictionary twice\n const file = new SettingsDictionary(dictionaryName, priority, settings);\n const doAdd = () => {\n for (let i = 0; i < this._dictionaries.length; ++i) {\n if (this._dictionaries[i].priority <= file.priority) {\n this._dictionaries.splice(i, 0, file);\n return;\n }\n }\n this._dictionaries.push(file);\n };\n doAdd();\n this.onSettingsChanged.raiseEvent();\n }\n\n public dropDictionary(dictionaryName: DictionaryName, raiseEvent = true) {\n for (let i = 0; i < this._dictionaries.length; ++i) {\n if (this._dictionaries[i].name === dictionaryName) {\n this._dictionaries.splice(i, 1);\n if (raiseEvent)\n this.onSettingsChanged.raiseEvent();\n return true;\n }\n }\n return false;\n }\n\n public resolveSetting<T extends SettingType>(name: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined {\n for (const dict of this._dictionaries) {\n const val = dict.getSetting(name) as T | undefined;\n const resolved = val && resolver(val, dict.name, dict.priority);\n if (undefined !== resolved)\n return resolved;\n }\n return defaultValue;\n }\n\n public getSetting<T extends SettingType>(name: SettingName, defaultValue?: T): T | undefined {\n return this.resolveSetting(name, (val) => deepClone<T>(val)) ?? defaultValue;\n }\n\n /** for debugging. Returns an array of all values for a setting, sorted by priority.\n * @note values are not cloned. Do not modify objects or arrays.\n */\n public inspectSetting<T extends SettingType>(name: SettingName): SettingInspector<T>[] {\n const all: SettingInspector<T>[] = [];\n this.resolveSetting<T>(name, (value, dictionary, priority) => {\n all.push({ value, dictionary, priority });\n return undefined;\n });\n\n return all;\n }\n\n public getString(name: SettingName, defaultValue: string): string;\n public getString(name: SettingName): string | undefined;\n public getString(name: SettingName, defaultValue?: string): string | undefined {\n const out = this.getSetting<string>(name);\n return typeof out === \"string\" ? out : defaultValue;\n }\n public getBoolean(name: SettingName, defaultValue: boolean): boolean;\n public getBoolean(name: SettingName): boolean | undefined;\n public getBoolean(name: SettingName, defaultValue?: boolean): boolean | undefined {\n const out = this.getSetting<boolean>(name);\n return typeof out === \"boolean\" ? out : defaultValue;\n }\n public getNumber(name: SettingName, defaultValue: number): number;\n public getNumber(name: SettingName): number | undefined;\n public getNumber(name: SettingName, defaultValue?: number): number | undefined {\n const out = this.getSetting<number>(name);\n return typeof out === \"number\" ? out : defaultValue;\n }\n public getObject<T extends object>(name: SettingName, defaultValue: T): T;\n public getObject<T extends object>(name: SettingName): T | undefined;\n public getObject<T extends object>(name: SettingName, defaultValue?: T): T | undefined {\n const out = this.getSetting<SettingObject>(name);\n return typeof out === \"object\" ? out as T : defaultValue;\n }\n public getArray<T extends SettingType>(name: SettingName, defaultValue: Array<T>): Array<T>;\n public getArray<T extends SettingType>(name: SettingName): Array<T> | undefined;\n public getArray<T extends SettingType>(name: SettingName, defaultValue?: Array<T>): Array<T> | undefined {\n const out = this.getSetting<Array<T>>(name);\n return Array.isArray(out) ? out : defaultValue;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Settings.js","sourceRoot":"","sources":["../../../src/workspace/Settings.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,+BAA+B;AAC/B,iCAA8B;AAC9B,+BAAqC;AACrC,sDAA8D;AAE9D,8CAA2C;AAmD3C;;;EAGE;AACF,IAAY,gBAWX;AAXD,WAAY,gBAAgB;IAC1B,6CAA6C;IAC7C,iEAAc,CAAA;IACd,iDAAiD;IACjD,uEAAiB,CAAA;IACjB,2DAA2D;IAC3D,yEAAkB,CAAA;IAClB,oDAAoD;IACpD,2DAAW,CAAA;IACX,4CAA4C;IAC5C,6DAAY,CAAA;AACd,CAAC,EAXW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAW3B;AAyGD,gBAAgB;AAChB,SAAS,SAAS,CAAwB,GAAQ;IAChD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QACjC,OAAO,GAAG,CAAC;IAEb,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAS,CAAC;IACnD,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO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U,CAAS,IAAI,CAAC,CAAC;QAC1C,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACtD,CAAC;IAGM,UAAU,CAAC,IAAiB,EAAE,YAAsB;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAU,IAAI,CAAC,CAAC;QAC3C,OAAO,OAAO,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACvD,CAAC;IAGM,SAAS,CAAC,IAAiB,EAAE,YAAqB;QACvD,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAS,IAAI,CAAC,CAAC;QAC1C,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACtD,CAAC;IAGM,SAAS,CAAmB,IAAiB,EAAE,YAAgB;QACpE,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAgB,IAAI,CAAC,CAAC;QACjD,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAQ,CAAC,CAAC,CAAC,YAAY,CAAC;IAC3D,CAAC;IAGM,QAAQ,CAAwB,IAAiB,EAAE,YAAuB;QAC/E,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAW,IAAI,CAAC,CAAC;QAC5C,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACjD,CAAC;CACF;AA5GD,oCA4GC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Workspace\n */\n\nimport * as fs from \"fs-extra\";\nimport { parse } from \"json5\";\nimport { extname, join } from \"path\";\nimport { BeEvent, JSONSchemaType } from \"@itwin/core-bentley\";\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\nimport { IModelJsFs } from \"../IModelJsFs\";\n\n/** The type of a Setting, according to its schema\n * @beta\n */\nexport type SettingType = JSONSchemaType;\n\n/**\n * The name of a Setting. SettingNames must be valid JavaScript property names, defined in a [[SettingSchema]].\n * @see [SettingName]($docs/learning/backend/Workspace#settingnames)\n * @beta\n */\nexport type SettingName = string;\n\n/** The name of a [[SettingDictionary]]. `SettingDictionary`s are stored in [[Settings]] and may be removed by DictionaryName.\n * DictionaryNames must be valid JavaScript property names.\n * @beta\n */\nexport type DictionaryName = string;\n\n/**\n * A function called by [[Settings.resolveSetting]] for every SettingDictionary with a Setting that matches a name. The\n * SettingDictionaries are sorted by priority and this function is called in priority order with the highest priority first.\n * When this function returns a non-undefined value, the iteration is stopped and that value is returned. In this way,\n * applications can \"combine\" the prioritized Setting values as appropriate. The default implementation of this function\n * used by [[Settings.getSetting]] merely returns a clone of the value the first time it is called, so the highest priority\n * value is returned.\n * @beta\n */\nexport type SettingResolver<T> = (val: T, dict: DictionaryName, priority: SettingsPriority) => T | undefined;\n\n/** An entry in the array returned by [[Settings.inspectSetting]]\n * @beta\n *\n */\nexport interface SettingInspector<T> { value: T, dictionary: DictionaryName, priority: number }\n\n/** An object with string-named members (as opposed to an array object).\n * @beta\n */\nexport interface SettingObject {\n [name: string]: SettingType;\n}\n\n/**\n * An object with Settings as its members. A SettingDictionary also has a name and generally comes from a parsed JSON file, but\n * may also be created in memory by applications\n * @beta\n */\nexport type SettingDictionary = SettingObject;\n\n/**\n * Values for SettingsPriority determine the sort order for Settings. Higher values take precedence over lower values.\n * @beta\n*/\nexport enum SettingsPriority {\n /** values supplied default-settings files */\n defaults = 100,\n /** values supplied by applications at runtime */\n application = 200,\n /** values that apply to all iTwins for an organization. */\n organization = 300,\n /** values that apply to all iModels in an iTwin. */\n iTwin = 400,\n /** values that apply to a single iModel. */\n iModel = 500,\n}\n\n/** The current set of Settings for a Workspace.\n * @beta\n */\nexport interface Settings {\n /** @internal */\n close(): void;\n\n /** Event raised whenever a SettingsDictionary is added or removed. */\n readonly onSettingsChanged: BeEvent<() => void>;\n\n /** Add a SettingDictionary from a local settings file. The file should be in [JSON5](https://json5.org/) format. It is read\n * and parsed and the fileName is used as the DictionaryName.\n * @param fileName the name of a local settings file of the SettingDictionary. This becomes the DictionaryName.\n * @param priority the SettingsPriority for the SettingDictionary\n * @note If the SettingDictionary was previously added, the new content overrides the old content.\n */\n addFile(fileName: LocalFileName, priority: SettingsPriority): void;\n\n /** Add all files in the supplied directory with the extension \".json\" or \".json5\"\n * @param dirName the name of a local settings directory\n */\n addDirectory(dirName: LocalDirName, priority: SettingsPriority): void;\n\n /** Add a SettingDictionary from a JSON5 stringified string. The string is parsed and the resultant object is added as a SettingDictionary.\n * @param dictionaryName the name of the SettingDictionary\n * @param priority the SettingsPriority for the SettingDictionary\n * @param settingsJson the JSON5 stringified string to be parsed.\n * @note If the SettingDictionary was previously added, the new content overrides the old content.\n */\n addJson(dictionaryName: DictionaryName, priority: SettingsPriority, settingsJson: string): void;\n\n /** Add a SettingDictionary object.\n * @param dictionaryName the name of the SettingDictionary\n * @param priority the SettingsPriority for the SettingDictionary\n * @param settings the SettingDictionary object to be added.\n * @note If the SettingDictionary was previously added, the new content overrides the old content.\n */\n addDictionary(dictionaryName: DictionaryName, priority: SettingsPriority, settings: SettingDictionary): void;\n\n /** Remove a SettingDictionary by name. */\n dropDictionary(dictionaryName: DictionaryName): void;\n\n /**\n * Resolve a setting, by name, using a SettingResolver.\n * @param settingName The name of the setting to resolve\n * @param resolver function to be called for each SettingDictionary with a matching Setting. Iteration stops when it returns a non-undefined value.\n * @param defaultValue value returned if settingName is not present in any SettingDictionary or resolver never returned a value.\n * @returns the resolved setting value.\n */\n resolveSetting<T extends SettingType>(settingName: SettingName, resolver: SettingResolver<T>, defaultValue: T): T;\n resolveSetting<T extends SettingType>(settingName: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined;\n\n /** Get the highest priority setting for a SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary.\n * @note This method is generic on SettingType, but no type checking is actually performed at run time. So, if you\n * use this method to get a setting with an expected type, but its value is a different type, the return type of this method will be wrong.\n * You must always type check the result. Use the non-generic \"get\" methods (e.g. [[getString]]) if you only want the value\n * if its type is correct.\n */\n getSetting<T extends SettingType>(settingName: SettingName, defaultValue?: T): T | undefined;\n\n /** Get a string setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a string.\n */\n getString(settingName: SettingName, defaultValue: string): string;\n getString(settingName: SettingName, defaultValue?: string): string | undefined;\n\n /** Get a boolean setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a boolean.\n */\n getBoolean(settingName: SettingName, defaultValue: boolean): boolean;\n getBoolean(settingName: SettingName, defaultValue?: boolean): boolean | undefined;\n\n /** Get a number setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a number.\n */\n getNumber(settingName: SettingName, defaultValue: number): number;\n getNumber(settingName: SettingName): number | undefined;\n\n /** Get an object setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not an object.\n */\n getObject<T extends object>(settingName: SettingName, defaultValue: T): T;\n getObject<T extends object>(settingName: SettingName): T | undefined;\n\n /** Get an array setting by SettingName.\n * @param settingName The name of the setting\n * @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not an array.\n */\n getArray<T extends SettingType>(settingName: SettingName, defaultValue: Array<T>): Array<T>;\n getArray<T extends SettingType>(settingName: SettingName): Array<T> | undefined;\n\n /** Get an array of [[SettingInspector] objects, sorted in priority order, for all Settings that match a SettingName.\n * @note this method is mainly for debugging and diagnostics.\n */\n inspectSetting<T extends SettingType>(name: SettingName): SettingInspector<T>[];\n}\n\n/** @internal */\nfunction deepClone<T extends SettingType>(obj: any): T {\n if (!obj || typeof obj !== \"object\")\n return obj;\n\n const result = Array.isArray(obj) ? [] : {} as any;\n Object.keys(obj).forEach((key: string) => {\n const val = obj[key];\n if (val && typeof val === \"object\") {\n result[key] = deepClone(val);\n } else {\n result[key] = val;\n }\n });\n return result;\n}\n\nclass SettingsDictionary {\n public constructor(public readonly name: string, public readonly priority: SettingsPriority, public readonly settings: SettingDictionary) { }\n public getSetting<T extends SettingType>(settingName: string): SettingType | undefined {\n return this.settings[settingName] as T | undefined;\n }\n}\n\n/**\n * Internal implementation of Settings interface.\n * @internal\n */\nexport class BaseSettings implements Settings {\n private _dictionaries: SettingsDictionary[] = [];\n protected verifyPriority(_priority: SettingsPriority) { }\n public close() { }\n public readonly onSettingsChanged = new BeEvent<() => void>();\n\n public addFile(fileName: LocalFileName, priority: SettingsPriority) {\n this.addJson(fileName, priority, fs.readFileSync(fileName, \"utf-8\"));\n }\n\n public addDirectory(dirName: LocalDirName, priority: SettingsPriority) {\n for (const fileName of IModelJsFs.readdirSync(dirName)) {\n const ext = extname(fileName);\n if (ext === \".json5\" || ext === \".json\")\n this.addFile(join(dirName, fileName), priority);\n }\n }\n\n public addJson(dictionaryName: string, priority: SettingsPriority, settingsJson: string) {\n this.addDictionary(dictionaryName, priority, parse(settingsJson));\n }\n\n public addDictionary(dictionaryName: string, priority: SettingsPriority, settings: SettingDictionary) {\n this.verifyPriority(priority);\n this.dropDictionary(dictionaryName, false); // make sure we don't have the same dictionary twice\n const file = new SettingsDictionary(dictionaryName, priority, settings);\n const doAdd = () => {\n for (let i = 0; i < this._dictionaries.length; ++i) {\n if (this._dictionaries[i].priority <= file.priority) {\n this._dictionaries.splice(i, 0, file);\n return;\n }\n }\n this._dictionaries.push(file);\n };\n doAdd();\n this.onSettingsChanged.raiseEvent();\n }\n\n public dropDictionary(dictionaryName: DictionaryName, raiseEvent = true) {\n for (let i = 0; i < this._dictionaries.length; ++i) {\n if (this._dictionaries[i].name === dictionaryName) {\n this._dictionaries.splice(i, 1);\n if (raiseEvent)\n this.onSettingsChanged.raiseEvent();\n return true;\n }\n }\n return false;\n }\n\n public resolveSetting<T extends SettingType>(name: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined {\n for (const dict of this._dictionaries) {\n const val = dict.getSetting(name) as T | undefined;\n const resolved = val && resolver(val, dict.name, dict.priority);\n if (undefined !== resolved)\n return resolved;\n }\n return defaultValue;\n }\n\n public getSetting<T extends SettingType>(name: SettingName, defaultValue?: T): T | undefined {\n return this.resolveSetting(name, (val) => deepClone<T>(val)) ?? defaultValue;\n }\n\n /** for debugging. Returns an array of all values for a setting, sorted by priority.\n * @note values are not cloned. Do not modify objects or arrays.\n */\n public inspectSetting<T extends SettingType>(name: SettingName): SettingInspector<T>[] {\n const all: SettingInspector<T>[] = [];\n this.resolveSetting<T>(name, (value, dictionary, priority) => {\n all.push({ value, dictionary, priority });\n return undefined;\n });\n\n return all;\n }\n\n public getString(name: SettingName, defaultValue: string): string;\n public getString(name: SettingName): string | undefined;\n public getString(name: SettingName, defaultValue?: string): string | undefined {\n const out = this.getSetting<string>(name);\n return typeof out === \"string\" ? out : defaultValue;\n }\n public getBoolean(name: SettingName, defaultValue: boolean): boolean;\n public getBoolean(name: SettingName): boolean | undefined;\n public getBoolean(name: SettingName, defaultValue?: boolean): boolean | undefined {\n const out = this.getSetting<boolean>(name);\n return typeof out === \"boolean\" ? out : defaultValue;\n }\n public getNumber(name: SettingName, defaultValue: number): number;\n public getNumber(name: SettingName): number | undefined;\n public getNumber(name: SettingName, defaultValue?: number): number | undefined {\n const out = this.getSetting<number>(name);\n return typeof out === \"number\" ? out : defaultValue;\n }\n public getObject<T extends object>(name: SettingName, defaultValue: T): T;\n public getObject<T extends object>(name: SettingName): T | undefined;\n public getObject<T extends object>(name: SettingName, defaultValue?: T): T | undefined {\n const out = this.getSetting<SettingObject>(name);\n return typeof out === \"object\" ? out as T : defaultValue;\n }\n public getArray<T extends SettingType>(name: SettingName, defaultValue: Array<T>): Array<T>;\n public getArray<T extends SettingType>(name: SettingName): Array<T> | undefined;\n public getArray<T extends SettingType>(name: SettingName, defaultValue?: Array<T>): Array<T> | undefined {\n const out = this.getSetting<Array<T>>(name);\n return Array.isArray(out) ? out : defaultValue;\n }\n}\n"]}
|
|
@@ -32,7 +32,7 @@ class SettingsSchemas {
|
|
|
32
32
|
/** @internal */
|
|
33
33
|
static validateArrayObject(val, schemaName, msg) {
|
|
34
34
|
const schema = this.allSchemas.get(schemaName);
|
|
35
|
-
const items = schema
|
|
35
|
+
const items = schema?.items;
|
|
36
36
|
if (undefined === items)
|
|
37
37
|
return val;
|
|
38
38
|
const required = items.required;
|
|
@@ -96,7 +96,7 @@ class SettingsSchemas {
|
|
|
96
96
|
}
|
|
97
97
|
static doRemove(groupName) {
|
|
98
98
|
const group = this._allGroups.get(groupName);
|
|
99
|
-
if (undefined !==
|
|
99
|
+
if (undefined !== group?.properties) {
|
|
100
100
|
for (const key of Object.keys(group.properties))
|
|
101
101
|
this.allSchemas.delete(key);
|
|
102
102
|
}
|
|
@@ -152,7 +152,6 @@ class SettingsSchemas {
|
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
154
|
static validateAndAdd(group) {
|
|
155
|
-
var _a;
|
|
156
155
|
const properties = group.properties;
|
|
157
156
|
if (undefined === properties)
|
|
158
157
|
throw new Error(`group ${group.groupName} has no properties`);
|
|
@@ -160,7 +159,7 @@ class SettingsSchemas {
|
|
|
160
159
|
this.validateName(key);
|
|
161
160
|
this.validateProperty(key, properties[key]);
|
|
162
161
|
const property = properties[key];
|
|
163
|
-
property.default =
|
|
162
|
+
property.default = property.default ?? this.getDefaultValue(property.type);
|
|
164
163
|
this.allSchemas.set(key, property);
|
|
165
164
|
}
|
|
166
165
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SettingsSchemas.js","sourceRoot":"","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KAAK,QAAQ;gBACX,OAAO,EAAE,CAAC;YACZ;gBACE,OAAO,SAAS,CAAC;SACpB;IACH,CAAC;;AA1LH,0CA2LC;AAzLyB,0BAAU,GAAG,IAAI,GAAG,EAA8B,CAAC;AAC3E,iDAAiD;AAC1B,0BAAU,GAAG,IAAI,GAAG,EAAyB,CAAC;AACrE,qFAAqF;AAC9D,+BAAe,GAAG,IAAI,sBAAO,EAAc,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Workspace\n */\n\nimport * as fs from \"fs-extra\";\nimport { parse } from \"json5\";\nimport { extname, join } from \"path\";\nimport { BeEvent, JSONSchema, JSONSchemaType, JSONSchemaTypeName, Mutable } from \"@itwin/core-bentley\";\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\nimport { IModelJsFs } from \"../IModelJsFs\";\n\n/**\n * The properties of a single Setting, used by the settings editor. This interface also includes the\n * default value if it is not specified in any Settings file.\n * This interface includes all members of [JSONSchema]($bentley) with the extensions added by VSCode.\n * @note the `type` member is marked optional in JSONSchema but is required for Settings.\n * @beta\n */\nexport interface SettingSchema extends Readonly<JSONSchema> {\n readonly items?: SettingSchema; // must be single object, not array\n readonly type: JSONSchemaTypeName; // type is required for settings\n readonly properties?: { [name: string]: SettingSchema };\n\n /** whether the setting replaces lower priority entries with the same name or combines with them. */\n readonly cumulative?: true;\n}\n\n/**\n * The properties of a group of [[SettingSchema]]s for an application. Groups can be added and removed from [[SettingsSchemas]]\n * and are identified by their (required) `groupName` member\n * @beta\n */\nexport interface SettingSchemaGroup {\n readonly groupName: string;\n readonly properties: { [name: string]: SettingSchema };\n readonly order?: number;\n readonly title?: string;\n readonly description?: string;\n readonly extensionId?: string;\n}\n\n/**\n * The registry of available [[SettingSchemaGroup]]s.\n * The registry is used for editing Settings files and for finding default values for settings.\n * @beta\n */\nexport class SettingsSchemas {\n private constructor() { } // singleton\n private static readonly _allGroups = new Map<string, SettingSchemaGroup>();\n /** a map of all registered [[SettingSchema]]s */\n public static readonly allSchemas = new Map<string, SettingSchema>();\n /** event that signals that the values in [[allSchemas]] have changed in some way. */\n public static readonly onSchemaChanged = new BeEvent<() => void>();\n\n /** Clear the contents of the registry and remove all event listeners.\n * @note This is really only necessary for tests of the Settings system.\n * @internal\n */\n public static reset() {\n this._allGroups.clear();\n this.allSchemas.clear();\n this.onSchemaChanged.clear();\n }\n\n /** @internal */\n public static validateArrayObject<T>(val: T, schemaName: string, msg: string): T {\n const schema = this.allSchemas.get(schemaName);\n const items = schema?.items;\n if (undefined === items)\n return val;\n const required = items.required;\n const properties = items.properties;\n if (undefined === required || undefined === properties)\n return val;\n\n for (const entry of required) {\n const entryType = properties[entry].type;\n const value = (val as any)[entry];\n if (entryType === \"array\" && Array.isArray(value))\n continue;\n if (typeof value !== entryType)\n throw new Error(`invalid \"${schemaName}\" setting entry for \"${msg}\": ${entry} is ${value}`);\n }\n return val;\n }\n\n /**\n * Add one or more [[SettingSchemaGroup]]s. `SettingSchemaGroup`s must include a `groupName` member that is used\n * to identify the group. If a group with the same name is already registered, the old values are first removed and then the new group is added.\n */\n public static addGroup(settingsGroup: SettingSchemaGroup | SettingSchemaGroup[]): void {\n if (!Array.isArray(settingsGroup))\n settingsGroup = [settingsGroup];\n\n this.doAdd(settingsGroup);\n this.onSchemaChanged.raiseEvent();\n }\n\n /** Add a [[SettingSchemaGroup]] from stringified json5. */\n public static addJson(settingSchema: string): void {\n this.addGroup(parse(settingSchema));\n }\n\n /** Add a [[SettingSchemaGroup]] from a json5 file. */\n public static addFile(fileName: LocalFileName): void {\n try {\n this.addJson(fs.readFileSync(fileName, \"utf-8\"));\n } catch (e: any) {\n throw new Error(`parsing SettingSchema file \"${fileName}\": ${e.message}\"`);\n }\n }\n\n /** Add all files with a either \".json\" or \".json5\" extension from a supplied directory. */\n public static addDirectory(dirName: LocalDirName) {\n for (const fileName of IModelJsFs.readdirSync(dirName)) {\n const ext = extname(fileName);\n if (ext === \".json5\" || ext === \".json\")\n this.addFile(join(dirName, fileName));\n }\n }\n\n /** Remove a previously added [[SettingSchemaGroup]] by groupName */\n public static removeGroup(groupName: string): void {\n this.doRemove(groupName);\n this.onSchemaChanged.raiseEvent();\n }\n\n private static doAdd(settingsGroup: SettingSchemaGroup[]) {\n settingsGroup.forEach((group) => {\n if (undefined === group.groupName)\n throw new Error(`settings group has no \"groupName\" member`);\n\n this.doRemove(group.groupName);\n this.validateAndAdd(group);\n this._allGroups.set(group.groupName, group);\n });\n }\n\n private static doRemove(groupName: string) {\n const group = this._allGroups.get(groupName);\n if (undefined !== group?.properties) {\n for (const key of Object.keys(group.properties))\n this.allSchemas.delete(key);\n }\n this._allGroups.delete(groupName);\n }\n\n private static validateName(name: string) {\n if (!name.trim())\n throw new Error(`empty property name`);\n if (this.allSchemas.has(name))\n throw new Error(`property \"${name}\" is already defined`);\n }\n\n private static validateProperty(name: string, property: SettingSchema | undefined) {\n if (!property)\n throw new Error(`missing required property ${name}`);\n\n if (!property.type)\n throw new Error(`property ${name} has no type`);\n\n switch (property.type) {\n case \"boolean\":\n case \"integer\":\n case \"null\":\n case \"number\":\n case \"string\":\n return;\n\n case \"object\":\n const required = property.required;\n const props = property.properties;\n if (required && props) {\n for (const entry of required)\n this.validateProperty(entry, props[entry]);\n }\n if (props) {\n for (const key of Object.keys(props))\n try {\n this.validateProperty(key, props[key]);\n } catch (e: any) {\n throw new Error(`property ${key} of ${name}: ${e.message}`);\n }\n }\n return;\n\n case \"array\":\n if (typeof property.items !== \"object\")\n throw new Error(`array property ${name} has no items member`);\n try {\n this.validateProperty(\"items\", property.items);\n } catch (e: any) {\n throw new Error(`array property ${name}: ${e.message}`);\n }\n return;\n\n default:\n throw new Error(`property ${name} has illegal type \"${property.type}\"`);\n }\n }\n\n private static validateAndAdd(group: SettingSchemaGroup) {\n const properties = group.properties;\n if (undefined === properties)\n throw new Error(`group ${group.groupName} has no properties`);\n\n for (const key of Object.keys(properties)) {\n this.validateName(key);\n this.validateProperty(key, properties[key]);\n const property: Mutable<SettingSchema> = properties[key];\n property.default = property.default ?? this.getDefaultValue(property.type);\n this.allSchemas.set(key, property);\n }\n }\n\n private static getDefaultValue(type: JSONSchemaTypeName | JSONSchemaTypeName[]): JSONSchemaType | undefined {\n type = Array.isArray(type) ? type[0] : type;\n switch (type) {\n case \"boolean\":\n return false;\n case \"integer\":\n case \"number\":\n return 0;\n case \"string\":\n return \"\";\n case \"array\":\n return [];\n case \"object\":\n return {};\n default:\n return undefined;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SettingsSchemas.js","sourceRoot":"","sources":["../../../src/workspace/SettingsSchemas.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,+BAA+B;AAC/B,iCAA8B;AAC9B,+BAAqC;AACrC,sDAAuG;AAEvG,8CAA2C;AAgC3C;;;;GAIG;AACH,MAAa,eAAe;IAC1B,gBAAwB,CAAC,CAAC,YAAY;IAOtC;;;OAGG;IACI,MAAM,CAAC,KAAK;QACjB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED,gBAAgB;IACT,MAAM,CAAC,mBAAmB,CAAI,GAAM,EAAE,UAAkB,EAAE,GAAW;QAC1E,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC/C,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,CAAC;QAC5B,IAAI,SAAS,KAAK,KAAK;YACrB,OAAO,GAAG,CAAC;QACb,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAChC,MAAM,UAAU,GAAG,KAAK,CAAC,UAAU,CAA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AC;IAEO,MAAM,CAAC,eAAe,CAAC,IAA+C;QAC5E,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC5C,QAAQ,IAAI,EAAE;YACZ,KAAK,SAAS;gBACZ,OAAO,KAAK,CAAC;YACf,KAAK,SAAS,CAAC;YACf,KAAK,QAAQ;gBACX,OAAO,CAAC,CAAC;YACX,KAAK,QAAQ;gBACX,OAAO,EAAE,CAAC;YACZ,KAAK,OAAO;gBACV,OAAO,EAAE,CAAC;YACZ,KAAK,QAAQ;gBACX,OAAO,EAAE,CAAC;YACZ;gBACE,OAAO,SAAS,CAAC;SACpB;IACH,CAAC;;AA1LH,0CA2LC;AAzLyB,0BAAU,GAAG,IAAI,GAAG,EAA8B,CAAC;AAC3E,iDAAiD;AAC1B,0BAAU,GAAG,IAAI,GAAG,EAAyB,CAAC;AACrE,qFAAqF;AAC9D,+BAAe,GAAG,IAAI,sBAAO,EAAc,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Workspace\n */\n\nimport * as fs from \"fs-extra\";\nimport { parse } from \"json5\";\nimport { extname, join } from \"path\";\nimport { BeEvent, JSONSchema, JSONSchemaType, JSONSchemaTypeName, Mutable } from \"@itwin/core-bentley\";\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\nimport { IModelJsFs } from \"../IModelJsFs\";\n\n/**\n * The properties of a single Setting, used by the settings editor. This interface also includes the\n * default value if it is not specified in any Settings file.\n * This interface includes all members of [JSONSchema]($bentley) with the extensions added by VSCode.\n * @note the `type` member is marked optional in JSONSchema but is required for Settings.\n * @beta\n */\nexport interface SettingSchema extends Readonly<JSONSchema> {\n readonly items?: SettingSchema; // must be single object, not array\n readonly type: JSONSchemaTypeName; // type is required for settings\n readonly properties?: { [name: string]: SettingSchema };\n\n /** whether the setting replaces lower priority entries with the same name or combines with them. */\n readonly cumulative?: true;\n}\n\n/**\n * The properties of a group of [[SettingSchema]]s for an application. Groups can be added and removed from [[SettingsSchemas]]\n * and are identified by their (required) `groupName` member\n * @beta\n */\nexport interface SettingSchemaGroup {\n readonly groupName: string;\n readonly properties: { [name: string]: SettingSchema };\n readonly order?: number;\n readonly title?: string;\n readonly description?: string;\n readonly extensionId?: string;\n}\n\n/**\n * The registry of available [[SettingSchemaGroup]]s.\n * The registry is used for editing Settings files and for finding default values for settings.\n * @beta\n */\nexport class SettingsSchemas {\n private constructor() { } // singleton\n private static readonly _allGroups = new Map<string, SettingSchemaGroup>();\n /** a map of all registered [[SettingSchema]]s */\n public static readonly allSchemas = new Map<string, SettingSchema>();\n /** event that signals that the values in [[allSchemas]] have changed in some way. */\n public static readonly onSchemaChanged = new BeEvent<() => void>();\n\n /** Clear the contents of the registry and remove all event listeners.\n * @note This is really only necessary for tests of the Settings system.\n * @internal\n */\n public static reset() {\n this._allGroups.clear();\n this.allSchemas.clear();\n this.onSchemaChanged.clear();\n }\n\n /** @internal */\n public static validateArrayObject<T>(val: T, schemaName: string, msg: string): T {\n const schema = this.allSchemas.get(schemaName);\n const items = schema?.items;\n if (undefined === items)\n return val;\n const required = items.required;\n const properties = items.properties;\n if (undefined === required || undefined === properties)\n return val;\n\n for (const entry of required) {\n const entryType = properties[entry].type;\n const value = (val as any)[entry];\n if (entryType === \"array\" && Array.isArray(value))\n continue;\n if (typeof value !== entryType)\n throw new Error(`invalid \"${schemaName}\" setting entry for \"${msg}\": ${entry} is ${value}`);\n }\n return val;\n }\n\n /**\n * Add one or more [[SettingSchemaGroup]]s. `SettingSchemaGroup`s must include a `groupName` member that is used\n * to identify the group. If a group with the same name is already registered, the old values are first removed and then the new group is added.\n */\n public static addGroup(settingsGroup: SettingSchemaGroup | SettingSchemaGroup[]): void {\n if (!Array.isArray(settingsGroup))\n settingsGroup = [settingsGroup];\n\n this.doAdd(settingsGroup);\n this.onSchemaChanged.raiseEvent();\n }\n\n /** Add a [[SettingSchemaGroup]] from stringified json5. */\n public static addJson(settingSchema: string): void {\n this.addGroup(parse(settingSchema));\n }\n\n /** Add a [[SettingSchemaGroup]] from a json5 file. */\n public static addFile(fileName: LocalFileName): void {\n try {\n this.addJson(fs.readFileSync(fileName, \"utf-8\"));\n } catch (e: any) {\n throw new Error(`parsing SettingSchema file \"${fileName}\": ${e.message}\"`);\n }\n }\n\n /** Add all files with a either \".json\" or \".json5\" extension from a supplied directory. */\n public static addDirectory(dirName: LocalDirName) {\n for (const fileName of IModelJsFs.readdirSync(dirName)) {\n const ext = extname(fileName);\n if (ext === \".json5\" || ext === \".json\")\n this.addFile(join(dirName, fileName));\n }\n }\n\n /** Remove a previously added [[SettingSchemaGroup]] by groupName */\n public static removeGroup(groupName: string): void {\n this.doRemove(groupName);\n this.onSchemaChanged.raiseEvent();\n }\n\n private static doAdd(settingsGroup: SettingSchemaGroup[]) {\n settingsGroup.forEach((group) => {\n if (undefined === group.groupName)\n throw new Error(`settings group has no \"groupName\" member`);\n\n this.doRemove(group.groupName);\n this.validateAndAdd(group);\n this._allGroups.set(group.groupName, group);\n });\n }\n\n private static doRemove(groupName: string) {\n const group = this._allGroups.get(groupName);\n if (undefined !== group?.properties) {\n for (const key of Object.keys(group.properties))\n this.allSchemas.delete(key);\n }\n this._allGroups.delete(groupName);\n }\n\n private static validateName(name: string) {\n if (!name.trim())\n throw new Error(`empty property name`);\n if (this.allSchemas.has(name))\n throw new Error(`property \"${name}\" is already defined`);\n }\n\n private static validateProperty(name: string, property: SettingSchema | undefined) {\n if (!property)\n throw new Error(`missing required property ${name}`);\n\n if (!property.type)\n throw new Error(`property ${name} has no type`);\n\n switch (property.type) {\n case \"boolean\":\n case \"integer\":\n case \"null\":\n case \"number\":\n case \"string\":\n return;\n\n case \"object\":\n const required = property.required;\n const props = property.properties;\n if (required && props) {\n for (const entry of required)\n this.validateProperty(entry, props[entry]);\n }\n if (props) {\n for (const key of Object.keys(props))\n try {\n this.validateProperty(key, props[key]);\n } catch (e: any) {\n throw new Error(`property ${key} of ${name}: ${e.message}`);\n }\n }\n return;\n\n case \"array\":\n if (typeof property.items !== \"object\")\n throw new Error(`array property ${name} has no items member`);\n try {\n this.validateProperty(\"items\", property.items);\n } catch (e: any) {\n throw new Error(`array property ${name}: ${e.message}`);\n }\n return;\n\n default:\n throw new Error(`property ${name} has illegal type \"${property.type}\"`);\n }\n }\n\n private static validateAndAdd(group: SettingSchemaGroup) {\n const properties = group.properties;\n if (undefined === properties)\n throw new Error(`group ${group.groupName} has no properties`);\n\n for (const key of Object.keys(properties)) {\n this.validateName(key);\n this.validateProperty(key, properties[key]);\n const property: Mutable<SettingSchema> = properties[key];\n property.default = property.default ?? this.getDefaultValue(property.type);\n this.allSchemas.set(key, property);\n }\n }\n\n private static getDefaultValue(type: JSONSchemaTypeName | JSONSchemaTypeName[]): JSONSchemaType | undefined {\n type = Array.isArray(type) ? type[0] : type;\n switch (type) {\n case \"boolean\":\n return false;\n case \"integer\":\n case \"number\":\n return 0;\n case \"string\":\n return \"\";\n case \"array\":\n return [];\n case \"object\":\n return {};\n default:\n return undefined;\n }\n }\n}\n"]}
|
|
@@ -33,12 +33,11 @@ exports.WorkspaceSetting = {
|
|
|
33
33
|
/** @internal */
|
|
34
34
|
class ITwinWorkspace {
|
|
35
35
|
constructor(settings, opts) {
|
|
36
|
-
var _a;
|
|
37
36
|
this._containers = new Map();
|
|
38
37
|
this.settings = settings;
|
|
39
|
-
this.containerDir =
|
|
40
|
-
this._cloudCache = opts
|
|
41
|
-
let settingsFiles = opts
|
|
38
|
+
this.containerDir = opts?.containerDir ?? (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, "Workspace");
|
|
39
|
+
this._cloudCache = opts?.testCloudCache;
|
|
40
|
+
let settingsFiles = opts?.settingsFiles;
|
|
42
41
|
if (settingsFiles) {
|
|
43
42
|
if (typeof settingsFiles === "string")
|
|
44
43
|
settingsFiles = [settingsFiles];
|
|
@@ -73,8 +72,7 @@ class ITwinWorkspace {
|
|
|
73
72
|
return this._containers.get(containerId);
|
|
74
73
|
}
|
|
75
74
|
getContainer(props, account) {
|
|
76
|
-
|
|
77
|
-
return (_a = this.findContainer(props.containerId)) !== null && _a !== void 0 ? _a : new ITwinWorkspaceContainer(this, props, account);
|
|
75
|
+
return this.findContainer(props.containerId) ?? new ITwinWorkspaceContainer(this, props, account);
|
|
78
76
|
}
|
|
79
77
|
getWorkspaceDbFromProps(dbProps, containerProps, account) {
|
|
80
78
|
return this.getContainer(containerProps, account).getWorkspaceDb(dbProps);
|
|
@@ -89,7 +87,7 @@ class ITwinWorkspace {
|
|
|
89
87
|
containerProps.accessToken = await tokenFunc(containerProps, account);
|
|
90
88
|
container = this.getContainer(containerProps, account);
|
|
91
89
|
}
|
|
92
|
-
return container
|
|
90
|
+
return container?.getWorkspaceDb(dbProps);
|
|
93
91
|
}
|
|
94
92
|
loadSettingsDictionary(settingRsc, db, priority) {
|
|
95
93
|
const setting = db.getString(settingRsc);
|
|
@@ -154,7 +152,7 @@ class ITwinWorkspaceContainer {
|
|
|
154
152
|
ITwinWorkspaceContainer.validateContainerId(props.containerId);
|
|
155
153
|
this.workspace = workspace;
|
|
156
154
|
this.id = props.containerId;
|
|
157
|
-
if (
|
|
155
|
+
if (account?.accessName && account.storageType)
|
|
158
156
|
this.cloudContainer = CloudSqlite_1.CloudSqlite.createCloudContainer({ accessToken: "", ...props, ...account });
|
|
159
157
|
workspace.addContainer(this);
|
|
160
158
|
this.filesDir = (0, path_1.join)(this.dirName, "Files");
|
|
@@ -191,12 +189,11 @@ class ITwinWorkspaceContainer {
|
|
|
191
189
|
this.noLeadingOrTrailingSpaces(dbName, "dbName");
|
|
192
190
|
}
|
|
193
191
|
static validateVersion(version) {
|
|
194
|
-
|
|
195
|
-
version = version !== null && version !== void 0 ? version : "1.0.0";
|
|
192
|
+
version = version ?? "1.0.0";
|
|
196
193
|
if (version) {
|
|
197
194
|
const opts = { loose: true, includePrerelease: true };
|
|
198
195
|
// clean allows prerelease, so try it first. If that fails attempt to coerce it (coerce strips prerelease even if you say not to.)
|
|
199
|
-
const semVersion =
|
|
196
|
+
const semVersion = semver.clean(version, opts) ?? semver.coerce(version, opts)?.version;
|
|
200
197
|
if (!semVersion)
|
|
201
198
|
throw new Error("invalid version specification");
|
|
202
199
|
version = semVersion;
|
|
@@ -211,7 +208,6 @@ class ITwinWorkspaceContainer {
|
|
|
211
208
|
return `${dbName}:${this.validateVersion(version)}`;
|
|
212
209
|
}
|
|
213
210
|
static resolveCloudFileName(cloudContainer, props) {
|
|
214
|
-
var _a;
|
|
215
211
|
const dbName = props.dbName;
|
|
216
212
|
const dbs = cloudContainer.queryDatabases(`${dbName}*`); // get all databases that start with dbName
|
|
217
213
|
const versions = [];
|
|
@@ -222,7 +218,7 @@ class ITwinWorkspaceContainer {
|
|
|
222
218
|
}
|
|
223
219
|
if (versions.length === 0)
|
|
224
220
|
versions[0] = "1.0.0";
|
|
225
|
-
const range =
|
|
221
|
+
const range = props.version ?? "*";
|
|
226
222
|
try {
|
|
227
223
|
const version = semver.maxSatisfying(versions, range, { loose: true, includePrerelease: props.includePrerelease });
|
|
228
224
|
if (version)
|
|
@@ -266,8 +262,7 @@ class ITwinWorkspaceContainer {
|
|
|
266
262
|
this._wsDbs.set(toAdd.dbName, toAdd);
|
|
267
263
|
}
|
|
268
264
|
getWorkspaceDb(props) {
|
|
269
|
-
|
|
270
|
-
const db = (_a = this._wsDbs.get(props.dbName)) !== null && _a !== void 0 ? _a : new ITwinWorkspaceDb(props, this);
|
|
265
|
+
const db = this._wsDbs.get(props.dbName) ?? new ITwinWorkspaceDb(props, this);
|
|
271
266
|
if (!db.isOpen)
|
|
272
267
|
db.open();
|
|
273
268
|
return db;
|
|
@@ -281,11 +276,10 @@ class ITwinWorkspaceContainer {
|
|
|
281
276
|
}
|
|
282
277
|
}
|
|
283
278
|
close() {
|
|
284
|
-
var _a;
|
|
285
279
|
for (const [_name, db] of this._wsDbs)
|
|
286
280
|
db.close();
|
|
287
281
|
this._wsDbs.clear();
|
|
288
|
-
|
|
282
|
+
this.cloudContainer?.disconnect();
|
|
289
283
|
}
|
|
290
284
|
/** Delete all local files extracted by [[WorkspaceDb.getFile]] for this container. */
|
|
291
285
|
purgeContainerFiles() {
|
|
@@ -359,7 +353,7 @@ class ITwinWorkspaceDb {
|
|
|
359
353
|
if (!file)
|
|
360
354
|
return undefined;
|
|
361
355
|
const info = file.info;
|
|
362
|
-
const localFileName = targetFileName
|
|
356
|
+
const localFileName = targetFileName ?? file.localFileName;
|
|
363
357
|
// check whether the file is already up to date.
|
|
364
358
|
const stat = fs.existsSync(localFileName) && fs.statSync(localFileName);
|
|
365
359
|
if (stat && Math.round(stat.mtimeMs) === info.date && stat.size === info.size)
|
|
@@ -411,7 +405,7 @@ class EditableWorkspaceDb extends ITwinWorkspaceDb {
|
|
|
411
405
|
performWriteSql(rscName, sql, bind) {
|
|
412
406
|
this.sqliteDb.withSqliteStatement(sql, (stmt) => {
|
|
413
407
|
stmt.bindString(1, rscName);
|
|
414
|
-
bind
|
|
408
|
+
bind?.(stmt);
|
|
415
409
|
const rc = stmt.step();
|
|
416
410
|
if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc) {
|
|
417
411
|
if (core_bentley_1.DbResult.BE_SQLITE_CONSTRAINT_PRIMARYKEY === rc)
|
|
@@ -516,8 +510,8 @@ class EditableWorkspaceDb extends ITwinWorkspaceDb {
|
|
|
516
510
|
*/
|
|
517
511
|
addFile(rscName, localFileName, fileExt) {
|
|
518
512
|
EditableWorkspaceDb.validateResourceName(rscName);
|
|
519
|
-
fileExt = fileExt
|
|
520
|
-
if (
|
|
513
|
+
fileExt = fileExt ?? (0, path_1.extname)(localFileName);
|
|
514
|
+
if (fileExt?.[0] === ".")
|
|
521
515
|
fileExt = fileExt.slice(1);
|
|
522
516
|
this.sqliteDb.nativeDb.embedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName), fileExt });
|
|
523
517
|
}
|