@casual-simulation/aux-records 3.4.6-alpha.14668890889 → 3.5.0-alpha.15117651144

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 (211) hide show
  1. package/AIController.js +835 -890
  2. package/AIController.js.map +1 -1
  3. package/AIHumeInterface.js +43 -54
  4. package/AIHumeInterface.js.map +1 -1
  5. package/AIOpenAIRealtimeInterface.js +60 -71
  6. package/AIOpenAIRealtimeInterface.js.map +1 -1
  7. package/AnthropicAIChatInterface.js +96 -142
  8. package/AnthropicAIChatInterface.js.map +1 -1
  9. package/AuthController.d.ts +3 -2
  10. package/AuthController.js +1907 -1933
  11. package/AuthController.js.map +1 -1
  12. package/AuthStore.d.ts +1 -10
  13. package/BlockadeLabsGenerateSkyboxInterface.js +57 -72
  14. package/BlockadeLabsGenerateSkyboxInterface.js.map +1 -1
  15. package/CachingConfigStore.js +30 -45
  16. package/CachingConfigStore.js.map +1 -1
  17. package/CachingPolicyStore.d.ts +8 -2
  18. package/CachingPolicyStore.js +108 -135
  19. package/CachingPolicyStore.js.map +1 -1
  20. package/ComIdConfig.d.ts +18 -18
  21. package/ComIdConfig.js.map +1 -1
  22. package/ConsoleAuthMessenger.js +7 -20
  23. package/ConsoleAuthMessenger.js.map +1 -1
  24. package/DataRecordsController.d.ts +2 -2
  25. package/DataRecordsController.js +369 -377
  26. package/DataRecordsController.js.map +1 -1
  27. package/DataRecordsStore.d.ts +1 -1
  28. package/DataRecordsStore.js +1 -1
  29. package/DataRecordsStore.js.map +1 -1
  30. package/EventRecordsController.js +226 -240
  31. package/EventRecordsController.js.map +1 -1
  32. package/FileRecordsController.d.ts +13 -2
  33. package/FileRecordsController.js +458 -450
  34. package/FileRecordsController.js.map +1 -1
  35. package/GoogleAIChatInterface.js +133 -179
  36. package/GoogleAIChatInterface.js.map +1 -1
  37. package/LivekitController.js +43 -54
  38. package/LivekitController.js.map +1 -1
  39. package/LoomController.js +64 -75
  40. package/LoomController.js.map +1 -1
  41. package/MemoryAuthMessenger.js +10 -23
  42. package/MemoryAuthMessenger.js.map +1 -1
  43. package/MemoryCache.js +18 -35
  44. package/MemoryCache.js.map +1 -1
  45. package/MemoryFileRecordsLookup.js +105 -125
  46. package/MemoryFileRecordsLookup.js.map +1 -1
  47. package/MemoryModerationJobProvider.js +17 -30
  48. package/MemoryModerationJobProvider.js.map +1 -1
  49. package/MemoryRateLimiter.js +12 -27
  50. package/MemoryRateLimiter.js.map +1 -1
  51. package/MemoryStore.d.ts +18 -6
  52. package/MemoryStore.js +1879 -1997
  53. package/MemoryStore.js.map +1 -1
  54. package/MetricsStore.d.ts +2 -2
  55. package/ModerationController.js +186 -200
  56. package/ModerationController.js.map +1 -1
  57. package/OpenAIChatInterface.js +105 -135
  58. package/OpenAIChatInterface.js.map +1 -1
  59. package/OpenAIImageInterface.js +57 -51
  60. package/OpenAIImageInterface.js.map +1 -1
  61. package/PolicyController.d.ts +150 -10
  62. package/PolicyController.js +1546 -1299
  63. package/PolicyController.js.map +1 -1
  64. package/PolicyStore.d.ts +110 -2
  65. package/PolicyStore.js +36 -1
  66. package/PolicyStore.js.map +1 -1
  67. package/PrivoClient.js +398 -435
  68. package/PrivoClient.js.map +1 -1
  69. package/RateLimitController.js +25 -36
  70. package/RateLimitController.js.map +1 -1
  71. package/RecordsClient.js +51 -74
  72. package/RecordsClient.js.map +1 -1
  73. package/RecordsController.d.ts +2 -42
  74. package/RecordsController.js +1026 -1182
  75. package/RecordsController.js.map +1 -1
  76. package/RecordsServer.d.ts +196 -27
  77. package/RecordsServer.js +1701 -1343
  78. package/RecordsServer.js.map +1 -1
  79. package/RecordsStore.d.ts +1 -10
  80. package/RecordsStore.js.map +1 -1
  81. package/ServerConfig.d.ts +339 -195
  82. package/ServerConfig.js +13 -0
  83. package/ServerConfig.js.map +1 -1
  84. package/SloydInterface.js +62 -75
  85. package/SloydInterface.js.map +1 -1
  86. package/StabilityAIImageInterface.js +150 -167
  87. package/StabilityAIImageInterface.js.map +1 -1
  88. package/SubscriptionConfigBuilder.d.ts +6 -1
  89. package/SubscriptionConfigBuilder.js +22 -0
  90. package/SubscriptionConfigBuilder.js.map +1 -1
  91. package/SubscriptionConfiguration.d.ts +266 -169
  92. package/SubscriptionConfiguration.js +101 -79
  93. package/SubscriptionConfiguration.js.map +1 -1
  94. package/SubscriptionController.d.ts +2 -1
  95. package/SubscriptionController.js +643 -650
  96. package/SubscriptionController.js.map +1 -1
  97. package/SystemNotificationMessenger.d.ts +21 -4
  98. package/SystemNotificationMessenger.js +36 -30
  99. package/SystemNotificationMessenger.js.map +1 -1
  100. package/TestUtils.d.ts +9 -1
  101. package/TestUtils.js +105 -129
  102. package/TestUtils.js.map +1 -1
  103. package/Utils.d.ts +2 -16
  104. package/Utils.js +21 -22
  105. package/Utils.js.map +1 -1
  106. package/crud/CrudHelpers.js +17 -26
  107. package/crud/CrudHelpers.js.map +1 -1
  108. package/crud/CrudRecordsController.d.ts +1 -1
  109. package/crud/CrudRecordsController.js +259 -267
  110. package/crud/CrudRecordsController.js.map +1 -1
  111. package/crud/CrudRecordsControllerTests.js +174 -185
  112. package/crud/CrudRecordsControllerTests.js.map +1 -1
  113. package/crud/CrudRecordsStore.d.ts +7 -3
  114. package/crud/MemoryCrudRecordsStore.d.ts +4 -4
  115. package/crud/MemoryCrudRecordsStore.js +98 -118
  116. package/crud/MemoryCrudRecordsStore.js.map +1 -1
  117. package/crud/sub/MemorySubCrudRecordsStore.d.ts +24 -0
  118. package/crud/sub/MemorySubCrudRecordsStore.js +146 -0
  119. package/crud/sub/MemorySubCrudRecordsStore.js.map +1 -0
  120. package/crud/sub/SubCrudRecordsController.d.ts +182 -0
  121. package/crud/sub/SubCrudRecordsController.js +360 -0
  122. package/crud/sub/SubCrudRecordsController.js.map +1 -0
  123. package/crud/sub/SubCrudRecordsControllerTests.d.ts +39 -0
  124. package/crud/sub/SubCrudRecordsControllerTests.js +821 -0
  125. package/crud/sub/SubCrudRecordsControllerTests.js.map +1 -0
  126. package/crud/sub/SubCrudRecordsStore.d.ts +95 -0
  127. package/{forms/index.js → crud/sub/SubCrudRecordsStore.js} +2 -2
  128. package/crud/sub/SubCrudRecordsStore.js.map +1 -0
  129. package/crud/sub/index.d.ts +3 -0
  130. package/crud/sub/index.js +20 -0
  131. package/{forms → crud/sub}/index.js.map +1 -1
  132. package/index.d.ts +1 -1
  133. package/index.js +1 -1
  134. package/index.js.map +1 -1
  135. package/notifications/MemoryNotificationRecordsStore.js +189 -198
  136. package/notifications/MemoryNotificationRecordsStore.js.map +1 -1
  137. package/notifications/NotificationRecordsController.js +438 -460
  138. package/notifications/NotificationRecordsController.js.map +1 -1
  139. package/notifications/NotificationRecordsStore.d.ts +2 -1
  140. package/notifications/WebPushInterface.d.ts +0 -1
  141. package/notifications/WebPushInterface.js +0 -1
  142. package/notifications/WebPushInterface.js.map +1 -1
  143. package/package.json +6 -6
  144. package/packages/MemoryPackageRecordsStore.d.ts +10 -0
  145. package/packages/MemoryPackageRecordsStore.js +38 -0
  146. package/packages/MemoryPackageRecordsStore.js.map +1 -0
  147. package/packages/PackageRecordsController.d.ts +26 -0
  148. package/packages/PackageRecordsController.js +49 -0
  149. package/packages/PackageRecordsController.js.map +1 -0
  150. package/packages/PackageRecordsStore.d.ts +32 -0
  151. package/packages/PackageRecordsStore.js +19 -0
  152. package/packages/PackageRecordsStore.js.map +1 -0
  153. package/packages/index.d.ts +4 -0
  154. package/packages/index.js +21 -0
  155. package/packages/index.js.map +1 -0
  156. package/packages/version/MemoryPackageVersionRecordsStore.d.ts +21 -0
  157. package/packages/version/MemoryPackageVersionRecordsStore.js +177 -0
  158. package/packages/version/MemoryPackageVersionRecordsStore.js.map +1 -0
  159. package/packages/version/PackageVersionRecordsController.d.ts +144 -0
  160. package/packages/version/PackageVersionRecordsController.js +656 -0
  161. package/packages/version/PackageVersionRecordsController.js.map +1 -0
  162. package/packages/version/PackageVersionRecordsStore.d.ts +342 -0
  163. package/packages/version/PackageVersionRecordsStore.js +126 -0
  164. package/packages/version/PackageVersionRecordsStore.js.map +1 -0
  165. package/packages/version/index.d.ts +4 -0
  166. package/packages/version/index.js +21 -0
  167. package/packages/version/index.js.map +1 -0
  168. package/tracing/TracingDecorators.js +31 -40
  169. package/tracing/TracingDecorators.js.map +1 -1
  170. package/webhooks/MemoryWebhookRecordsStore.js +56 -72
  171. package/webhooks/MemoryWebhookRecordsStore.js.map +1 -1
  172. package/webhooks/WebhookEnvironment.d.ts +3 -3
  173. package/webhooks/WebhookRecordsController.d.ts +2 -1
  174. package/webhooks/WebhookRecordsController.js +389 -382
  175. package/webhooks/WebhookRecordsController.js.map +1 -1
  176. package/webhooks/WebhookRecordsStore.d.ts +2 -1
  177. package/websockets/InstRecordsStore.d.ts +50 -0
  178. package/websockets/InstRecordsStore.js +17 -0
  179. package/websockets/InstRecordsStore.js.map +1 -1
  180. package/websockets/MemoryTempInstRecordsStore.d.ts +5 -0
  181. package/websockets/MemoryTempInstRecordsStore.js +168 -179
  182. package/websockets/MemoryTempInstRecordsStore.js.map +1 -1
  183. package/websockets/MemoryWebsocketConnectionStore.js +98 -135
  184. package/websockets/MemoryWebsocketConnectionStore.js.map +1 -1
  185. package/websockets/MemoryWebsocketMessenger.js +29 -48
  186. package/websockets/MemoryWebsocketMessenger.js.map +1 -1
  187. package/websockets/SplitInstRecordsStore.d.ts +4 -1
  188. package/websockets/SplitInstRecordsStore.js +167 -185
  189. package/websockets/SplitInstRecordsStore.js.map +1 -1
  190. package/websockets/TemporaryInstRecordsStore.d.ts +19 -1
  191. package/websockets/TemporaryInstRecordsStore.js +17 -0
  192. package/websockets/TemporaryInstRecordsStore.js.map +1 -1
  193. package/websockets/WebsocketController.d.ts +147 -3
  194. package/websockets/WebsocketController.js +1735 -1391
  195. package/websockets/WebsocketController.js.map +1 -1
  196. package/websockets/index.d.ts +0 -1
  197. package/websockets/index.js +0 -1
  198. package/websockets/index.js.map +1 -1
  199. package/AAGUID.d.ts +0 -11
  200. package/AAGUID.js +0 -116
  201. package/AAGUID.js.map +0 -1
  202. package/AuthUtils.d.ts +0 -162
  203. package/AuthUtils.js +0 -327
  204. package/AuthUtils.js.map +0 -1
  205. package/forms/FormError.d.ts +0 -43
  206. package/forms/FormError.js +0 -56
  207. package/forms/FormError.js.map +0 -1
  208. package/forms/index.d.ts +0 -2
  209. package/websockets/Utils.d.ts +0 -33
  210. package/websockets/Utils.js +0 -82
  211. package/websockets/Utils.js.map +0 -1
