@itwin/core-backend 3.4.0-dev.8 → 3.5.0-dev.4

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