@itwin/core-backend 4.0.0-dev.28 → 4.0.0-dev.32

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.
Files changed (244) hide show
  1. package/lib/cjs/AliCloudStorageService.d.ts +23 -23
  2. package/lib/cjs/AliCloudStorageService.js +71 -71
  3. package/lib/cjs/AliCloudStorageService.js.map +1 -1
  4. package/lib/cjs/BackendHubAccess.d.ts +224 -224
  5. package/lib/cjs/BackendHubAccess.js +41 -41
  6. package/lib/cjs/BackendHubAccess.js.map +1 -1
  7. package/lib/cjs/BackendLoggerCategory.d.ts +91 -91
  8. package/lib/cjs/BackendLoggerCategory.js +99 -99
  9. package/lib/cjs/BackendLoggerCategory.js.map +1 -1
  10. package/lib/cjs/BisCoreSchema.d.ts +21 -21
  11. package/lib/cjs/BisCoreSchema.js +60 -60
  12. package/lib/cjs/BisCoreSchema.js.map +1 -1
  13. package/lib/cjs/BriefcaseManager.d.ts +170 -170
  14. package/lib/cjs/BriefcaseManager.js +408 -408
  15. package/lib/cjs/BriefcaseManager.js.map +1 -1
  16. package/lib/cjs/Category.d.ts +153 -153
  17. package/lib/cjs/Category.js +243 -243
  18. package/lib/cjs/Category.js.map +1 -1
  19. package/lib/cjs/ChangeSummaryManager.d.ts +187 -187
  20. package/lib/cjs/ChangeSummaryManager.js +446 -446
  21. package/lib/cjs/ChangeSummaryManager.js.map +1 -1
  22. package/lib/cjs/ChangedElementsDb.d.ts +99 -99
  23. package/lib/cjs/ChangedElementsDb.js +165 -165
  24. package/lib/cjs/ChangedElementsDb.js.map +1 -1
  25. package/lib/cjs/ChangedElementsManager.d.ts +39 -39
  26. package/lib/cjs/ChangedElementsManager.js +88 -88
  27. package/lib/cjs/ChangedElementsManager.js.map +1 -1
  28. package/lib/cjs/CheckpointManager.d.ts +121 -121
  29. package/lib/cjs/CheckpointManager.js +348 -348
  30. package/lib/cjs/CheckpointManager.js.map +1 -1
  31. package/lib/cjs/ClassRegistry.d.ts +79 -79
  32. package/lib/cjs/ClassRegistry.js +249 -249
  33. package/lib/cjs/ClassRegistry.js.map +1 -1
  34. package/lib/cjs/CloudSqlite.d.ts +350 -350
  35. package/lib/cjs/CloudSqlite.js +153 -153
  36. package/lib/cjs/CloudSqlite.js.map +1 -1
  37. package/lib/cjs/CloudStorageBackend.d.ts +58 -58
  38. package/lib/cjs/CloudStorageBackend.js +170 -170
  39. package/lib/cjs/CloudStorageBackend.js.map +1 -1
  40. package/lib/cjs/CodeService.d.ts +396 -396
  41. package/lib/cjs/CodeService.js +63 -63
  42. package/lib/cjs/CodeService.js.map +1 -1
  43. package/lib/cjs/CodeSpecs.d.ts +55 -55
  44. package/lib/cjs/CodeSpecs.js +124 -124
  45. package/lib/cjs/CodeSpecs.js.map +1 -1
  46. package/lib/cjs/ConcurrentQuery.d.ts +13 -13
  47. package/lib/cjs/ConcurrentQuery.js +36 -36
  48. package/lib/cjs/ConcurrentQuery.js.map +1 -1
  49. package/lib/cjs/CustomViewState3dCreator.d.ts +21 -21
  50. package/lib/cjs/CustomViewState3dCreator.js +81 -81
  51. package/lib/cjs/CustomViewState3dCreator.js.map +1 -1
  52. package/lib/cjs/DevTools.d.ts +73 -73
  53. package/lib/cjs/DevTools.js +156 -156
  54. package/lib/cjs/DevTools.js.map +1 -1
  55. package/lib/cjs/DisplayStyle.d.ts +106 -106
  56. package/lib/cjs/DisplayStyle.js +253 -253
  57. package/lib/cjs/DisplayStyle.js.map +1 -1
  58. package/lib/cjs/ECDb.d.ts +191 -191
  59. package/lib/cjs/ECDb.js +348 -348
  60. package/lib/cjs/ECDb.js.map +1 -1
  61. package/lib/cjs/ECSchemaXmlContext.d.ts +18 -18
  62. package/lib/cjs/ECSchemaXmlContext.js +41 -41
  63. package/lib/cjs/ECSchemaXmlContext.js.map +1 -1
  64. package/lib/cjs/ECSqlStatement.d.ts +473 -473
  65. package/lib/cjs/ECSqlStatement.js +791 -791
  66. package/lib/cjs/ECSqlStatement.js.map +1 -1
  67. package/lib/cjs/Element.d.ts +1109 -1109
  68. package/lib/cjs/Element.js +1419 -1419
  69. package/lib/cjs/Element.js.map +1 -1
  70. package/lib/cjs/ElementAspect.d.ts +179 -179
  71. package/lib/cjs/ElementAspect.js +211 -211
  72. package/lib/cjs/ElementAspect.js.map +1 -1
  73. package/lib/cjs/ElementGraphics.d.ts +9 -9
  74. package/lib/cjs/ElementGraphics.js +41 -41
  75. package/lib/cjs/ElementGraphics.js.map +1 -1
  76. package/lib/cjs/ElementTreeWalker.d.ts +162 -162
  77. package/lib/cjs/ElementTreeWalker.js +409 -409
  78. package/lib/cjs/ElementTreeWalker.js.map +1 -1
  79. package/lib/cjs/Entity.d.ts +106 -106
  80. package/lib/cjs/Entity.js +134 -134
  81. package/lib/cjs/Entity.js.map +1 -1
  82. package/lib/cjs/EntityReferences.d.ts +49 -49
  83. package/lib/cjs/EntityReferences.js +95 -95
  84. package/lib/cjs/EntityReferences.js.map +1 -1
  85. package/lib/cjs/ExportGraphics.d.ts +317 -317
  86. package/lib/cjs/ExportGraphics.js +208 -208
  87. package/lib/cjs/ExportGraphics.js.map +1 -1
  88. package/lib/cjs/ExternalSource.d.ts +96 -96
  89. package/lib/cjs/ExternalSource.js +131 -131
  90. package/lib/cjs/ExternalSource.js.map +1 -1
  91. package/lib/cjs/GeoCoordConfig.d.ts +19 -19
  92. package/lib/cjs/GeoCoordConfig.js +85 -85
  93. package/lib/cjs/GeoCoordConfig.js.map +1 -1
  94. package/lib/cjs/GeometrySummary.d.ts +4 -4
  95. package/lib/cjs/GeometrySummary.js +380 -380
  96. package/lib/cjs/GeometrySummary.js.map +1 -1
  97. package/lib/cjs/HubMock.d.ts +94 -94
  98. package/lib/cjs/HubMock.js +220 -220
  99. package/lib/cjs/HubMock.js.map +1 -1
  100. package/lib/cjs/IModelCloneContext.d.ts +8 -8
  101. package/lib/cjs/IModelCloneContext.js +15 -15
  102. package/lib/cjs/IModelCloneContext.js.map +1 -1
  103. package/lib/cjs/IModelDb.d.ts +1210 -1210
  104. package/lib/cjs/IModelDb.js +2377 -2377
  105. package/lib/cjs/IModelDb.js.map +1 -1
  106. package/lib/cjs/IModelElementCloneContext.d.ts +89 -89
  107. package/lib/cjs/IModelElementCloneContext.js +159 -159
  108. package/lib/cjs/IModelElementCloneContext.js.map +1 -1
  109. package/lib/cjs/IModelHost.d.ts +369 -369
  110. package/lib/cjs/IModelHost.js +488 -488
  111. package/lib/cjs/IModelHost.js.map +1 -1
  112. package/lib/cjs/IModelJsFs.d.ts +62 -62
  113. package/lib/cjs/IModelJsFs.js +139 -139
  114. package/lib/cjs/IModelJsFs.js.map +1 -1
  115. package/lib/cjs/IpcHost.d.ts +104 -104
  116. package/lib/cjs/IpcHost.js +276 -276
  117. package/lib/cjs/IpcHost.js.map +1 -1
  118. package/lib/cjs/LineStyle.d.ts +311 -311
  119. package/lib/cjs/LineStyle.js +295 -295
  120. package/lib/cjs/LineStyle.js.map +1 -1
  121. package/lib/cjs/LocalHub.d.ts +162 -162
  122. package/lib/cjs/LocalHub.js +580 -580
  123. package/lib/cjs/LocalHub.js.map +1 -1
  124. package/lib/cjs/LocalhostIpcHost.d.ts +20 -20
  125. package/lib/cjs/LocalhostIpcHost.js +79 -79
  126. package/lib/cjs/LocalhostIpcHost.js.map +1 -1
  127. package/lib/cjs/Material.d.ts +131 -131
  128. package/lib/cjs/Material.js +180 -180
  129. package/lib/cjs/Material.js.map +1 -1
  130. package/lib/cjs/Model.d.ts +392 -392
  131. package/lib/cjs/Model.js +485 -485
  132. package/lib/cjs/Model.js.map +1 -1
  133. package/lib/cjs/NativeAppStorage.d.ts +51 -51
  134. package/lib/cjs/NativeAppStorage.js +202 -202
  135. package/lib/cjs/NativeAppStorage.js.map +1 -1
  136. package/lib/cjs/NativeHost.d.ts +52 -52
  137. package/lib/cjs/NativeHost.js +160 -160
  138. package/lib/cjs/NativeHost.js.map +1 -1
  139. package/lib/cjs/NavigationRelationship.d.ts +156 -156
  140. package/lib/cjs/NavigationRelationship.js +225 -225
  141. package/lib/cjs/NavigationRelationship.js.map +1 -1
  142. package/lib/cjs/PromiseMemoizer.d.ts +51 -51
  143. package/lib/cjs/PromiseMemoizer.js +101 -101
  144. package/lib/cjs/PromiseMemoizer.js.map +1 -1
  145. package/lib/cjs/PropertyStore.d.ts +132 -132
  146. package/lib/cjs/PropertyStore.js +11 -11
  147. package/lib/cjs/PropertyStore.js.map +1 -1
  148. package/lib/cjs/Relationship.d.ts +416 -416
  149. package/lib/cjs/Relationship.js +494 -494
  150. package/lib/cjs/Relationship.js.map +1 -1
  151. package/lib/cjs/RpcBackend.d.ts +5 -5
  152. package/lib/cjs/RpcBackend.js +32 -32
  153. package/lib/cjs/RpcBackend.js.map +1 -1
  154. package/lib/cjs/SQLiteDb.d.ts +219 -219
  155. package/lib/cjs/SQLiteDb.js +212 -212
  156. package/lib/cjs/SQLiteDb.js.map +1 -1
  157. package/lib/cjs/Schema.d.ts +55 -55
  158. package/lib/cjs/Schema.js +83 -83
  159. package/lib/cjs/Schema.js.map +1 -1
  160. package/lib/cjs/ServerBasedLocks.d.ts +57 -57
  161. package/lib/cjs/ServerBasedLocks.js +168 -168
  162. package/lib/cjs/ServerBasedLocks.js.map +1 -1
  163. package/lib/cjs/SqliteStatement.d.ts +360 -360
  164. package/lib/cjs/SqliteStatement.js +586 -586
  165. package/lib/cjs/SqliteStatement.js.map +1 -1
  166. package/lib/cjs/Texture.d.ts +58 -58
  167. package/lib/cjs/Texture.js +82 -82
  168. package/lib/cjs/Texture.js.map +1 -1
  169. package/lib/cjs/TileStorage.d.ts +18 -18
  170. package/lib/cjs/TileStorage.js +87 -87
  171. package/lib/cjs/TileStorage.js.map +1 -1
  172. package/lib/cjs/TxnManager.d.ts +202 -202
  173. package/lib/cjs/TxnManager.js +356 -356
  174. package/lib/cjs/TxnManager.js.map +1 -1
  175. package/lib/cjs/ViewDefinition.d.ts +435 -439
  176. package/lib/cjs/ViewDefinition.d.ts.map +1 -1
  177. package/lib/cjs/ViewDefinition.js +646 -646
  178. package/lib/cjs/ViewDefinition.js.map +1 -1
  179. package/lib/cjs/ViewStateHydrator.d.ts +13 -13
  180. package/lib/cjs/ViewStateHydrator.js +103 -103
  181. package/lib/cjs/ViewStateHydrator.js.map +1 -1
  182. package/lib/cjs/assets/IModelChange.02.00.00.ecschema.xml +90 -90
  183. package/lib/cjs/assets/Settings/Schemas/Cloud.Schema.json +67 -67
  184. package/lib/cjs/assets/Settings/Schemas/Gcs.schema.json +31 -31
  185. package/lib/cjs/assets/Settings/Schemas/Workspace.Schema.json +52 -52
  186. package/lib/cjs/assets/Settings/backend.setting.json5 +138 -138
  187. package/lib/cjs/core-backend.d.ts +184 -184
  188. package/lib/cjs/core-backend.js +204 -204
  189. package/lib/cjs/core-backend.js.map +1 -1
  190. package/lib/cjs/domains/FunctionalElements.d.ts +101 -101
  191. package/lib/cjs/domains/FunctionalElements.js +145 -145
  192. package/lib/cjs/domains/FunctionalElements.js.map +1 -1
  193. package/lib/cjs/domains/FunctionalSchema.d.ts +13 -13
  194. package/lib/cjs/domains/FunctionalSchema.js +40 -40
  195. package/lib/cjs/domains/FunctionalSchema.js.map +1 -1
  196. package/lib/cjs/domains/GenericElements.d.ts +177 -177
  197. package/lib/cjs/domains/GenericElements.js +263 -263
  198. package/lib/cjs/domains/GenericElements.js.map +1 -1
  199. package/lib/cjs/domains/GenericSchema.d.ts +10 -10
  200. package/lib/cjs/domains/GenericSchema.js +28 -28
  201. package/lib/cjs/domains/GenericSchema.js.map +1 -1
  202. package/lib/cjs/rpc/multipart.d.ts +11 -11
  203. package/lib/cjs/rpc/multipart.js +71 -71
  204. package/lib/cjs/rpc/multipart.js.map +1 -1
  205. package/lib/cjs/rpc/tracing.d.ts +28 -28
  206. package/lib/cjs/rpc/tracing.js +73 -73
  207. package/lib/cjs/rpc/tracing.js.map +1 -1
  208. package/lib/cjs/rpc/web/logging.d.ts +9 -9
  209. package/lib/cjs/rpc/web/logging.js +43 -43
  210. package/lib/cjs/rpc/web/logging.js.map +1 -1
  211. package/lib/cjs/rpc/web/request.d.ts +6 -6
  212. package/lib/cjs/rpc/web/request.js +73 -73
  213. package/lib/cjs/rpc/web/request.js.map +1 -1
  214. package/lib/cjs/rpc/web/response.d.ts +6 -6
  215. package/lib/cjs/rpc/web/response.js +105 -105
  216. package/lib/cjs/rpc/web/response.js.map +1 -1
  217. package/lib/cjs/rpc-impl/DevToolsRpcImpl.d.ts +15 -15
  218. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js +32 -32
  219. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js.map +1 -1
  220. package/lib/cjs/rpc-impl/IModelReadRpcImpl.d.ts +47 -47
  221. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js +293 -293
  222. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js.map +1 -1
  223. package/lib/cjs/rpc-impl/IModelTileRpcImpl.d.ts +22 -22
  224. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js +202 -202
  225. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js.map +1 -1
  226. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.d.ts +36 -36
  227. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js +166 -166
  228. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js.map +1 -1
  229. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.d.ts +16 -16
  230. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js +42 -42
  231. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js.map +1 -1
  232. package/lib/cjs/rpc-impl/WipRpcImpl.d.ts +15 -15
  233. package/lib/cjs/rpc-impl/WipRpcImpl.js +37 -37
  234. package/lib/cjs/rpc-impl/WipRpcImpl.js.map +1 -1
  235. package/lib/cjs/workspace/Settings.d.ts +186 -186
  236. package/lib/cjs/workspace/Settings.js +154 -154
  237. package/lib/cjs/workspace/Settings.js.map +1 -1
  238. package/lib/cjs/workspace/SettingsSchemas.d.ts +75 -75
  239. package/lib/cjs/workspace/SettingsSchemas.js +190 -190
  240. package/lib/cjs/workspace/SettingsSchemas.js.map +1 -1
  241. package/lib/cjs/workspace/Workspace.d.ts +414 -414
  242. package/lib/cjs/workspace/Workspace.js +537 -537
  243. package/lib/cjs/workspace/Workspace.js.map +1 -1
  244. package/package.json +11 -11