package/MemoryStore.js CHANGED
@@ -1,23 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- var __rest = (this && this.__rest) || function (s, e) {
11
- var t = {};
12
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
- t[p] = s[p];
14
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
- t[p[i]] = s[p[i]];
18
- }
19
- return t;
20
- };
21
1
  /* CasualOS is a set of web-based tools designed to facilitate the creation of real-time, multi-user, context-aware interactive experiences.
22
2
  *
23
3
  * Copyright (c) 2019-2025 Casual Simulation, Inc.
@@ -115,6 +95,9 @@ export class MemoryStore {
115
95
  get comIdRequests() {
116
96
  return this._comIdRequests;
117
97
  }
98
+ get grantedPackageEntitlements() {
99
+ return this._grantedPackageEntitlements;
100
+ }
118
101
  constructor(config) {
119
102
  var _a, _b;
120
103
  this._users = [];
@@ -149,8 +132,10 @@ export class MemoryStore {
149
132
  this._comIdRequests = [];
150
133
  this._resourcePermissionAssignments = [];
151
134
  this._markerPermissionAssignments = [];
135
+ this._grantedPackageEntitlements = [];
152
136
  this._studioLoomConfigs = new Map();
153
137
  this._studioHumeConfigs = new Map();
138
+ this._loadedPackages = new Map();
154
139
  // TODO: Support global permissions
155
140
  // private _globalPermissionAssignments: GlobalPermissionAssignment[] = [];
156
141
  this.maxAllowedInstSize = Infinity;
@@ -207,407 +192,331 @@ export class MemoryStore {
207
192
  newStore.roleAssignments = cloneDeep(this.roleAssignments);
208
193
  return newStore;
209
194
  }
210
- listUserAuthenticators(userId) {
211
- return __awaiter(this, void 0, void 0, function* () {
212
- return this._userAuthenticators.filter((a) => a.userId === userId);
213
- });
214
- }
215
- saveUserAuthenticator(authenticator) {
216
- return __awaiter(this, void 0, void 0, function* () {
217
- const index = this._userAuthenticators.findIndex((a) => a.id === authenticator.id);
218
- if (index >= 0) {
219
- this._userAuthenticators[index] = authenticator;
220
- }
221
- else {
222
- this._userAuthenticators.push(authenticator);
223
- }
224
- });
225
- }
226
- saveComIdRequest(request) {
227
- return __awaiter(this, void 0, void 0, function* () {
228
- this._comIdRequests.push(request);
229
- });
230
- }
231
- getStudioByComId(comId) {
232
- return __awaiter(this, void 0, void 0, function* () {
233
- return this._studios.find((s) => s.comId === comId);
234
- });
195
+ async listUserAuthenticators(userId) {
196
+ return this._userAuthenticators.filter((a) => a.userId === userId);
235
197
  }
236
- listStudiosForUserAndComId(userId, comId) {
237
- return __awaiter(this, void 0, void 0, function* () {
238
- const assignments = yield this.listUserAssignments(userId);
239
- const studios = yield Promise.all(assignments.map((a) => __awaiter(this, void 0, void 0, function* () {
240
- const s = yield this.getStudioById(a.studioId);
241
- return Object.assign(Object.assign({}, s), a);
242
- })));
243
- return studios
244
- .filter((s) => s.ownerStudioComId === comId)
245
- .map((s) => ({
246
- studioId: s.id,
247
- displayName: s.displayName,
248
- role: s.role,
249
- isPrimaryContact: s.isPrimaryContact,
250
- subscriptionId: s.subscriptionId,
251
- subscriptionStatus: s.subscriptionStatus,
252
- comId: s.comId,
253
- logoUrl: s.logoUrl,
254
- ownerStudioComId: s.ownerStudioComId,
255
- }));
256
- });
198
+ async saveUserAuthenticator(authenticator) {
199
+ const index = this._userAuthenticators.findIndex((a) => a.id === authenticator.id);
200
+ if (index >= 0) {
201
+ this._userAuthenticators[index] = authenticator;
202
+ }
203
+ else {
204
+ this._userAuthenticators.push(authenticator);
205
+ }
257
206
  }
258
- sendRecordNotification(notification) {
259
- return __awaiter(this, void 0, void 0, function* () {
260
- this._recordNotifications.push(notification);
261
- });
207
+ async saveComIdRequest(request) {
208
+ this._comIdRequests.push(request);
262
209
  }
263
- saveUserInstReport(report) {
264
- return __awaiter(this, void 0, void 0, function* () {
265
- const existingReportIndex = this._userInstReports.findIndex((r) => r.id === report.id);
266
- if (existingReportIndex >= 0) {
267
- this._userInstReports[existingReportIndex] = report;
268
- }
269
- else {
270
- this._userInstReports.push(report);
271
- }
272
- });
210
+ async getStudioByComId(comId) {
211
+ return this._studios.find((s) => s.comId === comId);
273
212
  }
274
- addModerationJob(job) {
275
- return __awaiter(this, void 0, void 0, function* () {
276
- this._moderationJobs.push(job);
277
- });
213
+ async listStudiosForUserAndComId(userId, comId) {
214
+ const assignments = await this.listUserAssignments(userId);
215
+ const studios = await Promise.all(assignments.map(async (a) => {
216
+ const s = await this.getStudioById(a.studioId);
217
+ return {
218
+ ...s,
219
+ ...a,
220
+ };
221
+ }));
222
+ return studios
223
+ .filter((s) => s.ownerStudioComId === comId)
224
+ .map((s) => ({
225
+ studioId: s.id,
226
+ displayName: s.displayName,
227
+ role: s.role,
228
+ isPrimaryContact: s.isPrimaryContact,
229
+ subscriptionId: s.subscriptionId,
230
+ subscriptionStatus: s.subscriptionStatus,
231
+ comId: s.comId,
232
+ logoUrl: s.logoUrl,
233
+ ownerStudioComId: s.ownerStudioComId,
234
+ }));
235
+ }
236
+ async sendRecordNotification(notification) {
237
+ this._recordNotifications.push(notification);
238
+ }
239
+ async saveUserInstReport(report) {
240
+ const existingReportIndex = this._userInstReports.findIndex((r) => r.id === report.id);
241
+ if (existingReportIndex >= 0) {
242
+ this._userInstReports[existingReportIndex] = report;
243
+ }
244
+ else {
245
+ this._userInstReports.push(report);
246
+ }
278
247
  }
279
- findMostRecentJobOfType(type) {
280
- return __awaiter(this, void 0, void 0, function* () {
281
- const jobs = this._moderationJobs.filter((j) => j.type === type);
282
- const mostRecent = orderBy(jobs, (j) => j.createdAtMs, 'desc');
283
- if (mostRecent.length > 0) {
284
- return mostRecent[0];
285
- }
286
- else {
287
- return null;
288
- }
289
- });
248
+ async addModerationJob(job) {
249
+ this._moderationJobs.push(job);
290
250
  }
291
- addFileModerationResult(result) {
292
- return __awaiter(this, void 0, void 0, function* () {
293
- this._moderationFileResults.push(result);
294
- });
251
+ async findMostRecentJobOfType(type) {
252
+ const jobs = this._moderationJobs.filter((j) => j.type === type);
253
+ const mostRecent = orderBy(jobs, (j) => j.createdAtMs, 'desc');
254
+ if (mostRecent.length > 0) {
255
+ return mostRecent[0];
256
+ }
257
+ else {
258
+ return null;
259
+ }
295
260
  }
296
- getSubscriptionConfiguration() {
297
- return __awaiter(this, void 0, void 0, function* () {
298
- return this._subscriptionConfiguration;
299
- });
261
+ async addFileModerationResult(result) {
262
+ this._moderationFileResults.push(result);
300
263
  }
301
- getPrivoConfiguration() {
302
- return __awaiter(this, void 0, void 0, function* () {
303
- return this._privoConfiguration;
304
- });
264
+ async getSubscriptionConfiguration() {
265
+ return this._subscriptionConfiguration;
305
266
  }
306
- getModerationConfig() {
307
- return __awaiter(this, void 0, void 0, function* () {
308
- return this._moderationConfiguration;
309
- });
267
+ async getPrivoConfiguration() {
268
+ return this._privoConfiguration;
310
269
  }
311
- getRecordByName(name) {
312
- return __awaiter(this, void 0, void 0, function* () {
313
- const record = this._records.find((r) => r.name === name);
314
- return record;
315
- });
270
+ async getModerationConfig() {
271
+ return this._moderationConfiguration;
316
272
  }
317
- updateRecord(record) {
318
- return __awaiter(this, void 0, void 0, function* () {
319
- const existingRecordIndex = this._records.findIndex((r) => r.name === record.name);
320
- if (existingRecordIndex >= 0) {
321
- this._records[existingRecordIndex] = record;
322
- }
323
- });
273
+ async getRecordByName(name) {
274
+ const record = this._records.find((r) => r.name === name);
275
+ return record;
324
276
  }
325
- addRecord(record) {
326
- return __awaiter(this, void 0, void 0, function* () {
327
- const existingRecordIndex = this._records.findIndex((r) => r.name === record.name);
328
- if (existingRecordIndex < 0) {
329
- this._records.push(record);
330
- }
331
- });
277
+ async updateRecord(record) {
278
+ const existingRecordIndex = this._records.findIndex((r) => r.name === record.name);
279
+ if (existingRecordIndex >= 0) {
280
+ this._records[existingRecordIndex] = record;
281
+ }
332
282
  }
333
- addRecordKey(key) {
334
- return __awaiter(this, void 0, void 0, function* () {
335
- const existingKeyIndex = this._recordKeys.findIndex((k) => k.recordName === key.recordName &&
336
- k.secretHash === key.secretHash);
337
- if (existingKeyIndex < 0) {
338
- this._recordKeys.push(key);
339
- }
340
- });
283
+ async addRecord(record) {
284
+ const existingRecordIndex = this._records.findIndex((r) => r.name === record.name);
285
+ if (existingRecordIndex < 0) {
286
+ this._records.push(record);
287
+ }
341
288
  }
342
- getRecordKeyByRecordAndHash(recordName, hash) {
343
- return __awaiter(this, void 0, void 0, function* () {
344
- const key = this._recordKeys.find((k) => k.recordName === recordName && k.secretHash == hash);
345
- return key;
346
- });
289
+ async addRecordKey(key) {
290
+ const existingKeyIndex = this._recordKeys.findIndex((k) => k.recordName === key.recordName &&
291
+ k.secretHash === key.secretHash);
292
+ if (existingKeyIndex < 0) {
293
+ this._recordKeys.push(key);
294
+ }
347
295
  }
348
- listRecordsByOwnerId(ownerId) {
349
- return __awaiter(this, void 0, void 0, function* () {
350
- return sortBy(this._records
351
- .filter((r) => r.ownerId === ownerId)
352
- .map((r) => ({
353
- name: r.name,
354
- ownerId: r.ownerId,
355
- studioId: r.studioId,
356
- })), (r) => r.name);
357
- });
296
+ async getRecordKeyByRecordAndHash(recordName, hash) {
297
+ const key = this._recordKeys.find((k) => k.recordName === recordName && k.secretHash == hash);
298
+ return key;
299
+ }
300
+ async listRecordsByOwnerId(ownerId) {
301
+ return sortBy(this._records
302
+ .filter((r) => r.ownerId === ownerId)
303
+ .map((r) => ({
304
+ name: r.name,
305
+ ownerId: r.ownerId,
306
+ studioId: r.studioId,
307
+ })), (r) => r.name);
308
+ }
309
+ async listRecordsByStudioId(studioId) {
310
+ return sortBy(this._records
311
+ .filter((r) => r.studioId === studioId)
312
+ .map((r) => ({
313
+ name: r.name,
314
+ ownerId: r.ownerId,
315
+ studioId: r.studioId,
316
+ })), (r) => r.name);
317
+ }
318
+ async listRecordsByStudioIdAndUserId(studioId, userId) {
319
+ return sortBy(this._records
320
+ .filter((s) => {
321
+ if (s.studioId !== studioId) {
322
+ return false;
323
+ }
324
+ const isAssigned = this._studioAssignments.some((a) => a.studioId === studioId && a.userId === userId);
325
+ return isAssigned;
326
+ })
327
+ .map((r) => ({
328
+ name: r.name,
329
+ ownerId: r.ownerId,
330
+ studioId: r.studioId,
331
+ })), (r) => r.name);
332
+ }
333
+ async addStudio(studio) {
334
+ const existingStudioIndex = this._studios.findIndex((r) => r.id === studio.id);
335
+ if (existingStudioIndex < 0) {
336
+ this._studios.push(studio);
337
+ }
358
338
  }
359
- listRecordsByStudioId(studioId) {
360
- return __awaiter(this, void 0, void 0, function* () {
361
- return sortBy(this._records
362
- .filter((r) => r.studioId === studioId)
363
- .map((r) => ({
364
- name: r.name,
365
- ownerId: r.ownerId,
366
- studioId: r.studioId,
367
- })), (r) => r.name);
368
- });
339
+ async createStudioForUser(studio, adminId) {
340
+ await this.addStudio(studio);
341
+ const assignment = {
342
+ studioId: studio.id,
343
+ userId: adminId,
344
+ isPrimaryContact: true,
345
+ role: 'admin',
346
+ };
347
+ await this.addStudioAssignment(assignment);
348
+ return {
349
+ studio,
350
+ assignment,
351
+ };
352
+ }
353
+ async updateStudio(studio) {
354
+ const existingStudioIndex = this._studios.findIndex((r) => r.id === studio.id);
355
+ if (existingStudioIndex >= 0) {
356
+ this._studios[existingStudioIndex] = studio;
357
+ }
369
358
  }
370
- listRecordsByStudioIdAndUserId(studioId, userId) {
371
- return __awaiter(this, void 0, void 0, function* () {
372
- return sortBy(this._records
373
- .filter((s) => {
374
- if (s.studioId !== studioId) {
375
- return false;
376
- }
377
- const isAssigned = this._studioAssignments.some((a) => a.studioId === studioId && a.userId === userId);
378
- return isAssigned;
379
- })
380
- .map((r) => ({
381
- name: r.name,
382
- ownerId: r.ownerId,
383
- studioId: r.studioId,
384
- })), (r) => r.name);
385
- });
359
+ async getStudioById(id) {
360
+ return this._studios.find((s) => s.id === id);
386
361
  }
387
- addStudio(studio) {
388
- return __awaiter(this, void 0, void 0, function* () {
389
- const existingStudioIndex = this._studios.findIndex((r) => r.id === studio.id);
390
- if (existingStudioIndex < 0) {
391
- this._studios.push(studio);
392
- }
393
- });
362
+ async getStudioByStripeCustomerId(customerId) {
363
+ return this._studios.find((s) => s.stripeCustomerId === customerId);
394
364
  }
395
- createStudioForUser(studio, adminId) {
396
- return __awaiter(this, void 0, void 0, function* () {
397
- yield this.addStudio(studio);
398
- const assignment = {
399
- studioId: studio.id,
400
- userId: adminId,
401
- isPrimaryContact: true,
402
- role: 'admin',
403
- };
404
- yield this.addStudioAssignment(assignment);
365
+ async listStudiosForUser(userId) {
366
+ const assignments = await this.listUserAssignments(userId);
367
+ const studios = await Promise.all(assignments.map(async (a) => {
368
+ const s = await this.getStudioById(a.studioId);
405
369
  return {
406
- studio,
407
- assignment,
370
+ ...s,
371
+ ...a,
408
372
  };
409
- });
410
- }
411
- updateStudio(studio) {
412
- return __awaiter(this, void 0, void 0, function* () {
413
- const existingStudioIndex = this._studios.findIndex((r) => r.id === studio.id);
414
- if (existingStudioIndex >= 0) {
415
- this._studios[existingStudioIndex] = studio;
416
- }
417
- });
373
+ }));
374
+ return studios
375
+ .filter((s) => !s.ownerStudioComId)
376
+ .map((s) => ({
377
+ studioId: s.id,
378
+ displayName: s.displayName,
379
+ role: s.role,
380
+ isPrimaryContact: s.isPrimaryContact,
381
+ subscriptionId: s.subscriptionId,
382
+ subscriptionStatus: s.subscriptionStatus,
383
+ comId: s.comId,
384
+ logoUrl: s.logoUrl,
385
+ ownerStudioComId: s.ownerStudioComId,
386
+ }));
387
+ }
388
+ async countStudiosInComId(comId) {
389
+ const studios = this._studios.filter((s) => s.ownerStudioComId === comId);
390
+ return studios.length;
391
+ }
392
+ async addStudioAssignment(assignment) {
393
+ const existingAssignmentIndex = this._studioAssignments.findIndex((r) => r.studioId === assignment.studioId &&
394
+ r.userId === assignment.userId);
395
+ if (existingAssignmentIndex < 0) {
396
+ this._studioAssignments.push(assignment);
397
+ }
418
398
  }
419
- getStudioById(id) {
420
- return __awaiter(this, void 0, void 0, function* () {
421
- return this._studios.find((s) => s.id === id);
422
- });
399
+ async removeStudioAssignment(studioId, userId) {
400
+ this._studioAssignments = this._studioAssignments.filter((s) => s.studioId !== studioId || s.userId !== userId);
423
401
  }
424
- getStudioByStripeCustomerId(customerId) {
425
- return __awaiter(this, void 0, void 0, function* () {
426
- return this._studios.find((s) => s.stripeCustomerId === customerId);
427
- });
402
+ async updateStudioAssignment(assignment) {
403
+ const existingAssignmentIndex = this._studioAssignments.findIndex((r) => r.studioId === assignment.studioId &&
404
+ r.userId === assignment.userId);
405
+ if (existingAssignmentIndex >= 0) {
406
+ this._studioAssignments[existingAssignmentIndex] = assignment;
407
+ }
428
408
  }
429
- listStudiosForUser(userId) {
430
- return __awaiter(this, void 0, void 0, function* () {
431
- const assignments = yield this.listUserAssignments(userId);
432
- const studios = yield Promise.all(assignments.map((a) => __awaiter(this, void 0, void 0, function* () {
433
- const s = yield this.getStudioById(a.studioId);
434
- return Object.assign(Object.assign({}, s), a);
435
- })));
436
- return studios
437
- .filter((s) => !s.ownerStudioComId)
438
- .map((s) => ({
439
- studioId: s.id,
440
- displayName: s.displayName,
441
- role: s.role,
409
+ async listStudioAssignments(studioId, filters) {
410
+ const assignments = this._studioAssignments.filter((s) => {
411
+ const matchesRole = !(filters === null || filters === void 0 ? void 0 : filters.role) || s.role === filters.role;
412
+ const matchesPrimaryContact = !(filters === null || filters === void 0 ? void 0 : filters.isPrimaryContact) ||
413
+ s.isPrimaryContact === filters.isPrimaryContact;
414
+ const matchesUserId = !(filters === null || filters === void 0 ? void 0 : filters.userId) || s.userId === filters.userId;
415
+ return (s.studioId === studioId &&
416
+ matchesRole &&
417
+ matchesPrimaryContact &&
418
+ matchesUserId);
419
+ });
420
+ let results = [];
421
+ for (let s of assignments) {
422
+ const user = await this.findUser(s.userId);
423
+ if (!user) {
424
+ continue;
425
+ }
426
+ results.push({
427
+ studioId: s.studioId,
428
+ userId: s.userId,
442
429
  isPrimaryContact: s.isPrimaryContact,
443
- subscriptionId: s.subscriptionId,
444
- subscriptionStatus: s.subscriptionStatus,
445
- comId: s.comId,
446
- logoUrl: s.logoUrl,
447
- ownerStudioComId: s.ownerStudioComId,
448
- }));
449
- });
450
- }
451
- countStudiosInComId(comId) {
452
- return __awaiter(this, void 0, void 0, function* () {
453
- const studios = this._studios.filter((s) => s.ownerStudioComId === comId);
454
- return studios.length;
455
- });
456
- }
457
- addStudioAssignment(assignment) {
458
- return __awaiter(this, void 0, void 0, function* () {
459
- const existingAssignmentIndex = this._studioAssignments.findIndex((r) => r.studioId === assignment.studioId &&
460
- r.userId === assignment.userId);
461
- if (existingAssignmentIndex < 0) {
462
- this._studioAssignments.push(assignment);
463
- }
464
- });
465
- }
466
- removeStudioAssignment(studioId, userId) {
467
- return __awaiter(this, void 0, void 0, function* () {
468
- this._studioAssignments = this._studioAssignments.filter((s) => s.studioId !== studioId || s.userId !== userId);
469
- });
470
- }
471
- updateStudioAssignment(assignment) {
472
- return __awaiter(this, void 0, void 0, function* () {
473
- const existingAssignmentIndex = this._studioAssignments.findIndex((r) => r.studioId === assignment.studioId &&
474
- r.userId === assignment.userId);
475
- if (existingAssignmentIndex >= 0) {
476
- this._studioAssignments[existingAssignmentIndex] = assignment;
477
- }
478
- });
479
- }
480
- listStudioAssignments(studioId, filters) {
481
- return __awaiter(this, void 0, void 0, function* () {
482
- const assignments = this._studioAssignments.filter((s) => {
483
- const matchesRole = !(filters === null || filters === void 0 ? void 0 : filters.role) || s.role === filters.role;
484
- const matchesPrimaryContact = !(filters === null || filters === void 0 ? void 0 : filters.isPrimaryContact) ||
485
- s.isPrimaryContact === filters.isPrimaryContact;
486
- const matchesUserId = !(filters === null || filters === void 0 ? void 0 : filters.userId) || s.userId === filters.userId;
487
- return (s.studioId === studioId &&
488
- matchesRole &&
489
- matchesPrimaryContact &&
490
- matchesUserId);
430
+ role: s.role,
431
+ user: {
432
+ id: user.id,
433
+ name: user.name,
434
+ email: user.email,
435
+ phoneNumber: user.phoneNumber,
436
+ privoServiceId: user.privoServiceId,
437
+ },
491
438
  });
492
- let results = [];
493
- for (let s of assignments) {
494
- const user = yield this.findUser(s.userId);
495
- if (!user) {
496
- continue;
497
- }
498
- results.push({
499
- studioId: s.studioId,
500
- userId: s.userId,
501
- isPrimaryContact: s.isPrimaryContact,
502
- role: s.role,
503
- user: {
504
- id: user.id,
505
- name: user.name,
506
- email: user.email,
507
- phoneNumber: user.phoneNumber,
508
- privoServiceId: user.privoServiceId,
509
- },
510
- });
511
- }
512
- return results;
513
- });
439
+ }
440
+ return results;
514
441
  }
515
- listUserAssignments(userId) {
516
- return __awaiter(this, void 0, void 0, function* () {
517
- const assignments = this._studioAssignments.filter((s) => s.userId === userId);
518
- return assignments.map((s) => {
519
- const studio = this._studios.find((studio) => studio.id === s.studioId);
520
- return {
521
- displayName: studio.displayName,
522
- studioId: s.studioId,
523
- userId: s.userId,
524
- isPrimaryContact: s.isPrimaryContact,
525
- role: s.role,
526
- };
527
- });
442
+ async listUserAssignments(userId) {
443
+ const assignments = this._studioAssignments.filter((s) => s.userId === userId);
444
+ return assignments.map((s) => {
445
+ const studio = this._studios.find((studio) => studio.id === s.studioId);
446
+ return {
447
+ displayName: studio.displayName,
448
+ studioId: s.studioId,
449
+ userId: s.userId,
450
+ isPrimaryContact: s.isPrimaryContact,
451
+ role: s.role,
452
+ };
528
453
  });
529
454
  }
530
- getStudioLoomConfig(studioId) {
455
+ async getStudioLoomConfig(studioId) {
531
456
  var _a;
532
- return __awaiter(this, void 0, void 0, function* () {
533
- return (_a = this._studioLoomConfigs.get(studioId)) !== null && _a !== void 0 ? _a : null;
534
- });
457
+ return (_a = this._studioLoomConfigs.get(studioId)) !== null && _a !== void 0 ? _a : null;
535
458
  }
536
- updateStudioLoomConfig(studioId, config) {
537
- return __awaiter(this, void 0, void 0, function* () {
538
- this._studioLoomConfigs.set(studioId, config);
539
- });
459
+ async updateStudioLoomConfig(studioId, config) {
460
+ this._studioLoomConfigs.set(studioId, config);
540
461
  }
541
- getStudioHumeConfig(studioId) {
462
+ async getStudioHumeConfig(studioId) {
542
463
  var _a;
543
- return __awaiter(this, void 0, void 0, function* () {
544
- return (_a = this._studioHumeConfigs.get(studioId)) !== null && _a !== void 0 ? _a : null;
545
- });
546
- }
547
- updateStudioHumeConfig(studioId, config) {
548
- return __awaiter(this, void 0, void 0, function* () {
549
- this._studioHumeConfigs.set(studioId, config);
550
- });
551
- }
552
- getUserPrivacyFeatures(userId) {
553
- return __awaiter(this, void 0, void 0, function* () {
554
- return yield this._getUserPrivacyFeatures(userId);
555
- });
464
+ return (_a = this._studioHumeConfigs.get(studioId)) !== null && _a !== void 0 ? _a : null;
556
465
  }
557
- getRecordOwnerPrivacyFeatures(recordName) {
558
- return __awaiter(this, void 0, void 0, function* () {
559
- const record = yield this.getRecordByName(recordName);
560
- if (!record || !record.ownerId) {
561
- return null;
562
- }
563
- return yield this._getUserPrivacyFeatures(record.ownerId);
564
- });
466
+ async updateStudioHumeConfig(studioId, config) {
467
+ this._studioHumeConfigs.set(studioId, config);
565
468
  }
566
- getPermissionForSubjectAndResource(subjectType, subjectId, recordName, resourceKind, resourceId, action, currentTimeMs) {
567
- return __awaiter(this, void 0, void 0, function* () {
568
- const existingRoles = subjectType === 'user'
569
- ? yield this.listRolesForUser(recordName, subjectId)
570
- : subjectType === 'inst'
571
- ? yield this.listRolesForInst(recordName, subjectId)
572
- : [];
573
- const roles = existingRoles.map((r) => r.role);
574
- const assignment = this._resourcePermissionAssignments.find((p) => p.recordName === recordName &&
575
- ((p.subjectType === 'role' &&
576
- roles.indexOf(p.subjectId) >= 0) ||
577
- (p.subjectType === subjectType &&
578
- p.subjectId === subjectId)) &&
579
- p.resourceKind === resourceKind &&
580
- p.resourceId === resourceId &&
581
- (p.action === null || p.action === action) &&
582
- (!p.expireTimeMs || p.expireTimeMs > currentTimeMs));
583
- return {
584
- success: true,
585
- permissionAssignment: assignment,
586
- };
587
- });
469
+ async getUserPrivacyFeatures(userId) {
470
+ return await this._getUserPrivacyFeatures(userId);
588
471
  }
589
- getPermissionForSubjectAndMarkers(subjectType, subjectId, recordName, resourceKind, markers, action, currentTimeMs) {
590
- return __awaiter(this, void 0, void 0, function* () {
591
- const existingRoles = subjectType === 'user'
592
- ? yield this.listRolesForUser(recordName, subjectId)
593
- : subjectType === 'inst'
594
- ? yield this.listRolesForInst(recordName, subjectId)
595
- : [];
596
- const roles = existingRoles.map((r) => r.role);
597
- const assignment = this._markerPermissionAssignments.find((p) => p.recordName === recordName &&
598
- markers.indexOf(p.marker) >= 0 &&
599
- ((p.subjectType === 'role' &&
600
- roles.indexOf(p.subjectId) >= 0) ||
601
- (p.subjectType === subjectType &&
602
- p.subjectId === subjectId)) &&
603
- p.resourceKind === resourceKind &&
604
- (p.action === null || p.action === action) &&
605
- (!p.expireTimeMs || p.expireTimeMs > currentTimeMs));
606
- return {
607
- success: true,
608
- permissionAssignment: assignment,
609
- };
610
- });
472
+ async getRecordOwnerPrivacyFeatures(recordName) {
473
+ const record = await this.getRecordByName(recordName);
474
+ if (!record || !record.ownerId) {
475
+ return null;
476
+ }
477
+ return await this._getUserPrivacyFeatures(record.ownerId);
478
+ }
479
+ async getPermissionForSubjectAndResource(subjectType, subjectId, recordName, resourceKind, resourceId, action, currentTimeMs) {
480
+ const existingRoles = subjectType === 'user'
481
+ ? await this.listRolesForUser(recordName, subjectId)
482
+ : subjectType === 'inst'
483
+ ? await this.listRolesForInst(recordName, subjectId)
484
+ : [];
485
+ const roles = existingRoles.map((r) => r.role);
486
+ const assignment = this._resourcePermissionAssignments.find((p) => p.recordName === recordName &&
487
+ ((p.subjectType === 'role' &&
488
+ roles.indexOf(p.subjectId) >= 0) ||
489
+ (p.subjectType === subjectType &&
490
+ p.subjectId === subjectId)) &&
491
+ p.resourceKind === resourceKind &&
492
+ p.resourceId === resourceId &&
493
+ (p.action === null || p.action === action) &&
494
+ (!p.expireTimeMs || p.expireTimeMs > currentTimeMs));
495
+ return {
496
+ success: true,
497
+ permissionAssignment: assignment,
498
+ };
499
+ }
500
+ async getPermissionForSubjectAndMarkers(subjectType, subjectId, recordName, resourceKind, markers, action, currentTimeMs) {
501
+ const existingRoles = subjectType === 'user'
502
+ ? await this.listRolesForUser(recordName, subjectId)
503
+ : subjectType === 'inst'
504
+ ? await this.listRolesForInst(recordName, subjectId)
505
+ : [];
506
+ const roles = existingRoles.map((r) => r.role);
507
+ const assignment = this._markerPermissionAssignments.find((p) => p.recordName === recordName &&
508
+ markers.indexOf(p.marker) >= 0 &&
509
+ ((p.subjectType === 'role' &&
510
+ roles.indexOf(p.subjectId) >= 0) ||
511
+ (p.subjectType === subjectType &&
512
+ p.subjectId === subjectId)) &&
513
+ p.resourceKind === resourceKind &&
514
+ (p.action === null || p.action === action) &&
515
+ (!p.expireTimeMs || p.expireTimeMs > currentTimeMs));
516
+ return {
517
+ success: true,
518
+ permissionAssignment: assignment,
519
+ };
611
520
  }
612
521
  // TODO: Support global permissions
613
522
  // async assignGlobalPermissionToSubject(
@@ -635,706 +544,738 @@ export class MemoryStore {
635
544
  // permissionAssignment: assignment,
636
545
  // };
637
546
  // }
638
- assignPermissionToSubjectAndResource(recordName, subjectType, subjectId, resourceKind, resourceId, action, options, expireTimeMs) {
639
- return __awaiter(this, void 0, void 0, function* () {
640
- const assignmentIndex = this._resourcePermissionAssignments.findIndex((a) => a.recordName === recordName &&
641
- a.subjectType === subjectType &&
642
- a.subjectId === subjectId &&
643
- a.resourceKind === resourceKind &&
644
- a.resourceId === resourceId &&
645
- a.action === action);
646
- if (assignmentIndex >= 0) {
647
- const assignment = this._resourcePermissionAssignments[assignmentIndex];
648
- this._resourcePermissionAssignments[assignmentIndex] = Object.assign(Object.assign({}, assignment), { options,
649
- expireTimeMs });
650
- return {
651
- success: true,
652
- permissionAssignment: assignment,
653
- };
654
- }
655
- const userId = getSubjectUserId(subjectType, subjectId);
656
- const assignment = {
657
- id: uuid(),
658
- recordName,
659
- userId,
660
- subjectType,
661
- subjectId,
662
- resourceKind,
663
- resourceId,
664
- action,
547
+ async assignPermissionToSubjectAndResource(recordName, subjectType, subjectId, resourceKind, resourceId, action, options, expireTimeMs) {
548
+ const assignmentIndex = this._resourcePermissionAssignments.findIndex((a) => a.recordName === recordName &&
549
+ a.subjectType === subjectType &&
550
+ a.subjectId === subjectId &&
551
+ a.resourceKind === resourceKind &&
552
+ a.resourceId === resourceId &&
553
+ a.action === action);
554
+ if (assignmentIndex >= 0) {
555
+ const assignment = this._resourcePermissionAssignments[assignmentIndex];
556
+ this._resourcePermissionAssignments[assignmentIndex] = {
557
+ ...assignment,
665
558
  options,
666
559
  expireTimeMs,
667
560
  };
668
- this._resourcePermissionAssignments.push(assignment);
669
561
  return {
670
562
  success: true,
671
563
  permissionAssignment: assignment,
672
564
  };
673
- });
674
- }
675
- assignPermissionToSubjectAndMarker(recordName, subjectType, subjectId, resourceKind, marker, action, options, expireTimeMs) {
676
- return __awaiter(this, void 0, void 0, function* () {
677
- const assignmentIndex = this._markerPermissionAssignments.findIndex((a) => a.recordName === recordName &&
678
- a.subjectType === subjectType &&
679
- a.subjectId === subjectId &&
680
- a.marker === marker &&
681
- a.resourceKind === resourceKind &&
682
- a.action === action);
683
- if (assignmentIndex >= 0) {
684
- const assignment = this._markerPermissionAssignments[assignmentIndex];
685
- this._markerPermissionAssignments[assignmentIndex] = Object.assign(Object.assign({}, assignment), { options,
686
- expireTimeMs });
687
- return {
688
- success: true,
689
- permissionAssignment: assignment,
690
- };
691
- }
692
- const userId = getSubjectUserId(subjectType, subjectId);
693
- const assignment = {
694
- id: uuid(),
695
- recordName,
696
- userId,
697
- subjectType,
698
- subjectId,
699
- resourceKind,
700
- marker,
701
- action,
565
+ }
566
+ const userId = getSubjectUserId(subjectType, subjectId);
567
+ const assignment = {
568
+ id: uuid(),
569
+ recordName,
570
+ userId,
571
+ subjectType,
572
+ subjectId,
573
+ resourceKind,
574
+ resourceId,
575
+ action,
576
+ options,
577
+ expireTimeMs,
578
+ };
579
+ this._resourcePermissionAssignments.push(assignment);
580
+ return {
581
+ success: true,
582
+ permissionAssignment: assignment,
583
+ };
584
+ }
585
+ async assignPermissionToSubjectAndMarker(recordName, subjectType, subjectId, resourceKind, marker, action, options, expireTimeMs) {
586
+ const assignmentIndex = this._markerPermissionAssignments.findIndex((a) => a.recordName === recordName &&
587
+ a.subjectType === subjectType &&
588
+ a.subjectId === subjectId &&
589
+ a.marker === marker &&
590
+ a.resourceKind === resourceKind &&
591
+ a.action === action);
592
+ if (assignmentIndex >= 0) {
593
+ const assignment = this._markerPermissionAssignments[assignmentIndex];
594
+ this._markerPermissionAssignments[assignmentIndex] = {
595
+ ...assignment,
702
596
  options,
703
597
  expireTimeMs,
704
598
  };
705
- this._markerPermissionAssignments.push(assignment);
706
599
  return {
707
600
  success: true,
708
601
  permissionAssignment: assignment,
709
602
  };
710
- });
711
- }
712
- getMarkerPermissionAssignmentById(id) {
603
+ }
604
+ const userId = getSubjectUserId(subjectType, subjectId);
605
+ const assignment = {
606
+ id: uuid(),
607
+ recordName,
608
+ userId,
609
+ subjectType,
610
+ subjectId,
611
+ resourceKind,
612
+ marker,
613
+ action,
614
+ options,
615
+ expireTimeMs,
616
+ };
617
+ this._markerPermissionAssignments.push(assignment);
618
+ return {
619
+ success: true,
620
+ permissionAssignment: assignment,
621
+ };
622
+ }
623
+ async getMarkerPermissionAssignmentById(id) {
713
624
  var _a;
714
- return __awaiter(this, void 0, void 0, function* () {
715
- return ((_a = this._markerPermissionAssignments.find((a) => a.id === id)) !== null && _a !== void 0 ? _a : null);
716
- });
625
+ return ((_a = this._markerPermissionAssignments.find((a) => a.id === id)) !== null && _a !== void 0 ? _a : null);
717
626
  }
718
- getResourcePermissionAssignmentById(id) {
627
+ async getResourcePermissionAssignmentById(id) {
719
628
  var _a;
720
- return __awaiter(this, void 0, void 0, function* () {
721
- return ((_a = this._resourcePermissionAssignments.find((a) => a.id === id)) !== null && _a !== void 0 ? _a : null);
722
- });
723
- }
724
- deleteResourcePermissionAssignment(assigment) {
725
- return __awaiter(this, void 0, void 0, function* () {
726
- this._resourcePermissionAssignments =
727
- this._resourcePermissionAssignments.filter((p) => p.id !== assigment.id);
728
- return {
729
- success: true,
629
+ return ((_a = this._resourcePermissionAssignments.find((a) => a.id === id)) !== null && _a !== void 0 ? _a : null);
630
+ }
631
+ async deleteResourcePermissionAssignment(assigment) {
632
+ this._resourcePermissionAssignments =
633
+ this._resourcePermissionAssignments.filter((p) => p.id !== assigment.id);
634
+ return {
635
+ success: true,
636
+ };
637
+ }
638
+ async deleteResourcePermissionAssignmentById(id) {
639
+ this._resourcePermissionAssignments =
640
+ this._resourcePermissionAssignments.filter((p) => p.id !== id);
641
+ return {
642
+ success: true,
643
+ };
644
+ }
645
+ async deleteMarkerPermissionAssignment(assigment) {
646
+ this._markerPermissionAssignments =
647
+ this._markerPermissionAssignments.filter((p) => p.id !== assigment.id);
648
+ return {
649
+ success: true,
650
+ };
651
+ }
652
+ async deleteMarkerPermissionAssignmentById(id) {
653
+ this._markerPermissionAssignments =
654
+ this._markerPermissionAssignments.filter((p) => p.id !== id);
655
+ return {
656
+ success: true,
657
+ };
658
+ }
659
+ async listPermissionsInRecord(recordName) {
660
+ const resourceAssignments = this._resourcePermissionAssignments.filter((p) => p.recordName === recordName);
661
+ const markerAssignments = this._markerPermissionAssignments.filter((p) => p.recordName === recordName);
662
+ return {
663
+ success: true,
664
+ resourceAssignments,
665
+ markerAssignments,
666
+ };
667
+ }
668
+ async listPermissionsForResource(recordName, resourceKind, resourceId) {
669
+ return this._resourcePermissionAssignments.filter((p) => p.recordName === recordName &&
670
+ p.resourceKind === resourceKind &&
671
+ p.resourceId === resourceId);
672
+ }
673
+ async listPermissionsForMarker(recordName, marker) {
674
+ return this._markerPermissionAssignments.filter((p) => p.recordName === recordName && p.marker === marker);
675
+ }
676
+ async listPermissionsForSubject(recordName, subjectType, subjectId) {
677
+ const resourceAssignments = this._resourcePermissionAssignments.filter((p) => p.recordName === recordName &&
678
+ p.subjectType === subjectType &&
679
+ p.subjectId === subjectId);
680
+ const markerAssignments = this._markerPermissionAssignments.filter((p) => p.recordName === recordName &&
681
+ p.subjectType === subjectType &&
682
+ p.subjectId === subjectId);
683
+ return {
684
+ success: true,
685
+ resourceAssignments,
686
+ markerAssignments,
687
+ };
688
+ }
689
+ async saveGrantedPackageEntitlement(grantedEntitlement) {
690
+ const existingIndex = this._grantedPackageEntitlements.findIndex((e) => e.id === grantedEntitlement.id);
691
+ if (existingIndex >= 0) {
692
+ this._grantedPackageEntitlements[existingIndex] = {
693
+ ...grantedEntitlement,
730
694
  };
731
- });
695
+ }
696
+ else {
697
+ this._grantedPackageEntitlements.push({
698
+ ...grantedEntitlement,
699
+ });
700
+ }
732
701
  }
733
- deleteResourcePermissionAssignmentById(id) {
734
- return __awaiter(this, void 0, void 0, function* () {
735
- this._resourcePermissionAssignments =
736
- this._resourcePermissionAssignments.filter((p) => p.id !== id);
737
- return {
738
- success: true,
739
- };
740
- });
702
+ async listGrantedEntitlementsByFeatureAndUserId(packageIds, feature, userId, recordName, nowMs) {
703
+ return this._grantedPackageEntitlements.filter((e) => e.userId === userId &&
704
+ e.feature === feature &&
705
+ e.recordName === recordName &&
706
+ e.expireTimeMs > nowMs &&
707
+ e.revokeTimeMs === null &&
708
+ packageIds.includes(e.packageId));
741
709
  }
742
- deleteMarkerPermissionAssignment(assigment) {
743
- return __awaiter(this, void 0, void 0, function* () {
744
- this._markerPermissionAssignments =
745
- this._markerPermissionAssignments.filter((p) => p.id !== assigment.id);
746
- return {
747
- success: true,
748
- };
749
- });
710
+ async findGrantedPackageEntitlementByUserIdPackageIdFeatureAndScope(userId, packageId, feature, scope, recordName) {
711
+ var _a;
712
+ return ((_a = this._grantedPackageEntitlements.find((e) => e.userId === userId &&
713
+ e.packageId === packageId &&
714
+ e.feature === feature &&
715
+ e.scope === scope &&
716
+ e.revokeTimeMs === null &&
717
+ e.recordName === recordName)) !== null && _a !== void 0 ? _a : null);
718
+ }
719
+ async findGrantedPackageEntitlementById(id) {
720
+ return this._grantedPackageEntitlements.find((e) => e.id === id);
721
+ }
722
+ async listGrantedEntitlementsForUser(userId, nowMs) {
723
+ return this._grantedPackageEntitlements.filter((e) => e.userId === userId &&
724
+ e.expireTimeMs > nowMs &&
725
+ e.revokeTimeMs === null);
726
+ }
727
+ async listGrantedEntitlementsForUserAndPackage(userId, packageId, nowMs) {
728
+ return this._grantedPackageEntitlements.filter((e) => e.userId === userId &&
729
+ e.packageId === packageId &&
730
+ e.expireTimeMs > nowMs &&
731
+ e.revokeTimeMs === null);
732
+ }
733
+ async countRecords(filter) {
734
+ let count = 0;
735
+ for (let record of this._records) {
736
+ if (filter.studioId && record.studioId === filter.studioId) {
737
+ count++;
738
+ }
739
+ else if (filter.ownerId && record.ownerId === filter.ownerId) {
740
+ count++;
741
+ }
742
+ else {
743
+ count++;
744
+ }
745
+ }
746
+ return count;
750
747
  }
751
- deleteMarkerPermissionAssignmentById(id) {
752
- return __awaiter(this, void 0, void 0, function* () {
753
- this._markerPermissionAssignments =
754
- this._markerPermissionAssignments.filter((p) => p.id !== id);
755
- return {
756
- success: true,
757
- };
758
- });
748
+ async saveUser(user) {
749
+ let index = this._findUserIndex(user.id);
750
+ if (index >= 0) {
751
+ this._users[index] = user;
752
+ }
753
+ else {
754
+ this._users.push(user);
755
+ }
759
756
  }
760
- listPermissionsInRecord(recordName) {
761
- return __awaiter(this, void 0, void 0, function* () {
762
- const resourceAssignments = this._resourcePermissionAssignments.filter((p) => p.recordName === recordName);
763
- const markerAssignments = this._markerPermissionAssignments.filter((p) => p.recordName === recordName);
757
+ async saveNewUser(user) {
758
+ let index = this._users.findIndex((u) => (!!user.email && u.email === user.email) ||
759
+ (!!user.phoneNumber && u.phoneNumber === user.phoneNumber));
760
+ if (index >= 0) {
764
761
  return {
765
- success: true,
766
- resourceAssignments,
767
- markerAssignments,
762
+ success: false,
763
+ errorCode: 'user_already_exists',
764
+ errorMessage: 'The user already exists.',
768
765
  };
769
- });
766
+ }
767
+ else {
768
+ this._users.push(user);
769
+ }
770
+ return {
771
+ success: true,
772
+ };
773
+ }
774
+ async findUser(userId) {
775
+ const user = this._users.find((u) => u.id === userId);
776
+ return user;
777
+ }
778
+ async setRevokeAllSessionsTimeForUser(userId, allSessionRevokeTimeMs) {
779
+ const user = await this.findUser(userId);
780
+ if (user) {
781
+ await this.saveUser({
782
+ ...user,
783
+ allSessionRevokeTimeMs: allSessionRevokeTimeMs,
784
+ });
785
+ }
770
786
  }
771
- listPermissionsForResource(recordName, resourceKind, resourceId) {
772
- return __awaiter(this, void 0, void 0, function* () {
773
- return this._resourcePermissionAssignments.filter((p) => p.recordName === recordName &&
774
- p.resourceKind === resourceKind &&
775
- p.resourceId === resourceId);
776
- });
787
+ async findUserByAddress(address, addressType) {
788
+ const user = this._users.find((u) => addressType === 'email'
789
+ ? u.email === address
790
+ : u.phoneNumber === address);
791
+ return user;
777
792
  }
778
- listPermissionsForMarker(recordName, marker) {
779
- return __awaiter(this, void 0, void 0, function* () {
780
- return this._markerPermissionAssignments.filter((p) => p.recordName === recordName && p.marker === marker);
781
- });
793
+ async findUserByStripeCustomerId(customerId) {
794
+ const user = this._users.find((u) => u.stripeCustomerId === customerId);
795
+ return user;
782
796
  }
783
- listPermissionsForSubject(recordName, subjectType, subjectId) {
784
- return __awaiter(this, void 0, void 0, function* () {
785
- const resourceAssignments = this._resourcePermissionAssignments.filter((p) => p.recordName === recordName &&
786
- p.subjectType === subjectType &&
787
- p.subjectId === subjectId);
788
- const markerAssignments = this._markerPermissionAssignments.filter((p) => p.recordName === recordName &&
789
- p.subjectType === subjectType &&
790
- p.subjectId === subjectId);
791
- return {
792
- success: true,
793
- resourceAssignments,
794
- markerAssignments,
795
- };
796
- });
797
+ async findUserByPrivoServiceId(serviceId) {
798
+ const user = this._users.find((u) => u.privoServiceId === serviceId);
799
+ return user;
797
800
  }
798
- countRecords(filter) {
799
- return __awaiter(this, void 0, void 0, function* () {
800
- let count = 0;
801
- for (let record of this._records) {
802
- if (filter.studioId && record.studioId === filter.studioId) {
803
- count++;
804
- }
805
- else if (filter.ownerId && record.ownerId === filter.ownerId) {
806
- count++;
807
- }
808
- else {
809
- count++;
810
- }
811
- }
812
- return count;
813
- });
801
+ async findLoginRequest(userId, requestId) {
802
+ return this._loginRequests.find((lr) => lr.userId === userId && lr.requestId === requestId);
814
803
  }
815
- saveUser(user) {
816
- return __awaiter(this, void 0, void 0, function* () {
817
- let index = this._findUserIndex(user.id);
818
- if (index >= 0) {
819
- this._users[index] = user;
820
- }
821
- else {
822
- this._users.push(user);
823
- }
824
- });
804
+ async findOpenIDLoginRequest(requestId) {
805
+ return this._oidLoginRequests.find((lr) => lr.requestId === requestId);
825
806
  }
826
- saveNewUser(user) {
827
- return __awaiter(this, void 0, void 0, function* () {
828
- let index = this._users.findIndex((u) => (!!user.email && u.email === user.email) ||
829
- (!!user.phoneNumber && u.phoneNumber === user.phoneNumber));
830
- if (index >= 0) {
831
- return {
832
- success: false,
833
- errorCode: 'user_already_exists',
834
- errorMessage: 'The user already exists.',
835
- };
836
- }
837
- else {
838
- this._users.push(user);
839
- }
840
- return {
841
- success: true,
842
- };
843
- });
807
+ async findOpenIDLoginRequestByState(state) {
808
+ return this._oidLoginRequests.find((lr) => lr.state === state);
844
809
  }
845
- findUser(userId) {
846
- return __awaiter(this, void 0, void 0, function* () {
847
- const user = this._users.find((u) => u.id === userId);
848
- return user;
849
- });
810
+ async findSession(userId, sessionId) {
811
+ return this._sessions.find((s) => s.userId === userId && s.sessionId === sessionId);
850
812
  }
851
- setRevokeAllSessionsTimeForUser(userId, allSessionRevokeTimeMs) {
852
- return __awaiter(this, void 0, void 0, function* () {
853
- const user = yield this.findUser(userId);
854
- if (user) {
855
- yield this.saveUser(Object.assign(Object.assign({}, user), { allSessionRevokeTimeMs: allSessionRevokeTimeMs }));
856
- }
857
- });
813
+ async saveLoginRequest(request) {
814
+ const index = this._loginRequests.findIndex((lr) => lr.userId === request.userId &&
815
+ lr.requestId === request.requestId);
816
+ if (index >= 0) {
817
+ this._loginRequests[index] = request;
818
+ }
819
+ else {
820
+ this._loginRequests.push(request);
821
+ }
822
+ return request;
858
823
  }
859
- findUserByAddress(address, addressType) {
860
- return __awaiter(this, void 0, void 0, function* () {
861
- const user = this._users.find((u) => addressType === 'email'
862
- ? u.email === address
863
- : u.phoneNumber === address);
864
- return user;
865
- });
824
+ async saveOpenIDLoginRequest(request) {
825
+ const index = this._oidLoginRequests.findIndex((lr) => lr.requestId === request.requestId);
826
+ if (index >= 0) {
827
+ this._oidLoginRequests[index] = request;
828
+ }
829
+ else {
830
+ this._oidLoginRequests.push(request);
831
+ }
832
+ return request;
866
833
  }
867
- findUserByStripeCustomerId(customerId) {
868
- return __awaiter(this, void 0, void 0, function* () {
869
- const user = this._users.find((u) => u.stripeCustomerId === customerId);
870
- return user;
871
- });
834
+ async findWebAuthnLoginRequest(requestId) {
835
+ return this._webauthnLoginRequests.find((r) => r.requestId === requestId);
872
836
  }
873
- findUserByPrivoServiceId(serviceId) {
874
- return __awaiter(this, void 0, void 0, function* () {
875
- const user = this._users.find((u) => u.privoServiceId === serviceId);
876
- return user;
877
- });
837
+ async saveWebAuthnLoginRequest(request) {
838
+ const index = this._webauthnLoginRequests.findIndex((r) => r.requestId === request.requestId);
839
+ if (index >= 0) {
840
+ this._webauthnLoginRequests[index] = { ...request };
841
+ }
842
+ else {
843
+ this._webauthnLoginRequests.push({ ...request });
844
+ }
845
+ return request;
846
+ }
847
+ async markWebAuthnLoginRequestComplete(requestId, userId, completedTimeMs) {
848
+ const index = this._webauthnLoginRequests.findIndex((r) => r.requestId === requestId);
849
+ if (index >= 0) {
850
+ const request = this._webauthnLoginRequests[index];
851
+ request.userId = userId;
852
+ request.completedTimeMs = completedTimeMs;
853
+ this._webauthnLoginRequests[index] = { ...request };
854
+ }
878
855
  }
879
- findLoginRequest(userId, requestId) {
880
- return __awaiter(this, void 0, void 0, function* () {
881
- return this._loginRequests.find((lr) => lr.userId === userId && lr.requestId === requestId);
882
- });
856
+ async findUserAuthenticatorByCredentialId(credentialId) {
857
+ const authenticator = this._userAuthenticators.find((a) => a.credentialId === credentialId);
858
+ if (!authenticator) {
859
+ return { authenticator: null, user: null };
860
+ }
861
+ const user = await this.findUser(authenticator.userId);
862
+ return { authenticator, user };
863
+ }
864
+ async findUserLoginMetadata(userId) {
865
+ let authenticatorIds = this._userAuthenticators
866
+ .filter((a) => a.userId === userId)
867
+ .map((a) => a.id);
868
+ return {
869
+ hasUserAuthenticator: authenticatorIds.length > 0,
870
+ userAuthenticatorCredentialIds: authenticatorIds,
871
+ hasPushSubscription: false,
872
+ pushSubscriptionIds: [],
873
+ };
874
+ }
875
+ async saveUserAuthenticatorCounter(id, newCounter) {
876
+ const index = this._userAuthenticators.findIndex((a) => a.id === id);
877
+ if (index >= 0) {
878
+ this._userAuthenticators[index] = {
879
+ ...this._userAuthenticators[index],
880
+ counter: newCounter,
881
+ };
882
+ }
883
883
  }
884
- findOpenIDLoginRequest(requestId) {
885
- return __awaiter(this, void 0, void 0, function* () {
886
- return this._oidLoginRequests.find((lr) => lr.requestId === requestId);
887
- });
884
+ async deleteUserAuthenticator(userId, authenticatorId) {
885
+ const index = this._userAuthenticators.findIndex((a) => a.userId === userId && a.id === authenticatorId);
886
+ if (index >= 0) {
887
+ this._userAuthenticators.splice(index, 1);
888
+ return 1;
889
+ }
890
+ return 0;
891
+ }
892
+ async setCurrentLoginRequest(userId, requestId) {
893
+ const userIndex = this._users.findIndex((u) => u.id === userId);
894
+ if (userIndex >= 0) {
895
+ const user = this._users[userIndex];
896
+ this._users[userIndex] = {
897
+ ...user,
898
+ currentLoginRequestId: requestId,
899
+ };
900
+ }
888
901
  }
889
- findOpenIDLoginRequestByState(state) {
890
- return __awaiter(this, void 0, void 0, function* () {
891
- return this._oidLoginRequests.find((lr) => lr.state === state);
892
- });
902
+ async setCurrentWebAuthnChallenge(userId, challenge) {
903
+ const userIndex = this._users.findIndex((u) => u.id === userId);
904
+ if (userIndex >= 0) {
905
+ const user = this._users[userIndex];
906
+ this._users[userIndex] = {
907
+ ...user,
908
+ currentWebAuthnChallenge: challenge,
909
+ };
910
+ }
893
911
  }
894
- findSession(userId, sessionId) {
895
- return __awaiter(this, void 0, void 0, function* () {
896
- return this._sessions.find((s) => s.userId === userId && s.sessionId === sessionId);
897
- });
912
+ async markLoginRequestComplete(userId, requestId, completedTimeMs) {
913
+ const index = this._loginRequests.findIndex((lr) => lr.userId === userId && lr.requestId === requestId);
914
+ if (index >= 0) {
915
+ this._loginRequests[index].completedTimeMs = completedTimeMs;
916
+ }
917
+ else {
918
+ throw new Error('Request not found.');
919
+ }
898
920
  }
899
- saveLoginRequest(request) {
900
- return __awaiter(this, void 0, void 0, function* () {
901
- const index = this._loginRequests.findIndex((lr) => lr.userId === request.userId &&
902
- lr.requestId === request.requestId);
903
- if (index >= 0) {
904
- this._loginRequests[index] = request;
905
- }
906
- else {
907
- this._loginRequests.push(request);
908
- }
909
- return request;
910
- });
921
+ async markOpenIDLoginRequestComplete(requestId, completedTimeMs) {
922
+ const index = this._oidLoginRequests.findIndex((lr) => lr.requestId === requestId);
923
+ if (index >= 0) {
924
+ this._oidLoginRequests[index].completedTimeMs = completedTimeMs;
925
+ }
926
+ else {
927
+ throw new Error('Request not found.');
928
+ }
911
929
  }
912
- saveOpenIDLoginRequest(request) {
913
- return __awaiter(this, void 0, void 0, function* () {
914
- const index = this._oidLoginRequests.findIndex((lr) => lr.requestId === request.requestId);
915
- if (index >= 0) {
916
- this._oidLoginRequests[index] = request;
917
- }
918
- else {
919
- this._oidLoginRequests.push(request);
920
- }
921
- return request;
922
- });
930
+ async saveOpenIDLoginRequestAuthorizationCode(requestId, authorizationCode, authorizationTimeMs) {
931
+ const index = this._oidLoginRequests.findIndex((lr) => lr.requestId === requestId);
932
+ if (index >= 0) {
933
+ const lr = this._oidLoginRequests[index];
934
+ lr.authorizationCode = authorizationCode;
935
+ lr.authorizationTimeMs = authorizationTimeMs;
936
+ }
937
+ else {
938
+ throw new Error('Request not found.');
939
+ }
923
940
  }
924
- findWebAuthnLoginRequest(requestId) {
925
- return __awaiter(this, void 0, void 0, function* () {
926
- return this._webauthnLoginRequests.find((r) => r.requestId === requestId);
927
- });
941
+ async incrementLoginRequestAttemptCount(userId, requestId) {
942
+ const request = this._loginRequests.find((lr) => lr.userId === userId && lr.requestId === requestId);
943
+ if (request) {
944
+ request.attemptCount += 1;
945
+ }
928
946
  }
929
- saveWebAuthnLoginRequest(request) {
930
- return __awaiter(this, void 0, void 0, function* () {
931
- const index = this._webauthnLoginRequests.findIndex((r) => r.requestId === request.requestId);
932
- if (index >= 0) {
933
- this._webauthnLoginRequests[index] = Object.assign({}, request);
934
- }
935
- else {
936
- this._webauthnLoginRequests.push(Object.assign({}, request));
937
- }
938
- return request;
939
- });
947
+ async saveSession(session) {
948
+ const index = this._sessions.findIndex((s) => s.userId === session.userId && s.sessionId === session.sessionId);
949
+ if (index >= 0) {
950
+ this._sessions[index] = session;
951
+ }
952
+ else {
953
+ this._sessions.push(session);
954
+ }
940
955
  }
941
- markWebAuthnLoginRequestComplete(requestId, userId, completedTimeMs) {
942
- return __awaiter(this, void 0, void 0, function* () {
943
- const index = this._webauthnLoginRequests.findIndex((r) => r.requestId === requestId);
944
- if (index >= 0) {
945
- const request = this._webauthnLoginRequests[index];
946
- request.userId = userId;
947
- request.completedTimeMs = completedTimeMs;
948
- this._webauthnLoginRequests[index] = Object.assign({}, request);
949
- }
956
+ async replaceSession(session, newSession, revokeTimeMs) {
957
+ this.saveSession({
958
+ ...session,
959
+ revokeTimeMs: revokeTimeMs,
960
+ nextSessionId: newSession.sessionId,
950
961
  });
951
- }
952
- findUserAuthenticatorByCredentialId(credentialId) {
953
- return __awaiter(this, void 0, void 0, function* () {
954
- const authenticator = this._userAuthenticators.find((a) => a.credentialId === credentialId);
955
- if (!authenticator) {
956
- return { authenticator: null, user: null };
957
- }
958
- const user = yield this.findUser(authenticator.userId);
959
- return { authenticator, user };
962
+ this.saveSession({
963
+ ...newSession,
964
+ previousSessionId: session.sessionId,
960
965
  });
961
966
  }
962
- findUserLoginMetadata(userId) {
963
- return __awaiter(this, void 0, void 0, function* () {
964
- let authenticatorIds = this._userAuthenticators
965
- .filter((a) => a.userId === userId)
966
- .map((a) => a.id);
967
- return {
968
- hasUserAuthenticator: authenticatorIds.length > 0,
969
- userAuthenticatorCredentialIds: authenticatorIds,
970
- hasPushSubscription: false,
971
- pushSubscriptionIds: [],
972
- };
973
- });
967
+ async listSessions(userId, expireTimeMs) {
968
+ let orderedSessions = sortBy(this._sessions.filter((s) => s.userId === userId), (s) => -s.expireTimeMs);
969
+ if (expireTimeMs) {
970
+ orderedSessions = orderedSessions.filter((s) => s.expireTimeMs < expireTimeMs);
971
+ }
972
+ return {
973
+ success: true,
974
+ sessions: orderedSessions.slice(0, 10),
975
+ };
974
976
  }
975
- saveUserAuthenticatorCounter(id, newCounter) {
976
- return __awaiter(this, void 0, void 0, function* () {
977
- const index = this._userAuthenticators.findIndex((a) => a.id === id);
978
- if (index >= 0) {
979
- this._userAuthenticators[index] = Object.assign(Object.assign({}, this._userAuthenticators[index]), { counter: newCounter });
980
- }
981
- });
977
+ async listEmailRules() {
978
+ return this._emailRules.slice();
982
979
  }
983
- deleteUserAuthenticator(userId, authenticatorId) {
984
- return __awaiter(this, void 0, void 0, function* () {
985
- const index = this._userAuthenticators.findIndex((a) => a.userId === userId && a.id === authenticatorId);
986
- if (index >= 0) {
987
- this._userAuthenticators.splice(index, 1);
988
- return 1;
989
- }
990
- return 0;
991
- });
980
+ async listSmsRules() {
981
+ return this._smsRules.slice();
992
982
  }
993
- setCurrentLoginRequest(userId, requestId) {
994
- return __awaiter(this, void 0, void 0, function* () {
995
- const userIndex = this._users.findIndex((u) => u.id === userId);
996
- if (userIndex >= 0) {
997
- const user = this._users[userIndex];
998
- this._users[userIndex] = Object.assign(Object.assign({}, user), { currentLoginRequestId: requestId });
999
- }
1000
- });
983
+ async saveSubscription(subscription) {
984
+ const index = this._subscriptions.findIndex((s) => s.id === subscription.id);
985
+ if (index >= 0) {
986
+ this._subscriptions[index] = subscription;
987
+ }
988
+ else {
989
+ this._subscriptions.push(subscription);
990
+ }
1001
991
  }
1002
- setCurrentWebAuthnChallenge(userId, challenge) {
1003
- return __awaiter(this, void 0, void 0, function* () {
1004
- const userIndex = this._users.findIndex((u) => u.id === userId);
1005
- if (userIndex >= 0) {
1006
- const user = this._users[userIndex];
1007
- this._users[userIndex] = Object.assign(Object.assign({}, user), { currentWebAuthnChallenge: challenge });
1008
- }
1009
- });
992
+ async getSubscriptionById(id) {
993
+ return this._subscriptions.find((s) => s.id === id);
1010
994
  }
1011
- markLoginRequestComplete(userId, requestId, completedTimeMs) {
1012
- return __awaiter(this, void 0, void 0, function* () {
1013
- const index = this._loginRequests.findIndex((lr) => lr.userId === userId && lr.requestId === requestId);
1014
- if (index >= 0) {
1015
- this._loginRequests[index].completedTimeMs = completedTimeMs;
1016
- }
1017
- else {
1018
- throw new Error('Request not found.');
1019
- }
1020
- });
1021
- }
1022
- markOpenIDLoginRequestComplete(requestId, completedTimeMs) {
1023
- return __awaiter(this, void 0, void 0, function* () {
1024
- const index = this._oidLoginRequests.findIndex((lr) => lr.requestId === requestId);
1025
- if (index >= 0) {
1026
- this._oidLoginRequests[index].completedTimeMs = completedTimeMs;
1027
- }
1028
- else {
1029
- throw new Error('Request not found.');
1030
- }
1031
- });
1032
- }
1033
- saveOpenIDLoginRequestAuthorizationCode(requestId, authorizationCode, authorizationTimeMs) {
1034
- return __awaiter(this, void 0, void 0, function* () {
1035
- const index = this._oidLoginRequests.findIndex((lr) => lr.requestId === requestId);
1036
- if (index >= 0) {
1037
- const lr = this._oidLoginRequests[index];
1038
- lr.authorizationCode = authorizationCode;
1039
- lr.authorizationTimeMs = authorizationTimeMs;
1040
- }
1041
- else {
1042
- throw new Error('Request not found.');
1043
- }
1044
- });
1045
- }
1046
- incrementLoginRequestAttemptCount(userId, requestId) {
1047
- return __awaiter(this, void 0, void 0, function* () {
1048
- const request = this._loginRequests.find((lr) => lr.userId === userId && lr.requestId === requestId);
1049
- if (request) {
1050
- request.attemptCount += 1;
1051
- }
1052
- });
1053
- }
1054
- saveSession(session) {
1055
- return __awaiter(this, void 0, void 0, function* () {
1056
- const index = this._sessions.findIndex((s) => s.userId === session.userId && s.sessionId === session.sessionId);
1057
- if (index >= 0) {
1058
- this._sessions[index] = session;
1059
- }
1060
- else {
1061
- this._sessions.push(session);
1062
- }
1063
- });
1064
- }
1065
- replaceSession(session, newSession, revokeTimeMs) {
1066
- return __awaiter(this, void 0, void 0, function* () {
1067
- this.saveSession(Object.assign(Object.assign({}, session), { revokeTimeMs: revokeTimeMs, nextSessionId: newSession.sessionId }));
1068
- this.saveSession(Object.assign(Object.assign({}, newSession), { previousSessionId: session.sessionId }));
1069
- });
1070
- }
1071
- listSessions(userId, expireTimeMs) {
1072
- return __awaiter(this, void 0, void 0, function* () {
1073
- let orderedSessions = sortBy(this._sessions.filter((s) => s.userId === userId), (s) => -s.expireTimeMs);
1074
- if (expireTimeMs) {
1075
- orderedSessions = orderedSessions.filter((s) => s.expireTimeMs < expireTimeMs);
1076
- }
1077
- return {
1078
- success: true,
1079
- sessions: orderedSessions.slice(0, 10),
1080
- };
1081
- });
1082
- }
1083
- listEmailRules() {
1084
- return __awaiter(this, void 0, void 0, function* () {
1085
- return this._emailRules.slice();
1086
- });
995
+ async getSubscriptionByStripeSubscriptionId(id) {
996
+ return this._subscriptions.find((s) => s.stripeSubscriptionId === id);
1087
997
  }
1088
- listSmsRules() {
1089
- return __awaiter(this, void 0, void 0, function* () {
1090
- return this._smsRules.slice();
1091
- });
1092
- }
1093
- saveSubscription(subscription) {
1094
- return __awaiter(this, void 0, void 0, function* () {
1095
- const index = this._subscriptions.findIndex((s) => s.id === subscription.id);
1096
- if (index >= 0) {
1097
- this._subscriptions[index] = subscription;
1098
- }
1099
- else {
1100
- this._subscriptions.push(subscription);
1101
- }
1102
- });
1103
- }
1104
- getSubscriptionById(id) {
1105
- return __awaiter(this, void 0, void 0, function* () {
1106
- return this._subscriptions.find((s) => s.id === id);
1107
- });
1108
- }
1109
- getSubscriptionByStripeSubscriptionId(id) {
1110
- return __awaiter(this, void 0, void 0, function* () {
1111
- return this._subscriptions.find((s) => s.stripeSubscriptionId === id);
1112
- });
1113
- }
1114
- saveSubscriptionPeriod(period) {
1115
- return __awaiter(this, void 0, void 0, function* () {
1116
- const index = this._periods.findIndex((p) => p.id === period.id);
1117
- if (index >= 0) {
1118
- this._periods[index] = period;
1119
- }
1120
- else {
1121
- this._periods.push(period);
1122
- }
1123
- });
998
+ async saveSubscriptionPeriod(period) {
999
+ const index = this._periods.findIndex((p) => p.id === period.id);
1000
+ if (index >= 0) {
1001
+ this._periods[index] = period;
1002
+ }
1003
+ else {
1004
+ this._periods.push(period);
1005
+ }
1124
1006
  }
1125
- getSubscriptionPeriodById(id) {
1126
- return __awaiter(this, void 0, void 0, function* () {
1127
- return this._periods.find((p) => p.id === id);
1128
- });
1007
+ async getSubscriptionPeriodById(id) {
1008
+ return this._periods.find((p) => p.id === id);
1129
1009
  }
1130
- listSubscriptionPeriodsBySubscriptionId(subscriptionId) {
1131
- return __awaiter(this, void 0, void 0, function* () {
1132
- return this._periods.filter((p) => p.subscriptionId === subscriptionId);
1133
- });
1010
+ async listSubscriptionPeriodsBySubscriptionId(subscriptionId) {
1011
+ return this._periods.filter((p) => p.subscriptionId === subscriptionId);
1134
1012
  }
1135
- saveInvoice(invoice) {
1136
- return __awaiter(this, void 0, void 0, function* () {
1137
- const index = this._invoices.findIndex((i) => i.id === invoice.id);
1138
- if (index >= 0) {
1139
- this._invoices[index] = invoice;
1140
- }
1141
- else {
1142
- this._invoices.push(invoice);
1143
- }
1144
- });
1013
+ async saveInvoice(invoice) {
1014
+ const index = this._invoices.findIndex((i) => i.id === invoice.id);
1015
+ if (index >= 0) {
1016
+ this._invoices[index] = invoice;
1017
+ }
1018
+ else {
1019
+ this._invoices.push(invoice);
1020
+ }
1145
1021
  }
1146
- getInvoiceById(id) {
1147
- return __awaiter(this, void 0, void 0, function* () {
1148
- return this._invoices.find((i) => i.id === id);
1149
- });
1022
+ async getInvoiceById(id) {
1023
+ return this._invoices.find((i) => i.id === id);
1150
1024
  }
1151
- updateSubscriptionInfo(request) {
1025
+ async updateSubscriptionInfo(request) {
1152
1026
  var _a, _b, _c, _d;
1153
- return __awaiter(this, void 0, void 0, function* () {
1154
- if (request.userId) {
1155
- const user = yield this.findUser(request.userId);
1156
- let subscription = request.stripeSubscriptionId
1157
- ? yield this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId)
1158
- : null;
1159
- if (subscription) {
1160
- yield this.saveSubscription(Object.assign(Object.assign({}, subscription), { stripeCustomerId: request.stripeCustomerId, stripeSubscriptionId: request.stripeSubscriptionId, subscriptionId: request.subscriptionId, subscriptionStatus: request.subscriptionStatus, currentPeriodEndMs: request.currentPeriodEndMs, currentPeriodStartMs: request.currentPeriodStartMs }));
1161
- }
1162
- else if (request.stripeSubscriptionId) {
1163
- subscription = {
1164
- id: uuid(),
1165
- userId: user.id,
1166
- studioId: null,
1167
- stripeCustomerId: request.stripeCustomerId,
1168
- stripeSubscriptionId: request.stripeSubscriptionId,
1169
- subscriptionId: request.subscriptionId,
1170
- subscriptionStatus: request.subscriptionStatus,
1171
- currentPeriodEndMs: request.currentPeriodEndMs,
1172
- currentPeriodStartMs: request.currentPeriodStartMs,
1173
- };
1174
- yield this.saveSubscription(subscription);
1175
- }
1176
- yield this.saveUser(Object.assign(Object.assign({}, user), { subscriptionId: request.subscriptionId, subscriptionStatus: request.subscriptionStatus, stripeCustomerId: (_a = request.stripeCustomerId) !== null && _a !== void 0 ? _a : user.stripeCustomerId, subscriptionPeriodStartMs: request.currentPeriodStartMs, subscriptionPeriodEndMs: request.currentPeriodEndMs, subscriptionInfoId: (_b = subscription === null || subscription === void 0 ? void 0 : subscription.id) !== null && _b !== void 0 ? _b : null }));
1177
- }
1178
- else if (request.studioId) {
1179
- const studio = yield this.getStudioById(request.studioId);
1180
- let subscription = request.stripeSubscriptionId
1181
- ? yield this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId)
1182
- : null;
1183
- if (subscription) {
1184
- yield this.saveSubscription(Object.assign(Object.assign({}, subscription), { stripeCustomerId: request.stripeCustomerId, stripeSubscriptionId: request.stripeSubscriptionId, subscriptionId: request.subscriptionId, subscriptionStatus: request.subscriptionStatus, currentPeriodEndMs: request.currentPeriodEndMs, currentPeriodStartMs: request.currentPeriodStartMs }));
1185
- }
1186
- else if (request.stripeSubscriptionId) {
1187
- subscription = {
1188
- id: uuid(),
1189
- userId: null,
1190
- studioId: studio.id,
1191
- stripeCustomerId: request.stripeCustomerId,
1192
- stripeSubscriptionId: request.stripeSubscriptionId,
1193
- subscriptionId: request.subscriptionId,
1194
- subscriptionStatus: request.subscriptionStatus,
1195
- currentPeriodEndMs: request.currentPeriodEndMs,
1196
- currentPeriodStartMs: request.currentPeriodStartMs,
1197
- };
1198
- yield this.saveSubscription(subscription);
1199
- }
1200
- yield this.updateStudio(Object.assign(Object.assign({}, studio), { subscriptionId: request.subscriptionId, subscriptionStatus: request.subscriptionStatus, stripeCustomerId: (_c = request.stripeCustomerId) !== null && _c !== void 0 ? _c : studio.stripeCustomerId, subscriptionPeriodStartMs: request.currentPeriodStartMs, subscriptionPeriodEndMs: request.currentPeriodEndMs, subscriptionInfoId: (_d = subscription === null || subscription === void 0 ? void 0 : subscription.id) !== null && _d !== void 0 ? _d : null }));
1201
- }
1202
- });
1203
- }
1204
- updateSubscriptionPeriod(request) {
1205
- return __awaiter(this, void 0, void 0, function* () {
1206
- if (request.userId) {
1207
- let user = yield this.findUser(request.userId);
1208
- let subscription = yield this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId);
1209
- if (!subscription) {
1210
- subscription = {
1211
- id: uuid(),
1212
- userId: user.id,
1213
- studioId: null,
1214
- stripeCustomerId: request.stripeCustomerId,
1215
- stripeSubscriptionId: request.stripeSubscriptionId,
1216
- subscriptionId: request.subscriptionId,
1217
- subscriptionStatus: request.subscriptionStatus,
1218
- currentPeriodEndMs: request.currentPeriodEndMs,
1219
- currentPeriodStartMs: request.currentPeriodStartMs,
1220
- };
1221
- user.stripeCustomerId = request.stripeCustomerId;
1222
- user.subscriptionStatus = request.subscriptionStatus;
1223
- user.subscriptionId = request.subscriptionId;
1224
- user.subscriptionInfoId = subscription.id;
1225
- yield this.saveSubscription(subscription);
1226
- }
1227
- yield this.saveUser(Object.assign(Object.assign({}, user), { subscriptionPeriodStartMs: request.currentPeriodStartMs, subscriptionPeriodEndMs: request.currentPeriodEndMs }));
1228
- const periodId = uuid();
1229
- const invoiceId = uuid();
1230
- yield this.saveInvoice(Object.assign({ id: invoiceId, periodId: periodId, subscriptionId: subscription.id }, request.invoice));
1231
- yield this.saveSubscriptionPeriod({
1232
- id: periodId,
1233
- invoiceId: invoiceId,
1234
- subscriptionId: subscription.id,
1235
- periodEndMs: request.currentPeriodEndMs,
1236
- periodStartMs: request.currentPeriodStartMs,
1027
+ if (request.userId) {
1028
+ const user = await this.findUser(request.userId);
1029
+ let subscription = request.stripeSubscriptionId
1030
+ ? await this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId)
1031
+ : null;
1032
+ if (subscription) {
1033
+ await this.saveSubscription({
1034
+ ...subscription,
1035
+ stripeCustomerId: request.stripeCustomerId,
1036
+ stripeSubscriptionId: request.stripeSubscriptionId,
1037
+ subscriptionId: request.subscriptionId,
1038
+ subscriptionStatus: request.subscriptionStatus,
1039
+ currentPeriodEndMs: request.currentPeriodEndMs,
1040
+ currentPeriodStartMs: request.currentPeriodStartMs,
1237
1041
  });
1238
1042
  }
1239
- else if (request.studioId) {
1240
- let studio = yield this.getStudioById(request.studioId);
1241
- let subscription = yield this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId);
1242
- if (!subscription) {
1243
- subscription = {
1244
- id: uuid(),
1245
- userId: null,
1246
- studioId: studio.id,
1247
- stripeCustomerId: request.stripeCustomerId,
1248
- stripeSubscriptionId: request.stripeSubscriptionId,
1249
- subscriptionId: request.subscriptionId,
1250
- subscriptionStatus: request.subscriptionStatus,
1251
- currentPeriodEndMs: request.currentPeriodEndMs,
1252
- currentPeriodStartMs: request.currentPeriodStartMs,
1253
- };
1254
- studio.stripeCustomerId = request.stripeCustomerId;
1255
- studio.subscriptionStatus = request.subscriptionStatus;
1256
- studio.subscriptionId = request.subscriptionId;
1257
- studio.subscriptionInfoId = subscription.id;
1258
- yield this.saveSubscription(subscription);
1259
- }
1260
- yield this.updateStudio(Object.assign(Object.assign({}, studio), { subscriptionPeriodStartMs: request.currentPeriodStartMs, subscriptionPeriodEndMs: request.currentPeriodEndMs }));
1261
- const periodId = uuid();
1262
- const invoiceId = uuid();
1263
- yield this.saveInvoice(Object.assign({ id: invoiceId, periodId: periodId, subscriptionId: subscription.id }, request.invoice));
1264
- yield this.saveSubscriptionPeriod({
1265
- id: periodId,
1266
- invoiceId: invoiceId,
1267
- subscriptionId: subscription.id,
1268
- periodEndMs: request.currentPeriodEndMs,
1269
- periodStartMs: request.currentPeriodStartMs,
1043
+ else if (request.stripeSubscriptionId) {
1044
+ subscription = {
1045
+ id: uuid(),
1046
+ userId: user.id,
1047
+ studioId: null,
1048
+ stripeCustomerId: request.stripeCustomerId,
1049
+ stripeSubscriptionId: request.stripeSubscriptionId,
1050
+ subscriptionId: request.subscriptionId,
1051
+ subscriptionStatus: request.subscriptionStatus,
1052
+ currentPeriodEndMs: request.currentPeriodEndMs,
1053
+ currentPeriodStartMs: request.currentPeriodStartMs,
1054
+ };
1055
+ await this.saveSubscription(subscription);
1056
+ }
1057
+ await this.saveUser({
1058
+ ...user,
1059
+ subscriptionId: request.subscriptionId,
1060
+ subscriptionStatus: request.subscriptionStatus,
1061
+ stripeCustomerId: (_a = request.stripeCustomerId) !== null && _a !== void 0 ? _a : user.stripeCustomerId,
1062
+ subscriptionPeriodStartMs: request.currentPeriodStartMs,
1063
+ subscriptionPeriodEndMs: request.currentPeriodEndMs,
1064
+ subscriptionInfoId: (_b = subscription === null || subscription === void 0 ? void 0 : subscription.id) !== null && _b !== void 0 ? _b : null,
1065
+ });
1066
+ }
1067
+ else if (request.studioId) {
1068
+ const studio = await this.getStudioById(request.studioId);
1069
+ let subscription = request.stripeSubscriptionId
1070
+ ? await this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId)
1071
+ : null;
1072
+ if (subscription) {
1073
+ await this.saveSubscription({
1074
+ ...subscription,
1075
+ stripeCustomerId: request.stripeCustomerId,
1076
+ stripeSubscriptionId: request.stripeSubscriptionId,
1077
+ subscriptionId: request.subscriptionId,
1078
+ subscriptionStatus: request.subscriptionStatus,
1079
+ currentPeriodEndMs: request.currentPeriodEndMs,
1080
+ currentPeriodStartMs: request.currentPeriodStartMs,
1270
1081
  });
1271
1082
  }
1272
- });
1083
+ else if (request.stripeSubscriptionId) {
1084
+ subscription = {
1085
+ id: uuid(),
1086
+ userId: null,
1087
+ studioId: studio.id,
1088
+ stripeCustomerId: request.stripeCustomerId,
1089
+ stripeSubscriptionId: request.stripeSubscriptionId,
1090
+ subscriptionId: request.subscriptionId,
1091
+ subscriptionStatus: request.subscriptionStatus,
1092
+ currentPeriodEndMs: request.currentPeriodEndMs,
1093
+ currentPeriodStartMs: request.currentPeriodStartMs,
1094
+ };
1095
+ await this.saveSubscription(subscription);
1096
+ }
1097
+ await this.updateStudio({
1098
+ ...studio,
1099
+ subscriptionId: request.subscriptionId,
1100
+ subscriptionStatus: request.subscriptionStatus,
1101
+ stripeCustomerId: (_c = request.stripeCustomerId) !== null && _c !== void 0 ? _c : studio.stripeCustomerId,
1102
+ subscriptionPeriodStartMs: request.currentPeriodStartMs,
1103
+ subscriptionPeriodEndMs: request.currentPeriodEndMs,
1104
+ subscriptionInfoId: (_d = subscription === null || subscription === void 0 ? void 0 : subscription.id) !== null && _d !== void 0 ? _d : null,
1105
+ });
1106
+ }
1107
+ }
1108
+ async updateSubscriptionPeriod(request) {
1109
+ if (request.userId) {
1110
+ let user = await this.findUser(request.userId);
1111
+ let subscription = await this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId);
1112
+ if (!subscription) {
1113
+ subscription = {
1114
+ id: uuid(),
1115
+ userId: user.id,
1116
+ studioId: null,
1117
+ stripeCustomerId: request.stripeCustomerId,
1118
+ stripeSubscriptionId: request.stripeSubscriptionId,
1119
+ subscriptionId: request.subscriptionId,
1120
+ subscriptionStatus: request.subscriptionStatus,
1121
+ currentPeriodEndMs: request.currentPeriodEndMs,
1122
+ currentPeriodStartMs: request.currentPeriodStartMs,
1123
+ };
1124
+ user.stripeCustomerId = request.stripeCustomerId;
1125
+ user.subscriptionStatus = request.subscriptionStatus;
1126
+ user.subscriptionId = request.subscriptionId;
1127
+ user.subscriptionInfoId = subscription.id;
1128
+ await this.saveSubscription(subscription);
1129
+ }
1130
+ await this.saveUser({
1131
+ ...user,
1132
+ subscriptionPeriodStartMs: request.currentPeriodStartMs,
1133
+ subscriptionPeriodEndMs: request.currentPeriodEndMs,
1134
+ });
1135
+ const periodId = uuid();
1136
+ const invoiceId = uuid();
1137
+ await this.saveInvoice({
1138
+ id: invoiceId,
1139
+ periodId: periodId,
1140
+ subscriptionId: subscription.id,
1141
+ ...request.invoice,
1142
+ });
1143
+ await this.saveSubscriptionPeriod({
1144
+ id: periodId,
1145
+ invoiceId: invoiceId,
1146
+ subscriptionId: subscription.id,
1147
+ periodEndMs: request.currentPeriodEndMs,
1148
+ periodStartMs: request.currentPeriodStartMs,
1149
+ });
1150
+ }
1151
+ else if (request.studioId) {
1152
+ let studio = await this.getStudioById(request.studioId);
1153
+ let subscription = await this.getSubscriptionByStripeSubscriptionId(request.stripeSubscriptionId);
1154
+ if (!subscription) {
1155
+ subscription = {
1156
+ id: uuid(),
1157
+ userId: null,
1158
+ studioId: studio.id,
1159
+ stripeCustomerId: request.stripeCustomerId,
1160
+ stripeSubscriptionId: request.stripeSubscriptionId,
1161
+ subscriptionId: request.subscriptionId,
1162
+ subscriptionStatus: request.subscriptionStatus,
1163
+ currentPeriodEndMs: request.currentPeriodEndMs,
1164
+ currentPeriodStartMs: request.currentPeriodStartMs,
1165
+ };
1166
+ studio.stripeCustomerId = request.stripeCustomerId;
1167
+ studio.subscriptionStatus = request.subscriptionStatus;
1168
+ studio.subscriptionId = request.subscriptionId;
1169
+ studio.subscriptionInfoId = subscription.id;
1170
+ await this.saveSubscription(subscription);
1171
+ }
1172
+ await this.updateStudio({
1173
+ ...studio,
1174
+ subscriptionPeriodStartMs: request.currentPeriodStartMs,
1175
+ subscriptionPeriodEndMs: request.currentPeriodEndMs,
1176
+ });
1177
+ const periodId = uuid();
1178
+ const invoiceId = uuid();
1179
+ await this.saveInvoice({
1180
+ id: invoiceId,
1181
+ periodId: periodId,
1182
+ subscriptionId: subscription.id,
1183
+ ...request.invoice,
1184
+ });
1185
+ await this.saveSubscriptionPeriod({
1186
+ id: periodId,
1187
+ invoiceId: invoiceId,
1188
+ subscriptionId: subscription.id,
1189
+ periodEndMs: request.currentPeriodEndMs,
1190
+ periodStartMs: request.currentPeriodStartMs,
1191
+ });
1192
+ }
1273
1193
  }
1274
1194
  _findUserIndex(id) {
1275
1195
  return this._users.findIndex((u) => u.id === id);
1276
1196
  }
1277
- setData(recordName, address, data, publisherId, subjectId, updatePolicy, deletePolicy, markers) {
1278
- return __awaiter(this, void 0, void 0, function* () {
1279
- let record = this._getDataRecord(recordName);
1280
- record.set(address, {
1281
- data: data,
1282
- publisherId: publisherId,
1283
- subjectId: subjectId,
1284
- updatePolicy,
1285
- deletePolicy,
1286
- markers,
1287
- });
1197
+ async setData(recordName, address, data, publisherId, subjectId, updatePolicy, deletePolicy, markers) {
1198
+ let record = this._getDataRecord(recordName);
1199
+ record.set(address, {
1200
+ data: data,
1201
+ publisherId: publisherId,
1202
+ subjectId: subjectId,
1203
+ updatePolicy,
1204
+ deletePolicy,
1205
+ markers,
1206
+ });
1207
+ return {
1208
+ success: true,
1209
+ };
1210
+ }
1211
+ async getData(recordName, address) {
1212
+ let record = this._getDataRecord(recordName);
1213
+ let data = record.get(address);
1214
+ if (!data) {
1288
1215
  return {
1289
- success: true,
1216
+ success: false,
1217
+ errorCode: 'data_not_found',
1218
+ errorMessage: 'The data was not found.',
1290
1219
  };
1291
- });
1292
- }
1293
- getData(recordName, address) {
1294
- return __awaiter(this, void 0, void 0, function* () {
1295
- let record = this._getDataRecord(recordName);
1296
- let data = record.get(address);
1297
- if (!data) {
1298
- return {
1299
- success: false,
1300
- errorCode: 'data_not_found',
1301
- errorMessage: 'The data was not found.',
1302
- };
1303
- }
1220
+ }
1221
+ return {
1222
+ success: true,
1223
+ data: data.data,
1224
+ publisherId: data.publisherId,
1225
+ subjectId: data.subjectId,
1226
+ updatePolicy: data.updatePolicy,
1227
+ deletePolicy: data.deletePolicy,
1228
+ markers: data.markers,
1229
+ };
1230
+ }
1231
+ async eraseData(recordName, address) {
1232
+ let record = this._getDataRecord(recordName);
1233
+ let deleted = record.delete(address);
1234
+ if (!deleted) {
1304
1235
  return {
1305
- success: true,
1306
- data: data.data,
1307
- publisherId: data.publisherId,
1308
- subjectId: data.subjectId,
1309
- updatePolicy: data.updatePolicy,
1310
- deletePolicy: data.deletePolicy,
1311
- markers: data.markers,
1236
+ success: false,
1237
+ errorCode: 'data_not_found',
1238
+ errorMessage: 'The data was not found.',
1312
1239
  };
1313
- });
1314
- }
1315
- eraseData(recordName, address) {
1316
- return __awaiter(this, void 0, void 0, function* () {
1317
- let record = this._getDataRecord(recordName);
1318
- let deleted = record.delete(address);
1319
- if (!deleted) {
1320
- return {
1321
- success: false,
1322
- errorCode: 'data_not_found',
1323
- errorMessage: 'The data was not found.',
1324
- };
1240
+ }
1241
+ return {
1242
+ success: true,
1243
+ };
1244
+ }
1245
+ async listData(recordName, address) {
1246
+ let record = this._getDataRecord(recordName);
1247
+ let items = [];
1248
+ const count = record.size;
1249
+ for (let [key, item] of record.entries()) {
1250
+ if (!address || key > address) {
1251
+ items.push({
1252
+ address: key,
1253
+ data: item.data,
1254
+ markers: item.markers,
1255
+ });
1325
1256
  }
1326
- return {
1327
- success: true,
1328
- };
1329
- });
1330
- }
1331
- listData(recordName, address) {
1332
- return __awaiter(this, void 0, void 0, function* () {
1333
- let record = this._getDataRecord(recordName);
1334
- let items = [];
1335
- const count = record.size;
1336
- for (let [key, item] of record.entries()) {
1337
- if (!address || key > address) {
1257
+ }
1258
+ return {
1259
+ success: true,
1260
+ items,
1261
+ totalCount: count,
1262
+ marker: null,
1263
+ };
1264
+ }
1265
+ async listDataByMarker(request) {
1266
+ var _a;
1267
+ const marker = request.marker;
1268
+ let record = this._getDataRecord(request.recordName);
1269
+ let items = [];
1270
+ const address = request.startingAddress;
1271
+ const sortAscending = ((_a = request.sort) !== null && _a !== void 0 ? _a : 'ascending') === 'ascending';
1272
+ let count = 0;
1273
+ for (let [key, item] of record.entries()) {
1274
+ if (item.markers.includes(marker)) {
1275
+ count += 1;
1276
+ if (!address ||
1277
+ (sortAscending && key > address) ||
1278
+ (!sortAscending && key < address)) {
1338
1279
  items.push({
1339
1280
  address: key,
1340
1281
  data: item.data,
@@ -1342,52 +1283,21 @@ export class MemoryStore {
1342
1283
  });
1343
1284
  }
1344
1285
  }
1345
- return {
1346
- success: true,
1347
- items,
1348
- totalCount: count,
1349
- marker: null,
1350
- };
1351
- });
1352
- }
1353
- listDataByMarker(request) {
1354
- var _a;
1355
- return __awaiter(this, void 0, void 0, function* () {
1356
- const marker = request.marker;
1357
- let record = this._getDataRecord(request.recordName);
1358
- let items = [];
1359
- const address = request.startingAddress;
1360
- const sortAscending = ((_a = request.sort) !== null && _a !== void 0 ? _a : 'ascending') === 'ascending';
1361
- let count = 0;
1362
- for (let [key, item] of record.entries()) {
1363
- if (item.markers.includes(marker)) {
1364
- count += 1;
1365
- if (!address ||
1366
- (sortAscending && key > address) ||
1367
- (!sortAscending && key < address)) {
1368
- items.push({
1369
- address: key,
1370
- data: item.data,
1371
- markers: item.markers,
1372
- });
1373
- }
1374
- }
1286
+ }
1287
+ if (request.sort) {
1288
+ if (request.sort === 'ascending') {
1289
+ items = sortBy(items, (i) => i.address);
1375
1290
  }
1376
- if (request.sort) {
1377
- if (request.sort === 'ascending') {
1378
- items = sortBy(items, (i) => i.address);
1379
- }
1380
- else if (request.sort === 'descending') {
1381
- items = orderBy(items, (i) => i.address, 'desc');
1382
- }
1291
+ else if (request.sort === 'descending') {
1292
+ items = orderBy(items, (i) => i.address, 'desc');
1383
1293
  }
1384
- return {
1385
- success: true,
1386
- items,
1387
- totalCount: count,
1388
- marker: marker,
1389
- };
1390
- });
1294
+ }
1295
+ return {
1296
+ success: true,
1297
+ items,
1298
+ totalCount: count,
1299
+ marker: marker,
1300
+ };
1391
1301
  }
1392
1302
  _getDataRecord(recordName) {
1393
1303
  let record = this._dataBuckets.get(recordName);
@@ -1397,246 +1307,233 @@ export class MemoryStore {
1397
1307
  }
1398
1308
  return record;
1399
1309
  }
1400
- presignFileUpload(request) {
1401
- return __awaiter(this, void 0, void 0, function* () {
1402
- return {
1403
- success: true,
1404
- uploadHeaders: Object.assign(Object.assign({}, request.headers), { 'record-name': request.recordName, 'content-type': request.fileMimeType }),
1405
- uploadMethod: 'POST',
1406
- uploadUrl: `${this._fileUploadUrl}/${request.recordName}/${request.fileName}`,
1407
- };
1408
- });
1409
- }
1410
- presignFileRead(request) {
1411
- return __awaiter(this, void 0, void 0, function* () {
1412
- return {
1413
- success: true,
1414
- requestHeaders: Object.assign(Object.assign({}, request.headers), { 'record-name': request.recordName }),
1415
- requestMethod: 'GET',
1416
- requestUrl: `${this._fileUploadUrl}/${request.recordName}/${request.fileName}`,
1417
- };
1418
- });
1419
- }
1420
- getFileNameFromUrl(fileUrl) {
1421
- return __awaiter(this, void 0, void 0, function* () {
1422
- if (fileUrl.startsWith(this._fileUploadUrl)) {
1423
- let recordNameAndFileName = fileUrl.slice(this._fileUploadUrl.length + 1);
1424
- let nextSlash = recordNameAndFileName.indexOf('/');
1425
- if (nextSlash < 0) {
1426
- return {
1427
- success: false,
1428
- errorCode: 'unacceptable_url',
1429
- errorMessage: 'The URL does not match an expected format.',
1430
- };
1431
- }
1432
- let recordName = recordNameAndFileName.slice(0, nextSlash);
1433
- let fileName = recordNameAndFileName.slice(nextSlash + 1);
1434
- if (recordName && fileName) {
1435
- return {
1436
- success: true,
1437
- recordName,
1438
- fileName,
1439
- };
1440
- }
1310
+ async presignFileUpload(request) {
1311
+ return {
1312
+ success: true,
1313
+ uploadHeaders: {
1314
+ ...request.headers,
1315
+ 'record-name': request.recordName,
1316
+ 'content-type': request.fileMimeType,
1317
+ },
1318
+ uploadMethod: 'POST',
1319
+ uploadUrl: `${this._fileUploadUrl}/${request.recordName}/${request.fileName}`,
1320
+ };
1321
+ }
1322
+ async presignFileRead(request) {
1323
+ return {
1324
+ success: true,
1325
+ requestHeaders: {
1326
+ ...request.headers,
1327
+ 'record-name': request.recordName,
1328
+ },
1329
+ requestMethod: 'GET',
1330
+ requestUrl: `${this._fileUploadUrl}/${request.recordName}/${request.fileName}`,
1331
+ };
1332
+ }
1333
+ async getFileNameFromUrl(fileUrl) {
1334
+ if (fileUrl.startsWith(this._fileUploadUrl)) {
1335
+ let recordNameAndFileName = fileUrl.slice(this._fileUploadUrl.length + 1);
1336
+ let nextSlash = recordNameAndFileName.indexOf('/');
1337
+ if (nextSlash < 0) {
1441
1338
  return {
1442
1339
  success: false,
1443
1340
  errorCode: 'unacceptable_url',
1444
1341
  errorMessage: 'The URL does not match an expected format.',
1445
1342
  };
1446
1343
  }
1447
- return {
1448
- success: false,
1449
- errorCode: 'unacceptable_url',
1450
- errorMessage: 'The URL does not match an expected format.',
1451
- };
1452
- });
1453
- }
1454
- getFileRecord(recordName, fileName) {
1455
- return __awaiter(this, void 0, void 0, function* () {
1456
- let file = this._files.get(fileName);
1457
- if (file) {
1344
+ let recordName = recordNameAndFileName.slice(0, nextSlash);
1345
+ let fileName = recordNameAndFileName.slice(nextSlash + 1);
1346
+ if (recordName && fileName) {
1458
1347
  return {
1459
1348
  success: true,
1460
- fileName: file.fileName,
1461
- recordName: file.recordName,
1462
- publisherId: file.publisherId,
1463
- subjectId: file.subjectId,
1464
- sizeInBytes: file.sizeInBytes,
1465
- uploaded: file.uploaded,
1466
- description: file.description,
1467
- url: `${this._fileUploadUrl}/${file.recordName}/${file.fileName}`,
1468
- markers: file.markers,
1469
- };
1470
- }
1471
- else {
1472
- return {
1473
- success: false,
1474
- errorCode: 'file_not_found',
1475
- errorMessage: 'The file was not found in the store.',
1349
+ recordName,
1350
+ fileName,
1476
1351
  };
1477
1352
  }
1478
- });
1479
- }
1480
- listUploadedFiles(recordName, fileName) {
1481
- return __awaiter(this, void 0, void 0, function* () {
1482
- let files = sortBy([...this._files.values()].filter((f) => f.recordName === recordName && f.uploaded), (f) => f.fileName);
1483
- const count = files.length;
1484
- if (fileName) {
1485
- files = files.filter((f) => f.fileName > fileName);
1486
- }
1487
1353
  return {
1488
- success: true,
1489
- files: files.slice(0, 10).map((f) => ({
1490
- fileName: f.fileName,
1491
- uploaded: f.uploaded,
1492
- markers: f.markers,
1493
- description: f.description,
1494
- sizeInBytes: f.sizeInBytes,
1495
- url: `${this._fileUploadUrl}/${f.recordName}/${f.fileName}`,
1496
- })),
1497
- totalCount: count,
1498
- };
1499
- });
1500
- }
1501
- addFileRecord(recordName, fileName, publisherId, subjectId, sizeInBytes, description, markers) {
1502
- return __awaiter(this, void 0, void 0, function* () {
1503
- if (this._files.has(fileName)) {
1504
- return {
1505
- success: false,
1506
- errorCode: 'file_already_exists',
1507
- errorMessage: 'The file already exists in the store.',
1508
- };
1509
- }
1510
- let file = {
1511
- fileName: fileName,
1512
- recordName: recordName,
1513
- publisherId,
1514
- subjectId,
1515
- sizeInBytes,
1516
- description,
1517
- markers,
1518
- uploaded: false,
1354
+ success: false,
1355
+ errorCode: 'unacceptable_url',
1356
+ errorMessage: 'The URL does not match an expected format.',
1519
1357
  };
1520
- this._files.set(fileName, file);
1358
+ }
1359
+ return {
1360
+ success: false,
1361
+ errorCode: 'unacceptable_url',
1362
+ errorMessage: 'The URL does not match an expected format.',
1363
+ };
1364
+ }
1365
+ async getFileRecord(recordName, fileName) {
1366
+ let file = this._files.get(fileName);
1367
+ if (file) {
1521
1368
  return {
1522
1369
  success: true,
1370
+ fileName: file.fileName,
1371
+ recordName: file.recordName,
1372
+ publisherId: file.publisherId,
1373
+ subjectId: file.subjectId,
1374
+ sizeInBytes: file.sizeInBytes,
1375
+ uploaded: file.uploaded,
1376
+ description: file.description,
1377
+ url: `${this._fileUploadUrl}/${file.recordName}/${file.fileName}`,
1378
+ markers: file.markers,
1523
1379
  };
1524
- });
1525
- }
1526
- updateFileRecord(recordName, fileName, markers) {
1527
- return __awaiter(this, void 0, void 0, function* () {
1528
- if (!this._files.has(fileName)) {
1529
- return {
1530
- success: false,
1531
- errorCode: 'file_not_found',
1532
- errorMessage: 'The file was not found in the store.',
1533
- };
1534
- }
1535
- let file = this._files.get(fileName);
1536
- this._files.set(fileName, Object.assign(Object.assign({}, file), { markers: markers.slice() }));
1380
+ }
1381
+ else {
1537
1382
  return {
1538
- success: true,
1383
+ success: false,
1384
+ errorCode: 'file_not_found',
1385
+ errorMessage: 'The file was not found in the store.',
1539
1386
  };
1540
- });
1387
+ }
1541
1388
  }
1542
- setFileRecordAsUploaded(recordName, fileName) {
1543
- return __awaiter(this, void 0, void 0, function* () {
1544
- let file = this._files.get(fileName);
1545
- if (!file) {
1546
- return {
1547
- success: false,
1548
- errorCode: 'file_not_found',
1549
- errorMessage: 'The file was not found in the store.',
1550
- };
1551
- }
1552
- file.uploaded = true;
1553
- return {
1554
- success: true,
1555
- };
1556
- });
1389
+ async listUploadedFiles(recordName, fileName) {
1390
+ let files = sortBy([...this._files.values()].filter((f) => f.recordName === recordName && f.uploaded), (f) => f.fileName);
1391
+ const count = files.length;
1392
+ if (fileName) {
1393
+ files = files.filter((f) => f.fileName > fileName);
1394
+ }
1395
+ return {
1396
+ success: true,
1397
+ files: files.slice(0, 10).map((f) => ({
1398
+ fileName: f.fileName,
1399
+ uploaded: f.uploaded,
1400
+ markers: f.markers,
1401
+ description: f.description,
1402
+ sizeInBytes: f.sizeInBytes,
1403
+ url: `${this._fileUploadUrl}/${f.recordName}/${f.fileName}`,
1404
+ })),
1405
+ totalCount: count,
1406
+ };
1557
1407
  }
1558
- eraseFileRecord(recordName, fileName) {
1559
- return __awaiter(this, void 0, void 0, function* () {
1560
- const deleted = this._files.delete(fileName);
1561
- if (!deleted) {
1562
- return {
1563
- success: false,
1564
- errorCode: 'file_not_found',
1565
- errorMessage: 'The file was not found in the store.',
1566
- };
1567
- }
1408
+ async addFileRecord(recordName, fileName, publisherId, subjectId, sizeInBytes, description, markers) {
1409
+ if (this._files.has(fileName)) {
1568
1410
  return {
1569
- success: true,
1411
+ success: false,
1412
+ errorCode: 'file_already_exists',
1413
+ errorMessage: 'The file already exists in the store.',
1570
1414
  };
1571
- });
1572
- }
1573
- getAllowedUploadHeaders() {
1574
- return ['record-name', 'content-type'];
1575
- }
1576
- addEventCount(recordName, eventName, count) {
1577
- return __awaiter(this, void 0, void 0, function* () {
1578
- const record = this._getEventRecord(recordName);
1579
- if (record.has(eventName)) {
1580
- let data = record.get(eventName);
1581
- data.count += count;
1582
- }
1583
- else {
1584
- record.set(eventName, {
1585
- count: count,
1586
- });
1587
- }
1415
+ }
1416
+ let file = {
1417
+ fileName: fileName,
1418
+ recordName: recordName,
1419
+ publisherId,
1420
+ subjectId,
1421
+ sizeInBytes,
1422
+ description,
1423
+ markers,
1424
+ uploaded: false,
1425
+ };
1426
+ this._files.set(fileName, file);
1427
+ return {
1428
+ success: true,
1429
+ };
1430
+ }
1431
+ async updateFileRecord(recordName, fileName, markers) {
1432
+ if (!this._files.has(fileName)) {
1588
1433
  return {
1589
- success: true,
1434
+ success: false,
1435
+ errorCode: 'file_not_found',
1436
+ errorMessage: 'The file was not found in the store.',
1590
1437
  };
1591
- });
1592
- }
1593
- getEventCount(recordName, eventName) {
1594
- return __awaiter(this, void 0, void 0, function* () {
1595
- const record = this._getEventRecord(recordName);
1596
- const e = record.has(eventName)
1597
- ? record.get(eventName)
1598
- : {
1599
- count: 0,
1600
- };
1438
+ }
1439
+ let file = this._files.get(fileName);
1440
+ this._files.set(fileName, {
1441
+ ...file,
1442
+ markers: markers.slice(),
1443
+ });
1444
+ return {
1445
+ success: true,
1446
+ };
1447
+ }
1448
+ async setFileRecordAsUploaded(recordName, fileName) {
1449
+ let file = this._files.get(fileName);
1450
+ if (!file) {
1601
1451
  return {
1602
- success: true,
1603
- count: e.count,
1604
- markers: e.markers,
1452
+ success: false,
1453
+ errorCode: 'file_not_found',
1454
+ errorMessage: 'The file was not found in the store.',
1605
1455
  };
1606
- });
1607
- }
1608
- updateEvent(recordName, eventName, updates) {
1609
- return __awaiter(this, void 0, void 0, function* () {
1610
- const record = this._getEventRecord(recordName);
1611
- const e = record.has(eventName)
1612
- ? record.get(eventName)
1613
- : {
1614
- count: 0,
1615
- };
1616
- record.set(eventName, Object.assign(Object.assign({}, e), updates));
1456
+ }
1457
+ file.uploaded = true;
1458
+ return {
1459
+ success: true,
1460
+ };
1461
+ }
1462
+ async eraseFileRecord(recordName, fileName) {
1463
+ const deleted = this._files.delete(fileName);
1464
+ if (!deleted) {
1617
1465
  return {
1618
- success: true,
1466
+ success: false,
1467
+ errorCode: 'file_not_found',
1468
+ errorMessage: 'The file was not found in the store.',
1619
1469
  };
1620
- });
1470
+ }
1471
+ return {
1472
+ success: true,
1473
+ };
1621
1474
  }
1622
- listEvents(recordName, eventName) {
1623
- return __awaiter(this, void 0, void 0, function* () {
1624
- const record = this._getEventRecord(recordName);
1625
- const totalCount = record.size;
1626
- let events = sortBy([...record.entries()], ([name, data]) => name);
1627
- if (eventName) {
1628
- events = events.filter(([name, data]) => name > eventName);
1629
- }
1630
- return {
1631
- success: true,
1632
- events: events.slice(0, 10).map(([name, data]) => ({
1633
- eventName: name,
1634
- count: data.count,
1635
- markers: data.markers,
1636
- })),
1637
- totalCount,
1475
+ getAllowedUploadHeaders() {
1476
+ return ['record-name', 'content-type'];
1477
+ }
1478
+ async addEventCount(recordName, eventName, count) {
1479
+ const record = this._getEventRecord(recordName);
1480
+ if (record.has(eventName)) {
1481
+ let data = record.get(eventName);
1482
+ data.count += count;
1483
+ }
1484
+ else {
1485
+ record.set(eventName, {
1486
+ count: count,
1487
+ });
1488
+ }
1489
+ return {
1490
+ success: true,
1491
+ };
1492
+ }
1493
+ async getEventCount(recordName, eventName) {
1494
+ const record = this._getEventRecord(recordName);
1495
+ const e = record.has(eventName)
1496
+ ? record.get(eventName)
1497
+ : {
1498
+ count: 0,
1638
1499
  };
1639
- });
1500
+ return {
1501
+ success: true,
1502
+ count: e.count,
1503
+ markers: e.markers,
1504
+ };
1505
+ }
1506
+ async updateEvent(recordName, eventName, updates) {
1507
+ const record = this._getEventRecord(recordName);
1508
+ const e = record.has(eventName)
1509
+ ? record.get(eventName)
1510
+ : {
1511
+ count: 0,
1512
+ };
1513
+ record.set(eventName, {
1514
+ ...e,
1515
+ ...updates,
1516
+ });
1517
+ return {
1518
+ success: true,
1519
+ };
1520
+ }
1521
+ async listEvents(recordName, eventName) {
1522
+ const record = this._getEventRecord(recordName);
1523
+ const totalCount = record.size;
1524
+ let events = sortBy([...record.entries()], ([name, data]) => name);
1525
+ if (eventName) {
1526
+ events = events.filter(([name, data]) => name > eventName);
1527
+ }
1528
+ return {
1529
+ success: true,
1530
+ events: events.slice(0, 10).map(([name, data]) => ({
1531
+ eventName: name,
1532
+ count: data.count,
1533
+ markers: data.markers,
1534
+ })),
1535
+ totalCount,
1536
+ };
1640
1537
  }
1641
1538
  _getEventRecord(recordName) {
1642
1539
  let record = this._eventBuckets.get(recordName);
@@ -1646,140 +1543,129 @@ export class MemoryStore {
1646
1543
  }
1647
1544
  return record;
1648
1545
  }
1649
- _getUserPrivacyFeatures(userId) {
1650
- return __awaiter(this, void 0, void 0, function* () {
1651
- const user = yield this.findUser(userId);
1652
- if (user === null || user === void 0 ? void 0 : user.privacyFeatures) {
1653
- return Object.assign(Object.assign({}, user.privacyFeatures), { userRole: user === null || user === void 0 ? void 0 : user.role });
1654
- }
1546
+ async _getUserPrivacyFeatures(userId) {
1547
+ const user = await this.findUser(userId);
1548
+ if (user === null || user === void 0 ? void 0 : user.privacyFeatures) {
1655
1549
  return {
1656
- publishData: true,
1657
- allowPublicData: true,
1658
- allowAI: true,
1659
- allowPublicInsts: true,
1550
+ ...user.privacyFeatures,
1660
1551
  userRole: user === null || user === void 0 ? void 0 : user.role,
1661
1552
  };
1662
- });
1663
- }
1664
- listRolesForUser(recordName, userId) {
1665
- return __awaiter(this, void 0, void 0, function* () {
1666
- return this._getRolesForEntity(recordName, userId);
1667
- });
1668
- }
1669
- listRolesForInst(recordName, inst) {
1670
- return __awaiter(this, void 0, void 0, function* () {
1671
- return this._getRolesForEntity(recordName, inst);
1672
- });
1673
- }
1674
- listAssignmentsForRole(recordName, role) {
1675
- return __awaiter(this, void 0, void 0, function* () {
1676
- let record = this.roles[recordName];
1677
- let assignedRoles = this.roleAssignments[recordName];
1678
- let assignments = [];
1679
- for (let id in record) {
1680
- if (record[id].has(role)) {
1681
- assignments.push({
1682
- type: 'user',
1683
- userId: id,
1684
- role: {
1685
- role,
1686
- expireTimeMs: null,
1687
- },
1688
- });
1689
- }
1553
+ }
1554
+ return {
1555
+ publishData: true,
1556
+ allowPublicData: true,
1557
+ allowAI: true,
1558
+ allowPublicInsts: true,
1559
+ userRole: user === null || user === void 0 ? void 0 : user.role,
1560
+ };
1561
+ }
1562
+ async listRolesForUser(recordName, userId) {
1563
+ return this._getRolesForEntity(recordName, userId);
1564
+ }
1565
+ async listRolesForInst(recordName, inst) {
1566
+ return this._getRolesForEntity(recordName, inst);
1567
+ }
1568
+ async listAssignmentsForRole(recordName, role) {
1569
+ let record = this.roles[recordName];
1570
+ let assignedRoles = this.roleAssignments[recordName];
1571
+ let assignments = [];
1572
+ for (let id in record) {
1573
+ if (record[id].has(role)) {
1574
+ assignments.push({
1575
+ type: 'user',
1576
+ userId: id,
1577
+ role: {
1578
+ role,
1579
+ expireTimeMs: null,
1580
+ },
1581
+ });
1690
1582
  }
1691
- for (let id in assignedRoles) {
1692
- let roles = assignedRoles[id];
1693
- let assignment = roles.find((r) => r.role === role);
1694
- if (assignment) {
1695
- assignments.push({
1696
- type: 'user',
1697
- userId: id,
1698
- role: assignment,
1699
- });
1700
- }
1583
+ }
1584
+ for (let id in assignedRoles) {
1585
+ let roles = assignedRoles[id];
1586
+ let assignment = roles.find((r) => r.role === role);
1587
+ if (assignment) {
1588
+ assignments.push({
1589
+ type: 'user',
1590
+ userId: id,
1591
+ role: assignment,
1592
+ });
1701
1593
  }
1702
- return {
1703
- assignments,
1704
- totalCount: assignments.length,
1705
- };
1706
- });
1707
- }
1708
- listAssignments(recordName, startingRole) {
1709
- return __awaiter(this, void 0, void 0, function* () {
1710
- let record = this.roles[recordName];
1711
- let assignedRoles = this.roleAssignments[recordName];
1712
- let totalCount = 0;
1713
- let assignments = [];
1714
- for (let id in record) {
1715
- const roles = record[id];
1716
- for (let role of roles) {
1717
- assignments.push({
1718
- type: 'user',
1719
- userId: id,
1720
- role: {
1721
- role,
1722
- expireTimeMs: null,
1723
- },
1724
- });
1725
- totalCount += 1;
1726
- }
1727
- }
1728
- for (let id in assignedRoles) {
1729
- let roles = assignedRoles[id];
1730
- for (let role of roles) {
1731
- assignments.push({
1732
- type: 'user',
1733
- userId: id,
1594
+ }
1595
+ return {
1596
+ assignments,
1597
+ totalCount: assignments.length,
1598
+ };
1599
+ }
1600
+ async listAssignments(recordName, startingRole) {
1601
+ let record = this.roles[recordName];
1602
+ let assignedRoles = this.roleAssignments[recordName];
1603
+ let totalCount = 0;
1604
+ let assignments = [];
1605
+ for (let id in record) {
1606
+ const roles = record[id];
1607
+ for (let role of roles) {
1608
+ assignments.push({
1609
+ type: 'user',
1610
+ userId: id,
1611
+ role: {
1734
1612
  role,
1735
- });
1736
- totalCount += 1;
1737
- }
1613
+ expireTimeMs: null,
1614
+ },
1615
+ });
1616
+ totalCount += 1;
1738
1617
  }
1739
- assignments = sortBy(assignments, (a) => a.role.role, (a) => { var _a; return (_a = a.userId) !== null && _a !== void 0 ? _a : a.inst; });
1740
- if (startingRole) {
1741
- assignments = assignments.filter((a) => a.role.role > startingRole);
1618
+ }
1619
+ for (let id in assignedRoles) {
1620
+ let roles = assignedRoles[id];
1621
+ for (let role of roles) {
1622
+ assignments.push({
1623
+ type: 'user',
1624
+ userId: id,
1625
+ role,
1626
+ });
1627
+ totalCount += 1;
1742
1628
  }
1743
- return {
1744
- assignments: assignments.slice(0, 10),
1745
- totalCount: totalCount,
1746
- };
1747
- });
1629
+ }
1630
+ assignments = sortBy(assignments, (a) => a.role.role, (a) => { var _a; return (_a = a.userId) !== null && _a !== void 0 ? _a : a.inst; });
1631
+ if (startingRole) {
1632
+ assignments = assignments.filter((a) => a.role.role > startingRole);
1633
+ }
1634
+ return {
1635
+ assignments: assignments.slice(0, 10),
1636
+ totalCount: totalCount,
1637
+ };
1748
1638
  }
1749
- assignSubjectRole(recordName, subjectId, type, role) {
1639
+ async assignSubjectRole(recordName, subjectId, type, role) {
1750
1640
  var _a;
1751
- return __awaiter(this, void 0, void 0, function* () {
1752
- if (!this.roleAssignments[recordName]) {
1753
- this.roleAssignments[recordName] = {};
1754
- }
1755
- const roles = (_a = this.roleAssignments[recordName][subjectId]) !== null && _a !== void 0 ? _a : [];
1756
- const filtered = roles.filter((r) => r.role !== role.role ||
1757
- getExpireTime(r.expireTimeMs) <= role.expireTimeMs);
1758
- this.roleAssignments[recordName][subjectId] = [
1759
- ...filtered,
1760
- {
1761
- role: role.role,
1762
- expireTimeMs: role.expireTimeMs === Infinity ? null : role.expireTimeMs,
1763
- },
1764
- ];
1765
- return {
1766
- success: true,
1767
- };
1768
- });
1641
+ if (!this.roleAssignments[recordName]) {
1642
+ this.roleAssignments[recordName] = {};
1643
+ }
1644
+ const roles = (_a = this.roleAssignments[recordName][subjectId]) !== null && _a !== void 0 ? _a : [];
1645
+ const filtered = roles.filter((r) => r.role !== role.role ||
1646
+ getExpireTime(r.expireTimeMs) <= role.expireTimeMs);
1647
+ this.roleAssignments[recordName][subjectId] = [
1648
+ ...filtered,
1649
+ {
1650
+ role: role.role,
1651
+ expireTimeMs: role.expireTimeMs === Infinity ? null : role.expireTimeMs,
1652
+ },
1653
+ ];
1654
+ return {
1655
+ success: true,
1656
+ };
1769
1657
  }
1770
- revokeSubjectRole(recordName, subjectId, type, role) {
1658
+ async revokeSubjectRole(recordName, subjectId, type, role) {
1771
1659
  var _a;
1772
- return __awaiter(this, void 0, void 0, function* () {
1773
- if (!this.roleAssignments[recordName]) {
1774
- this.roleAssignments[recordName] = {};
1775
- }
1776
- const roles = (_a = this.roleAssignments[recordName][subjectId]) !== null && _a !== void 0 ? _a : [];
1777
- const filtered = roles.filter((r) => r.role !== role);
1778
- this.roleAssignments[recordName][subjectId] = filtered;
1779
- return {
1780
- success: true,
1781
- };
1782
- });
1660
+ if (!this.roleAssignments[recordName]) {
1661
+ this.roleAssignments[recordName] = {};
1662
+ }
1663
+ const roles = (_a = this.roleAssignments[recordName][subjectId]) !== null && _a !== void 0 ? _a : [];
1664
+ const filtered = roles.filter((r) => r.role !== role);
1665
+ this.roleAssignments[recordName][subjectId] = filtered;
1666
+ return {
1667
+ success: true,
1668
+ };
1783
1669
  }
1784
1670
  _getRolesForEntity(recordName, id) {
1785
1671
  var _a, _b, _c, _d;
@@ -1793,309 +1679,370 @@ export class MemoryStore {
1793
1679
  ...assignments.filter((a) => getExpireTime(a.expireTimeMs) > Date.now()),
1794
1680
  ];
1795
1681
  }
1796
- getSubscriptionDataMetricsByRecordName(recordName) {
1797
- return __awaiter(this, void 0, void 0, function* () {
1798
- const info = yield this._getSubscriptionInfo(recordName);
1799
- const records = yield this._listRecordsForSubscription(recordName);
1800
- let totalItems = 0;
1801
- for (let record of records) {
1802
- let bucket = this._dataBuckets.get(record.name);
1803
- if (!bucket) {
1804
- continue;
1805
- }
1806
- totalItems += bucket.size;
1682
+ async getSubscriptionDataMetricsByRecordName(recordName) {
1683
+ const info = await this._getSubscriptionInfo(recordName);
1684
+ const records = await this._listRecordsForSubscription(recordName);
1685
+ let totalItems = 0;
1686
+ for (let record of records) {
1687
+ let bucket = this._dataBuckets.get(record.name);
1688
+ if (!bucket) {
1689
+ continue;
1807
1690
  }
1808
- return Object.assign(Object.assign({}, info), { totalItems });
1809
- });
1810
- }
1811
- getSubscriptionFileMetricsByRecordName(recordName) {
1812
- return __awaiter(this, void 0, void 0, function* () {
1813
- const info = yield this._getSubscriptionInfo(recordName);
1814
- const records = yield this._listRecordsForSubscription(recordName);
1815
- let totalFiles = 0;
1816
- let totalBytesStored = 0;
1817
- let totalBytesReserved = 0;
1818
- for (let record of records) {
1819
- let files = [...this.files.values()].filter((f) => f.recordName === record.name);
1820
- for (let file of files) {
1821
- totalFiles++;
1822
- totalBytesReserved += file.sizeInBytes;
1823
- if (file.uploaded) {
1824
- totalBytesStored += file.sizeInBytes;
1825
- }
1826
- }
1827
- }
1828
- return Object.assign(Object.assign({}, info), { totalFiles, totalFileBytesReserved: totalBytesReserved });
1829
- });
1830
- }
1831
- getSubscriptionEventMetricsByRecordName(recordName) {
1832
- return __awaiter(this, void 0, void 0, function* () {
1833
- const info = yield this._getSubscriptionInfo(recordName);
1834
- const records = yield this._listRecordsForSubscription(recordName);
1835
- let totalEventNames = 0;
1836
- for (let record of records) {
1837
- let bucket = this._eventBuckets.get(record.name);
1838
- if (!bucket) {
1839
- continue;
1840
- }
1841
- totalEventNames += bucket.size;
1842
- }
1843
- return Object.assign(Object.assign({}, info), { totalEventNames });
1844
- });
1845
- }
1846
- getSubscriptionRecordMetrics(filter) {
1847
- return __awaiter(this, void 0, void 0, function* () {
1848
- const metrics = yield this._getSubscriptionMetrics(filter);
1849
- const totalRecords = yield this.countRecords(filter);
1850
- return Object.assign(Object.assign({}, metrics), { totalRecords });
1851
- });
1852
- }
1853
- getSubscriptionAiChatMetrics(filter) {
1854
- return __awaiter(this, void 0, void 0, function* () {
1855
- const info = yield this._getSubscriptionMetrics(filter);
1856
- const metrics = filter.ownerId
1857
- ? this._aiChatMetrics.filter((m) => m.userId === filter.ownerId &&
1858
- (!info.currentPeriodStartMs ||
1859
- (m.createdAtMs >= info.currentPeriodStartMs &&
1860
- m.createdAtMs < info.currentPeriodEndMs)))
1861
- : this._aiChatMetrics.filter((m) => m.studioId === filter.studioId &&
1862
- (!info.currentPeriodStartMs ||
1863
- (m.createdAtMs >= info.currentPeriodStartMs &&
1864
- m.createdAtMs < info.currentPeriodEndMs)));
1865
- let totalTokens = 0;
1866
- for (let m of metrics) {
1867
- totalTokens += m.tokens;
1868
- }
1869
- return Object.assign(Object.assign({}, info), { totalTokensInCurrentPeriod: totalTokens });
1870
- });
1871
- }
1872
- getSubscriptionInstMetrics(filter) {
1873
- return __awaiter(this, void 0, void 0, function* () {
1874
- const info = yield this._getSubscriptionMetrics(filter);
1875
- let totalInsts = 0;
1876
- for (let [recordName, insts] of this._instRecords) {
1877
- let r = this._records.find((r) => r.name === recordName);
1878
- if (!r) {
1879
- continue;
1880
- }
1881
- else if (r.ownerId === filter.ownerId ||
1882
- r.studioId === filter.studioId) {
1883
- totalInsts += insts.size;
1691
+ totalItems += bucket.size;
1692
+ }
1693
+ return {
1694
+ ...info,
1695
+ totalItems,
1696
+ };
1697
+ }
1698
+ async getSubscriptionFileMetricsByRecordName(recordName) {
1699
+ const info = await this._getSubscriptionInfo(recordName);
1700
+ const records = await this._listRecordsForSubscription(recordName);
1701
+ let totalFiles = 0;
1702
+ let totalBytesStored = 0;
1703
+ let totalBytesReserved = 0;
1704
+ for (let record of records) {
1705
+ let files = [...this.files.values()].filter((f) => f.recordName === record.name);
1706
+ for (let file of files) {
1707
+ totalFiles++;
1708
+ totalBytesReserved += file.sizeInBytes;
1709
+ if (file.uploaded) {
1710
+ totalBytesStored += file.sizeInBytes;
1884
1711
  }
1885
1712
  }
1886
- return Object.assign(Object.assign({}, info), { totalInsts });
1887
- });
1888
- }
1889
- getSubscriptionInstMetricsByRecordName(recordName) {
1890
- return __awaiter(this, void 0, void 0, function* () {
1891
- const info = yield this._getSubscriptionInfo(recordName);
1892
- let totalInsts = 0;
1893
- for (let [recordName, insts] of this._instRecords) {
1894
- let r = this._records.find((r) => r.name === recordName);
1895
- if (!r) {
1896
- continue;
1897
- }
1898
- else if (r.ownerId === info.ownerId ||
1899
- r.studioId === info.studioId) {
1900
- totalInsts += insts.size;
1901
- }
1713
+ }
1714
+ return {
1715
+ ...info,
1716
+ totalFiles,
1717
+ totalFileBytesReserved: totalBytesReserved,
1718
+ };
1719
+ }
1720
+ async getSubscriptionEventMetricsByRecordName(recordName) {
1721
+ const info = await this._getSubscriptionInfo(recordName);
1722
+ const records = await this._listRecordsForSubscription(recordName);
1723
+ let totalEventNames = 0;
1724
+ for (let record of records) {
1725
+ let bucket = this._eventBuckets.get(record.name);
1726
+ if (!bucket) {
1727
+ continue;
1728
+ }
1729
+ totalEventNames += bucket.size;
1730
+ }
1731
+ return {
1732
+ ...info,
1733
+ totalEventNames,
1734
+ };
1735
+ }
1736
+ async getSubscriptionRecordMetrics(filter) {
1737
+ const metrics = await this._getSubscriptionMetrics(filter);
1738
+ const totalRecords = await this.countRecords(filter);
1739
+ return {
1740
+ ...metrics,
1741
+ totalRecords,
1742
+ };
1743
+ }
1744
+ async getSubscriptionAiChatMetrics(filter) {
1745
+ const info = await this._getSubscriptionMetrics(filter);
1746
+ const metrics = filter.ownerId
1747
+ ? this._aiChatMetrics.filter((m) => m.userId === filter.ownerId &&
1748
+ (!info.currentPeriodStartMs ||
1749
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1750
+ m.createdAtMs < info.currentPeriodEndMs)))
1751
+ : this._aiChatMetrics.filter((m) => m.studioId === filter.studioId &&
1752
+ (!info.currentPeriodStartMs ||
1753
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1754
+ m.createdAtMs < info.currentPeriodEndMs)));
1755
+ let totalTokens = 0;
1756
+ for (let m of metrics) {
1757
+ totalTokens += m.tokens;
1758
+ }
1759
+ return {
1760
+ ...info,
1761
+ totalTokensInCurrentPeriod: totalTokens,
1762
+ };
1763
+ }
1764
+ async getSubscriptionInstMetrics(filter) {
1765
+ const info = await this._getSubscriptionMetrics(filter);
1766
+ let totalInsts = 0;
1767
+ for (let [recordName, insts] of this._instRecords) {
1768
+ let r = this._records.find((r) => r.name === recordName);
1769
+ if (!r) {
1770
+ continue;
1902
1771
  }
1903
- return Object.assign(Object.assign({}, info), { totalInsts });
1904
- });
1905
- }
1906
- getSubscriptionInfoForRecord(recordName) {
1907
- return __awaiter(this, void 0, void 0, function* () {
1908
- return yield this._getSubscriptionInfo(recordName);
1909
- });
1910
- }
1911
- listRecordsForSubscriptionByRecordName(recordName) {
1912
- return __awaiter(this, void 0, void 0, function* () {
1913
- return yield this._listRecordsForSubscription(recordName);
1914
- });
1915
- }
1916
- getSubscriptionAiSloydMetrics(filter) {
1917
- return __awaiter(this, void 0, void 0, function* () {
1918
- const info = yield this._getSubscriptionMetrics(filter);
1919
- const metrics = filter.ownerId
1920
- ? this._aiSloydMetrics.filter((m) => m.userId === filter.ownerId &&
1921
- (!info.currentPeriodStartMs ||
1922
- (m.createdAtMs >= info.currentPeriodStartMs &&
1923
- m.createdAtMs < info.currentPeriodEndMs)))
1924
- : this._aiSloydMetrics.filter((m) => m.studioId === filter.studioId &&
1925
- (!info.currentPeriodStartMs ||
1926
- (m.createdAtMs >= info.currentPeriodStartMs &&
1927
- m.createdAtMs < info.currentPeriodEndMs)));
1928
- let totalModels = 0;
1929
- for (let m of metrics) {
1930
- totalModels += m.modelsCreated;
1772
+ else if (r.ownerId === filter.ownerId ||
1773
+ r.studioId === filter.studioId) {
1774
+ totalInsts += insts.size;
1931
1775
  }
1932
- return Object.assign(Object.assign({}, info), { totalModelsInCurrentPeriod: totalModels });
1933
- });
1934
- }
1935
- getSubscriptionAiSloydMetricsByRecordName(recordName) {
1936
- return __awaiter(this, void 0, void 0, function* () {
1937
- const info = yield this._getSubscriptionInfo(recordName);
1938
- let totalModels = 0;
1939
- for (let metric of this._aiSloydMetrics) {
1940
- if (metric.userId === info.ownerId ||
1941
- metric.studioId === info.studioId) {
1942
- totalModels += metric.modelsCreated;
1943
- }
1776
+ }
1777
+ return {
1778
+ ...info,
1779
+ totalInsts,
1780
+ };
1781
+ }
1782
+ async getSubscriptionInstMetricsByRecordName(recordName) {
1783
+ const info = await this._getSubscriptionInfo(recordName);
1784
+ let totalInsts = 0;
1785
+ for (let [recordName, insts] of this._instRecords) {
1786
+ let r = this._records.find((r) => r.name === recordName);
1787
+ if (!r) {
1788
+ continue;
1944
1789
  }
1945
- return Object.assign(Object.assign({}, info), { totalModelsInCurrentPeriod: totalModels });
1946
- });
1947
- }
1948
- recordSloydMetrics(metrics) {
1949
- return __awaiter(this, void 0, void 0, function* () {
1950
- this._aiSloydMetrics.push(metrics);
1951
- });
1952
- }
1953
- getSubscriptionAiOpenAIRealtimeMetrics(filter) {
1954
- return __awaiter(this, void 0, void 0, function* () {
1955
- const info = yield this._getSubscriptionMetrics(filter);
1956
- const metrics = filter.ownerId
1957
- ? this._aiRealtimeMetrics.filter((m) => m.userId === filter.ownerId &&
1958
- (!info.currentPeriodStartMs ||
1959
- (m.createdAtMs >= info.currentPeriodStartMs &&
1960
- m.createdAtMs < info.currentPeriodEndMs)))
1961
- : this._aiRealtimeMetrics.filter((m) => m.studioId === filter.studioId &&
1962
- (!info.currentPeriodStartMs ||
1963
- (m.createdAtMs >= info.currentPeriodStartMs &&
1964
- m.createdAtMs < info.currentPeriodEndMs)));
1965
- let totalModels = metrics.length;
1966
- return Object.assign(Object.assign({}, info), { totalSessionsInCurrentPeriod: totalModels });
1967
- });
1968
- }
1969
- recordOpenAIRealtimeMetrics(metrics) {
1970
- return __awaiter(this, void 0, void 0, function* () {
1971
- this._aiRealtimeMetrics.push(metrics);
1972
- });
1973
- }
1974
- recordChatMetrics(metrics) {
1975
- return __awaiter(this, void 0, void 0, function* () {
1976
- this._aiChatMetrics.push(metrics);
1977
- });
1978
- }
1979
- getSubscriptionAiImageMetrics(filter) {
1980
- return __awaiter(this, void 0, void 0, function* () {
1981
- const info = yield this._getSubscriptionMetrics(filter);
1982
- const metrics = filter.ownerId
1983
- ? this._aiImageMetrics.filter((m) => m.userId === filter.ownerId &&
1984
- (!info.currentPeriodStartMs ||
1985
- (m.createdAtMs >= info.currentPeriodStartMs &&
1986
- m.createdAtMs < info.currentPeriodEndMs)))
1987
- : this._aiImageMetrics.filter((m) => m.studioId === filter.studioId &&
1988
- (!info.currentPeriodStartMs ||
1989
- (m.createdAtMs >= info.currentPeriodStartMs &&
1990
- m.createdAtMs < info.currentPeriodEndMs)));
1991
- let totalPixels = 0;
1992
- for (let m of metrics) {
1993
- totalPixels += m.squarePixels;
1790
+ else if (r.ownerId === info.ownerId ||
1791
+ r.studioId === info.studioId) {
1792
+ totalInsts += insts.size;
1994
1793
  }
1995
- return Object.assign(Object.assign({}, info), { totalSquarePixelsInCurrentPeriod: totalPixels });
1996
- });
1997
- }
1998
- recordImageMetrics(metrics) {
1999
- return __awaiter(this, void 0, void 0, function* () {
2000
- this._aiImageMetrics.push(metrics);
2001
- });
2002
- }
2003
- getSubscriptionAiSkyboxMetrics(filter) {
2004
- return __awaiter(this, void 0, void 0, function* () {
2005
- const info = yield this._getSubscriptionMetrics(filter);
2006
- const metrics = filter.ownerId
2007
- ? this._aiSkyboxMetrics.filter((m) => m.userId === filter.ownerId &&
2008
- (!info.currentPeriodStartMs ||
2009
- (m.createdAtMs >= info.currentPeriodStartMs &&
2010
- m.createdAtMs < info.currentPeriodEndMs)))
2011
- : this._aiSkyboxMetrics.filter((m) => m.studioId === filter.studioId &&
2012
- (!info.currentPeriodStartMs ||
2013
- (m.createdAtMs >= info.currentPeriodStartMs &&
2014
- m.createdAtMs < info.currentPeriodEndMs)));
2015
- let totalSkyboxes = 0;
2016
- for (let m of metrics) {
2017
- totalSkyboxes += m.skyboxes;
1794
+ }
1795
+ return {
1796
+ ...info,
1797
+ totalInsts,
1798
+ };
1799
+ }
1800
+ async getSubscriptionInfoForRecord(recordName) {
1801
+ return await this._getSubscriptionInfo(recordName);
1802
+ }
1803
+ async listRecordsForSubscriptionByRecordName(recordName) {
1804
+ return await this._listRecordsForSubscription(recordName);
1805
+ }
1806
+ async getSubscriptionAiSloydMetrics(filter) {
1807
+ const info = await this._getSubscriptionMetrics(filter);
1808
+ const metrics = filter.ownerId
1809
+ ? this._aiSloydMetrics.filter((m) => m.userId === filter.ownerId &&
1810
+ (!info.currentPeriodStartMs ||
1811
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1812
+ m.createdAtMs < info.currentPeriodEndMs)))
1813
+ : this._aiSloydMetrics.filter((m) => m.studioId === filter.studioId &&
1814
+ (!info.currentPeriodStartMs ||
1815
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1816
+ m.createdAtMs < info.currentPeriodEndMs)));
1817
+ let totalModels = 0;
1818
+ for (let m of metrics) {
1819
+ totalModels += m.modelsCreated;
1820
+ }
1821
+ return {
1822
+ ...info,
1823
+ totalModelsInCurrentPeriod: totalModels,
1824
+ };
1825
+ }
1826
+ async getSubscriptionAiSloydMetricsByRecordName(recordName) {
1827
+ const info = await this._getSubscriptionInfo(recordName);
1828
+ let totalModels = 0;
1829
+ for (let metric of this._aiSloydMetrics) {
1830
+ if (metric.userId === info.ownerId ||
1831
+ metric.studioId === info.studioId) {
1832
+ totalModels += metric.modelsCreated;
2018
1833
  }
2019
- return Object.assign(Object.assign({}, info), { totalSkyboxesInCurrentPeriod: totalSkyboxes });
2020
- });
2021
- }
2022
- recordSkyboxMetrics(metrics) {
2023
- return __awaiter(this, void 0, void 0, function* () {
2024
- this._aiSkyboxMetrics.push(metrics);
2025
- });
2026
- }
2027
- _getSubscriptionInfo(recordName) {
2028
- return __awaiter(this, void 0, void 0, function* () {
2029
- const record = yield this.getRecordByName(recordName);
2030
- const metrics = yield this._getSubscriptionMetrics(record);
2031
- return Object.assign(Object.assign({}, metrics), { recordName: record.name });
2032
- });
2033
- }
2034
- _getSubscriptionMetrics(filter) {
1834
+ }
1835
+ return {
1836
+ ...info,
1837
+ totalModelsInCurrentPeriod: totalModels,
1838
+ };
1839
+ }
1840
+ async recordSloydMetrics(metrics) {
1841
+ this._aiSloydMetrics.push(metrics);
1842
+ }
1843
+ async getSubscriptionAiOpenAIRealtimeMetrics(filter) {
1844
+ const info = await this._getSubscriptionMetrics(filter);
1845
+ const metrics = filter.ownerId
1846
+ ? this._aiRealtimeMetrics.filter((m) => m.userId === filter.ownerId &&
1847
+ (!info.currentPeriodStartMs ||
1848
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1849
+ m.createdAtMs < info.currentPeriodEndMs)))
1850
+ : this._aiRealtimeMetrics.filter((m) => m.studioId === filter.studioId &&
1851
+ (!info.currentPeriodStartMs ||
1852
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1853
+ m.createdAtMs < info.currentPeriodEndMs)));
1854
+ let totalModels = metrics.length;
1855
+ return {
1856
+ ...info,
1857
+ totalSessionsInCurrentPeriod: totalModels,
1858
+ };
1859
+ }
1860
+ async recordOpenAIRealtimeMetrics(metrics) {
1861
+ this._aiRealtimeMetrics.push(metrics);
1862
+ }
1863
+ async recordChatMetrics(metrics) {
1864
+ this._aiChatMetrics.push(metrics);
1865
+ }
1866
+ async getSubscriptionAiImageMetrics(filter) {
1867
+ const info = await this._getSubscriptionMetrics(filter);
1868
+ const metrics = filter.ownerId
1869
+ ? this._aiImageMetrics.filter((m) => m.userId === filter.ownerId &&
1870
+ (!info.currentPeriodStartMs ||
1871
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1872
+ m.createdAtMs < info.currentPeriodEndMs)))
1873
+ : this._aiImageMetrics.filter((m) => m.studioId === filter.studioId &&
1874
+ (!info.currentPeriodStartMs ||
1875
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1876
+ m.createdAtMs < info.currentPeriodEndMs)));
1877
+ let totalPixels = 0;
1878
+ for (let m of metrics) {
1879
+ totalPixels += m.squarePixels;
1880
+ }
1881
+ return {
1882
+ ...info,
1883
+ totalSquarePixelsInCurrentPeriod: totalPixels,
1884
+ };
1885
+ }
1886
+ async recordImageMetrics(metrics) {
1887
+ this._aiImageMetrics.push(metrics);
1888
+ }
1889
+ async getSubscriptionAiSkyboxMetrics(filter) {
1890
+ const info = await this._getSubscriptionMetrics(filter);
1891
+ const metrics = filter.ownerId
1892
+ ? this._aiSkyboxMetrics.filter((m) => m.userId === filter.ownerId &&
1893
+ (!info.currentPeriodStartMs ||
1894
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1895
+ m.createdAtMs < info.currentPeriodEndMs)))
1896
+ : this._aiSkyboxMetrics.filter((m) => m.studioId === filter.studioId &&
1897
+ (!info.currentPeriodStartMs ||
1898
+ (m.createdAtMs >= info.currentPeriodStartMs &&
1899
+ m.createdAtMs < info.currentPeriodEndMs)));
1900
+ let totalSkyboxes = 0;
1901
+ for (let m of metrics) {
1902
+ totalSkyboxes += m.skyboxes;
1903
+ }
1904
+ return {
1905
+ ...info,
1906
+ totalSkyboxesInCurrentPeriod: totalSkyboxes,
1907
+ };
1908
+ }
1909
+ async recordSkyboxMetrics(metrics) {
1910
+ this._aiSkyboxMetrics.push(metrics);
1911
+ }
1912
+ async _getSubscriptionInfo(recordName) {
1913
+ const record = await this.getRecordByName(recordName);
1914
+ const metrics = await this._getSubscriptionMetrics(record);
1915
+ return {
1916
+ ...metrics,
1917
+ recordName: record.name,
1918
+ };
1919
+ }
1920
+ async _getSubscriptionMetrics(filter) {
2035
1921
  var _a;
2036
- return __awaiter(this, void 0, void 0, function* () {
2037
- const config = yield this.getSubscriptionConfiguration();
2038
- let currentPeriodStart = null;
2039
- let currentPeriodEnd = null;
2040
- if ((_a = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _a === void 0 ? void 0 : _a.defaultPeriodLength) {
2041
- const now = DateTime.utc();
2042
- const periodStart = now.minus(config.defaultFeatures.defaultPeriodLength);
2043
- currentPeriodStart = periodStart.toMillis();
2044
- currentPeriodEnd = now.toMillis();
2045
- }
2046
- let metrics = {
2047
- ownerId: filter.ownerId,
2048
- studioId: filter.studioId,
2049
- subscriptionId: null,
2050
- subscriptionStatus: null,
2051
- currentPeriodStartMs: currentPeriodStart,
2052
- currentPeriodEndMs: currentPeriodEnd,
2053
- subscriptionType: filter.ownerId ? 'user' : 'studio',
2054
- };
2055
- if (filter.ownerId) {
2056
- const user = yield this.findUser(filter.ownerId);
2057
- if (user) {
2058
- metrics.subscriptionStatus = user.subscriptionStatus;
2059
- metrics.subscriptionId = user.subscriptionId;
2060
- metrics.currentPeriodEndMs = user.subscriptionPeriodEndMs;
2061
- metrics.currentPeriodStartMs = user.subscriptionPeriodStartMs;
2062
- }
1922
+ const config = await this.getSubscriptionConfiguration();
1923
+ let currentPeriodStart = null;
1924
+ let currentPeriodEnd = null;
1925
+ if ((_a = config === null || config === void 0 ? void 0 : config.defaultFeatures) === null || _a === void 0 ? void 0 : _a.defaultPeriodLength) {
1926
+ const now = DateTime.utc();
1927
+ const periodStart = now.minus(config.defaultFeatures.defaultPeriodLength);
1928
+ currentPeriodStart = periodStart.toMillis();
1929
+ currentPeriodEnd = now.toMillis();
1930
+ }
1931
+ let metrics = {
1932
+ ownerId: filter.ownerId,
1933
+ studioId: filter.studioId,
1934
+ subscriptionId: null,
1935
+ subscriptionStatus: null,
1936
+ currentPeriodStartMs: currentPeriodStart,
1937
+ currentPeriodEndMs: currentPeriodEnd,
1938
+ subscriptionType: filter.ownerId ? 'user' : 'studio',
1939
+ };
1940
+ if (filter.ownerId) {
1941
+ const user = await this.findUser(filter.ownerId);
1942
+ if (user) {
1943
+ metrics.subscriptionStatus = user.subscriptionStatus;
1944
+ metrics.subscriptionId = user.subscriptionId;
1945
+ metrics.currentPeriodEndMs = user.subscriptionPeriodEndMs;
1946
+ metrics.currentPeriodStartMs = user.subscriptionPeriodStartMs;
2063
1947
  }
2064
- else if (filter.studioId) {
2065
- const studio = yield this.getStudioById(filter.studioId);
2066
- if (studio) {
2067
- metrics.subscriptionId = studio.subscriptionId;
2068
- metrics.subscriptionStatus = studio.subscriptionStatus;
2069
- metrics.currentPeriodEndMs = studio.subscriptionPeriodEndMs;
2070
- metrics.currentPeriodStartMs = studio.subscriptionPeriodStartMs;
2071
- }
1948
+ }
1949
+ else if (filter.studioId) {
1950
+ const studio = await this.getStudioById(filter.studioId);
1951
+ if (studio) {
1952
+ metrics.subscriptionId = studio.subscriptionId;
1953
+ metrics.subscriptionStatus = studio.subscriptionStatus;
1954
+ metrics.currentPeriodEndMs = studio.subscriptionPeriodEndMs;
1955
+ metrics.currentPeriodStartMs = studio.subscriptionPeriodStartMs;
2072
1956
  }
2073
- return metrics;
2074
- });
1957
+ }
1958
+ return metrics;
2075
1959
  }
2076
- _listRecordsForSubscription(recordName) {
2077
- return __awaiter(this, void 0, void 0, function* () {
2078
- const record = yield this.getRecordByName(recordName);
2079
- if (record.ownerId) {
2080
- return this.listRecordsByOwnerId(record.ownerId);
2081
- }
2082
- else {
2083
- return this.listRecordsByStudioId(record.studioId);
2084
- }
2085
- });
1960
+ async _listRecordsForSubscription(recordName) {
1961
+ const record = await this.getRecordByName(recordName);
1962
+ if (record.ownerId) {
1963
+ return this.listRecordsByOwnerId(record.ownerId);
1964
+ }
1965
+ else {
1966
+ return this.listRecordsByStudioId(record.studioId);
1967
+ }
2086
1968
  }
2087
- getInstByName(recordName, inst) {
2088
- return __awaiter(this, void 0, void 0, function* () {
2089
- const i = yield this._getInst(recordName, inst);
2090
- if (!i) {
2091
- return null;
2092
- }
2093
- const r = this._records.find((r) => r.name === recordName);
2094
- if (!r) {
2095
- return null;
2096
- }
2097
- const metrics = yield this.getSubscriptionInstMetrics(Object.assign({}, r));
1969
+ async getInstByName(recordName, inst) {
1970
+ const i = await this._getInst(recordName, inst);
1971
+ if (!i) {
1972
+ return null;
1973
+ }
1974
+ const r = this._records.find((r) => r.name === recordName);
1975
+ if (!r) {
1976
+ return null;
1977
+ }
1978
+ const metrics = await this.getSubscriptionInstMetrics({
1979
+ ...r,
1980
+ });
1981
+ return {
1982
+ recordName: i.recordName,
1983
+ inst: i.inst,
1984
+ markers: i.markers,
1985
+ subscriptionId: metrics.subscriptionId,
1986
+ subscriptionStatus: metrics.subscriptionStatus,
1987
+ subscriptionType: !metrics.subscriptionId
1988
+ ? undefined
1989
+ : metrics.ownerId
1990
+ ? 'user'
1991
+ : 'studio',
1992
+ };
1993
+ }
1994
+ async listInstsByRecord(recordName, startingInst) {
1995
+ if (!recordName) {
2098
1996
  return {
1997
+ success: true,
1998
+ insts: [],
1999
+ totalCount: 0,
2000
+ };
2001
+ }
2002
+ const record = await this._getInstRecord(recordName);
2003
+ if (!record) {
2004
+ return {
2005
+ success: false,
2006
+ errorCode: 'record_not_found',
2007
+ errorMessage: 'The record was not found.',
2008
+ };
2009
+ }
2010
+ let insts = [...record.values()];
2011
+ if (startingInst) {
2012
+ insts = insts.filter((i) => i.inst > startingInst);
2013
+ }
2014
+ return {
2015
+ success: true,
2016
+ insts: insts.slice(0, 10).map((i) => ({
2017
+ recordName: i.recordName,
2018
+ inst: i.inst,
2019
+ markers: i.markers,
2020
+ })),
2021
+ totalCount: insts.length,
2022
+ };
2023
+ }
2024
+ async getBranchByName(recordName, inst, branch) {
2025
+ let i = await this._getInst(recordName, inst);
2026
+ if (!i) {
2027
+ return null;
2028
+ }
2029
+ const b = i.branches.find((b) => b.branch === branch);
2030
+ if (!b) {
2031
+ return null;
2032
+ }
2033
+ const r = this._records.find((r) => r.name === recordName);
2034
+ if (!r) {
2035
+ return null;
2036
+ }
2037
+ const metrics = await this.getSubscriptionInstMetrics({
2038
+ ...r,
2039
+ });
2040
+ return {
2041
+ recordName: b.recordName,
2042
+ inst: b.inst,
2043
+ branch: b.branch,
2044
+ temporary: b.temporary,
2045
+ linkedInst: {
2099
2046
  recordName: i.recordName,
2100
2047
  inst: i.inst,
2101
2048
  markers: i.markers,
@@ -2106,237 +2053,52 @@ export class MemoryStore {
2106
2053
  : metrics.ownerId
2107
2054
  ? 'user'
2108
2055
  : 'studio',
2109
- };
2110
- });
2056
+ },
2057
+ };
2111
2058
  }
2112
- listInstsByRecord(recordName, startingInst) {
2113
- return __awaiter(this, void 0, void 0, function* () {
2114
- if (!recordName) {
2115
- return {
2116
- success: true,
2117
- insts: [],
2118
- totalCount: 0,
2119
- };
2120
- }
2121
- const record = yield this._getInstRecord(recordName);
2122
- if (!record) {
2123
- return {
2124
- success: false,
2125
- errorCode: 'record_not_found',
2126
- errorMessage: 'The record was not found.',
2127
- };
2128
- }
2129
- let insts = [...record.values()];
2130
- if (startingInst) {
2131
- insts = insts.filter((i) => i.inst > startingInst);
2132
- }
2133
- return {
2134
- success: true,
2135
- insts: insts.slice(0, 10).map((i) => ({
2136
- recordName: i.recordName,
2137
- inst: i.inst,
2138
- markers: i.markers,
2139
- })),
2140
- totalCount: insts.length,
2141
- };
2142
- });
2059
+ async saveLoadedPackage(loadedPackage) {
2060
+ this._loadedPackages.set(loadedPackage.id, { ...loadedPackage });
2143
2061
  }
2144
- getBranchByName(recordName, inst, branch) {
2145
- return __awaiter(this, void 0, void 0, function* () {
2146
- let i = yield this._getInst(recordName, inst);
2147
- if (!i) {
2148
- return null;
2149
- }
2150
- const b = i.branches.find((b) => b.branch === branch);
2151
- if (!b) {
2152
- return null;
2153
- }
2154
- const r = this._records.find((r) => r.name === recordName);
2155
- if (!r) {
2156
- return null;
2062
+ async listLoadedPackages(recordName, inst) {
2063
+ let loadedPackages = [];
2064
+ for (let [id, loadedPackage] of this._loadedPackages) {
2065
+ if (loadedPackage.recordName === recordName &&
2066
+ loadedPackage.inst === inst) {
2067
+ loadedPackages.push(loadedPackage);
2157
2068
  }
2158
- const metrics = yield this.getSubscriptionInstMetrics(Object.assign({}, r));
2159
- return {
2160
- recordName: b.recordName,
2161
- inst: b.inst,
2162
- branch: b.branch,
2163
- temporary: b.temporary,
2164
- linkedInst: {
2165
- recordName: i.recordName,
2166
- inst: i.inst,
2167
- markers: i.markers,
2168
- subscriptionId: metrics.subscriptionId,
2169
- subscriptionStatus: metrics.subscriptionStatus,
2170
- subscriptionType: !metrics.subscriptionId
2171
- ? undefined
2172
- : metrics.ownerId
2173
- ? 'user'
2174
- : 'studio',
2175
- },
2176
- };
2177
- });
2178
- }
2179
- saveInst(inst) {
2180
- return __awaiter(this, void 0, void 0, function* () {
2181
- const r = yield this._getInstRecord(inst.recordName);
2182
- if (!r) {
2183
- return {
2184
- success: false,
2185
- errorCode: 'record_not_found',
2186
- errorMessage: 'The record was not found',
2187
- };
2188
- }
2189
- let i = yield this._getInst(inst.recordName, inst.inst);
2190
- const { branches } = inst, rest = __rest(inst, ["branches"]);
2191
- let update = Object.assign(Object.assign({ branches: null }, (i !== null && i !== void 0 ? i : {
2192
- instSizeInBytes: 0,
2193
- })), rest);
2194
- if (branches) {
2195
- update.branches = branches.map((b) => {
2196
- return {
2197
- recordName: inst.recordName,
2198
- inst: inst.inst,
2199
- branch: b.branch,
2200
- temporary: b.temporary,
2201
- updates: {
2202
- updates: [],
2203
- timestamps: [],
2204
- },
2205
- archived: {
2206
- updates: [],
2207
- timestamps: [],
2208
- },
2209
- };
2210
- });
2211
- }
2212
- else if (!update.branches) {
2213
- update.branches = [];
2214
- }
2215
- r.set(inst.inst, update);
2216
- return {
2217
- success: true,
2218
- };
2219
- });
2220
- }
2221
- deleteInst(recordName, inst) {
2222
- return __awaiter(this, void 0, void 0, function* () {
2223
- const r = yield this._getInstRecord(recordName);
2224
- if (!r) {
2225
- return;
2226
- }
2227
- r.delete(inst);
2228
- });
2229
- }
2230
- saveBranch(branch) {
2231
- return __awaiter(this, void 0, void 0, function* () {
2232
- let i = yield this._getInst(branch.recordName, branch.inst);
2233
- if (!i) {
2234
- return {
2235
- success: false,
2236
- errorCode: 'inst_not_found',
2237
- errorMessage: 'The inst was not found.',
2238
- };
2239
- }
2240
- const b = i.branches.find((b) => b.branch === branch.branch);
2241
- if (!b) {
2242
- i.branches.push(Object.assign(Object.assign({}, branch), { updates: {
2243
- updates: [],
2244
- timestamps: [],
2245
- }, archived: {
2246
- updates: [],
2247
- timestamps: [],
2248
- } }));
2249
- return {
2250
- success: true,
2251
- };
2252
- }
2253
- b.temporary = branch.temporary;
2254
- return {
2255
- success: true,
2256
- };
2257
- });
2069
+ }
2070
+ return loadedPackages;
2258
2071
  }
2259
- getAllUpdates(recordName, inst, branch) {
2260
- return __awaiter(this, void 0, void 0, function* () {
2261
- const i = yield this._getInst(recordName, inst);
2262
- if (!i) {
2263
- return null;
2264
- }
2265
- const b = i.branches.find((b) => b.branch === branch);
2266
- if (!b) {
2267
- return null;
2268
- }
2269
- return {
2270
- updates: b.archived.updates.slice(),
2271
- timestamps: b.archived.timestamps.slice(),
2272
- instSizeInBytes: i.instSizeInBytes,
2273
- };
2274
- });
2072
+ async isPackageLoaded(recordName, inst, packageId) {
2073
+ var _a;
2074
+ const loaded = await this.listLoadedPackages(recordName, inst);
2075
+ return (_a = loaded.find((p) => p.packageId === packageId)) !== null && _a !== void 0 ? _a : null;
2275
2076
  }
2276
- getCurrentUpdates(recordName, inst, branch) {
2277
- return __awaiter(this, void 0, void 0, function* () {
2278
- const i = yield this._getInst(recordName, inst);
2279
- if (!i) {
2280
- return null;
2281
- }
2282
- const b = i.branches.find((b) => b.branch === branch);
2283
- if (!b) {
2284
- return null;
2285
- }
2077
+ async saveInst(inst) {
2078
+ const r = await this._getInstRecord(inst.recordName);
2079
+ if (!r) {
2286
2080
  return {
2287
- updates: b.updates.updates.slice(),
2288
- timestamps: b.updates.timestamps.slice(),
2289
- instSizeInBytes: i.instSizeInBytes,
2081
+ success: false,
2082
+ errorCode: 'record_not_found',
2083
+ errorMessage: 'The record was not found',
2290
2084
  };
2291
- });
2292
- }
2293
- getInstSize(recordName, inst) {
2294
- return __awaiter(this, void 0, void 0, function* () {
2295
- const i = yield this._getInst(recordName, inst);
2296
- if (!i) {
2297
- return null;
2298
- }
2299
- return i.instSizeInBytes;
2300
- });
2301
- }
2302
- countUpdates(recordName, inst, branch) {
2303
- return __awaiter(this, void 0, void 0, function* () {
2304
- const i = yield this._getInst(recordName, inst);
2305
- if (!i) {
2306
- return 0;
2307
- }
2308
- const b = i.branches.find((b) => b.branch === branch);
2309
- if (!b) {
2310
- return 0;
2311
- }
2312
- return b.updates.updates.length;
2313
- });
2314
- }
2315
- addUpdates(recordName, inst, branch, updates, sizeInBytes) {
2316
- return __awaiter(this, void 0, void 0, function* () {
2317
- const r = this._instRecords.get(recordName);
2318
- if (!r) {
2319
- return {
2320
- success: false,
2321
- errorCode: 'record_not_found',
2322
- branch,
2323
- };
2324
- }
2325
- const i = yield this._getInst(recordName, inst);
2326
- if (!i) {
2085
+ }
2086
+ let i = await this._getInst(inst.recordName, inst.inst);
2087
+ const { branches, ...rest } = inst;
2088
+ let update = {
2089
+ branches: null,
2090
+ ...(i !== null && i !== void 0 ? i : {
2091
+ instSizeInBytes: 0,
2092
+ }),
2093
+ ...rest,
2094
+ };
2095
+ if (branches) {
2096
+ update.branches = branches.map((b) => {
2327
2097
  return {
2328
- success: false,
2329
- errorCode: 'inst_not_found',
2330
- branch,
2331
- };
2332
- }
2333
- let b = i.branches.find((b) => b.branch === branch);
2334
- if (!b) {
2335
- b = {
2336
- branch,
2337
- inst: i.inst,
2338
- recordName: i.recordName,
2339
- temporary: false,
2098
+ recordName: inst.recordName,
2099
+ inst: inst.inst,
2100
+ branch: b.branch,
2101
+ temporary: b.temporary,
2340
2102
  updates: {
2341
2103
  updates: [],
2342
2104
  timestamps: [],
@@ -2346,114 +2108,234 @@ export class MemoryStore {
2346
2108
  timestamps: [],
2347
2109
  },
2348
2110
  };
2349
- i.branches.push(b);
2350
- }
2351
- let storedUpdates = b.updates;
2352
- const newSize = i.instSizeInBytes + sizeInBytes;
2353
- if (newSize > this.maxAllowedInstSize) {
2354
- return {
2355
- success: false,
2356
- errorCode: 'max_size_reached',
2357
- branch,
2358
- maxInstSizeInBytes: this.maxAllowedInstSize,
2359
- neededInstSizeInBytes: newSize,
2360
- };
2361
- }
2362
- i.instSizeInBytes = newSize;
2363
- storedUpdates.updates.push(...updates);
2364
- storedUpdates.timestamps.push(Date.now());
2365
- const archivedUpdates = b.archived;
2366
- archivedUpdates.updates.push(...updates);
2367
- archivedUpdates.timestamps.push(Date.now());
2111
+ });
2112
+ }
2113
+ else if (!update.branches) {
2114
+ update.branches = [];
2115
+ }
2116
+ r.set(inst.inst, update);
2117
+ return {
2118
+ success: true,
2119
+ };
2120
+ }
2121
+ async deleteInst(recordName, inst) {
2122
+ const r = await this._getInstRecord(recordName);
2123
+ if (!r) {
2124
+ return;
2125
+ }
2126
+ r.delete(inst);
2127
+ }
2128
+ async saveBranch(branch) {
2129
+ let i = await this._getInst(branch.recordName, branch.inst);
2130
+ if (!i) {
2131
+ return {
2132
+ success: false,
2133
+ errorCode: 'inst_not_found',
2134
+ errorMessage: 'The inst was not found.',
2135
+ };
2136
+ }
2137
+ const b = i.branches.find((b) => b.branch === branch.branch);
2138
+ if (!b) {
2139
+ i.branches.push({
2140
+ ...branch,
2141
+ updates: {
2142
+ updates: [],
2143
+ timestamps: [],
2144
+ },
2145
+ archived: {
2146
+ updates: [],
2147
+ timestamps: [],
2148
+ },
2149
+ });
2368
2150
  return {
2369
2151
  success: true,
2370
2152
  };
2371
- });
2153
+ }
2154
+ b.temporary = branch.temporary;
2155
+ return {
2156
+ success: true,
2157
+ };
2158
+ }
2159
+ async getAllUpdates(recordName, inst, branch) {
2160
+ const i = await this._getInst(recordName, inst);
2161
+ if (!i) {
2162
+ return null;
2163
+ }
2164
+ const b = i.branches.find((b) => b.branch === branch);
2165
+ if (!b) {
2166
+ return null;
2167
+ }
2168
+ return {
2169
+ updates: b.archived.updates.slice(),
2170
+ timestamps: b.archived.timestamps.slice(),
2171
+ instSizeInBytes: i.instSizeInBytes,
2172
+ };
2173
+ }
2174
+ async getCurrentUpdates(recordName, inst, branch) {
2175
+ const i = await this._getInst(recordName, inst);
2176
+ if (!i) {
2177
+ return null;
2178
+ }
2179
+ const b = i.branches.find((b) => b.branch === branch);
2180
+ if (!b) {
2181
+ return null;
2182
+ }
2183
+ return {
2184
+ updates: b.updates.updates.slice(),
2185
+ timestamps: b.updates.timestamps.slice(),
2186
+ instSizeInBytes: i.instSizeInBytes,
2187
+ };
2188
+ }
2189
+ async getInstSize(recordName, inst) {
2190
+ const i = await this._getInst(recordName, inst);
2191
+ if (!i) {
2192
+ return null;
2193
+ }
2194
+ return i.instSizeInBytes;
2372
2195
  }
2373
- replaceCurrentUpdates(recordName, inst, branch, updateToAdd, sizeInBytes) {
2374
- return __awaiter(this, void 0, void 0, function* () {
2375
- const r = this._instRecords.get(recordName);
2376
- if (!r) {
2377
- return {
2378
- success: false,
2379
- errorCode: 'record_not_found',
2380
- branch,
2381
- };
2382
- }
2383
- const i = yield this._getInst(recordName, inst);
2384
- if (!i) {
2385
- return {
2386
- success: false,
2387
- errorCode: 'inst_not_found',
2388
- branch,
2389
- };
2390
- }
2391
- let b = i.branches.find((b) => b.branch === branch);
2392
- if (!b) {
2393
- b = {
2394
- branch,
2395
- inst: i.inst,
2396
- recordName: i.recordName,
2397
- temporary: false,
2398
- updates: {
2399
- updates: [],
2400
- timestamps: [],
2401
- },
2402
- archived: {
2403
- updates: [],
2404
- timestamps: [],
2405
- },
2406
- };
2407
- i.branches.push(b);
2408
- }
2409
- const storedUpdates = b.updates;
2410
- storedUpdates.updates = [];
2411
- storedUpdates.timestamps = [];
2412
- return this.addUpdates(recordName, inst, branch, [updateToAdd], sizeInBytes);
2413
- });
2196
+ async countUpdates(recordName, inst, branch) {
2197
+ const i = await this._getInst(recordName, inst);
2198
+ if (!i) {
2199
+ return 0;
2200
+ }
2201
+ const b = i.branches.find((b) => b.branch === branch);
2202
+ if (!b) {
2203
+ return 0;
2204
+ }
2205
+ return b.updates.updates.length;
2414
2206
  }
2415
- deleteBranch(recordName, inst, branch) {
2416
- return __awaiter(this, void 0, void 0, function* () {
2417
- const r = this._instRecords.get(recordName);
2418
- if (!r) {
2419
- return;
2420
- }
2421
- const i = yield this._getInst(recordName, inst);
2422
- if (!i) {
2423
- return;
2424
- }
2425
- const index = i.branches.findIndex((b) => b.branch === branch);
2426
- if (index >= 0) {
2427
- const b = i.branches[index];
2428
- for (let update of b.updates.updates) {
2429
- i.instSizeInBytes -= update.length;
2430
- }
2431
- i.branches.splice(index, 1);
2207
+ async addUpdates(recordName, inst, branch, updates, sizeInBytes) {
2208
+ const r = this._instRecords.get(recordName);
2209
+ if (!r) {
2210
+ return {
2211
+ success: false,
2212
+ errorCode: 'record_not_found',
2213
+ branch,
2214
+ };
2215
+ }
2216
+ const i = await this._getInst(recordName, inst);
2217
+ if (!i) {
2218
+ return {
2219
+ success: false,
2220
+ errorCode: 'inst_not_found',
2221
+ branch,
2222
+ };
2223
+ }
2224
+ let b = i.branches.find((b) => b.branch === branch);
2225
+ if (!b) {
2226
+ b = {
2227
+ branch,
2228
+ inst: i.inst,
2229
+ recordName: i.recordName,
2230
+ temporary: false,
2231
+ updates: {
2232
+ updates: [],
2233
+ timestamps: [],
2234
+ },
2235
+ archived: {
2236
+ updates: [],
2237
+ timestamps: [],
2238
+ },
2239
+ };
2240
+ i.branches.push(b);
2241
+ }
2242
+ let storedUpdates = b.updates;
2243
+ const newSize = i.instSizeInBytes + sizeInBytes;
2244
+ if (newSize > this.maxAllowedInstSize) {
2245
+ return {
2246
+ success: false,
2247
+ errorCode: 'max_size_reached',
2248
+ branch,
2249
+ maxInstSizeInBytes: this.maxAllowedInstSize,
2250
+ neededInstSizeInBytes: newSize,
2251
+ };
2252
+ }
2253
+ i.instSizeInBytes = newSize;
2254
+ storedUpdates.updates.push(...updates);
2255
+ storedUpdates.timestamps.push(Date.now());
2256
+ const archivedUpdates = b.archived;
2257
+ archivedUpdates.updates.push(...updates);
2258
+ archivedUpdates.timestamps.push(Date.now());
2259
+ return {
2260
+ success: true,
2261
+ };
2262
+ }
2263
+ async replaceCurrentUpdates(recordName, inst, branch, updateToAdd, sizeInBytes) {
2264
+ const r = this._instRecords.get(recordName);
2265
+ if (!r) {
2266
+ return {
2267
+ success: false,
2268
+ errorCode: 'record_not_found',
2269
+ branch,
2270
+ };
2271
+ }
2272
+ const i = await this._getInst(recordName, inst);
2273
+ if (!i) {
2274
+ return {
2275
+ success: false,
2276
+ errorCode: 'inst_not_found',
2277
+ branch,
2278
+ };
2279
+ }
2280
+ let b = i.branches.find((b) => b.branch === branch);
2281
+ if (!b) {
2282
+ b = {
2283
+ branch,
2284
+ inst: i.inst,
2285
+ recordName: i.recordName,
2286
+ temporary: false,
2287
+ updates: {
2288
+ updates: [],
2289
+ timestamps: [],
2290
+ },
2291
+ archived: {
2292
+ updates: [],
2293
+ timestamps: [],
2294
+ },
2295
+ };
2296
+ i.branches.push(b);
2297
+ }
2298
+ const storedUpdates = b.updates;
2299
+ storedUpdates.updates = [];
2300
+ storedUpdates.timestamps = [];
2301
+ return this.addUpdates(recordName, inst, branch, [updateToAdd], sizeInBytes);
2302
+ }
2303
+ async deleteBranch(recordName, inst, branch) {
2304
+ const r = this._instRecords.get(recordName);
2305
+ if (!r) {
2306
+ return;
2307
+ }
2308
+ const i = await this._getInst(recordName, inst);
2309
+ if (!i) {
2310
+ return;
2311
+ }
2312
+ const index = i.branches.findIndex((b) => b.branch === branch);
2313
+ if (index >= 0) {
2314
+ const b = i.branches[index];
2315
+ for (let update of b.updates.updates) {
2316
+ i.instSizeInBytes -= update.length;
2432
2317
  }
2433
- });
2318
+ i.branches.splice(index, 1);
2319
+ }
2434
2320
  }
2435
2321
  // reset() {
2436
2322
  // this._instRecords = new Map();
2437
2323
  // this.maxAllowedInstSize = Infinity;
2438
2324
  // }
2439
- _getInst(recordName, inst) {
2440
- return __awaiter(this, void 0, void 0, function* () {
2441
- let record = yield this._getInstRecord(recordName);
2442
- return record === null || record === void 0 ? void 0 : record.get(inst);
2443
- });
2325
+ async _getInst(recordName, inst) {
2326
+ let record = await this._getInstRecord(recordName);
2327
+ return record === null || record === void 0 ? void 0 : record.get(inst);
2444
2328
  }
2445
- _getInstRecord(recordName) {
2446
- return __awaiter(this, void 0, void 0, function* () {
2447
- let record = this._instRecords.get(recordName);
2448
- if (!record) {
2449
- const r = yield this.getRecordByName(recordName);
2450
- if (r) {
2451
- record = new Map();
2452
- this._instRecords.set(recordName, record);
2453
- }
2329
+ async _getInstRecord(recordName) {
2330
+ let record = this._instRecords.get(recordName);
2331
+ if (!record) {
2332
+ const r = await this.getRecordByName(recordName);
2333
+ if (r) {
2334
+ record = new Map();
2335
+ this._instRecords.set(recordName, record);
2454
2336
  }
2455
- return record;
2456
- });
2337
+ }
2338
+ return record;
2457
2339
  }
2458
2340
  }
2459
2341
  //# sourceMappingURL=MemoryStore.js.map