@@ -1,538 +1,538 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
- * See LICENSE.md in the project root for license terms and full copyright notice.
5
- *--------------------------------------------------------------------------------------------*/
6
- /** @packageDocumentation
7
- * @module Workspace
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.EditableWorkspaceDb = exports.ITwinWorkspaceDb = exports.ITwinWorkspaceContainer = exports.ITwinWorkspace = exports.WorkspaceSetting = void 0;
11
- const crypto_1 = require("crypto");
12
- const fs = require("fs-extra");
13
- const path_1 = require("path");
14
- const semver = require("semver");
15
- const core_bentley_1 = require("@itwin/core-bentley");
16
- const core_common_1 = require("@itwin/core-common");
17
- const CloudSqlite_1 = require("../CloudSqlite");
18
- const IModelHost_1 = require("../IModelHost");
19
- const IModelJsFs_1 = require("../IModelJsFs");
20
- const SQLiteDb_1 = require("../SQLiteDb");
21
- const Settings_1 = require("./Settings");
22
- const SettingsSchemas_1 = require("./SettingsSchemas");
23
- /* eslint-disable @typescript-eslint/naming-convention */
24
- // cspell:ignore rowid primarykey julianday
25
- /** The Settings used by Workspace api
26
- * @beta
27
- */
28
- exports.WorkspaceSetting = {
29
- Accounts: "cloud/accounts",
30
- Containers: "cloud/containers",
31
- Databases: "workspace/databases",
32
- };
33
- /** @internal */
34
- class ITwinWorkspace {
35
- constructor(settings, opts) {
36
- this._containers = new Map();
37
- this.settings = settings;
38
- this.containerDir = opts?.containerDir ?? (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, "Workspace");
39
- this._cloudCache = opts?.testCloudCache;
40
- let settingsFiles = opts?.settingsFiles;
41
- if (settingsFiles) {
42
- if (typeof settingsFiles === "string")
43
- settingsFiles = [settingsFiles];
44
- settingsFiles.forEach((file) => settings.addFile(file, Settings_1.SettingsPriority.application));
45
- }
46
- }
47
- get cloudCache() {
48
- if (undefined === this._cloudCache)
49
- this._cloudCache = ITwinWorkspace.getSharedCloudCache();
50
- return this._cloudCache;
51
- }
52
- static getSharedCloudCache() {
53
- if (undefined === this._sharedCloudCache) {
54
- const rootDir = (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, "Workspace", "cloud");
55
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync(rootDir);
56
- this._sharedCloudCache = CloudSqlite_1.CloudSqlite.createCloudCache({ rootDir, cacheSize: "20G", name: "workspace" });
57
- }
58
- return this._sharedCloudCache;
59
- }
60
- static finalize() {
61
- if (this._sharedCloudCache) {
62
- this._sharedCloudCache.destroy();
63
- this._sharedCloudCache = undefined;
64
- }
65
- }
66
- addContainer(toAdd) {
67
- if (undefined !== this._containers.get(toAdd.id))
68
- throw new Error("container already exists in workspace");
69
- this._containers.set(toAdd.id, toAdd);
70
- }
71
- findContainer(containerId) {
72
- return this._containers.get(containerId);
73
- }
74
- getContainer(props, account) {
75
- return this.findContainer(props.containerId) ?? new ITwinWorkspaceContainer(this, props, account);
76
- }
77
- getWorkspaceDbFromProps(dbProps, containerProps, account) {
78
- return this.getContainer(containerProps, account).getWorkspaceDb(dbProps);
79
- }
80
- async getWorkspaceDb(dbAlias, tokenFunc) {
81
- const dbProps = this.resolveDatabase(dbAlias);
82
- const containerProps = this.resolveContainer(dbProps.containerName);
83
- const account = containerProps.accountName !== "" ? this.resolveAccount(containerProps.accountName) : undefined;
84
- let container = this.findContainer(containerProps.containerId);
85
- if (undefined === container) {
86
- if (tokenFunc && account)
87
- containerProps.accessToken = await tokenFunc(containerProps, account);
88
- container = this.getContainer(containerProps, account);
89
- }
90
- return container?.getWorkspaceDb(dbProps);
91
- }
92
- loadSettingsDictionary(settingRsc, db, priority) {
93
- const setting = db.getString(settingRsc);
94
- if (undefined === setting)
95
- throw new Error(`could not load setting resource ${settingRsc}`);
96
- this.settings.addJson(`${db.container.id}/${db.dbName}/${settingRsc}`, priority, setting);
97
- }
98
- close() {
99
- this.settings.close();
100
- for (const [_id, container] of this._containers)
101
- container.close();
102
- this._containers.clear();
103
- }
104
- resolveAccount(accountName) {
105
- const resolved = this.settings.resolveSetting(exports.WorkspaceSetting.Accounts, (val) => {
106
- if (Array.isArray(val)) {
107
- for (const entry of val) {
108
- if (typeof entry === "object" && entry.name === accountName)
109
- return SettingsSchemas_1.SettingsSchemas.validateArrayObject(entry, exports.WorkspaceSetting.Accounts, accountName);
110
- }
111
- }
112
- return undefined; // keep going through all settings dictionaries
113
- });
114
- if (resolved === undefined)
115
- throw new Error(`no setting "${exports.WorkspaceSetting.Accounts}" entry for "${accountName}"`);
116
- return resolved;
117
- }
118
- resolveContainer(containerName) {
119
- const resolved = this.settings.resolveSetting(exports.WorkspaceSetting.Containers, (val) => {
120
- if (Array.isArray(val)) {
121
- for (const entry of val) {
122
- if (typeof entry === "object" && entry.name === containerName)
123
- return SettingsSchemas_1.SettingsSchemas.validateArrayObject(entry, exports.WorkspaceSetting.Containers, containerName);
124
- }
125
- }
126
- return undefined; // keep going through all settings dictionaries
127
- });
128
- if (resolved === undefined)
129
- throw new Error(`no setting "${exports.WorkspaceSetting.Containers}" entry for "${containerName}"`);
130
- return resolved;
131
- }
132
- resolveDatabase(databaseName) {
133
- const resolved = this.settings.resolveSetting(exports.WorkspaceSetting.Databases, (val) => {
134
- if (Array.isArray(val)) {
135
- for (const entry of val) {
136
- if (typeof entry === "object" && entry.name === databaseName)
137
- return SettingsSchemas_1.SettingsSchemas.validateArrayObject(entry, exports.WorkspaceSetting.Databases, databaseName);
138
- }
139
- }
140
- return undefined; // keep going through all settings dictionaries
141
- });
142
- if (resolved === undefined)
143
- throw new Error(`no setting "${exports.WorkspaceSetting.Databases}" entry for "${databaseName}"`);
144
- return resolved;
145
- }
146
- }
147
- exports.ITwinWorkspace = ITwinWorkspace;
148
- /** @internal */
149
- class ITwinWorkspaceContainer {
150
- constructor(workspace, props, account) {
151
- this._wsDbs = new Map();
152
- ITwinWorkspaceContainer.validateContainerId(props.containerId);
153
- this.workspace = workspace;
154
- this.id = props.containerId;
155
- if (account?.accessName && account.storageType)
156
- this.cloudContainer = CloudSqlite_1.CloudSqlite.createCloudContainer({ accessToken: "", ...props, ...account });
157
- workspace.addContainer(this);
158
- this.filesDir = (0, path_1.join)(this.dirName, "Files");
159
- const cloudContainer = this.cloudContainer;
160
- if (undefined === cloudContainer)
161
- return;
162
- cloudContainer.connect(this.workspace.cloudCache);
163
- if (false !== props.syncOnConnect) {
164
- try {
165
- cloudContainer.checkForChanges();
166
- }
167
- catch (e) {
168
- // must be offline
169
- }
170
- }
171
- }
172
- get dirName() { return (0, path_1.join)(this.workspace.containerDir, this.id); }
173
- static noLeadingOrTrailingSpaces(name, msg) {
174
- if (name.trim() !== name)
175
- throw new Error(`${msg} [${name}] may not have leading or tailing spaces`);
176
- }
177
- /** rules for ContainerIds (from Azure, see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata)
178
- * - may only contain lower case letters, numbers or dashes
179
- * - may not start or end with with a dash nor have more than one dash in a row
180
- * - may not be shorter than 3 or longer than 63 characters
181
- */
182
- static validateContainerId(id) {
183
- if (!/^(?=.{3,63}$)[a-z0-9]+(-[a-z0-9]+)*$/g.test(id))
184
- throw new Error(`invalid containerId: [${id}]`);
185
- }
186
- static validateDbName(dbName) {
187
- if (dbName === "" || dbName.length > 255 || /[#\.<>:"/\\"`'|?*\u0000-\u001F]/g.test(dbName) || /^(con|prn|aux|nul|com\d|lpt\d)$/i.test(dbName))
188
- throw new Error(`invalid dbName: [${dbName}]`);
189
- this.noLeadingOrTrailingSpaces(dbName, "dbName");
190
- }
191
- static validateVersion(version) {
192
- version = version ?? "1.0.0";
193
- if (version) {
194
- const opts = { loose: true, includePrerelease: true };
195
- // clean allows prerelease, so try it first. If that fails attempt to coerce it (coerce strips prerelease even if you say not to.)
196
- const semVersion = semver.clean(version, opts) ?? semver.coerce(version, opts)?.version;
197
- if (!semVersion)
198
- throw new Error("invalid version specification");
199
- version = semVersion;
200
- }
201
- return version;
202
- }
203
- static parseDbFileName(dbFileName) {
204
- const parts = dbFileName.split(":");
205
- return { dbName: parts[0], version: parts[1] };
206
- }
207
- static makeDbFileName(dbName, version) {
208
- return `${dbName}:${this.validateVersion(version)}`;
209
- }
210
- static resolveCloudFileName(cloudContainer, props) {
211
- const dbName = props.dbName;
212
- const dbs = cloudContainer.queryDatabases(`${dbName}*`); // get all databases that start with dbName
213
- const versions = [];
214
- for (const db of dbs) {
215
- const thisDb = ITwinWorkspaceContainer.parseDbFileName(db);
216
- if (thisDb.dbName === dbName && "string" === typeof thisDb.version && thisDb.version.length > 0)
217
- versions.push(thisDb.version);
218
- }
219
- if (versions.length === 0)
220
- versions[0] = "1.0.0";
221
- const range = props.version ?? "*";
222
- try {
223
- const version = semver.maxSatisfying(versions, range, { loose: true, includePrerelease: props.includePrerelease });
224
- if (version)
225
- return `${dbName}:${version}`;
226
- }
227
- catch (e) {
228
- }
229
- throw new Error(`No version of [${dbName}] available for "${range}"`);
230
- }
231
- /**
232
- * Create a copy of an existing [[WorkspaceDb]] in a cloud container with a new version number.
233
- * @param cloudContainer The attached cloud container holding the existing WorkspaceDb
234
- * @param fromProps Properties that describe the source WorkspaceDb for the new version
235
- * @param versionType The type of version increment to apply to the existing version.
236
- * @note This requires that the cloudContainer is attached and the write lock on the container be held. The copy should be modified with
237
- * new content before the write lock is released, and thereafter should never be modified again.
238
- */
239
- static async makeNewVersion(cloudContainer, fromProps, versionType) {
240
- const oldName = this.resolveCloudFileName(cloudContainer, fromProps);
241
- const oldDb = this.parseDbFileName(oldName);
242
- const newVersion = semver.inc(oldDb.version, versionType);
243
- if (!newVersion)
244
- throw new Error("invalid version");
245
- const newName = this.makeDbFileName(oldDb.dbName, newVersion);
246
- await cloudContainer.copyDatabase(oldName, newName);
247
- return { oldName, newName };
248
- }
249
- /**
250
- * Convert a WorkspaceDb.Props specification into a DbFileName. For cloud-based containers, this resolves to the dbName, incorporating the appropriate
251
- * version. For file-based containers, this returns a local filename of a WorkspaceDb file with the extension ".itwin-workspace"
252
- */
253
- resolveDbFileName(props) {
254
- const cloudContainer = this.cloudContainer;
255
- if (undefined === cloudContainer)
256
- return (0, path_1.join)(this.dirName, `${props.dbName}.${ITwinWorkspaceDb.fileExt}`); // local file, versions not allowed
257
- return ITwinWorkspaceContainer.resolveCloudFileName(cloudContainer, props);
258
- }
259
- addWorkspaceDb(toAdd) {
260
- if (undefined !== this._wsDbs.get(toAdd.dbName))
261
- throw new Error(`workspaceDb ${toAdd.dbName} already exists in workspace`);
262
- this._wsDbs.set(toAdd.dbName, toAdd);
263
- }
264
- getWorkspaceDb(props) {
265
- const db = this._wsDbs.get(props.dbName) ?? new ITwinWorkspaceDb(props, this);
266
- if (!db.isOpen)
267
- db.open();
268
- return db;
269
- }
270
- dropWorkspaceDb(toDrop) {
271
- const name = toDrop.dbName;
272
- const wsDb = this._wsDbs.get(name);
273
- if (wsDb === toDrop) {
274
- this._wsDbs.delete(name);
275
- wsDb.close();
276
- }
277
- }
278
- close() {
279
- for (const [_name, db] of this._wsDbs)
280
- db.close();
281
- this._wsDbs.clear();
282
- this.cloudContainer?.disconnect();
283
- }
284
- /** Delete all local files extracted by [[WorkspaceDb.getFile]] for this container. */
285
- purgeContainerFiles() {
286
- IModelJsFs_1.IModelJsFs.purgeDirSync(this.filesDir);
287
- }
288
- }
289
- exports.ITwinWorkspaceContainer = ITwinWorkspaceContainer;
290
- /**
291
- * Implementation of WorkspaceDb
292
- * @internal
293
- */
294
- class ITwinWorkspaceDb {
295
- constructor(props, container) {
296
- /** the SQLiteDb for this WorkspaceDb*/
297
- this.sqliteDb = new SQLiteDb_1.SQLiteDb();
298
- /** called before db is closed */
299
- this.onClose = new core_bentley_1.BeEvent();
300
- ITwinWorkspaceContainer.validateDbName(props.dbName);
301
- this.dbName = props.dbName;
302
- this.container = container;
303
- this.dbFileName = container.resolveDbFileName(props);
304
- container.addWorkspaceDb(this);
305
- }
306
- /** true if this WorkspaceDb is currently open */
307
- get isOpen() { return this.sqliteDb.isOpen; }
308
- queryFileResource(rscName) {
309
- const info = this.sqliteDb.nativeDb.queryEmbeddedFile(rscName);
310
- if (undefined === info)
311
- return undefined;
312
- // since resource names can contain illegal characters, path separators, etc., we make the local file name from its hash, in hex.
313
- let localFileName = (0, path_1.join)(this.container.filesDir, (0, crypto_1.createHash)("sha1").update(this.dbFileName).update(rscName).digest("hex"));
314
- if (info.fileExt !== "") // since some applications may expect to see the extension, append it here if it was supplied.
315
- localFileName = `${localFileName}.${info.fileExt}`;
316
- return { localFileName, info };
317
- }
318
- open() {
319
- this.sqliteDb.openDb(this.dbFileName, core_bentley_1.OpenMode.Readonly, this.container.cloudContainer);
320
- }
321
- close() {
322
- if (this.isOpen) {
323
- this.onClose.raiseEvent();
324
- this.sqliteDb.closeDb();
325
- this.container.dropWorkspaceDb(this);
326
- }
327
- }
328
- getString(rscName) {
329
- return this.sqliteDb.withSqliteStatement("SELECT value from strings WHERE id=?", (stmt) => {
330
- stmt.bindString(1, rscName);
331
- return core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getValueString(0) : undefined;
332
- });
333
- }
334
- /** Get a BlobIO reader for a blob WorkspaceResource.
335
- * @note when finished, caller *must* call `close` on the BlobIO.
336
- */
337
- getBlobReader(rscName) {
338
- return this.sqliteDb.withSqliteStatement("SELECT rowid from blobs WHERE id=?", (stmt) => {
339
- stmt.bindString(1, rscName);
340
- const blobReader = SQLiteDb_1.SQLiteDb.createBlobIO();
341
- blobReader.open(this.sqliteDb.nativeDb, { tableName: "blobs", columnName: "value", row: stmt.getValueInteger(0) });
342
- return blobReader;
343
- });
344
- }
345
- getBlob(rscName) {
346
- return this.sqliteDb.withSqliteStatement("SELECT value from blobs WHERE id=?", (stmt) => {
347
- stmt.bindString(1, rscName);
348
- return core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getValueBlob(0) : undefined;
349
- });
350
- }
351
- getFile(rscName, targetFileName) {
352
- const file = this.queryFileResource(rscName);
353
- if (!file)
354
- return undefined;
355
- const info = file.info;
356
- const localFileName = targetFileName ?? file.localFileName;
357
- // check whether the file is already up to date.
358
- const stat = fs.existsSync(localFileName) && fs.statSync(localFileName);
359
- if (stat && Math.round(stat.mtimeMs) === info.date && stat.size === info.size)
360
- return localFileName; // yes, we're done
361
- // extractEmbeddedFile fails if the file exists or if the directory does not exist
362
- if (stat)
363
- fs.removeSync(localFileName);
364
- else
365
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync((0, path_1.dirname)(localFileName));
366
- this.sqliteDb.nativeDb.extractEmbeddedFile({ name: rscName, localFileName });
367
- const date = new Date(info.date);
368
- fs.utimesSync(localFileName, date, date); // set the last-modified date of the file to match date in container
369
- fs.chmodSync(localFileName, "0444"); // set file readonly
370
- return localFileName;
371
- }
372
- prefetch(opts) {
373
- const cloudContainer = this.container.cloudContainer;
374
- if (cloudContainer === undefined)
375
- throw new Error("no cloud container to prefetch");
376
- return CloudSqlite_1.CloudSqlite.startCloudPrefetch(cloudContainer, this.dbFileName, opts);
377
- }
378
- }
379
- exports.ITwinWorkspaceDb = ITwinWorkspaceDb;
380
- /** file extension for local WorkspaceDbs */
381
- ITwinWorkspaceDb.fileExt = "itwin-workspace";
382
- /**
383
- * An editable [[WorkspaceDb]]. This is used by administrators for creating and modifying `WorkspaceDb`s.
384
- * For cloud-backed containers, the write token must be obtained before this class may be used. Only one user at at time
385
- * may be editing.
386
- * @internal
387
- */
388
- class EditableWorkspaceDb extends ITwinWorkspaceDb {
389
- static validateResourceName(name) {
390
- ITwinWorkspaceContainer.noLeadingOrTrailingSpaces(name, "resource name");
391
- if (name.length > 1024)
392
- throw new Error("resource name too long");
393
- }
394
- validateResourceSize(val) {
395
- const len = typeof val === "string" ? val.length : val.byteLength;
396
- if (len > (1024 * 1024 * 1024)) // one gigabyte
397
- throw new Error("value is too large");
398
- }
399
- open() {
400
- this.sqliteDb.openDb(this.dbFileName, core_bentley_1.OpenMode.ReadWrite, this.container.cloudContainer);
401
- }
402
- getFileModifiedTime(localFileName) {
403
- return Math.round(fs.statSync(localFileName).mtimeMs);
404
- }
405
- performWriteSql(rscName, sql, bind) {
406
- this.sqliteDb.withSqliteStatement(sql, (stmt) => {
407
- stmt.bindString(1, rscName);
408
- bind?.(stmt);
409
- const rc = stmt.step();
410
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc) {
411
- if (core_bentley_1.DbResult.BE_SQLITE_CONSTRAINT_PRIMARYKEY === rc)
412
- throw new core_common_1.IModelError(rc, `resource "${rscName}" already exists`);
413
- throw new core_common_1.IModelError(rc, `workspace [${sql}]`);
414
- }
415
- });
416
- this.sqliteDb.saveChanges();
417
- }
418
- async createDb(version) {
419
- if (!this.container.cloudContainer) {
420
- EditableWorkspaceDb.createEmpty(this.dbFileName);
421
- }
422
- else {
423
- // currently the only way to create a workspaceDb in a cloud container is to create a temporary workspaceDb and upload it.
424
- const tempDbFile = (0, path_1.join)(IModelHost_1.KnownLocations.tmpdir, `empty.${ITwinWorkspaceDb.fileExt}`);
425
- if (fs.existsSync(tempDbFile))
426
- IModelJsFs_1.IModelJsFs.removeSync(tempDbFile);
427
- EditableWorkspaceDb.createEmpty(tempDbFile);
428
- this.dbFileName = ITwinWorkspaceContainer.makeDbFileName(this.dbName, version);
429
- await CloudSqlite_1.CloudSqlite.uploadDb(this.container.cloudContainer, { localFileName: tempDbFile, dbName: this.dbFileName });
430
- IModelJsFs_1.IModelJsFs.removeSync(tempDbFile);
431
- }
432
- this.open();
433
- }
434
- /** Create a new, empty, EditableWorkspaceDb for importing Workspace resources. */
435
- static createEmpty(fileName) {
436
- const db = new SQLiteDb_1.SQLiteDb();
437
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync((0, path_1.dirname)(fileName));
438
- db.createDb(fileName);
439
- const timeStampCol = "lastMod TIMESTAMP NOT NULL DEFAULT(julianday('now'))";
440
- db.executeSQL(`CREATE TABLE strings(id TEXT PRIMARY KEY NOT NULL,value TEXT,${timeStampCol})`);
441
- db.executeSQL(`CREATE TABLE blobs(id TEXT PRIMARY KEY NOT NULL,value BLOB,${timeStampCol})`);
442
- const createTrigger = (tableName) => {
443
- db.executeSQL(`CREATE TRIGGER ${tableName}_timeStamp AFTER UPDATE ON ${tableName} WHEN old.lastMod=new.lastMod AND old.lastMod != julianday('now') BEGIN UPDATE ${tableName} SET lastMod=julianday('now') WHERE id=new.id; END`);
444
- };
445
- createTrigger("strings");
446
- createTrigger("blobs");
447
- db.closeDb(true);
448
- }
449
- /** Add a new string resource to this WorkspaceDb.
450
- * @param rscName The name of the string resource.
451
- * @param val The string to save.
452
- */
453
- addString(rscName, val) {
454
- EditableWorkspaceDb.validateResourceName(rscName);
455
- this.validateResourceSize(val);
456
- this.performWriteSql(rscName, "INSERT INTO strings(id,value) VALUES(?,?)", (stmt) => stmt.bindString(2, val));
457
- }
458
- /** Update an existing string resource with a new value.
459
- * @param rscName The name of the string resource.
460
- * @param val The new value.
461
- * @throws if rscName does not exist
462
- */
463
- updateString(rscName, val) {
464
- this.validateResourceSize(val);
465
- this.performWriteSql(rscName, "UPDATE strings SET value=?2 WHERE id=?1", (stmt) => stmt.bindString(2, val));
466
- }
467
- /** Remove a string resource. */
468
- removeString(rscName) {
469
- this.performWriteSql(rscName, "DELETE FROM strings WHERE id=?");
470
- }
471
- /** Add a new blob resource to this WorkspaceDb.
472
- * @param rscName The name of the blob resource.
473
- * @param val The blob to save.
474
- */
475
- addBlob(rscName, val) {
476
- EditableWorkspaceDb.validateResourceName(rscName);
477
- this.validateResourceSize(val);
478
- this.performWriteSql(rscName, "INSERT INTO blobs(id,value) VALUES(?,?)", (stmt) => stmt.bindBlob(2, val));
479
- }
480
- /** Update an existing blob resource with a new value.
481
- * @param rscName The name of the blob resource.
482
- * @param val The new value.
483
- * @throws if rscName does not exist
484
- */
485
- updateBlob(rscName, val) {
486
- this.validateResourceSize(val);
487
- this.performWriteSql(rscName, "UPDATE blobs SET value=?2 WHERE id=?1", (stmt) => stmt.bindBlob(2, val));
488
- }
489
- /** Get a BlobIO writer for a previously-added blob WorkspaceResource.
490
- * @note after writing is complete, caller must call `close` on the BlobIO and must call `saveChanges` on the `db`.
491
- */
492
- getBlobWriter(rscName) {
493
- return this.sqliteDb.withSqliteStatement("SELECT rowid from blobs WHERE id=?", (stmt) => {
494
- stmt.bindString(1, rscName);
495
- const blobWriter = SQLiteDb_1.SQLiteDb.createBlobIO();
496
- blobWriter.open(this.sqliteDb.nativeDb, { tableName: "blobs", columnName: "value", row: stmt.getValueInteger(0), writeable: true });
497
- return blobWriter;
498
- });
499
- }
500
- /** Remove a blob resource. */
501
- removeBlob(rscName) {
502
- this.performWriteSql(rscName, "DELETE FROM blobs WHERE id=?");
503
- }
504
- /** Copy the contents of an existing local file into this WorkspaceDb as a file resource.
505
- * @param rscName The name of the file resource.
506
- * @param localFileName The name of a local file to be read.
507
- * @param fileExt The extension (do not include the leading ".") to be appended to the generated fileName
508
- * when this WorkspaceDb is extracted from the WorkspaceDb. By default the characters after the last "." in `localFileName`
509
- * are used. Pass this argument to override that.
510
- */
511
- addFile(rscName, localFileName, fileExt) {
512
- EditableWorkspaceDb.validateResourceName(rscName);
513
- fileExt = fileExt ?? (0, path_1.extname)(localFileName);
514
- if (fileExt?.[0] === ".")
515
- fileExt = fileExt.slice(1);
516
- this.sqliteDb.nativeDb.embedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName), fileExt });
517
- }
518
- /** Replace an existing file resource with the contents of another local file.
519
- * @param rscName The name of the file resource.
520
- * @param localFileName The name of a local file to be read.
521
- * @throws if rscName does not exist
522
- */
523
- updateFile(rscName, localFileName) {
524
- this.queryFileResource(rscName); // throws if not present
525
- this.sqliteDb.nativeDb.replaceEmbeddedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName) });
526
- }
527
- /** Remove a file resource. */
528
- removeFile(rscName) {
529
- const file = this.queryFileResource(rscName);
530
- if (undefined === file)
531
- throw new Error(`file resource "${rscName}" does not exist`);
532
- if (file && fs.existsSync(file.localFileName))
533
- fs.unlinkSync(file.localFileName);
534
- this.sqliteDb.nativeDb.removeEmbeddedFile(rscName);
535
- }
536
- }
537
- exports.EditableWorkspaceDb = EditableWorkspaceDb;
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
+ * See LICENSE.md in the project root for license terms and full copyright notice.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ /** @packageDocumentation
7
+ * @module Workspace
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.EditableWorkspaceDb = exports.ITwinWorkspaceDb = exports.ITwinWorkspaceContainer = exports.ITwinWorkspace = exports.WorkspaceSetting = void 0;
11
+ const crypto_1 = require("crypto");
12
+ const fs = require("fs-extra");
13
+ const path_1 = require("path");
14
+ const semver = require("semver");
15
+ const core_bentley_1 = require("@itwin/core-bentley");
16
+ const core_common_1 = require("@itwin/core-common");
17
+ const CloudSqlite_1 = require("../CloudSqlite");
18
+ const IModelHost_1 = require("../IModelHost");
19
+ const IModelJsFs_1 = require("../IModelJsFs");
20
+ const SQLiteDb_1 = require("../SQLiteDb");
21
+ const Settings_1 = require("./Settings");
22
+ const SettingsSchemas_1 = require("./SettingsSchemas");
23
+ /* eslint-disable @typescript-eslint/naming-convention */
24
+ // cspell:ignore rowid primarykey julianday
25
+ /** The Settings used by Workspace api
26
+ * @beta
27
+ */
28
+ exports.WorkspaceSetting = {
29
+ Accounts: "cloud/accounts",
30
+ Containers: "cloud/containers",
31
+ Databases: "workspace/databases",
32
+ };
33
+ /** @internal */
34
+ class ITwinWorkspace {
35
+ constructor(settings, opts) {
36
+ this._containers = new Map();
37
+ this.settings = settings;
38
+ this.containerDir = opts?.containerDir ?? (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, "Workspace");
39
+ this._cloudCache = opts?.testCloudCache;
40
+ let settingsFiles = opts?.settingsFiles;
41
+ if (settingsFiles) {
42
+ if (typeof settingsFiles === "string")
43
+ settingsFiles = [settingsFiles];
44
+ settingsFiles.forEach((file) => settings.addFile(file, Settings_1.SettingsPriority.application));
45
+ }
46
+ }
47
+ get cloudCache() {
48
+ if (undefined === this._cloudCache)
49
+ this._cloudCache = ITwinWorkspace.getSharedCloudCache();
50
+ return this._cloudCache;
51
+ }
52
+ static getSharedCloudCache() {
53
+ if (undefined === this._sharedCloudCache) {
54
+ const rootDir = (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, "Workspace", "cloud");
55
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync(rootDir);
56
+ this._sharedCloudCache = CloudSqlite_1.CloudSqlite.createCloudCache({ rootDir, cacheSize: "20G", name: "workspace" });
57
+ }
58
+ return this._sharedCloudCache;
59
+ }
60
+ static finalize() {
61
+ if (this._sharedCloudCache) {
62
+ this._sharedCloudCache.destroy();
63
+ this._sharedCloudCache = undefined;
64
+ }
65
+ }
66
+ addContainer(toAdd) {
67
+ if (undefined !== this._containers.get(toAdd.id))
68
+ throw new Error("container already exists in workspace");
69
+ this._containers.set(toAdd.id, toAdd);
70
+ }
71
+ findContainer(containerId) {
72
+ return this._containers.get(containerId);
73
+ }
74
+ getContainer(props, account) {
75
+ return this.findContainer(props.containerId) ?? new ITwinWorkspaceContainer(this, props, account);
76
+ }
77
+ getWorkspaceDbFromProps(dbProps, containerProps, account) {
78
+ return this.getContainer(containerProps, account).getWorkspaceDb(dbProps);
79
+ }
80
+ async getWorkspaceDb(dbAlias, tokenFunc) {
81
+ const dbProps = this.resolveDatabase(dbAlias);
82
+ const containerProps = this.resolveContainer(dbProps.containerName);
83
+ const account = containerProps.accountName !== "" ? this.resolveAccount(containerProps.accountName) : undefined;
84
+ let container = this.findContainer(containerProps.containerId);
85
+ if (undefined === container) {
86
+ if (tokenFunc && account)
87
+ containerProps.accessToken = await tokenFunc(containerProps, account);
88
+ container = this.getContainer(containerProps, account);
89
+ }
90
+ return container?.getWorkspaceDb(dbProps);
91
+ }
92
+ loadSettingsDictionary(settingRsc, db, priority) {
93
+ const setting = db.getString(settingRsc);
94
+ if (undefined === setting)
95
+ throw new Error(`could not load setting resource ${settingRsc}`);
96
+ this.settings.addJson(`${db.container.id}/${db.dbName}/${settingRsc}`, priority, setting);
97
+ }
98
+ close() {
99
+ this.settings.close();
100
+ for (const [_id, container] of this._containers)
101
+ container.close();
102
+ this._containers.clear();
103
+ }
104
+ resolveAccount(accountName) {
105
+ const resolved = this.settings.resolveSetting(exports.WorkspaceSetting.Accounts, (val) => {
106
+ if (Array.isArray(val)) {
107
+ for (const entry of val) {
108
+ if (typeof entry === "object" && entry.name === accountName)
109
+ return SettingsSchemas_1.SettingsSchemas.validateArrayObject(entry, exports.WorkspaceSetting.Accounts, accountName);
110
+ }
111
+ }
112
+ return undefined; // keep going through all settings dictionaries
113
+ });
114
+ if (resolved === undefined)
115
+ throw new Error(`no setting "${exports.WorkspaceSetting.Accounts}" entry for "${accountName}"`);
116
+ return resolved;
117
+ }
118
+ resolveContainer(containerName) {
119
+ const resolved = this.settings.resolveSetting(exports.WorkspaceSetting.Containers, (val) => {
120
+ if (Array.isArray(val)) {
121
+ for (const entry of val) {
122
+ if (typeof entry === "object" && entry.name === containerName)
123
+ return SettingsSchemas_1.SettingsSchemas.validateArrayObject(entry, exports.WorkspaceSetting.Containers, containerName);
124
+ }
125
+ }
126
+ return undefined; // keep going through all settings dictionaries
127
+ });
128
+ if (resolved === undefined)
129
+ throw new Error(`no setting "${exports.WorkspaceSetting.Containers}" entry for "${containerName}"`);
130
+ return resolved;
131
+ }
132
+ resolveDatabase(databaseName) {
133
+ const resolved = this.settings.resolveSetting(exports.WorkspaceSetting.Databases, (val) => {
134
+ if (Array.isArray(val)) {
135
+ for (const entry of val) {
136
+ if (typeof entry === "object" && entry.name === databaseName)
137
+ return SettingsSchemas_1.SettingsSchemas.validateArrayObject(entry, exports.WorkspaceSetting.Databases, databaseName);
138
+ }
139
+ }
140
+ return undefined; // keep going through all settings dictionaries
141
+ });
142
+ if (resolved === undefined)
143
+ throw new Error(`no setting "${exports.WorkspaceSetting.Databases}" entry for "${databaseName}"`);
144
+ return resolved;
145
+ }
146
+ }
147
+ exports.ITwinWorkspace = ITwinWorkspace;
148
+ /** @internal */
149
+ class ITwinWorkspaceContainer {
150
+ constructor(workspace, props, account) {
151
+ this._wsDbs = new Map();
152
+ ITwinWorkspaceContainer.validateContainerId(props.containerId);
153
+ this.workspace = workspace;
154
+ this.id = props.containerId;
155
+ if (account?.accessName && account.storageType)
156
+ this.cloudContainer = CloudSqlite_1.CloudSqlite.createCloudContainer({ accessToken: "", ...props, ...account });
157
+ workspace.addContainer(this);
158
+ this.filesDir = (0, path_1.join)(this.dirName, "Files");
159
+ const cloudContainer = this.cloudContainer;
160
+ if (undefined === cloudContainer)
161
+ return;
162
+ cloudContainer.connect(this.workspace.cloudCache);
163
+ if (false !== props.syncOnConnect) {
164
+ try {
165
+ cloudContainer.checkForChanges();
166
+ }
167
+ catch (e) {
168
+ // must be offline
169
+ }
170
+ }
171
+ }
172
+ get dirName() { return (0, path_1.join)(this.workspace.containerDir, this.id); }
173
+ static noLeadingOrTrailingSpaces(name, msg) {
174
+ if (name.trim() !== name)
175
+ throw new Error(`${msg} [${name}] may not have leading or tailing spaces`);
176
+ }
177
+ /** rules for ContainerIds (from Azure, see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata)
178
+ * - may only contain lower case letters, numbers or dashes
179
+ * - may not start or end with with a dash nor have more than one dash in a row
180
+ * - may not be shorter than 3 or longer than 63 characters
181
+ */
182
+ static validateContainerId(id) {
183
+ if (!/^(?=.{3,63}$)[a-z0-9]+(-[a-z0-9]+)*$/g.test(id))
184
+ throw new Error(`invalid containerId: [${id}]`);
185
+ }
186
+ static validateDbName(dbName) {
187
+ if (dbName === "" || dbName.length > 255 || /[#\.<>:"/\\"`'|?*\u0000-\u001F]/g.test(dbName) || /^(con|prn|aux|nul|com\d|lpt\d)$/i.test(dbName))
188
+ throw new Error(`invalid dbName: [${dbName}]`);
189
+ this.noLeadingOrTrailingSpaces(dbName, "dbName");
190
+ }
191
+ static validateVersion(version) {
192
+ version = version ?? "1.0.0";
193
+ if (version) {
194
+ const opts = { loose: true, includePrerelease: true };
195
+ // clean allows prerelease, so try it first. If that fails attempt to coerce it (coerce strips prerelease even if you say not to.)
196
+ const semVersion = semver.clean(version, opts) ?? semver.coerce(version, opts)?.version;
197
+ if (!semVersion)
198
+ throw new Error("invalid version specification");
199
+ version = semVersion;
200
+ }
201
+ return version;
202
+ }
203
+ static parseDbFileName(dbFileName) {
204
+ const parts = dbFileName.split(":");
205
+ return { dbName: parts[0], version: parts[1] };
206
+ }
207
+ static makeDbFileName(dbName, version) {
208
+ return `${dbName}:${this.validateVersion(version)}`;
209
+ }
210
+ static resolveCloudFileName(cloudContainer, props) {
211
+ const dbName = props.dbName;
212
+ const dbs = cloudContainer.queryDatabases(`${dbName}*`); // get all databases that start with dbName
213
+ const versions = [];
214
+ for (const db of dbs) {
215
+ const thisDb = ITwinWorkspaceContainer.parseDbFileName(db);
216
+ if (thisDb.dbName === dbName && "string" === typeof thisDb.version && thisDb.version.length > 0)
217
+ versions.push(thisDb.version);
218
+ }
219
+ if (versions.length === 0)
220
+ versions[0] = "1.0.0";
221
+ const range = props.version ?? "*";
222
+ try {
223
+ const version = semver.maxSatisfying(versions, range, { loose: true, includePrerelease: props.includePrerelease });
224
+ if (version)
225
+ return `${dbName}:${version}`;
226
+ }
227
+ catch (e) {
228
+ }
229
+ throw new Error(`No version of [${dbName}] available for "${range}"`);
230
+ }
231
+ /**
232
+ * Create a copy of an existing [[WorkspaceDb]] in a cloud container with a new version number.
233
+ * @param cloudContainer The attached cloud container holding the existing WorkspaceDb
234
+ * @param fromProps Properties that describe the source WorkspaceDb for the new version
235
+ * @param versionType The type of version increment to apply to the existing version.
236
+ * @note This requires that the cloudContainer is attached and the write lock on the container be held. The copy should be modified with
237
+ * new content before the write lock is released, and thereafter should never be modified again.
238
+ */
239
+ static async makeNewVersion(cloudContainer, fromProps, versionType) {
240
+ const oldName = this.resolveCloudFileName(cloudContainer, fromProps);
241
+ const oldDb = this.parseDbFileName(oldName);
242
+ const newVersion = semver.inc(oldDb.version, versionType);
243
+ if (!newVersion)
244
+ throw new Error("invalid version");
245
+ const newName = this.makeDbFileName(oldDb.dbName, newVersion);
246
+ await cloudContainer.copyDatabase(oldName, newName);
247
+ return { oldName, newName };
248
+ }
249
+ /**
250
+ * Convert a WorkspaceDb.Props specification into a DbFileName. For cloud-based containers, this resolves to the dbName, incorporating the appropriate
251
+ * version. For file-based containers, this returns a local filename of a WorkspaceDb file with the extension ".itwin-workspace"
252
+ */
253
+ resolveDbFileName(props) {
254
+ const cloudContainer = this.cloudContainer;
255
+ if (undefined === cloudContainer)
256
+ return (0, path_1.join)(this.dirName, `${props.dbName}.${ITwinWorkspaceDb.fileExt}`); // local file, versions not allowed
257
+ return ITwinWorkspaceContainer.resolveCloudFileName(cloudContainer, props);
258
+ }
259
+ addWorkspaceDb(toAdd) {
260
+ if (undefined !== this._wsDbs.get(toAdd.dbName))
261
+ throw new Error(`workspaceDb ${toAdd.dbName} already exists in workspace`);
262
+ this._wsDbs.set(toAdd.dbName, toAdd);
263
+ }
264
+ getWorkspaceDb(props) {
265
+ const db = this._wsDbs.get(props.dbName) ?? new ITwinWorkspaceDb(props, this);
266
+ if (!db.isOpen)
267
+ db.open();
268
+ return db;
269
+ }
270
+ dropWorkspaceDb(toDrop) {
271
+ const name = toDrop.dbName;
272
+ const wsDb = this._wsDbs.get(name);
273
+ if (wsDb === toDrop) {
274
+ this._wsDbs.delete(name);
275
+ wsDb.close();
276
+ }
277
+ }
278
+ close() {
279
+ for (const [_name, db] of this._wsDbs)
280
+ db.close();
281
+ this._wsDbs.clear();
282
+ this.cloudContainer?.disconnect();
283
+ }
284
+ /** Delete all local files extracted by [[WorkspaceDb.getFile]] for this container. */
285
+ purgeContainerFiles() {
286
+ IModelJsFs_1.IModelJsFs.purgeDirSync(this.filesDir);
287
+ }
288
+ }
289
+ exports.ITwinWorkspaceContainer = ITwinWorkspaceContainer;
290
+ /**
291
+ * Implementation of WorkspaceDb
292
+ * @internal
293
+ */
294
+ class ITwinWorkspaceDb {
295
+ constructor(props, container) {
296
+ /** the SQLiteDb for this WorkspaceDb*/
297
+ this.sqliteDb = new SQLiteDb_1.SQLiteDb();
298
+ /** called before db is closed */
299
+ this.onClose = new core_bentley_1.BeEvent();
300
+ ITwinWorkspaceContainer.validateDbName(props.dbName);
301
+ this.dbName = props.dbName;
302
+ this.container = container;
303
+ this.dbFileName = container.resolveDbFileName(props);
304
+ container.addWorkspaceDb(this);
305
+ }
306
+ /** true if this WorkspaceDb is currently open */
307
+ get isOpen() { return this.sqliteDb.isOpen; }
308
+ queryFileResource(rscName) {
309
+ const info = this.sqliteDb.nativeDb.queryEmbeddedFile(rscName);
310
+ if (undefined === info)
311
+ return undefined;
312
+ // since resource names can contain illegal characters, path separators, etc., we make the local file name from its hash, in hex.
313
+ let localFileName = (0, path_1.join)(this.container.filesDir, (0, crypto_1.createHash)("sha1").update(this.dbFileName).update(rscName).digest("hex"));
314
+ if (info.fileExt !== "") // since some applications may expect to see the extension, append it here if it was supplied.
315
+ localFileName = `${localFileName}.${info.fileExt}`;
316
+ return { localFileName, info };
317
+ }
318
+ open() {
319
+ this.sqliteDb.openDb(this.dbFileName, core_bentley_1.OpenMode.Readonly, this.container.cloudContainer);
320
+ }
321
+ close() {
322
+ if (this.isOpen) {
323
+ this.onClose.raiseEvent();
324
+ this.sqliteDb.closeDb();
325
+ this.container.dropWorkspaceDb(this);
326
+ }
327
+ }
328
+ getString(rscName) {
329
+ return this.sqliteDb.withSqliteStatement("SELECT value from strings WHERE id=?", (stmt) => {
330
+ stmt.bindString(1, rscName);
331
+ return core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getValueString(0) : undefined;
332
+ });
333
+ }
334
+ /** Get a BlobIO reader for a blob WorkspaceResource.
335
+ * @note when finished, caller *must* call `close` on the BlobIO.
336
+ */
337
+ getBlobReader(rscName) {
338
+ return this.sqliteDb.withSqliteStatement("SELECT rowid from blobs WHERE id=?", (stmt) => {
339
+ stmt.bindString(1, rscName);
340
+ const blobReader = SQLiteDb_1.SQLiteDb.createBlobIO();
341
+ blobReader.open(this.sqliteDb.nativeDb, { tableName: "blobs", columnName: "value", row: stmt.getValueInteger(0) });
342
+ return blobReader;
343
+ });
344
+ }
345
+ getBlob(rscName) {
346
+ return this.sqliteDb.withSqliteStatement("SELECT value from blobs WHERE id=?", (stmt) => {
347
+ stmt.bindString(1, rscName);
348
+ return core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getValueBlob(0) : undefined;
349
+ });
350
+ }
351
+ getFile(rscName, targetFileName) {
352
+ const file = this.queryFileResource(rscName);
353
+ if (!file)
354
+ return undefined;
355
+ const info = file.info;
356
+ const localFileName = targetFileName ?? file.localFileName;
357
+ // check whether the file is already up to date.
358
+ const stat = fs.existsSync(localFileName) && fs.statSync(localFileName);
359
+ if (stat && Math.round(stat.mtimeMs) === info.date && stat.size === info.size)
360
+ return localFileName; // yes, we're done
361
+ // extractEmbeddedFile fails if the file exists or if the directory does not exist
362
+ if (stat)
363
+ fs.removeSync(localFileName);
364
+ else
365
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync((0, path_1.dirname)(localFileName));
366
+ this.sqliteDb.nativeDb.extractEmbeddedFile({ name: rscName, localFileName });
367
+ const date = new Date(info.date);
368
+ fs.utimesSync(localFileName, date, date); // set the last-modified date of the file to match date in container
369
+ fs.chmodSync(localFileName, "0444"); // set file readonly
370
+ return localFileName;
371
+ }
372
+ prefetch(opts) {
373
+ const cloudContainer = this.container.cloudContainer;
374
+ if (cloudContainer === undefined)
375
+ throw new Error("no cloud container to prefetch");
376
+ return CloudSqlite_1.CloudSqlite.startCloudPrefetch(cloudContainer, this.dbFileName, opts);
377
+ }
378
+ }
379
+ exports.ITwinWorkspaceDb = ITwinWorkspaceDb;
380
+ /** file extension for local WorkspaceDbs */
381
+ ITwinWorkspaceDb.fileExt = "itwin-workspace";
382
+ /**
383
+ * An editable [[WorkspaceDb]]. This is used by administrators for creating and modifying `WorkspaceDb`s.
384
+ * For cloud-backed containers, the write token must be obtained before this class may be used. Only one user at at time
385
+ * may be editing.
386
+ * @internal
387
+ */
388
+ class EditableWorkspaceDb extends ITwinWorkspaceDb {
389
+ static validateResourceName(name) {
390
+ ITwinWorkspaceContainer.noLeadingOrTrailingSpaces(name, "resource name");
391
+ if (name.length > 1024)
392
+ throw new Error("resource name too long");
393
+ }
394
+ validateResourceSize(val) {
395
+ const len = typeof val === "string" ? val.length : val.byteLength;
396
+ if (len > (1024 * 1024 * 1024)) // one gigabyte
397
+ throw new Error("value is too large");
398
+ }
399
+ open() {
400
+ this.sqliteDb.openDb(this.dbFileName, core_bentley_1.OpenMode.ReadWrite, this.container.cloudContainer);
401
+ }
402
+ getFileModifiedTime(localFileName) {
403
+ return Math.round(fs.statSync(localFileName).mtimeMs);
404
+ }
405
+ performWriteSql(rscName, sql, bind) {
406
+ this.sqliteDb.withSqliteStatement(sql, (stmt) => {
407
+ stmt.bindString(1, rscName);
408
+ bind?.(stmt);
409
+ const rc = stmt.step();
410
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc) {
411
+ if (core_bentley_1.DbResult.BE_SQLITE_CONSTRAINT_PRIMARYKEY === rc)
412
+ throw new core_common_1.IModelError(rc, `resource "${rscName}" already exists`);
413
+ throw new core_common_1.IModelError(rc, `workspace [${sql}]`);
414
+ }
415
+ });
416
+ this.sqliteDb.saveChanges();
417
+ }
418
+ async createDb(version) {
419
+ if (!this.container.cloudContainer) {
420
+ EditableWorkspaceDb.createEmpty(this.dbFileName);
421
+ }
422
+ else {
423
+ // currently the only way to create a workspaceDb in a cloud container is to create a temporary workspaceDb and upload it.
424
+ const tempDbFile = (0, path_1.join)(IModelHost_1.KnownLocations.tmpdir, `empty.${ITwinWorkspaceDb.fileExt}`);
425
+ if (fs.existsSync(tempDbFile))
426
+ IModelJsFs_1.IModelJsFs.removeSync(tempDbFile);
427
+ EditableWorkspaceDb.createEmpty(tempDbFile);
428
+ this.dbFileName = ITwinWorkspaceContainer.makeDbFileName(this.dbName, version);
429
+ await CloudSqlite_1.CloudSqlite.uploadDb(this.container.cloudContainer, { localFileName: tempDbFile, dbName: this.dbFileName });
430
+ IModelJsFs_1.IModelJsFs.removeSync(tempDbFile);
431
+ }
432
+ this.open();
433
+ }
434
+ /** Create a new, empty, EditableWorkspaceDb for importing Workspace resources. */
435
+ static createEmpty(fileName) {
436
+ const db = new SQLiteDb_1.SQLiteDb();
437
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync((0, path_1.dirname)(fileName));
438
+ db.createDb(fileName);
439
+ const timeStampCol = "lastMod TIMESTAMP NOT NULL DEFAULT(julianday('now'))";
440
+ db.executeSQL(`CREATE TABLE strings(id TEXT PRIMARY KEY NOT NULL,value TEXT,${timeStampCol})`);
441
+ db.executeSQL(`CREATE TABLE blobs(id TEXT PRIMARY KEY NOT NULL,value BLOB,${timeStampCol})`);
442
+ const createTrigger = (tableName) => {
443
+ db.executeSQL(`CREATE TRIGGER ${tableName}_timeStamp AFTER UPDATE ON ${tableName} WHEN old.lastMod=new.lastMod AND old.lastMod != julianday('now') BEGIN UPDATE ${tableName} SET lastMod=julianday('now') WHERE id=new.id; END`);
444
+ };
445
+ createTrigger("strings");
446
+ createTrigger("blobs");
447
+ db.closeDb(true);
448
+ }
449
+ /** Add a new string resource to this WorkspaceDb.
450
+ * @param rscName The name of the string resource.
451
+ * @param val The string to save.
452
+ */
453
+ addString(rscName, val) {
454
+ EditableWorkspaceDb.validateResourceName(rscName);
455
+ this.validateResourceSize(val);
456
+ this.performWriteSql(rscName, "INSERT INTO strings(id,value) VALUES(?,?)", (stmt) => stmt.bindString(2, val));
457
+ }
458
+ /** Update an existing string resource with a new value.
459
+ * @param rscName The name of the string resource.
460
+ * @param val The new value.
461
+ * @throws if rscName does not exist
462
+ */
463
+ updateString(rscName, val) {
464
+ this.validateResourceSize(val);
465
+ this.performWriteSql(rscName, "UPDATE strings SET value=?2 WHERE id=?1", (stmt) => stmt.bindString(2, val));
466
+ }
467
+ /** Remove a string resource. */
468
+ removeString(rscName) {
469
+ this.performWriteSql(rscName, "DELETE FROM strings WHERE id=?");
470
+ }
471
+ /** Add a new blob resource to this WorkspaceDb.
472
+ * @param rscName The name of the blob resource.
473
+ * @param val The blob to save.
474
+ */
475
+ addBlob(rscName, val) {
476
+ EditableWorkspaceDb.validateResourceName(rscName);
477
+ this.validateResourceSize(val);
478
+ this.performWriteSql(rscName, "INSERT INTO blobs(id,value) VALUES(?,?)", (stmt) => stmt.bindBlob(2, val));
479
+ }
480
+ /** Update an existing blob resource with a new value.
481
+ * @param rscName The name of the blob resource.
482
+ * @param val The new value.
483
+ * @throws if rscName does not exist
484
+ */
485
+ updateBlob(rscName, val) {
486
+ this.validateResourceSize(val);
487
+ this.performWriteSql(rscName, "UPDATE blobs SET value=?2 WHERE id=?1", (stmt) => stmt.bindBlob(2, val));
488
+ }
489
+ /** Get a BlobIO writer for a previously-added blob WorkspaceResource.
490
+ * @note after writing is complete, caller must call `close` on the BlobIO and must call `saveChanges` on the `db`.
491
+ */
492
+ getBlobWriter(rscName) {
493
+ return this.sqliteDb.withSqliteStatement("SELECT rowid from blobs WHERE id=?", (stmt) => {
494
+ stmt.bindString(1, rscName);
495
+ const blobWriter = SQLiteDb_1.SQLiteDb.createBlobIO();
496
+ blobWriter.open(this.sqliteDb.nativeDb, { tableName: "blobs", columnName: "value", row: stmt.getValueInteger(0), writeable: true });
497
+ return blobWriter;
498
+ });
499
+ }
500
+ /** Remove a blob resource. */
501
+ removeBlob(rscName) {
502
+ this.performWriteSql(rscName, "DELETE FROM blobs WHERE id=?");
503
+ }
504
+ /** Copy the contents of an existing local file into this WorkspaceDb as a file resource.
505
+ * @param rscName The name of the file resource.
506
+ * @param localFileName The name of a local file to be read.
507
+ * @param fileExt The extension (do not include the leading ".") to be appended to the generated fileName
508
+ * when this WorkspaceDb is extracted from the WorkspaceDb. By default the characters after the last "." in `localFileName`
509
+ * are used. Pass this argument to override that.
510
+ */
511
+ addFile(rscName, localFileName, fileExt) {
512
+ EditableWorkspaceDb.validateResourceName(rscName);
513
+ fileExt = fileExt ?? (0, path_1.extname)(localFileName);
514
+ if (fileExt?.[0] === ".")
515
+ fileExt = fileExt.slice(1);
516
+ this.sqliteDb.nativeDb.embedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName), fileExt });
517
+ }
518
+ /** Replace an existing file resource with the contents of another local file.
519
+ * @param rscName The name of the file resource.
520
+ * @param localFileName The name of a local file to be read.
521
+ * @throws if rscName does not exist
522
+ */
523
+ updateFile(rscName, localFileName) {
524
+ this.queryFileResource(rscName); // throws if not present
525
+ this.sqliteDb.nativeDb.replaceEmbeddedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName) });
526
+ }
527
+ /** Remove a file resource. */
528
+ removeFile(rscName) {
529
+ const file = this.queryFileResource(rscName);
530
+ if (undefined === file)
531
+ throw new Error(`file resource "${rscName}" does not exist`);
532
+ if (file && fs.existsSync(file.localFileName))
533
+ fs.unlinkSync(file.localFileName);
534
+ this.sqliteDb.nativeDb.removeEmbeddedFile(rscName);
535
+ }
536
+ }
537
+ exports.EditableWorkspaceDb = EditableWorkspaceDb;
538
538
  //# sourceMappingURL=Workspace.js.map