@casual-simulation/aux-vm 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.
@@ -1,39 +1,12 @@
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
- var __asyncValues = (this && this.__asyncValues) || function (o) {
22
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
23
- var m = o[Symbol.asyncIterator], i;
24
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
25
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
26
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
27
- };
28
- import { hasValue, asyncResult, asyncError, APPROVED_SYMBOL, iterableNext, iterableThrow, iterableComplete, } from '@casual-simulation/aux-common';
1
+ import { hasValue, asyncResult, asyncError, APPROVED_SYMBOL, iterableNext, iterableThrow, iterableComplete, formatVersionNumber, remote, installAuxFile, formatInstId, isRecordKey, parseRecordKey, } from '@casual-simulation/aux-common';
29
2
  import axios from 'axios';
30
- import { isRecordKey, formatInstId, parseRecordKey, } from '@casual-simulation/aux-records';
31
3
  import { sha256 } from 'hash.js';
32
4
  import stringify from '@casual-simulation/fast-json-stable-stringify';
33
5
  import '@casual-simulation/aux-common/BlobPolyfill';
34
6
  import { ReplaySubject, Subject, filter, firstValueFrom, map, share, takeWhile, } from 'rxjs';
35
7
  import { DateTime } from 'luxon';
36
- import { createRecordsClient, } from '@casual-simulation/aux-records/RecordsClient';
8
+ /* eslint-disable casualos/no-non-type-imports */
9
+ import { createRecordsClient } from '@casual-simulation/aux-records/RecordsClient';
37
10
  /**
38
11
  * The list of headers that JavaScript applications are not allowed to set by themselves.
39
12
  */
@@ -123,6 +96,13 @@ export class RecordsManager {
123
96
  'listNotificationSubscriptions',
124
97
  'listUserNotificationSubscriptions',
125
98
  'createOpenAIRealtimeSession',
99
+ 'erasePackageVersion',
100
+ 'listPackageVersions',
101
+ 'getPackageVersion',
102
+ 'recordPackage',
103
+ 'erasePackage',
104
+ 'listPackages',
105
+ 'getPackage',
126
106
  ]);
127
107
  this._config = config;
128
108
  this._helper = helper;
@@ -222,1198 +202,1539 @@ export class RecordsManager {
222
202
  else if (event.type === 'records_call_procedure') {
223
203
  this._recordsCallProcedure(event);
224
204
  }
205
+ else if (event.type === 'record_package_version') {
206
+ this._recordPackageVersion(event);
207
+ }
208
+ else if (event.type === 'install_package') {
209
+ this._installPackage(event);
210
+ }
211
+ else if (event.type === 'list_installed_packages') {
212
+ this._listInstalledPackages(event);
213
+ }
225
214
  }
226
215
  }
227
- _getRecordsEndpoint(event) {
228
- if (hasValue(event.taskId)) {
229
- this._helper.transaction(asyncResult(event.taskId, this._config.recordsOrigin));
216
+ async grantEntitlements(event) {
217
+ const info = await this._resolveInfoForEvent(event);
218
+ if (info.error) {
219
+ return;
230
220
  }
231
- }
232
- _recordsCallProcedure(event) {
233
- return __awaiter(this, void 0, void 0, function* () {
234
- let name;
235
- let input;
236
- let query;
237
- for (let key in event.procedure) {
238
- if (Object.hasOwn(event.procedure, key)) {
239
- const val = event.procedure[key];
240
- if (val) {
241
- name = key;
242
- input = val.input;
243
- query = val.query;
244
- break;
245
- }
246
- }
247
- }
248
- if (!name || !this._allowedProcedures.has(name)) {
249
- console.warn('[RecordsManager] No procedure found in the call procedure event.');
221
+ let grantIds = [];
222
+ for (let feature of event.request.features) {
223
+ const result = await this._client.grantEntitlement({
224
+ packageId: event.request.packageId,
225
+ feature: feature,
226
+ scope: event.request.scope,
227
+ recordName: event.request.recordName,
228
+ expireTimeMs: event.request.expireTimeMs,
229
+ }, {
230
+ sessionKey: info.token,
231
+ endpoint: info.recordsOrigin,
232
+ });
233
+ if (result.success === false) {
234
+ console.error('[RecordsManager] Unable to grant entitlement:', result);
250
235
  if (hasValue(event.taskId)) {
251
- this._helper.transaction(asyncResult(event.taskId, {
252
- success: false,
253
- errorCode: 'not_found',
254
- errorMessage: `The procedure was either not found or not allowed. (name: ${name !== null && name !== void 0 ? name : 'undefined'})`,
255
- }));
236
+ await this._helper.transaction(asyncResult(event.taskId, result));
256
237
  }
257
238
  return;
258
239
  }
259
- const info = yield this._resolveInfoForEvent(event);
260
- if (info.error) {
261
- return;
240
+ else {
241
+ grantIds.push(result.grantId);
262
242
  }
263
- if (hasValue(this._helper.origin)) {
264
- const instances = [
265
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
266
- ];
267
- if (query) {
268
- query.instances = instances;
269
- }
270
- else {
271
- input.instances = instances;
243
+ }
244
+ if (hasValue(event.taskId)) {
245
+ await this._helper.transaction(asyncResult(event.taskId, {
246
+ success: true,
247
+ grantIds,
248
+ }));
249
+ }
250
+ }
251
+ _getRecordsEndpoint(event) {
252
+ if (hasValue(event.taskId)) {
253
+ this._helper.transaction(asyncResult(event.taskId, this._config.recordsOrigin));
254
+ }
255
+ }
256
+ async _recordsCallProcedure(event) {
257
+ let name;
258
+ let input;
259
+ let query;
260
+ for (let key in event.procedure) {
261
+ if (Object.hasOwn(event.procedure, key)) {
262
+ const val = event.procedure[key];
263
+ if (val) {
264
+ name = key;
265
+ input = val.input;
266
+ query = val.query;
267
+ break;
272
268
  }
273
269
  }
274
- const result = yield this._client.callProcedure(name, input, {
275
- sessionKey: info.token,
276
- endpoint: info.recordsOrigin,
277
- }, query);
270
+ }
271
+ if (!name || !this._allowedProcedures.has(name)) {
272
+ console.warn('[RecordsManager] No procedure found in the call procedure event.');
278
273
  if (hasValue(event.taskId)) {
279
- this._helper.transaction(asyncResult(event.taskId, result));
274
+ this._helper.transaction(asyncResult(event.taskId, {
275
+ success: false,
276
+ errorCode: 'not_found',
277
+ errorMessage: `The procedure was either not found or not allowed. (name: ${name !== null && name !== void 0 ? name : 'undefined'})`,
278
+ }));
280
279
  }
281
- });
280
+ return;
281
+ }
282
+ const info = await this._resolveInfoForEvent(event);
283
+ if (info.error) {
284
+ return;
285
+ }
286
+ if (hasValue(this._helper.origin)) {
287
+ const instances = [
288
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
289
+ ];
290
+ if (query) {
291
+ query.instances = instances;
292
+ }
293
+ else {
294
+ input.instances = instances;
295
+ }
296
+ }
297
+ const result = await this._client.callProcedure(name, input, {
298
+ sessionKey: info.token,
299
+ endpoint: info.recordsOrigin,
300
+ }, query);
301
+ if (hasValue(event.taskId)) {
302
+ this._helper.transaction(asyncResult(event.taskId, result));
303
+ }
282
304
  }
283
305
  /**
284
306
  * Reports the given inst to the server.
285
307
  * @param request The request to send to the server.
286
308
  */
287
- reportInst(request) {
288
- return __awaiter(this, void 0, void 0, function* () {
289
- const info = yield this._getEndpointInfo(null, false);
290
- if (info.error) {
291
- return;
292
- }
293
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/insts/report'), Object.assign({}, request), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
294
- return result.data;
309
+ async reportInst(request) {
310
+ const info = await this._resolveInfoForEvent({ options: {} }, false);
311
+ if (info.error) {
312
+ return;
313
+ }
314
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/insts/report'), {
315
+ ...request,
316
+ }, {
317
+ ...this._axiosOptions,
318
+ headers: info.headers,
295
319
  });
320
+ return result.data;
296
321
  }
297
322
  /**
298
323
  * Gets a token that can be used to access loom for the given record.
299
324
  * @param recordName The name of the record.
300
325
  */
301
- getLoomToken(recordName) {
302
- return __awaiter(this, void 0, void 0, function* () {
303
- const info = yield this._resolveInfoForEvent({ options: {} });
304
- const result = yield this._client.getLoomAccessToken({
305
- recordName,
306
- }, {
307
- sessionKey: info.token,
308
- endpoint: info.recordsOrigin,
326
+ async getLoomToken(recordName) {
327
+ const info = await this._resolveInfoForEvent({ options: {} });
328
+ if (info.error) {
329
+ return;
330
+ }
331
+ const result = await this._client.getLoomAccessToken({
332
+ recordName,
333
+ }, {
334
+ sessionKey: info.token,
335
+ endpoint: info.recordsOrigin,
336
+ });
337
+ if (result.success === false) {
338
+ console.error('[RecordsManager] Unable to get loom token:', result);
339
+ return null;
340
+ }
341
+ return result.token;
342
+ }
343
+ async _recordData(event) {
344
+ if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
345
+ return;
346
+ }
347
+ try {
348
+ const info = await this._resolveInfoForEvent(event);
349
+ if (info.error) {
350
+ return;
351
+ }
352
+ console.log('[RecordsManager] Recording data...', event);
353
+ let requestData = {
354
+ recordKey: event.recordKey,
355
+ address: event.address,
356
+ data: event.data,
357
+ };
358
+ if (hasValue(this._helper.origin)) {
359
+ requestData.instances = [
360
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
361
+ ];
362
+ }
363
+ if (hasValue(event.options.markers)) {
364
+ requestData.markers = event.options.markers;
365
+ }
366
+ if (hasValue(event.options.updatePolicy)) {
367
+ requestData.updatePolicy = event.options.updatePolicy;
368
+ }
369
+ if (hasValue(event.options.deletePolicy)) {
370
+ requestData.deletePolicy = event.options.deletePolicy;
371
+ }
372
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, !event.requiresApproval
373
+ ? '/api/v2/records/data'
374
+ : '/api/v2/records/manual/data'), requestData, {
375
+ ...this._axiosOptions,
376
+ headers: info.headers,
309
377
  });
310
- if (result.success === false) {
311
- console.error('[RecordsManager] Unable to get loom token:', result);
312
- return null;
378
+ if (result.data.success) {
379
+ console.log('[RecordsManager] Data recorded!');
313
380
  }
314
- return result.token;
315
- });
381
+ if (hasValue(event.taskId)) {
382
+ this._helper.transaction(asyncResult(event.taskId, result.data));
383
+ }
384
+ }
385
+ catch (e) {
386
+ console.error('[RecordsManager] Error publishing record:', e);
387
+ if (hasValue(event.taskId)) {
388
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
389
+ }
390
+ }
316
391
  }
317
- _recordData(event) {
318
- return __awaiter(this, void 0, void 0, function* () {
319
- if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
392
+ async _getRecordData(event) {
393
+ if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
394
+ return;
395
+ }
396
+ try {
397
+ const info = await this._resolveInfoForEvent(event, false);
398
+ if (info.error) {
320
399
  return;
321
400
  }
322
- try {
323
- const info = yield this._resolveInfoForEvent(event);
324
- if (info.error) {
325
- return;
326
- }
327
- console.log('[RecordsManager] Recording data...', event);
328
- let requestData = {
329
- recordKey: event.recordKey,
330
- address: event.address,
331
- data: event.data,
332
- };
333
- if (hasValue(this._helper.origin)) {
334
- requestData.instances = [
335
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
336
- ];
337
- }
338
- if (hasValue(event.options.markers)) {
339
- requestData.markers = event.options.markers;
340
- }
341
- if (hasValue(event.options.updatePolicy)) {
342
- requestData.updatePolicy = event.options.updatePolicy;
343
- }
344
- if (hasValue(event.options.deletePolicy)) {
345
- requestData.deletePolicy = event.options.deletePolicy;
346
- }
347
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, !event.requiresApproval
401
+ let instances = undefined;
402
+ if (hasValue(this._helper.origin)) {
403
+ instances = [
404
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
405
+ ];
406
+ }
407
+ if (hasValue(event.taskId)) {
408
+ const result = await axios.get(await this._publishUrl(info.recordsOrigin, !event.requiresApproval
348
409
  ? '/api/v2/records/data'
349
- : '/api/v2/records/manual/data'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
350
- if (result.data.success) {
351
- console.log('[RecordsManager] Data recorded!');
352
- }
353
- if (hasValue(event.taskId)) {
354
- this._helper.transaction(asyncResult(event.taskId, result.data));
355
- }
410
+ : '/api/v2/records/manual/data', {
411
+ recordName: event.recordName,
412
+ address: event.address,
413
+ instances,
414
+ }), {
415
+ ...this._axiosOptions,
416
+ headers: info.headers,
417
+ });
418
+ this._helper.transaction(asyncResult(event.taskId, result.data));
356
419
  }
357
- catch (e) {
358
- console.error('[RecordsManager] Error publishing record:', e);
359
- if (hasValue(event.taskId)) {
360
- this._helper.transaction(asyncError(event.taskId, e.toString()));
361
- }
420
+ }
421
+ catch (e) {
422
+ console.error('[RecordsManager] Error getting record:', e);
423
+ if (hasValue(event.taskId)) {
424
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
362
425
  }
363
- });
426
+ }
364
427
  }
365
- _getRecordData(event) {
366
- return __awaiter(this, void 0, void 0, function* () {
367
- if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
428
+ async _listRecordData(event) {
429
+ if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
430
+ return;
431
+ }
432
+ try {
433
+ const info = await this._resolveInfoForEvent(event);
434
+ if (info.error) {
368
435
  return;
369
436
  }
370
- try {
371
- const info = yield this._resolveInfoForEvent(event, false);
372
- if (info.error) {
373
- return;
374
- }
375
- let instances = undefined;
376
- if (hasValue(this._helper.origin)) {
377
- instances = [
378
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
379
- ];
380
- }
437
+ if (event.requiresApproval) {
381
438
  if (hasValue(event.taskId)) {
382
- const result = yield axios.get(yield this._publishUrl(info.recordsOrigin, !event.requiresApproval
383
- ? '/api/v2/records/data'
384
- : '/api/v2/records/manual/data', {
385
- recordName: event.recordName,
386
- address: event.address,
387
- instances,
388
- }), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
389
- this._helper.transaction(asyncResult(event.taskId, result.data));
439
+ this._helper.transaction(asyncResult(event.taskId, {
440
+ success: false,
441
+ errorCode: 'not_supported',
442
+ errorMessage: 'It is not possible to list manual approval records.',
443
+ }));
390
444
  }
445
+ return;
391
446
  }
392
- catch (e) {
393
- console.error('[RecordsManager] Error getting record:', e);
394
- if (hasValue(event.taskId)) {
395
- this._helper.transaction(asyncError(event.taskId, e.toString()));
396
- }
447
+ let instances = undefined;
448
+ if (hasValue(this._helper.origin)) {
449
+ instances = [
450
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
451
+ ];
397
452
  }
398
- });
453
+ if (hasValue(event.taskId)) {
454
+ let query = {
455
+ recordName: event.recordName,
456
+ };
457
+ if (event.type === 'list_record_data_by_marker') {
458
+ query.marker = event.marker;
459
+ }
460
+ query.address = event.startingAddress || null;
461
+ query.instances = instances;
462
+ const result = await axios.get(await this._publishUrl(info.recordsOrigin, '/api/v2/records/data/list', query), {
463
+ ...this._axiosOptions,
464
+ headers: info.headers,
465
+ });
466
+ this._helper.transaction(asyncResult(event.taskId, result.data));
467
+ }
468
+ }
469
+ catch (e) {
470
+ console.error('[RecordsManager] Error listing record:', e);
471
+ if (hasValue(event.taskId)) {
472
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
473
+ }
474
+ }
399
475
  }
400
- _listRecordData(event) {
401
- return __awaiter(this, void 0, void 0, function* () {
402
- if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
476
+ async _eraseRecordData(event) {
477
+ if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
478
+ return;
479
+ }
480
+ try {
481
+ const info = await this._resolveInfoForEvent(event);
482
+ if (info.error) {
403
483
  return;
404
484
  }
405
- try {
406
- const info = yield this._resolveInfoForEvent(event);
407
- if (info.error) {
408
- return;
409
- }
410
- if (event.requiresApproval) {
411
- if (hasValue(event.taskId)) {
412
- this._helper.transaction(asyncResult(event.taskId, {
413
- success: false,
414
- errorCode: 'not_supported',
415
- errorMessage: 'It is not possible to list manual approval records.',
416
- }));
417
- }
418
- return;
419
- }
420
- let instances = undefined;
421
- if (hasValue(this._helper.origin)) {
422
- instances = [
423
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
424
- ];
425
- }
426
- if (hasValue(event.taskId)) {
427
- let query = {
428
- recordName: event.recordName,
429
- };
430
- if (event.type === 'list_record_data_by_marker') {
431
- query.marker = event.marker;
432
- }
433
- query.address = event.startingAddress || null;
434
- query.instances = instances;
435
- const result = yield axios.get(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/data/list', query), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
436
- this._helper.transaction(asyncResult(event.taskId, result.data));
437
- }
485
+ console.log('[RecordsManager] Deleting data...', event);
486
+ let instances = undefined;
487
+ if (hasValue(this._helper.origin)) {
488
+ instances = [
489
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
490
+ ];
438
491
  }
439
- catch (e) {
440
- console.error('[RecordsManager] Error listing record:', e);
441
- if (hasValue(event.taskId)) {
442
- this._helper.transaction(asyncError(event.taskId, e.toString()));
443
- }
492
+ const result = await axios.request({
493
+ ...this._axiosOptions,
494
+ method: 'DELETE',
495
+ url: await this._publishUrl(info.recordsOrigin, !event.requiresApproval
496
+ ? '/api/v2/records/data'
497
+ : '/api/v2/records/manual/data'),
498
+ data: {
499
+ recordKey: event.recordKey,
500
+ address: event.address,
501
+ instances,
502
+ },
503
+ headers: info.headers,
504
+ });
505
+ if (result.data.success) {
506
+ console.log('[RecordsManager] Data deleted!');
444
507
  }
445
- });
508
+ if (hasValue(event.taskId)) {
509
+ this._helper.transaction(asyncResult(event.taskId, result.data));
510
+ }
511
+ }
512
+ catch (e) {
513
+ console.error('[RecordsManager] Error deleting record:', e);
514
+ if (hasValue(event.taskId)) {
515
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
516
+ }
517
+ }
446
518
  }
447
- _eraseRecordData(event) {
448
- return __awaiter(this, void 0, void 0, function* () {
449
- if (event.requiresApproval && !event[APPROVED_SYMBOL]) {
519
+ async _recordFile(event) {
520
+ var _a;
521
+ try {
522
+ const info = await this._resolveInfoForEvent(event);
523
+ if (info.error) {
450
524
  return;
451
525
  }
452
- try {
453
- const info = yield this._resolveInfoForEvent(event);
454
- if (info.error) {
455
- return;
456
- }
457
- console.log('[RecordsManager] Deleting data...', event);
458
- let instances = undefined;
459
- if (hasValue(this._helper.origin)) {
460
- instances = [
461
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
462
- ];
463
- }
464
- const result = yield axios.request(Object.assign(Object.assign({}, this._axiosOptions), { method: 'DELETE', url: yield this._publishUrl(info.recordsOrigin, !event.requiresApproval
465
- ? '/api/v2/records/data'
466
- : '/api/v2/records/manual/data'), data: {
467
- recordKey: event.recordKey,
468
- address: event.address,
469
- instances,
470
- }, headers: info.headers }));
471
- if (result.data.success) {
472
- console.log('[RecordsManager] Data deleted!');
473
- }
526
+ console.log('[RecordsManager] Recording file...', event);
527
+ const fileInfo = await this._resolveRecordFileInfo(event.data, event.mimeType);
528
+ if (fileInfo.success === false) {
474
529
  if (hasValue(event.taskId)) {
475
- this._helper.transaction(asyncResult(event.taskId, result.data));
530
+ this._helper.transaction(asyncResult(event.taskId, fileInfo));
476
531
  }
532
+ return;
477
533
  }
478
- catch (e) {
479
- console.error('[RecordsManager] Error deleting record:', e);
480
- if (hasValue(event.taskId)) {
481
- this._helper.transaction(asyncError(event.taskId, e.toString()));
482
- }
534
+ const { byteLength, hash, mimeType, data } = fileInfo;
535
+ let instances = undefined;
536
+ if (hasValue(this._helper.origin)) {
537
+ instances = [
538
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
539
+ ];
540
+ }
541
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/file'), {
542
+ recordKey: event.recordKey,
543
+ fileSha256Hex: hash,
544
+ fileMimeType: mimeType,
545
+ fileByteLength: byteLength,
546
+ fileDescription: event.description,
547
+ markers: (_a = event.options) === null || _a === void 0 ? void 0 : _a.markers,
548
+ instances,
549
+ }, {
550
+ ...this._axiosOptions,
551
+ headers: info.headers,
552
+ });
553
+ const uploadResult = await this._uploadFile(result.data, data, hash);
554
+ if (hasValue(event.taskId)) {
555
+ this._helper.transaction(asyncResult(event.taskId, uploadResult));
556
+ }
557
+ }
558
+ catch (e) {
559
+ console.error('[RecordsManager] Error recording file:', e);
560
+ if (hasValue(event.taskId)) {
561
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
483
562
  }
563
+ }
564
+ }
565
+ async _uploadFile(result, data, hash) {
566
+ if (result.success === false) {
567
+ return result;
568
+ }
569
+ const method = result.uploadMethod;
570
+ const url = result.uploadUrl;
571
+ const headers = { ...result.uploadHeaders };
572
+ for (let name of UNSAFE_HEADERS) {
573
+ delete headers[name];
574
+ }
575
+ const uploadResult = await axios.request({
576
+ ...this._axiosOptions,
577
+ method: method.toLowerCase(),
578
+ url: url,
579
+ headers: headers,
580
+ data: data,
484
581
  });
582
+ if (uploadResult.status >= 200 && uploadResult.status < 300) {
583
+ console.log('[RecordsManager] File recorded!');
584
+ return {
585
+ success: true,
586
+ url: url,
587
+ sha256Hash: hash,
588
+ };
589
+ // if (hasValue(event.taskId)) {
590
+ // this._helper.transaction(
591
+ // asyncResult(event.taskId, {
592
+ // success: true,
593
+ // url: url,
594
+ // sha256Hash: hash,
595
+ // } as FileRecordedResult)
596
+ // );
597
+ // }
598
+ }
599
+ else {
600
+ console.error('[RecordsManager] File upload failed!', uploadResult);
601
+ return {
602
+ success: false,
603
+ errorCode: 'upload_failed',
604
+ errorMessage: 'The file upload failed.',
605
+ };
606
+ // if (hasValue(event.taskId)) {
607
+ // this._helper.transaction(
608
+ // asyncResult(event.taskId, {
609
+ // success: false,
610
+ // errorCode: 'upload_failed',
611
+ // errorMessage: 'The file upload failed.',
612
+ // } as FileRecordedResult)
613
+ // );
614
+ // }
615
+ }
485
616
  }
486
- _recordFile(event) {
487
- var _a;
488
- return __awaiter(this, void 0, void 0, function* () {
489
- try {
490
- const info = yield this._resolveInfoForEvent(event);
491
- if (info.error) {
492
- return;
493
- }
494
- console.log('[RecordsManager] Recording file...', event);
495
- let byteLength;
496
- let hash;
497
- let mimeType;
498
- let data;
499
- if (typeof event.data === 'function') {
500
- if (hasValue(event.taskId)) {
501
- this._helper.transaction(asyncResult(event.taskId, {
502
- success: false,
503
- errorCode: 'invalid_file_data',
504
- errorMessage: 'Function instances cannot be stored in files.',
505
- }));
617
+ async _resolveRecordFileInfo(eventData, eventMimeType) {
618
+ let byteLength;
619
+ let hash;
620
+ let mimeType;
621
+ let data;
622
+ if (typeof eventData === 'function') {
623
+ // if (hasValue(event.taskId)) {
624
+ // this._helper.transaction(
625
+ // asyncResult(event.taskId, {
626
+ // success: false,
627
+ // errorCode: 'invalid_file_data',
628
+ // errorMessage:
629
+ // 'Function instances cannot be stored in files.',
630
+ // } as RecordFileResult)
631
+ // );
632
+ // }
633
+ return {
634
+ success: false,
635
+ errorCode: 'invalid_file_data',
636
+ errorMessage: 'Function instances cannot be stored in files.',
637
+ };
638
+ }
639
+ else if (typeof eventData === 'undefined' || eventData === null) {
640
+ return {
641
+ success: false,
642
+ errorCode: 'invalid_file_data',
643
+ errorMessage: 'Null or undefined values cannot be stored in files.',
644
+ };
645
+ }
646
+ else if (typeof eventData === 'string' ||
647
+ typeof eventData === 'number' ||
648
+ typeof eventData === 'boolean') {
649
+ const encoder = new TextEncoder();
650
+ data = encoder.encode(eventData.toString());
651
+ byteLength = data.byteLength;
652
+ mimeType = eventMimeType || 'text/plain';
653
+ hash = getHash(data);
654
+ }
655
+ else if (typeof eventData === 'object') {
656
+ if (eventData instanceof Blob) {
657
+ const buffer = await eventData.arrayBuffer();
658
+ data = new Uint8Array(buffer);
659
+ byteLength = data.byteLength;
660
+ mimeType =
661
+ eventMimeType ||
662
+ eventData.type ||
663
+ 'application/octet-stream';
664
+ hash = getHash(data);
665
+ }
666
+ else if (eventData instanceof ArrayBuffer) {
667
+ data = new Uint8Array(eventData);
668
+ byteLength = data.byteLength;
669
+ mimeType = eventMimeType || 'application/octet-stream';
670
+ hash = getHash(data);
671
+ }
672
+ else if (ArrayBuffer.isView(eventData)) {
673
+ data = new Uint8Array(eventData.buffer);
674
+ byteLength = data.byteLength;
675
+ mimeType = eventMimeType || 'application/octet-stream';
676
+ hash = getHash(data);
677
+ }
678
+ else {
679
+ const obj = eventData;
680
+ if ('data' in obj &&
681
+ 'mimeType' in obj &&
682
+ (obj.data instanceof ArrayBuffer ||
683
+ typeof obj.data === 'string') &&
684
+ typeof obj.mimeType === 'string') {
685
+ if (typeof obj.data === 'string') {
686
+ data = new TextEncoder().encode(obj.data);
506
687
  }
507
- return;
508
- }
509
- else if (typeof event.data === 'undefined' ||
510
- event.data === null) {
511
- if (hasValue(event.taskId)) {
512
- this._helper.transaction(asyncResult(event.taskId, {
513
- success: false,
514
- errorCode: 'invalid_file_data',
515
- errorMessage: 'Null or undefined values cannot be stored in files.',
516
- }));
688
+ else {
689
+ data = new Uint8Array(obj.data);
517
690
  }
518
- return;
519
- }
520
- else if (typeof event.data === 'string' ||
521
- typeof event.data === 'number' ||
522
- typeof event.data === 'boolean') {
523
- const encoder = new TextEncoder();
524
- data = encoder.encode(event.data.toString());
525
691
  byteLength = data.byteLength;
526
- mimeType = event.mimeType || 'text/plain';
692
+ mimeType =
693
+ eventMimeType ||
694
+ obj.mimeType ||
695
+ (typeof obj.data === 'string'
696
+ ? 'text/plain'
697
+ : 'application/octet-stream');
527
698
  hash = getHash(data);
528
699
  }
529
- else if (typeof event.data === 'object') {
530
- if (event.data instanceof Blob) {
531
- const buffer = yield event.data.arrayBuffer();
532
- data = new Uint8Array(buffer);
533
- byteLength = data.byteLength;
534
- mimeType =
535
- event.mimeType ||
536
- event.data.type ||
537
- 'application/octet-stream';
538
- hash = getHash(data);
539
- }
540
- else if (event.data instanceof ArrayBuffer) {
541
- data = new Uint8Array(event.data);
542
- byteLength = data.byteLength;
543
- mimeType = event.mimeType || 'application/octet-stream';
544
- hash = getHash(data);
545
- }
546
- else if (ArrayBuffer.isView(event.data)) {
547
- data = new Uint8Array(event.data.buffer);
548
- byteLength = data.byteLength;
549
- mimeType = event.mimeType || 'application/octet-stream';
550
- hash = getHash(data);
551
- }
552
- else {
553
- const obj = event.data;
554
- if ('data' in obj &&
555
- 'mimeType' in obj &&
556
- (obj.data instanceof ArrayBuffer ||
557
- typeof obj.data === 'string') &&
558
- typeof obj.mimeType === 'string') {
559
- if (typeof obj.data === 'string') {
560
- data = new TextEncoder().encode(obj.data);
561
- }
562
- else {
563
- data = new Uint8Array(obj.data);
564
- }
565
- byteLength = data.byteLength;
566
- mimeType =
567
- event.mimeType ||
568
- obj.mimeType ||
569
- (typeof obj.data === 'string'
570
- ? 'text/plain'
571
- : 'application/octet-stream');
572
- hash = getHash(data);
573
- }
574
- else {
575
- let json = stringify(event.data);
576
- data = new TextEncoder().encode(json);
577
- byteLength = data.byteLength;
578
- mimeType = event.mimeType || 'application/json';
579
- hash = getHash(data);
580
- }
581
- }
700
+ else {
701
+ let json = stringify(eventData);
702
+ data = new TextEncoder().encode(json);
703
+ byteLength = data.byteLength;
704
+ mimeType = eventMimeType || 'application/json';
705
+ hash = getHash(data);
582
706
  }
583
- let instances = undefined;
584
- if (hasValue(this._helper.origin)) {
585
- instances = [
586
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
587
- ];
588
- }
589
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/file'), {
590
- recordKey: event.recordKey,
591
- fileSha256Hex: hash,
592
- fileMimeType: mimeType,
593
- fileByteLength: byteLength,
594
- fileDescription: event.description,
595
- markers: (_a = event.options) === null || _a === void 0 ? void 0 : _a.markers,
596
- instances,
597
- }, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
598
- if (result.data.success === true) {
599
- const method = result.data.uploadMethod;
600
- const url = result.data.uploadUrl;
601
- const headers = Object.assign({}, result.data.uploadHeaders);
602
- for (let name of UNSAFE_HEADERS) {
603
- delete headers[name];
604
- }
605
- const uploadResult = yield axios.request(Object.assign(Object.assign({}, this._axiosOptions), { method: method.toLowerCase(), url: url, headers: headers, data: data }));
606
- if (uploadResult.status >= 200 && uploadResult.status < 300) {
607
- console.log('[RecordsManager] File recorded!');
608
- if (hasValue(event.taskId)) {
609
- this._helper.transaction(asyncResult(event.taskId, {
610
- success: true,
611
- url: url,
612
- sha256Hash: hash,
613
- }));
614
- }
707
+ }
708
+ }
709
+ return {
710
+ success: true,
711
+ byteLength,
712
+ hash,
713
+ mimeType,
714
+ data,
715
+ };
716
+ }
717
+ async _getFile(event) {
718
+ try {
719
+ const info = await this._resolveInfoForEvent(event, false);
720
+ if (info.error) {
721
+ return;
722
+ }
723
+ let instances = undefined;
724
+ if (hasValue(this._helper.origin)) {
725
+ instances = [
726
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
727
+ ];
728
+ }
729
+ const result = await axios.get(await this._publishUrl(info.recordsOrigin, '/api/v2/records/file', {
730
+ fileUrl: event.fileUrl,
731
+ instances,
732
+ }), {
733
+ ...this._axiosOptions,
734
+ headers: info.headers,
735
+ });
736
+ if (hasValue(event.taskId)) {
737
+ if (result.data.success) {
738
+ const getResult = await axios.request({
739
+ ...this._axiosOptions,
740
+ method: result.data.requestMethod,
741
+ url: result.data.requestUrl,
742
+ headers: result.data.requestHeaders,
743
+ });
744
+ if (getResult.status >= 200 && getResult.status < 300) {
745
+ this._helper.transaction(asyncResult(event.taskId, getResult.data));
615
746
  }
616
747
  else {
617
- console.error('[RecordsManager] File upload failed!', uploadResult);
618
- if (hasValue(event.taskId)) {
619
- this._helper.transaction(asyncResult(event.taskId, {
620
- success: false,
621
- errorCode: 'upload_failed',
622
- errorMessage: 'The file upload failed.',
623
- }));
624
- }
748
+ this._helper.transaction(asyncError(event.taskId, {
749
+ success: false,
750
+ errorCode: getResult.status === 404
751
+ ? 'file_not_found'
752
+ : getResult.status >= 500
753
+ ? 'server_error'
754
+ : 'not_authorized',
755
+ errorMessage: 'The file upload failed.',
756
+ }));
625
757
  }
626
758
  }
627
759
  else {
628
- if (hasValue(event.taskId)) {
629
- this._helper.transaction(asyncResult(event.taskId, result.data));
630
- }
760
+ this._helper.transaction(asyncError(event.taskId, result.data));
631
761
  }
632
762
  }
633
- catch (e) {
634
- console.error('[RecordsManager] Error recording file:', e);
635
- if (hasValue(event.taskId)) {
636
- this._helper.transaction(asyncError(event.taskId, e.toString()));
637
- }
763
+ }
764
+ catch (e) {
765
+ console.error('[RecordsManager] Error getting file:', e);
766
+ if (hasValue(event.taskId)) {
767
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
638
768
  }
769
+ }
770
+ }
771
+ async _readFile(result) {
772
+ const getResult = await axios.request({
773
+ ...this._axiosOptions,
774
+ method: result.requestMethod,
775
+ url: result.requestUrl,
776
+ headers: result.requestHeaders,
639
777
  });
778
+ if (getResult.status >= 200 && getResult.status < 300) {
779
+ return {
780
+ success: true,
781
+ data: getResult.data,
782
+ };
783
+ }
784
+ else {
785
+ return {
786
+ success: false,
787
+ errorCode: getResult.status === 404
788
+ ? 'file_not_found'
789
+ : getResult.status >= 500
790
+ ? 'server_error'
791
+ : 'not_authorized',
792
+ errorMessage: getResult.status === 404
793
+ ? 'The file was not found.'
794
+ : 'The file download failed.',
795
+ };
796
+ }
640
797
  }
641
- _getFile(event) {
642
- return __awaiter(this, void 0, void 0, function* () {
643
- try {
644
- const info = yield this._resolveInfoForEvent(event, false);
645
- if (info.error) {
646
- return;
647
- }
648
- let instances = undefined;
649
- if (hasValue(this._helper.origin)) {
650
- instances = [
651
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
652
- ];
653
- }
654
- const result = yield axios.get(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/file', {
798
+ async _eraseFile(event) {
799
+ try {
800
+ const info = await this._resolveInfoForEvent(event);
801
+ if (info.error) {
802
+ return;
803
+ }
804
+ console.log('[RecordsManager] Deleting file...', event);
805
+ let instances = undefined;
806
+ if (hasValue(this._helper.origin)) {
807
+ instances = [
808
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
809
+ ];
810
+ }
811
+ const result = await axios.request({
812
+ ...this._axiosOptions,
813
+ method: 'DELETE',
814
+ url: await this._publishUrl(info.recordsOrigin, '/api/v2/records/file'),
815
+ data: {
816
+ recordKey: event.recordKey,
655
817
  fileUrl: event.fileUrl,
656
818
  instances,
657
- }), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
658
- if (hasValue(event.taskId)) {
659
- if (result.data.success) {
660
- const getResult = yield axios.request(Object.assign(Object.assign({}, this._axiosOptions), { method: result.data.requestMethod, url: result.data.requestUrl, headers: result.data.requestHeaders }));
661
- if (getResult.status >= 200 && getResult.status < 300) {
662
- this._helper.transaction(asyncResult(event.taskId, getResult.data));
663
- }
664
- else {
665
- this._helper.transaction(asyncError(event.taskId, {
666
- success: false,
667
- errorCode: getResult.status === 404
668
- ? 'file_not_found'
669
- : getResult.status >= 500
670
- ? 'server_error'
671
- : 'not_authorized',
672
- errorMessage: 'The file upload failed.',
673
- }));
674
- }
675
- }
676
- else {
677
- this._helper.transaction(asyncError(event.taskId, result.data));
678
- }
679
- }
819
+ },
820
+ headers: info.headers,
821
+ });
822
+ if (result.data.success) {
823
+ console.log('[RecordsManager] File deleted!');
680
824
  }
681
- catch (e) {
682
- console.error('[RecordsManager] Error getting file:', e);
683
- if (hasValue(event.taskId)) {
684
- this._helper.transaction(asyncError(event.taskId, e.toString()));
685
- }
825
+ if (hasValue(event.taskId)) {
826
+ this._helper.transaction(asyncResult(event.taskId, result.data));
686
827
  }
687
- });
828
+ }
829
+ catch (e) {
830
+ console.error('[RecordsManager] Error deleting file:', e);
831
+ if (hasValue(event.taskId)) {
832
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
833
+ }
834
+ }
688
835
  }
689
- _eraseFile(event) {
690
- return __awaiter(this, void 0, void 0, function* () {
691
- try {
692
- const info = yield this._resolveInfoForEvent(event);
693
- if (info.error) {
694
- return;
695
- }
696
- console.log('[RecordsManager] Deleting file...', event);
697
- let instances = undefined;
698
- if (hasValue(this._helper.origin)) {
699
- instances = [
700
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
701
- ];
702
- }
703
- const result = yield axios.request(Object.assign(Object.assign({}, this._axiosOptions), { method: 'DELETE', url: yield this._publishUrl(info.recordsOrigin, '/api/v2/records/file'), data: {
704
- recordKey: event.recordKey,
705
- fileUrl: event.fileUrl,
706
- instances,
707
- }, headers: info.headers }));
708
- if (result.data.success) {
709
- console.log('[RecordsManager] File deleted!');
710
- }
711
- if (hasValue(event.taskId)) {
712
- this._helper.transaction(asyncResult(event.taskId, result.data));
713
- }
836
+ async _recordEvent(event) {
837
+ try {
838
+ const info = await this._resolveInfoForEvent(event);
839
+ if (info.error) {
840
+ return;
714
841
  }
715
- catch (e) {
716
- console.error('[RecordsManager] Error deleting file:', e);
717
- if (hasValue(event.taskId)) {
718
- this._helper.transaction(asyncError(event.taskId, e.toString()));
719
- }
842
+ console.log('[RecordsManager] Recording event...', event);
843
+ let instances = undefined;
844
+ if (hasValue(this._helper.origin)) {
845
+ instances = [
846
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
847
+ ];
720
848
  }
721
- });
849
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/events/count'), {
850
+ recordKey: event.recordKey,
851
+ eventName: event.eventName,
852
+ count: event.count,
853
+ instances,
854
+ }, {
855
+ ...this._axiosOptions,
856
+ headers: info.headers,
857
+ });
858
+ if (result.data.success) {
859
+ console.log('[RecordsManager] Event recorded!');
860
+ }
861
+ if (hasValue(event.taskId)) {
862
+ this._helper.transaction(asyncResult(event.taskId, result.data));
863
+ }
864
+ }
865
+ catch (e) {
866
+ console.error('[RecordsManager] Error recording event:', e);
867
+ if (hasValue(event.taskId)) {
868
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
869
+ }
870
+ }
722
871
  }
723
- _recordEvent(event) {
724
- return __awaiter(this, void 0, void 0, function* () {
725
- try {
726
- const info = yield this._resolveInfoForEvent(event);
727
- if (info.error) {
728
- return;
729
- }
730
- console.log('[RecordsManager] Recording event...', event);
872
+ async _getEventCount(event) {
873
+ try {
874
+ const info = await this._resolveInfoForEvent(event);
875
+ if (info.error) {
876
+ return;
877
+ }
878
+ if (hasValue(event.taskId)) {
731
879
  let instances = undefined;
732
880
  if (hasValue(this._helper.origin)) {
733
881
  instances = [
734
882
  formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
735
883
  ];
736
884
  }
737
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/events/count'), {
738
- recordKey: event.recordKey,
885
+ const result = await axios.get(await this._publishUrl(info.recordsOrigin, '/api/v2/records/events/count', {
886
+ recordName: event.recordName,
739
887
  eventName: event.eventName,
740
- count: event.count,
741
888
  instances,
742
- }, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
743
- if (result.data.success) {
744
- console.log('[RecordsManager] Event recorded!');
745
- }
746
- if (hasValue(event.taskId)) {
747
- this._helper.transaction(asyncResult(event.taskId, result.data));
748
- }
749
- }
750
- catch (e) {
751
- console.error('[RecordsManager] Error recording event:', e);
752
- if (hasValue(event.taskId)) {
753
- this._helper.transaction(asyncError(event.taskId, e.toString()));
754
- }
889
+ }), { ...this._axiosOptions, headers: info.headers });
890
+ this._helper.transaction(asyncResult(event.taskId, result.data));
755
891
  }
756
- });
757
- }
758
- _getEventCount(event) {
759
- return __awaiter(this, void 0, void 0, function* () {
760
- try {
761
- const info = yield this._resolveInfoForEvent(event);
762
- if (info.error) {
763
- return;
764
- }
765
- if (hasValue(event.taskId)) {
766
- let instances = undefined;
767
- if (hasValue(this._helper.origin)) {
768
- instances = [
769
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
770
- ];
771
- }
772
- const result = yield axios.get(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/events/count', {
773
- recordName: event.recordName,
774
- eventName: event.eventName,
775
- instances,
776
- }), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
777
- this._helper.transaction(asyncResult(event.taskId, result.data));
778
- }
779
- }
780
- catch (e) {
781
- console.error('[RecordsManager] Error getting event count:', e);
782
- if (hasValue(event.taskId)) {
783
- this._helper.transaction(asyncError(event.taskId, e.toString()));
784
- }
785
- }
786
- });
787
- }
788
- _joinRoom(event) {
789
- return __awaiter(this, void 0, void 0, function* () {
790
- try {
791
- const info = yield this._resolveInfoForEvent(event, false);
792
- if (info.error) {
793
- // if (hasValue(event.taskId)) {
794
- // this._helper.transaction(
795
- // asyncResult(event.taskId, {
796
- // success: false,
797
- // errorCode: 'not_supported',
798
- // errorMessage:
799
- // 'Records are not supported on this inst.',
800
- // } as IssueMeetTokenResult)
801
- // );
802
- // }
803
- return;
804
- }
805
- if (hasValue(event.taskId)) {
806
- const userId = this._helper.userId;
807
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/meet/token'), {
808
- roomName: event.roomName,
809
- userName: userId,
810
- }, Object.assign({}, this._axiosOptions));
811
- const data = result.data;
812
- if (data.success) {
813
- const join = {
814
- roomName: data.roomName,
815
- token: data.token,
816
- url: data.url,
817
- options: event.options,
818
- resolve: (options) => {
819
- this._helper.transaction(asyncResult(event.taskId, {
820
- success: true,
821
- roomName: data.roomName,
822
- options,
823
- }));
824
- },
825
- reject: (code, message) => {
826
- this._helper.transaction(asyncResult(event.taskId, {
827
- success: false,
828
- roomName: data.roomName,
829
- errorCode: code,
830
- errorMessage: message,
831
- }));
832
- },
833
- };
834
- this._roomJoin.next(join);
835
- }
836
- else {
837
- this._helper.transaction(asyncResult(event.taskId, data));
838
- }
839
- }
840
- }
841
- catch (e) {
842
- console.error('[RecordsManager] Error joining room:', e);
843
- if (hasValue(event.taskId)) {
844
- this._helper.transaction(asyncError(event.taskId, e.toString()));
845
- }
892
+ }
893
+ catch (e) {
894
+ console.error('[RecordsManager] Error getting event count:', e);
895
+ if (hasValue(event.taskId)) {
896
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
846
897
  }
847
- });
898
+ }
848
899
  }
849
- _leaveRoom(event) {
850
- return __awaiter(this, void 0, void 0, function* () {
851
- try {
852
- if (hasValue(event.taskId)) {
853
- const leave = {
854
- roomName: event.roomName,
855
- resolve: () => {
856
- this._helper.transaction(asyncResult(event.taskId, {
857
- success: true,
858
- roomName: event.roomName,
859
- }));
860
- },
861
- reject: (code, message) => {
862
- this._helper.transaction(asyncResult(event.taskId, {
863
- success: false,
864
- roomName: event.roomName,
865
- errorCode: code,
866
- errorMessage: message,
867
- }));
868
- },
869
- };
870
- this._roomLeave.next(leave);
871
- }
872
- }
873
- catch (e) {
874
- console.error('[RecordsManager] Error leaving room:', e);
875
- if (hasValue(event.taskId)) {
876
- this._helper.transaction(asyncError(event.taskId, e.toString()));
877
- }
900
+ async _joinRoom(event) {
901
+ try {
902
+ const info = await this._resolveInfoForEvent(event, false);
903
+ if (info.error) {
904
+ // if (hasValue(event.taskId)) {
905
+ // this._helper.transaction(
906
+ // asyncResult(event.taskId, {
907
+ // success: false,
908
+ // errorCode: 'not_supported',
909
+ // errorMessage:
910
+ // 'Records are not supported on this inst.',
911
+ // } as IssueMeetTokenResult)
912
+ // );
913
+ // }
914
+ return;
878
915
  }
879
- });
880
- }
881
- _setRoomOptions(event) {
882
- return __awaiter(this, void 0, void 0, function* () {
883
- try {
884
- if (hasValue(event.taskId)) {
885
- const leave = {
886
- roomName: event.roomName,
916
+ if (hasValue(event.taskId)) {
917
+ const userId = this._helper.userId;
918
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/meet/token'), {
919
+ roomName: event.roomName,
920
+ userName: userId,
921
+ }, { ...this._axiosOptions });
922
+ const data = result.data;
923
+ if (data.success) {
924
+ const join = {
925
+ roomName: data.roomName,
926
+ token: data.token,
927
+ url: data.url,
887
928
  options: event.options,
888
929
  resolve: (options) => {
889
930
  this._helper.transaction(asyncResult(event.taskId, {
890
931
  success: true,
891
- roomName: event.roomName,
932
+ roomName: data.roomName,
892
933
  options,
893
934
  }));
894
935
  },
895
936
  reject: (code, message) => {
896
937
  this._helper.transaction(asyncResult(event.taskId, {
897
938
  success: false,
898
- roomName: event.roomName,
939
+ roomName: data.roomName,
899
940
  errorCode: code,
900
941
  errorMessage: message,
901
942
  }));
902
943
  },
903
944
  };
904
- this._onSetRoomOptions.next(leave);
945
+ this._roomJoin.next(join);
905
946
  }
906
- }
907
- catch (e) {
908
- console.error('[RecordsManager] Error setting room options:', e);
909
- if (hasValue(event.taskId)) {
910
- this._helper.transaction(asyncError(event.taskId, e.toString()));
947
+ else {
948
+ this._helper.transaction(asyncResult(event.taskId, data));
911
949
  }
912
950
  }
913
- });
951
+ }
952
+ catch (e) {
953
+ console.error('[RecordsManager] Error joining room:', e);
954
+ if (hasValue(event.taskId)) {
955
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
956
+ }
957
+ }
914
958
  }
915
- _getRoomOptions(event) {
916
- return __awaiter(this, void 0, void 0, function* () {
917
- try {
918
- if (hasValue(event.taskId)) {
919
- const getRoomOptions = {
920
- roomName: event.roomName,
921
- resolve: (options) => {
922
- this._helper.transaction(asyncResult(event.taskId, {
923
- success: true,
924
- roomName: event.roomName,
925
- options: options,
926
- }));
927
- },
928
- reject: (code, message) => {
929
- this._helper.transaction(asyncResult(event.taskId, {
930
- success: false,
931
- roomName: event.roomName,
932
- errorCode: code,
933
- errorMessage: message,
934
- }));
935
- },
936
- };
937
- this._onGetRoomOptions.next(getRoomOptions);
938
- }
959
+ async _leaveRoom(event) {
960
+ try {
961
+ if (hasValue(event.taskId)) {
962
+ const leave = {
963
+ roomName: event.roomName,
964
+ resolve: () => {
965
+ this._helper.transaction(asyncResult(event.taskId, {
966
+ success: true,
967
+ roomName: event.roomName,
968
+ }));
969
+ },
970
+ reject: (code, message) => {
971
+ this._helper.transaction(asyncResult(event.taskId, {
972
+ success: false,
973
+ roomName: event.roomName,
974
+ errorCode: code,
975
+ errorMessage: message,
976
+ }));
977
+ },
978
+ };
979
+ this._roomLeave.next(leave);
939
980
  }
940
- catch (e) {
941
- console.error('[RecordsManager] Error setting room options:', e);
942
- if (hasValue(event.taskId)) {
943
- this._helper.transaction(asyncError(event.taskId, e.toString()));
944
- }
981
+ }
982
+ catch (e) {
983
+ console.error('[RecordsManager] Error leaving room:', e);
984
+ if (hasValue(event.taskId)) {
985
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
945
986
  }
946
- });
987
+ }
947
988
  }
948
- _grantRecordPermission(event) {
949
- return __awaiter(this, void 0, void 0, function* () {
950
- try {
951
- const info = yield this._resolveInfoForEvent(event);
952
- if (info.error) {
953
- return;
954
- }
955
- console.log('[RecordsManager] Granting policy permission...', event);
956
- let instances = undefined;
957
- if (hasValue(this._helper.origin)) {
958
- instances = [
959
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
960
- ];
961
- }
962
- let requestData = {
963
- recordName: event.recordName,
964
- permission: event.permission,
965
- instances,
989
+ async _setRoomOptions(event) {
990
+ try {
991
+ if (hasValue(event.taskId)) {
992
+ const leave = {
993
+ roomName: event.roomName,
994
+ options: event.options,
995
+ resolve: (options) => {
996
+ this._helper.transaction(asyncResult(event.taskId, {
997
+ success: true,
998
+ roomName: event.roomName,
999
+ options,
1000
+ }));
1001
+ },
1002
+ reject: (code, message) => {
1003
+ this._helper.transaction(asyncResult(event.taskId, {
1004
+ success: false,
1005
+ roomName: event.roomName,
1006
+ errorCode: code,
1007
+ errorMessage: message,
1008
+ }));
1009
+ },
966
1010
  };
967
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/permissions'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
968
- if (result.data.success) {
969
- console.log('[RecordsManager] Permission granted!');
970
- }
971
- if (hasValue(event.taskId)) {
972
- this._helper.transaction(asyncResult(event.taskId, result.data));
973
- }
1011
+ this._onSetRoomOptions.next(leave);
974
1012
  }
975
- catch (e) {
976
- console.error('[RecordsManager] Error granting record permission:', e);
977
- if (hasValue(event.taskId)) {
978
- this._helper.transaction(asyncError(event.taskId, e.toString()));
979
- }
1013
+ }
1014
+ catch (e) {
1015
+ console.error('[RecordsManager] Error setting room options:', e);
1016
+ if (hasValue(event.taskId)) {
1017
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
980
1018
  }
981
- });
1019
+ }
982
1020
  }
983
- _revokeRecordPermission(event) {
984
- return __awaiter(this, void 0, void 0, function* () {
985
- try {
986
- const info = yield this._resolveInfoForEvent(event);
987
- if (info.error) {
988
- return;
989
- }
990
- console.log('[RecordsManager] Revoking policy permission...', event);
991
- let instances = undefined;
992
- if (hasValue(this._helper.origin)) {
993
- instances = [
994
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
995
- ];
996
- }
997
- let requestData = {
998
- recordName: event.recordName,
999
- permissionId: event.permissionId,
1000
- instances,
1021
+ async _getRoomOptions(event) {
1022
+ try {
1023
+ if (hasValue(event.taskId)) {
1024
+ const getRoomOptions = {
1025
+ roomName: event.roomName,
1026
+ resolve: (options) => {
1027
+ this._helper.transaction(asyncResult(event.taskId, {
1028
+ success: true,
1029
+ roomName: event.roomName,
1030
+ options: options,
1031
+ }));
1032
+ },
1033
+ reject: (code, message) => {
1034
+ this._helper.transaction(asyncResult(event.taskId, {
1035
+ success: false,
1036
+ roomName: event.roomName,
1037
+ errorCode: code,
1038
+ errorMessage: message,
1039
+ }));
1040
+ },
1001
1041
  };
1002
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/permissions/revoke'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1003
- if (result.data.success) {
1004
- console.log('[RecordsManager] Permission revoked!');
1005
- }
1042
+ this._onGetRoomOptions.next(getRoomOptions);
1043
+ }
1044
+ }
1045
+ catch (e) {
1046
+ console.error('[RecordsManager] Error setting room options:', e);
1047
+ if (hasValue(event.taskId)) {
1048
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1049
+ }
1050
+ }
1051
+ }
1052
+ async _grantRecordPermission(event) {
1053
+ try {
1054
+ const info = await this._resolveInfoForEvent(event);
1055
+ if (info.error) {
1056
+ return;
1057
+ }
1058
+ console.log('[RecordsManager] Granting policy permission...', event);
1059
+ let instances = undefined;
1060
+ if (hasValue(this._helper.origin)) {
1061
+ instances = [
1062
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1063
+ ];
1064
+ }
1065
+ let requestData = {
1066
+ recordName: event.recordName,
1067
+ permission: event.permission,
1068
+ instances,
1069
+ };
1070
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/permissions'), requestData, {
1071
+ ...this._axiosOptions,
1072
+ headers: info.headers,
1073
+ });
1074
+ if (result.data.success) {
1075
+ console.log('[RecordsManager] Permission granted!');
1076
+ }
1077
+ if (hasValue(event.taskId)) {
1078
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1079
+ }
1080
+ }
1081
+ catch (e) {
1082
+ console.error('[RecordsManager] Error granting record permission:', e);
1083
+ if (hasValue(event.taskId)) {
1084
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1085
+ }
1086
+ }
1087
+ }
1088
+ async _revokeRecordPermission(event) {
1089
+ try {
1090
+ const info = await this._resolveInfoForEvent(event);
1091
+ if (info.error) {
1092
+ return;
1093
+ }
1094
+ console.log('[RecordsManager] Revoking policy permission...', event);
1095
+ let instances = undefined;
1096
+ if (hasValue(this._helper.origin)) {
1097
+ instances = [
1098
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1099
+ ];
1100
+ }
1101
+ let requestData = {
1102
+ recordName: event.recordName,
1103
+ permissionId: event.permissionId,
1104
+ instances,
1105
+ };
1106
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/permissions/revoke'), requestData, {
1107
+ ...this._axiosOptions,
1108
+ headers: info.headers,
1109
+ });
1110
+ if (result.data.success) {
1111
+ console.log('[RecordsManager] Permission revoked!');
1112
+ }
1113
+ if (hasValue(event.taskId)) {
1114
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1115
+ }
1116
+ }
1117
+ catch (e) {
1118
+ console.error('[RecordsManager] Error revoking policy permission:', e);
1119
+ if (hasValue(event.taskId)) {
1120
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1121
+ }
1122
+ }
1123
+ }
1124
+ async _grantInstAdminPermission(event) {
1125
+ if (!event[APPROVED_SYMBOL]) {
1126
+ return;
1127
+ }
1128
+ try {
1129
+ const info = await this._resolveInfoForEvent(event);
1130
+ if (info.error) {
1131
+ return;
1132
+ }
1133
+ if (!hasValue(this._helper.origin)) {
1006
1134
  if (hasValue(event.taskId)) {
1007
- this._helper.transaction(asyncResult(event.taskId, result.data));
1135
+ this._helper.transaction(asyncError(event.taskId, 'Unable to grant inst admin permission with no simulation origin!'));
1008
1136
  }
1137
+ return;
1138
+ }
1139
+ const now = DateTime.now();
1140
+ const plusOneDay = now.plus({ day: 1 });
1141
+ const startOfNextDay = plusOneDay.set({
1142
+ hour: 0,
1143
+ minute: 0,
1144
+ second: 0,
1145
+ millisecond: 0,
1146
+ });
1147
+ console.log('[RecordsManager] Granting inst admin role...', event);
1148
+ let requestData = {
1149
+ recordName: event.recordName,
1150
+ inst: formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1151
+ role: 'admin',
1152
+ expireTimeMs: startOfNextDay.toMillis(),
1153
+ };
1154
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/role/grant'), requestData, {
1155
+ ...this._axiosOptions,
1156
+ headers: info.headers,
1157
+ });
1158
+ if (result.data.success) {
1159
+ console.log('[RecordsManager] Role granted!');
1160
+ }
1161
+ if (hasValue(event.taskId)) {
1162
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1163
+ }
1164
+ }
1165
+ catch (e) {
1166
+ console.error('[RecordsManager] Error granting inst admin role:', e);
1167
+ if (hasValue(event.taskId)) {
1168
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1169
+ }
1170
+ }
1171
+ }
1172
+ async _grantRole(event) {
1173
+ try {
1174
+ const info = await this._resolveInfoForEvent(event);
1175
+ if (info.error) {
1176
+ return;
1177
+ }
1178
+ console.log('[RecordsManager] Granting role...', event);
1179
+ let instances = undefined;
1180
+ if (hasValue(this._helper.origin)) {
1181
+ instances = [
1182
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1183
+ ];
1184
+ }
1185
+ let requestData = {
1186
+ recordName: event.recordName,
1187
+ userId: event.userId,
1188
+ inst: event.inst,
1189
+ role: event.role,
1190
+ expireTimeMs: event.expireTimeMs,
1191
+ instances,
1192
+ };
1193
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/role/grant'), requestData, {
1194
+ ...this._axiosOptions,
1195
+ headers: info.headers,
1196
+ });
1197
+ if (result.data.success) {
1198
+ console.log('[RecordsManager] Role granted!');
1199
+ }
1200
+ if (hasValue(event.taskId)) {
1201
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1202
+ }
1203
+ }
1204
+ catch (e) {
1205
+ console.error('[RecordsManager] Error granting role:', e);
1206
+ if (hasValue(event.taskId)) {
1207
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1009
1208
  }
1010
- catch (e) {
1011
- console.error('[RecordsManager] Error revoking policy permission:', e);
1209
+ }
1210
+ }
1211
+ async _revokeRole(event) {
1212
+ try {
1213
+ const info = await this._resolveInfoForEvent(event);
1214
+ if (info.error) {
1215
+ return;
1216
+ }
1217
+ let instances = undefined;
1218
+ if (hasValue(this._helper.origin)) {
1219
+ instances = [
1220
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1221
+ ];
1222
+ }
1223
+ console.log('[RecordsManager] Revoking role...', event);
1224
+ let requestData = {
1225
+ recordName: event.recordName,
1226
+ userId: event.userId,
1227
+ inst: event.inst,
1228
+ role: event.role,
1229
+ instances,
1230
+ };
1231
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/records/role/revoke'), requestData, {
1232
+ ...this._axiosOptions,
1233
+ headers: info.headers,
1234
+ });
1235
+ if (result.data.success) {
1236
+ console.log('[RecordsManager] Role revoked!');
1237
+ }
1238
+ if (hasValue(event.taskId)) {
1239
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1240
+ }
1241
+ }
1242
+ catch (e) {
1243
+ console.error('[RecordsManager] Error revoking role:', e);
1244
+ if (hasValue(event.taskId)) {
1245
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1246
+ }
1247
+ }
1248
+ }
1249
+ async _aiChat(event) {
1250
+ try {
1251
+ const info = await this._resolveInfoForEvent(event);
1252
+ if (info.error) {
1253
+ return;
1254
+ }
1255
+ if (!info.token) {
1012
1256
  if (hasValue(event.taskId)) {
1013
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1257
+ this._helper.transaction(asyncResult(event.taskId, {
1258
+ success: false,
1259
+ errorCode: 'not_logged_in',
1260
+ errorMessage: 'The user is not logged in.',
1261
+ }));
1014
1262
  }
1263
+ return;
1015
1264
  }
1016
- });
1265
+ const { endpoint, preferredModel, ...rest } = event.options;
1266
+ let requestData = {
1267
+ ...rest,
1268
+ model: preferredModel,
1269
+ messages: event.messages,
1270
+ };
1271
+ if (hasValue(this._helper.origin)) {
1272
+ requestData.instances = [
1273
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1274
+ ];
1275
+ }
1276
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/ai/chat'), requestData, {
1277
+ ...this._axiosOptions,
1278
+ headers: info.headers,
1279
+ });
1280
+ if (hasValue(event.taskId)) {
1281
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1282
+ }
1283
+ }
1284
+ catch (e) {
1285
+ console.error('[RecordsManager] Error sending chat message:', e);
1286
+ if (hasValue(event.taskId)) {
1287
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1288
+ }
1289
+ }
1017
1290
  }
1018
- _grantInstAdminPermission(event) {
1019
- return __awaiter(this, void 0, void 0, function* () {
1020
- if (!event[APPROVED_SYMBOL]) {
1291
+ async _aiChatStream(event) {
1292
+ try {
1293
+ const info = await this._resolveInfoForEvent(event);
1294
+ if (info.error) {
1021
1295
  return;
1022
1296
  }
1023
- try {
1024
- const info = yield this._resolveInfoForEvent(event);
1025
- if (info.error) {
1026
- return;
1027
- }
1028
- if (!hasValue(this._helper.origin)) {
1029
- if (hasValue(event.taskId)) {
1030
- this._helper.transaction(asyncError(event.taskId, 'Unable to grant inst admin permission with no simulation origin!'));
1031
- }
1032
- return;
1297
+ if (!info.token) {
1298
+ if (hasValue(event.taskId)) {
1299
+ this._helper.transaction(asyncResult(event.taskId, {
1300
+ success: false,
1301
+ errorCode: 'not_logged_in',
1302
+ errorMessage: 'The user is not logged in.',
1303
+ }));
1033
1304
  }
1034
- const now = DateTime.now();
1035
- const plusOneDay = now.plus({ day: 1 });
1036
- const startOfNextDay = plusOneDay.set({
1037
- hour: 0,
1038
- minute: 0,
1039
- second: 0,
1040
- millisecond: 0,
1305
+ return;
1306
+ }
1307
+ const { endpoint, preferredModel, ...rest } = event.options;
1308
+ let requestData = {
1309
+ ...rest,
1310
+ model: preferredModel,
1311
+ messages: event.messages,
1312
+ };
1313
+ if (hasValue(this._helper.origin)) {
1314
+ requestData.instances = [
1315
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1316
+ ];
1317
+ }
1318
+ if (USE_HTTP_STREAMING) {
1319
+ const result = await this._client.aiChatStream(requestData, {
1320
+ sessionKey: info.token,
1321
+ endpoint: info.recordsOrigin,
1041
1322
  });
1042
- console.log('[RecordsManager] Granting inst admin role...', event);
1043
- let requestData = {
1044
- recordName: event.recordName,
1045
- inst: formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1046
- role: 'admin',
1047
- expireTimeMs: startOfNextDay.toMillis(),
1048
- };
1049
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/role/grant'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1050
- if (result.data.success) {
1051
- console.log('[RecordsManager] Role granted!');
1052
- }
1053
1323
  if (hasValue(event.taskId)) {
1054
- this._helper.transaction(asyncResult(event.taskId, result.data));
1324
+ if (Symbol.asyncIterator in result) {
1325
+ this._helper.transaction(asyncResult(event.taskId, {
1326
+ success: true,
1327
+ }));
1328
+ try {
1329
+ for await (let data of result) {
1330
+ this._helper.transaction(iterableNext(event.taskId, data));
1331
+ }
1332
+ this._helper.transaction(iterableComplete(event.taskId));
1333
+ }
1334
+ catch (err) {
1335
+ this._helper.transaction(iterableThrow(event.taskId, err));
1336
+ }
1337
+ }
1338
+ else {
1339
+ this._helper.transaction(asyncResult(event.taskId, result));
1340
+ }
1055
1341
  }
1342
+ return;
1056
1343
  }
1057
- catch (e) {
1058
- console.error('[RecordsManager] Error granting inst admin role:', e);
1344
+ const client = await this._getWebsocketClient(info.websocketOrigin, info.websocketProtocol);
1345
+ if (!client) {
1059
1346
  if (hasValue(event.taskId)) {
1060
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1347
+ this._helper.transaction(asyncResult(event.taskId, {
1348
+ success: false,
1349
+ errorCode: 'not_supported',
1350
+ errorMessage: 'Streaming AI chat is not supported on this inst.',
1351
+ }));
1061
1352
  }
1353
+ return;
1062
1354
  }
1063
- });
1355
+ const result = await this._sendWebsocketStreamRequest(client, 'POST', '/api/v2/ai/chat/stream', {}, requestData, info.headers);
1356
+ if (hasValue(event.taskId)) {
1357
+ this._helper.transaction(asyncResult(event.taskId, {
1358
+ success: true,
1359
+ }));
1360
+ result.subscribe({
1361
+ next: (data) => {
1362
+ this._helper.transaction(iterableNext(event.taskId, data));
1363
+ },
1364
+ error: (err) => {
1365
+ this._helper.transaction(iterableThrow(event.taskId, err));
1366
+ },
1367
+ complete: () => {
1368
+ this._helper.transaction(iterableComplete(event.taskId));
1369
+ },
1370
+ });
1371
+ }
1372
+ }
1373
+ catch (e) {
1374
+ console.error('[RecordsManager] Error sending chat message:', e);
1375
+ if (hasValue(event.taskId)) {
1376
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1377
+ }
1378
+ }
1064
1379
  }
1065
- _grantRole(event) {
1066
- return __awaiter(this, void 0, void 0, function* () {
1067
- try {
1068
- const info = yield this._resolveInfoForEvent(event);
1069
- if (info.error) {
1070
- return;
1071
- }
1072
- console.log('[RecordsManager] Granting role...', event);
1073
- let instances = undefined;
1074
- if (hasValue(this._helper.origin)) {
1075
- instances = [
1076
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1077
- ];
1078
- }
1079
- let requestData = {
1080
- recordName: event.recordName,
1081
- userId: event.userId,
1082
- inst: event.inst,
1083
- role: event.role,
1084
- expireTimeMs: event.expireTimeMs,
1085
- instances,
1086
- };
1087
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/role/grant'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1088
- if (result.data.success) {
1089
- console.log('[RecordsManager] Role granted!');
1090
- }
1380
+ async _aiGenerateSkybox(event) {
1381
+ try {
1382
+ const info = await this._resolveInfoForEvent(event);
1383
+ if (info.error) {
1384
+ return;
1385
+ }
1386
+ if (!info.token) {
1091
1387
  if (hasValue(event.taskId)) {
1092
- this._helper.transaction(asyncResult(event.taskId, result.data));
1388
+ this._helper.transaction(asyncResult(event.taskId, {
1389
+ success: false,
1390
+ errorCode: 'not_logged_in',
1391
+ errorMessage: 'The user is not logged in.',
1392
+ }));
1093
1393
  }
1394
+ return;
1094
1395
  }
1095
- catch (e) {
1096
- console.error('[RecordsManager] Error granting role:', e);
1396
+ const { endpoint, blockadeLabs, ...rest } = event.options;
1397
+ let requestData = {
1398
+ prompt: event.prompt,
1399
+ negativePrompt: event.negativePrompt,
1400
+ blockadeLabs: blockadeLabs,
1401
+ };
1402
+ let instances = undefined;
1403
+ if (hasValue(this._helper.origin)) {
1404
+ instances = [
1405
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1406
+ ];
1407
+ }
1408
+ const result = await axios.post(await this._publishUrl(info.recordsOrigin, '/api/v2/ai/skybox'), {
1409
+ ...requestData,
1410
+ instances,
1411
+ }, {
1412
+ ...this._axiosOptions,
1413
+ headers: info.headers,
1414
+ });
1415
+ if (!result.data.success) {
1097
1416
  if (hasValue(event.taskId)) {
1098
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1417
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1099
1418
  }
1419
+ return;
1100
1420
  }
1101
- });
1102
- }
1103
- _revokeRole(event) {
1104
- return __awaiter(this, void 0, void 0, function* () {
1105
- try {
1106
- const info = yield this._resolveInfoForEvent(event);
1107
- if (info.error) {
1108
- return;
1109
- }
1110
- let instances = undefined;
1111
- if (hasValue(this._helper.origin)) {
1112
- instances = [
1113
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1114
- ];
1115
- }
1116
- console.log('[RecordsManager] Revoking role...', event);
1117
- let requestData = {
1118
- recordName: event.recordName,
1119
- userId: event.userId,
1120
- inst: event.inst,
1121
- role: event.role,
1421
+ const skyboxId = result.data.skyboxId;
1422
+ for (let i = 0; i < 10; i++) {
1423
+ if (!this._skipTimers) {
1424
+ const seconds = i === 0
1425
+ ? 1
1426
+ : i === 1
1427
+ ? 4
1428
+ : i === 2
1429
+ ? 4
1430
+ : i === 3
1431
+ ? 8
1432
+ : i === 4
1433
+ ? 16
1434
+ : i === 5
1435
+ ? 32
1436
+ : 32;
1437
+ await wait(seconds);
1438
+ }
1439
+ const getResult = await axios.get(await this._publishUrl(info.recordsOrigin, '/api/v2/ai/skybox', {
1440
+ skyboxId: result.data.skyboxId,
1122
1441
  instances,
1123
- };
1124
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/records/role/revoke'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1125
- if (result.data.success) {
1126
- console.log('[RecordsManager] Role revoked!');
1442
+ }), {
1443
+ ...this._axiosOptions,
1444
+ headers: info.headers,
1445
+ });
1446
+ if (getResult.data.success) {
1447
+ if (getResult.data.status === 'generated') {
1448
+ if (hasValue(event.taskId)) {
1449
+ this._helper.transaction(asyncResult(event.taskId, getResult.data));
1450
+ }
1451
+ return;
1452
+ }
1127
1453
  }
1454
+ }
1455
+ if (hasValue(event.taskId)) {
1456
+ this._helper.transaction(asyncResult(event.taskId, {
1457
+ success: false,
1458
+ errorCode: 'server_error',
1459
+ errorMessage: 'The request timed out.',
1460
+ }));
1461
+ }
1462
+ }
1463
+ catch (e) {
1464
+ console.error('[RecordsManager] Error generating skybox:', e);
1465
+ if (hasValue(event.taskId)) {
1466
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1467
+ }
1468
+ }
1469
+ }
1470
+ async _aiGenerateImage(event) {
1471
+ try {
1472
+ const info = await this._resolveInfoForEvent(event);
1473
+ if (info.error) {
1474
+ return;
1475
+ }
1476
+ if (!info.token) {
1128
1477
  if (hasValue(event.taskId)) {
1129
- this._helper.transaction(asyncResult(event.taskId, result.data));
1478
+ this._helper.transaction(asyncResult(event.taskId, {
1479
+ success: false,
1480
+ errorCode: 'not_logged_in',
1481
+ errorMessage: 'The user is not logged in.',
1482
+ }));
1130
1483
  }
1484
+ return;
1485
+ }
1486
+ const { taskId, type, options, ...rest } = event;
1487
+ let requestData = {
1488
+ ...rest,
1489
+ };
1490
+ let instances = undefined;
1491
+ if (hasValue(this._helper.origin)) {
1492
+ instances = [
1493
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1494
+ ];
1495
+ }
1496
+ const result = await this._sendWebsocketSupportedRequest(info.recordsOrigin, info.websocketOrigin, info.websocketProtocol, 'POST', '/api/v2/ai/image', {}, {
1497
+ ...requestData,
1498
+ instances,
1499
+ }, info.headers);
1500
+ if (hasValue(event.taskId)) {
1501
+ this._helper.transaction(asyncResult(event.taskId, result));
1131
1502
  }
1132
- catch (e) {
1133
- console.error('[RecordsManager] Error revoking role:', e);
1503
+ }
1504
+ catch (e) {
1505
+ console.error('[RecordsManager] Error generating image:', e);
1506
+ if (hasValue(event.taskId)) {
1507
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1508
+ }
1509
+ }
1510
+ }
1511
+ async _aiHumeGetAccessToken(event) {
1512
+ try {
1513
+ const info = await this._resolveInfoForEvent(event);
1514
+ if (info.error) {
1515
+ return;
1516
+ }
1517
+ if (!info.token) {
1134
1518
  if (hasValue(event.taskId)) {
1135
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1519
+ this._helper.transaction(asyncResult(event.taskId, {
1520
+ success: false,
1521
+ errorCode: 'not_logged_in',
1522
+ errorMessage: 'The user is not logged in.',
1523
+ }));
1136
1524
  }
1525
+ return;
1137
1526
  }
1138
- });
1527
+ const result = await this._client.getHumeAccessToken({
1528
+ recordName: event.recordName,
1529
+ }, {
1530
+ sessionKey: info.token,
1531
+ endpoint: info.recordsOrigin,
1532
+ });
1533
+ if (hasValue(event.taskId)) {
1534
+ this._helper.transaction(asyncResult(event.taskId, result));
1535
+ }
1536
+ }
1537
+ catch (e) {
1538
+ console.error('[RecordsManager] Error getting Hume access token:', e);
1539
+ if (hasValue(event.taskId)) {
1540
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1541
+ }
1542
+ }
1139
1543
  }
1140
- _aiChat(event) {
1141
- return __awaiter(this, void 0, void 0, function* () {
1142
- try {
1143
- const info = yield this._resolveInfoForEvent(event);
1144
- if (info.error) {
1145
- return;
1146
- }
1147
- if (!info.token) {
1148
- if (hasValue(event.taskId)) {
1149
- this._helper.transaction(asyncResult(event.taskId, {
1150
- success: false,
1151
- errorCode: 'not_logged_in',
1152
- errorMessage: 'The user is not logged in.',
1153
- }));
1154
- }
1155
- return;
1544
+ async _aiSloydGenerateModel(event) {
1545
+ try {
1546
+ const info = await this._resolveInfoForEvent(event);
1547
+ if (info.error) {
1548
+ return;
1549
+ }
1550
+ if (!info.token) {
1551
+ if (hasValue(event.taskId)) {
1552
+ this._helper.transaction(asyncResult(event.taskId, {
1553
+ success: false,
1554
+ errorCode: 'not_logged_in',
1555
+ errorMessage: 'The user is not logged in.',
1556
+ }));
1156
1557
  }
1157
- const _a = event.options, { endpoint, preferredModel } = _a, rest = __rest(_a, ["endpoint", "preferredModel"]);
1158
- let requestData = Object.assign(Object.assign({}, rest), { model: preferredModel, messages: event.messages });
1159
- if (hasValue(this._helper.origin)) {
1160
- requestData.instances = [
1161
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1162
- ];
1558
+ return;
1559
+ }
1560
+ const result = await this._client.createSloydModel({
1561
+ recordName: event.recordName,
1562
+ prompt: event.prompt,
1563
+ baseModelId: event.baseModelId,
1564
+ levelOfDetail: event.levelOfDetail,
1565
+ outputMimeType: event.outputMimeType,
1566
+ thumbnail: event.thumbnail,
1567
+ }, {
1568
+ endpoint: info.recordsOrigin,
1569
+ sessionKey: info.token,
1570
+ });
1571
+ if (hasValue(event.taskId)) {
1572
+ this._helper.transaction(asyncResult(event.taskId, result));
1573
+ }
1574
+ }
1575
+ catch (e) {
1576
+ console.error('[RecordsManager] Error generating Sloyd model:', e);
1577
+ if (hasValue(event.taskId)) {
1578
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1579
+ }
1580
+ }
1581
+ }
1582
+ async _recordPackageVersion(event) {
1583
+ try {
1584
+ const info = await this._resolveInfoForEvent(event);
1585
+ if (info.error) {
1586
+ return;
1587
+ }
1588
+ const fileInfo = await this._resolveRecordFileInfo(event.request.state, 'application/json');
1589
+ if (fileInfo.success === false) {
1590
+ if (hasValue(event.taskId)) {
1591
+ this._helper.transaction(asyncResult(event.taskId, fileInfo));
1163
1592
  }
1164
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/ai/chat'), requestData, Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1593
+ return;
1594
+ }
1595
+ const { byteLength, hash, mimeType, data } = fileInfo;
1596
+ let instances = undefined;
1597
+ if (hasValue(this._helper.origin)) {
1598
+ instances = [
1599
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1600
+ ];
1601
+ }
1602
+ const result = await this._client.recordPackageVersion({
1603
+ recordName: event.request.recordName,
1604
+ item: {
1605
+ address: event.request.address,
1606
+ key: event.request.key,
1607
+ description: event.request.description,
1608
+ entitlements: event.request.entitlements,
1609
+ markers: event.request.markers,
1610
+ auxFileRequest: {
1611
+ fileByteLength: byteLength,
1612
+ fileSha256Hex: hash,
1613
+ fileMimeType: mimeType,
1614
+ fileDescription: `${event.request.recordName}/${event.request.address}@${formatVersionNumber(event.request.key.major, event.request.key.minor, event.request.key.patch, event.request.key.tag)}`,
1615
+ },
1616
+ },
1617
+ instances,
1618
+ }, {
1619
+ endpoint: info.recordsOrigin,
1620
+ sessionKey: info.token,
1621
+ });
1622
+ if (result.success === false) {
1165
1623
  if (hasValue(event.taskId)) {
1166
- this._helper.transaction(asyncResult(event.taskId, result.data));
1624
+ this._helper.transaction(asyncResult(event.taskId, result));
1167
1625
  }
1626
+ return;
1168
1627
  }
1169
- catch (e) {
1170
- console.error('[RecordsManager] Error sending chat message:', e);
1628
+ const uploadResult = await this._uploadFile(result.auxFileResult, data, hash);
1629
+ if (uploadResult.success === false) {
1171
1630
  if (hasValue(event.taskId)) {
1172
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1631
+ this._helper.transaction(asyncResult(event.taskId, uploadResult));
1173
1632
  }
1633
+ return;
1174
1634
  }
1175
- });
1635
+ if (hasValue(event.taskId)) {
1636
+ this._helper.transaction(asyncResult(event.taskId, {
1637
+ success: true,
1638
+ recordName: result.recordName,
1639
+ address: result.address,
1640
+ auxFileResult: uploadResult,
1641
+ }));
1642
+ }
1643
+ }
1644
+ catch (e) {
1645
+ console.error('[RecordsManager] Error recording package version:', e);
1646
+ if (hasValue(event.taskId)) {
1647
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1648
+ }
1649
+ }
1176
1650
  }
1177
- _aiChatStream(event) {
1178
- var _a, e_1, _b, _c;
1179
- return __awaiter(this, void 0, void 0, function* () {
1180
- try {
1181
- const info = yield this._resolveInfoForEvent(event);
1182
- if (info.error) {
1183
- return;
1651
+ async _installPackage(event) {
1652
+ var _a;
1653
+ try {
1654
+ const info = await this._resolveInfoForEvent(event);
1655
+ if (info.error) {
1656
+ return;
1657
+ }
1658
+ let instances = undefined;
1659
+ if (hasValue(this._helper.origin)) {
1660
+ instances = [
1661
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1662
+ ];
1663
+ }
1664
+ if ((_a = this._helper.origin) === null || _a === void 0 ? void 0 : _a.isStatic) {
1665
+ // static origins need to install packages via fetching the package
1666
+ const input = {
1667
+ recordName: event.recordName,
1668
+ address: event.address,
1669
+ instances,
1670
+ };
1671
+ if (typeof event.key === 'string') {
1672
+ input.key = event.key;
1184
1673
  }
1185
- if (!info.token) {
1186
- if (hasValue(event.taskId)) {
1187
- this._helper.transaction(asyncResult(event.taskId, {
1188
- success: false,
1189
- errorCode: 'not_logged_in',
1190
- errorMessage: 'The user is not logged in.',
1191
- }));
1674
+ else if (typeof event.key === 'object') {
1675
+ if (event.key.sha256) {
1676
+ input.sha256 = event.key.sha256;
1192
1677
  }
1193
- return;
1194
- }
1195
- const _d = event.options, { endpoint, preferredModel } = _d, rest = __rest(_d, ["endpoint", "preferredModel"]);
1196
- let requestData = Object.assign(Object.assign({}, rest), { model: preferredModel, messages: event.messages });
1197
- if (hasValue(this._helper.origin)) {
1198
- requestData.instances = [
1199
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1200
- ];
1201
- }
1202
- if (USE_HTTP_STREAMING) {
1203
- const result = yield this._client.aiChatStream(requestData, {
1204
- sessionKey: info.token,
1205
- endpoint: info.recordsOrigin,
1206
- });
1207
- if (hasValue(event.taskId)) {
1208
- if (Symbol.asyncIterator in result) {
1209
- this._helper.transaction(asyncResult(event.taskId, {
1210
- success: true,
1211
- }));
1212
- try {
1213
- try {
1214
- for (var _e = true, result_1 = __asyncValues(result), result_1_1; result_1_1 = yield result_1.next(), _a = result_1_1.done, !_a; _e = true) {
1215
- _c = result_1_1.value;
1216
- _e = false;
1217
- let data = _c;
1218
- this._helper.transaction(iterableNext(event.taskId, data));
1219
- }
1220
- }
1221
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1222
- finally {
1223
- try {
1224
- if (!_e && !_a && (_b = result_1.return)) yield _b.call(result_1);
1225
- }
1226
- finally { if (e_1) throw e_1.error; }
1227
- }
1228
- this._helper.transaction(iterableComplete(event.taskId));
1229
- }
1230
- catch (err) {
1231
- this._helper.transaction(iterableThrow(event.taskId, err));
1232
- }
1233
- }
1234
- else {
1235
- this._helper.transaction(asyncResult(event.taskId, result));
1236
- }
1678
+ else {
1679
+ input.major = event.key.major;
1680
+ input.minor = event.key.minor;
1681
+ input.patch = event.key.patch;
1682
+ input.tag = event.key.tag;
1237
1683
  }
1238
- return;
1239
1684
  }
1240
- const client = yield this._getWebsocketClient(info.websocketOrigin, info.websocketProtocol);
1241
- if (!client) {
1685
+ const result = await this._client.getPackageVersion(input, {
1686
+ sessionKey: info.token,
1687
+ endpoint: info.recordsOrigin,
1688
+ });
1689
+ if (result.success === false) {
1242
1690
  if (hasValue(event.taskId)) {
1243
- this._helper.transaction(asyncResult(event.taskId, {
1244
- success: false,
1245
- errorCode: 'not_supported',
1246
- errorMessage: 'Streaming AI chat is not supported on this inst.',
1247
- }));
1691
+ this._helper.transaction(asyncResult(event.taskId, result));
1248
1692
  }
1249
1693
  return;
1250
1694
  }
1251
- const result = yield this._sendWebsocketStreamRequest(client, 'POST', '/api/v2/ai/chat/stream', {}, requestData, info.headers);
1252
- if (hasValue(event.taskId)) {
1253
- this._helper.transaction(asyncResult(event.taskId, {
1254
- success: true,
1255
- }));
1256
- result.subscribe({
1257
- next: (data) => {
1258
- this._helper.transaction(iterableNext(event.taskId, data));
1259
- },
1260
- error: (err) => {
1261
- this._helper.transaction(iterableThrow(event.taskId, err));
1262
- },
1263
- complete: () => {
1264
- this._helper.transaction(iterableComplete(event.taskId));
1265
- },
1266
- });
1267
- }
1268
- }
1269
- catch (e) {
1270
- console.error('[RecordsManager] Error sending chat message:', e);
1271
- if (hasValue(event.taskId)) {
1272
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1273
- }
1274
- }
1275
- });
1276
- }
1277
- _aiGenerateSkybox(event) {
1278
- return __awaiter(this, void 0, void 0, function* () {
1279
- try {
1280
- const info = yield this._resolveInfoForEvent(event);
1281
- if (info.error) {
1282
- return;
1283
- }
1284
- if (!info.token) {
1695
+ if (result.auxFile.success === false) {
1285
1696
  if (hasValue(event.taskId)) {
1286
- this._helper.transaction(asyncResult(event.taskId, {
1287
- success: false,
1288
- errorCode: 'not_logged_in',
1289
- errorMessage: 'The user is not logged in.',
1290
- }));
1697
+ this._helper.transaction(asyncResult(event.taskId, result.auxFile));
1291
1698
  }
1292
1699
  return;
1293
1700
  }
1294
- const _a = event.options, { endpoint, blockadeLabs } = _a, rest = __rest(_a, ["endpoint", "blockadeLabs"]);
1295
- let requestData = {
1296
- prompt: event.prompt,
1297
- negativePrompt: event.negativePrompt,
1298
- blockadeLabs: blockadeLabs,
1299
- };
1300
- let instances = undefined;
1301
- if (hasValue(this._helper.origin)) {
1302
- instances = [
1303
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1304
- ];
1305
- }
1306
- const result = yield axios.post(yield this._publishUrl(info.recordsOrigin, '/api/v2/ai/skybox'), Object.assign(Object.assign({}, requestData), { instances }), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1307
- if (!result.data.success) {
1701
+ const fileResult = await this._readFile(result.auxFile);
1702
+ if (fileResult.success === false) {
1308
1703
  if (hasValue(event.taskId)) {
1309
- this._helper.transaction(asyncResult(event.taskId, result.data));
1704
+ this._helper.transaction(asyncResult(event.taskId, fileResult));
1310
1705
  }
1311
1706
  return;
1312
1707
  }
1313
- const skyboxId = result.data.skyboxId;
1314
- for (let i = 0; i < 10; i++) {
1315
- if (!this._skipTimers) {
1316
- const seconds = i === 0
1317
- ? 1
1318
- : i === 1
1319
- ? 4
1320
- : i === 2
1321
- ? 4
1322
- : i === 3
1323
- ? 8
1324
- : i === 4
1325
- ? 16
1326
- : i === 5
1327
- ? 32
1328
- : 32;
1329
- yield wait(seconds);
1330
- }
1331
- const getResult = yield axios.get(yield this._publishUrl(info.recordsOrigin, '/api/v2/ai/skybox', {
1332
- skyboxId: result.data.skyboxId,
1333
- instances,
1334
- }), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1335
- if (getResult.data.success) {
1336
- if (getResult.data.status === 'generated') {
1337
- if (hasValue(event.taskId)) {
1338
- this._helper.transaction(asyncResult(event.taskId, getResult.data));
1339
- }
1340
- return;
1341
- }
1342
- }
1343
- }
1344
- if (hasValue(event.taskId)) {
1345
- this._helper.transaction(asyncResult(event.taskId, {
1346
- success: false,
1347
- errorCode: 'server_error',
1348
- errorMessage: 'The request timed out.',
1349
- }));
1350
- }
1351
- }
1352
- catch (e) {
1353
- console.error('[RecordsManager] Error generating skybox:', e);
1354
- if (hasValue(event.taskId)) {
1355
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1356
- }
1357
- }
1358
- });
1359
- }
1360
- _aiGenerateImage(event) {
1361
- return __awaiter(this, void 0, void 0, function* () {
1362
- try {
1363
- const info = yield this._resolveInfoForEvent(event);
1364
- if (info.error) {
1365
- return;
1366
- }
1367
- if (!info.token) {
1708
+ else {
1709
+ // get json and apply it
1710
+ const aux = fileResult.data;
1711
+ await this._helper.transaction(remote(installAuxFile(aux, 'default')));
1368
1712
  if (hasValue(event.taskId)) {
1369
1713
  this._helper.transaction(asyncResult(event.taskId, {
1370
- success: false,
1371
- errorCode: 'not_logged_in',
1372
- errorMessage: 'The user is not logged in.',
1714
+ success: true,
1715
+ packageLoadId: null,
1716
+ package: result.item,
1373
1717
  }));
1374
1718
  }
1375
- return;
1376
- }
1377
- const { taskId, type, options } = event, rest = __rest(event, ["taskId", "type", "options"]);
1378
- let requestData = Object.assign({}, rest);
1379
- let instances = undefined;
1380
- if (hasValue(this._helper.origin)) {
1381
- instances = [
1382
- formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1383
- ];
1384
- }
1385
- const result = yield this._sendWebsocketSupportedRequest(info.recordsOrigin, info.websocketOrigin, info.websocketProtocol, 'POST', '/api/v2/ai/image', {}, Object.assign(Object.assign({}, requestData), { instances }), info.headers);
1386
- if (hasValue(event.taskId)) {
1387
- this._helper.transaction(asyncResult(event.taskId, result));
1388
- }
1389
- }
1390
- catch (e) {
1391
- console.error('[RecordsManager] Error generating image:', e);
1392
- if (hasValue(event.taskId)) {
1393
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1394
1719
  }
1395
1720
  }
1396
- });
1397
- }
1398
- _aiHumeGetAccessToken(event) {
1399
- return __awaiter(this, void 0, void 0, function* () {
1400
- try {
1401
- const info = yield this._resolveInfoForEvent(event);
1402
- if (info.error) {
1403
- return;
1404
- }
1405
- if (!info.token) {
1721
+ else {
1722
+ if (!this._helper.origin) {
1406
1723
  if (hasValue(event.taskId)) {
1407
- this._helper.transaction(asyncResult(event.taskId, {
1408
- success: false,
1409
- errorCode: 'not_logged_in',
1410
- errorMessage: 'The user is not logged in.',
1411
- }));
1724
+ this._helper.transaction(asyncError(event.taskId, 'Unable to install package with no simulation origin!'));
1412
1725
  }
1413
1726
  return;
1414
1727
  }
1415
- const result = yield this._client.getHumeAccessToken({
1416
- recordName: event.recordName,
1728
+ // other origins can install via a HTTP request
1729
+ const result = await this._client.installPackage({
1730
+ recordName: this._helper.origin.recordName,
1731
+ inst: this._helper.origin.inst,
1732
+ package: {
1733
+ recordName: event.recordName,
1734
+ address: event.address,
1735
+ key: event.key,
1736
+ },
1737
+ instances,
1417
1738
  }, {
1418
1739
  sessionKey: info.token,
1419
1740
  endpoint: info.recordsOrigin,
@@ -1422,108 +1743,76 @@ export class RecordsManager {
1422
1743
  this._helper.transaction(asyncResult(event.taskId, result));
1423
1744
  }
1424
1745
  }
1425
- catch (e) {
1426
- console.error('[RecordsManager] Error getting Hume access token:', e);
1427
- if (hasValue(event.taskId)) {
1428
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1429
- }
1746
+ }
1747
+ catch (e) {
1748
+ console.error('[RecordsManager] Error installing package:', e);
1749
+ if (hasValue(event.taskId)) {
1750
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1430
1751
  }
1431
- });
1752
+ }
1432
1753
  }
1433
- _aiSloydGenerateModel(event) {
1434
- return __awaiter(this, void 0, void 0, function* () {
1435
- try {
1436
- const info = yield this._resolveInfoForEvent(event);
1437
- if (info.error) {
1438
- return;
1439
- }
1440
- if (!info.token) {
1441
- if (hasValue(event.taskId)) {
1442
- this._helper.transaction(asyncResult(event.taskId, {
1443
- success: false,
1444
- errorCode: 'not_logged_in',
1445
- errorMessage: 'The user is not logged in.',
1446
- }));
1447
- }
1448
- return;
1754
+ async _listInstalledPackages(event) {
1755
+ try {
1756
+ const info = await this._resolveInfoForEvent(event);
1757
+ if (info.error) {
1758
+ return;
1759
+ }
1760
+ let instances = undefined;
1761
+ if (hasValue(this._helper.origin)) {
1762
+ instances = [
1763
+ formatInstId(this._helper.origin.recordName, this._helper.origin.inst),
1764
+ ];
1765
+ }
1766
+ if (!hasValue(this._helper.origin) ||
1767
+ this._helper.origin.isStatic) {
1768
+ console.warn(`[RecordsManager] Unable to list packages for local insts.`);
1769
+ if (hasValue(event.taskId)) {
1770
+ this._helper.transaction(asyncResult(event.taskId, {
1771
+ success: false,
1772
+ errorCode: 'not_supported',
1773
+ errorMessage: 'Listing packages is not supported for local insts.',
1774
+ }));
1449
1775
  }
1450
- const result = yield this._client.createSloydModel({
1451
- recordName: event.recordName,
1452
- prompt: event.prompt,
1453
- baseModelId: event.baseModelId,
1454
- levelOfDetail: event.levelOfDetail,
1455
- outputMimeType: event.outputMimeType,
1456
- thumbnail: event.thumbnail,
1776
+ }
1777
+ else {
1778
+ const result = await this._client.listInstalledPackages({
1779
+ recordName: this._helper.origin.recordName,
1780
+ inst: this._helper.origin.inst,
1781
+ instances,
1457
1782
  }, {
1458
- endpoint: info.recordsOrigin,
1459
1783
  sessionKey: info.token,
1784
+ endpoint: info.recordsOrigin,
1460
1785
  });
1461
1786
  if (hasValue(event.taskId)) {
1462
1787
  this._helper.transaction(asyncResult(event.taskId, result));
1463
1788
  }
1464
1789
  }
1465
- catch (e) {
1466
- console.error('[RecordsManager] Error generating Sloyd model:', e);
1467
- if (hasValue(event.taskId)) {
1468
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1469
- }
1470
- }
1471
- });
1472
- }
1473
- _sendWebsocketSupportedRequest(recordsOrigin, websocketOrigin, websocketProtocol, method, path, query, data, headers) {
1474
- return __awaiter(this, void 0, void 0, function* () {
1475
- const client = this._getConnectionClient(websocketOrigin, websocketProtocol);
1476
- if (!client) {
1477
- const result = yield axios.request(Object.assign(Object.assign({ url: yield this._publishUrl(recordsOrigin, path, query), method }, this._axiosOptions), { data: data, headers }));
1478
- return result.data;
1479
- }
1480
- else {
1481
- yield firstValueFrom(client.connectionState.pipe(filter((c) => c.connected)));
1482
- const id = this._httpRequestId++;
1483
- const promise = firstValueFrom(client
1484
- .event('http_response')
1485
- .pipe(filter((response) => response.id === id)));
1486
- client.send({
1487
- type: 'http_request',
1488
- id,
1489
- request: {
1490
- path,
1491
- method,
1492
- headers,
1493
- pathParams: {},
1494
- query: query,
1495
- body: JSON.stringify(data),
1496
- },
1497
- });
1498
- const response = yield promise;
1499
- if (response.response.body) {
1500
- return JSON.parse(response.response.body);
1501
- }
1502
- return null;
1790
+ }
1791
+ catch (e) {
1792
+ console.error('[RecordsManager] Error listing packages:', e);
1793
+ if (hasValue(event.taskId)) {
1794
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1503
1795
  }
1504
- });
1505
- }
1506
- _getWebsocketClient(websocketOrigin, websocketProtocol) {
1507
- return __awaiter(this, void 0, void 0, function* () {
1508
- const client = this._getConnectionClient(websocketOrigin, websocketProtocol);
1509
- return client;
1510
- });
1796
+ }
1511
1797
  }
1512
- _sendWebsocketStreamRequest(client, method, path, query, data, headers) {
1513
- return __awaiter(this, void 0, void 0, function* () {
1514
- yield firstValueFrom(client.connectionState.pipe(filter((c) => c.connected)));
1798
+ async _sendWebsocketSupportedRequest(recordsOrigin, websocketOrigin, websocketProtocol, method, path, query, data, headers) {
1799
+ const client = this._getConnectionClient(websocketOrigin, websocketProtocol);
1800
+ if (!client) {
1801
+ const result = await axios.request({
1802
+ url: await this._publishUrl(recordsOrigin, path, query),
1803
+ method,
1804
+ ...this._axiosOptions,
1805
+ data: data,
1806
+ headers,
1807
+ });
1808
+ return result.data;
1809
+ }
1810
+ else {
1811
+ await firstValueFrom(client.connectionState.pipe(filter((c) => c.connected)));
1515
1812
  const id = this._httpRequestId++;
1516
- const responses = client.event('http_partial_response').pipe(filter((response) => response.id === id), takeWhile((response) => !response.final), map((response) => {
1517
- if (response.response.body) {
1518
- return JSON.parse(response.response.body);
1519
- }
1520
- return null;
1521
- }), share({
1522
- connector: () => new ReplaySubject(),
1523
- resetOnError: false,
1524
- resetOnComplete: false,
1525
- resetOnRefCountZero: false,
1526
- }));
1813
+ const promise = firstValueFrom(client
1814
+ .event('http_response')
1815
+ .pipe(filter((response) => response.id === id)));
1527
1816
  client.send({
1528
1817
  type: 'http_request',
1529
1818
  id,
@@ -1536,8 +1825,44 @@ export class RecordsManager {
1536
1825
  body: JSON.stringify(data),
1537
1826
  },
1538
1827
  });
1539
- return responses;
1828
+ const response = await promise;
1829
+ if (response.response.body) {
1830
+ return JSON.parse(response.response.body);
1831
+ }
1832
+ return null;
1833
+ }
1834
+ }
1835
+ async _getWebsocketClient(websocketOrigin, websocketProtocol) {
1836
+ const client = this._getConnectionClient(websocketOrigin, websocketProtocol);
1837
+ return client;
1838
+ }
1839
+ async _sendWebsocketStreamRequest(client, method, path, query, data, headers) {
1840
+ await firstValueFrom(client.connectionState.pipe(filter((c) => c.connected)));
1841
+ const id = this._httpRequestId++;
1842
+ const responses = client.event('http_partial_response').pipe(filter((response) => response.id === id), takeWhile((response) => !response.final), map((response) => {
1843
+ if (response.response.body) {
1844
+ return JSON.parse(response.response.body);
1845
+ }
1846
+ return null;
1847
+ }), share({
1848
+ connector: () => new ReplaySubject(),
1849
+ resetOnError: false,
1850
+ resetOnComplete: false,
1851
+ resetOnRefCountZero: false,
1852
+ }));
1853
+ client.send({
1854
+ type: 'http_request',
1855
+ id,
1856
+ request: {
1857
+ path,
1858
+ method,
1859
+ headers,
1860
+ pathParams: {},
1861
+ query: query,
1862
+ body: JSON.stringify(data),
1863
+ },
1540
1864
  });
1865
+ return responses;
1541
1866
  }
1542
1867
  _getConnectionClient(origin, protocol) {
1543
1868
  if (!origin || !protocol || !this._connectionClientFactory) {
@@ -1553,70 +1878,13 @@ export class RecordsManager {
1553
1878
  }
1554
1879
  return client;
1555
1880
  }
1556
- _listUserStudios(event) {
1557
- return __awaiter(this, void 0, void 0, function* () {
1558
- try {
1559
- const info = yield this._resolveInfoForEvent(event);
1560
- if (info.error) {
1561
- return;
1562
- }
1563
- if (!info.token) {
1564
- if (hasValue(event.taskId)) {
1565
- this._helper.transaction(asyncResult(event.taskId, {
1566
- success: false,
1567
- errorCode: 'not_logged_in',
1568
- errorMessage: 'The user is not logged in.',
1569
- }));
1570
- }
1571
- return;
1572
- }
1573
- const query = {};
1574
- if (this._config.comId) {
1575
- query['comId'] = this._config.comId;
1576
- }
1577
- const result = yield axios.get(yield this._publishUrl(info.recordsOrigin, '/api/v2/studios/list', query), Object.assign(Object.assign({}, this._axiosOptions), { headers: info.headers }));
1578
- if (hasValue(event.taskId)) {
1579
- this._helper.transaction(asyncResult(event.taskId, result.data));
1580
- }
1581
- }
1582
- catch (e) {
1583
- console.error('[RecordsManager] Error listing studios:', e);
1584
- if (hasValue(event.taskId)) {
1585
- this._helper.transaction(asyncError(event.taskId, e.toString()));
1586
- }
1587
- }
1588
- });
1589
- }
1590
- _resolveInfoForEvent(event, authenticateIfNotLoggedIn = true) {
1591
- return __awaiter(this, void 0, void 0, function* () {
1592
- let recordKeyPolicy = null;
1593
- if ('recordKey' in event && isRecordKey(event.recordKey)) {
1594
- const parsed = parseRecordKey(event.recordKey);
1595
- if (parsed) {
1596
- const [name, password, policy] = parsed;
1597
- recordKeyPolicy = policy;
1598
- if (recordKeyPolicy === 'subjectless') {
1599
- authenticateIfNotLoggedIn = false;
1600
- }
1601
- }
1602
- }
1603
- const info = yield this._getInfoFromEvent(event.options, authenticateIfNotLoggedIn);
1604
- if (!info) {
1605
- if (hasValue(event.taskId)) {
1606
- this._helper.transaction(asyncResult(event.taskId, {
1607
- success: false,
1608
- errorCode: 'not_supported',
1609
- errorMessage: 'Records are not supported on this inst.',
1610
- }));
1611
- }
1612
- return {
1613
- error: true,
1614
- recordsOrigin: null,
1615
- headers: null,
1616
- token: null,
1617
- };
1881
+ async _listUserStudios(event) {
1882
+ try {
1883
+ const info = await this._resolveInfoForEvent(event);
1884
+ if (info.error) {
1885
+ return;
1618
1886
  }
1619
- if (!hasValue(info.token) && recordKeyPolicy === 'subjectfull') {
1887
+ if (!info.token) {
1620
1888
  if (hasValue(event.taskId)) {
1621
1889
  this._helper.transaction(asyncResult(event.taskId, {
1622
1890
  success: false,
@@ -1624,15 +1892,71 @@ export class RecordsManager {
1624
1892
  errorMessage: 'The user is not logged in.',
1625
1893
  }));
1626
1894
  }
1627
- return {
1628
- error: true,
1629
- recordsOrigin: null,
1630
- headers: null,
1631
- token: null,
1632
- };
1895
+ return;
1633
1896
  }
1634
- return info;
1635
- });
1897
+ const query = {};
1898
+ if (this._config.comId) {
1899
+ query['comId'] = this._config.comId;
1900
+ }
1901
+ const result = await axios.get(await this._publishUrl(info.recordsOrigin, '/api/v2/studios/list', query), {
1902
+ ...this._axiosOptions,
1903
+ headers: info.headers,
1904
+ });
1905
+ if (hasValue(event.taskId)) {
1906
+ this._helper.transaction(asyncResult(event.taskId, result.data));
1907
+ }
1908
+ }
1909
+ catch (e) {
1910
+ console.error('[RecordsManager] Error listing studios:', e);
1911
+ if (hasValue(event.taskId)) {
1912
+ this._helper.transaction(asyncError(event.taskId, e.toString()));
1913
+ }
1914
+ }
1915
+ }
1916
+ async _resolveInfoForEvent(event, authenticateIfNotLoggedIn = true) {
1917
+ let recordKeyPolicy = null;
1918
+ if ('recordKey' in event && isRecordKey(event.recordKey)) {
1919
+ const parsed = parseRecordKey(event.recordKey);
1920
+ if (parsed) {
1921
+ const [name, password, policy] = parsed;
1922
+ recordKeyPolicy = policy;
1923
+ if (recordKeyPolicy === 'subjectless') {
1924
+ authenticateIfNotLoggedIn = false;
1925
+ }
1926
+ }
1927
+ }
1928
+ const info = await this._getInfoFromEvent(event.options, authenticateIfNotLoggedIn);
1929
+ if (!info) {
1930
+ if (hasValue(event.taskId)) {
1931
+ this._helper.transaction(asyncResult(event.taskId, {
1932
+ success: false,
1933
+ errorCode: 'not_supported',
1934
+ errorMessage: 'Records are not supported on this inst.',
1935
+ }));
1936
+ }
1937
+ return {
1938
+ error: true,
1939
+ recordsOrigin: null,
1940
+ headers: null,
1941
+ token: null,
1942
+ };
1943
+ }
1944
+ if (!hasValue(info.token) && recordKeyPolicy === 'subjectfull') {
1945
+ if (hasValue(event.taskId)) {
1946
+ this._helper.transaction(asyncResult(event.taskId, {
1947
+ success: false,
1948
+ errorCode: 'not_logged_in',
1949
+ errorMessage: 'The user is not logged in.',
1950
+ }));
1951
+ }
1952
+ return {
1953
+ error: true,
1954
+ recordsOrigin: null,
1955
+ headers: null,
1956
+ token: null,
1957
+ };
1958
+ }
1959
+ return info;
1636
1960
  }
1637
1961
  /**
1638
1962
  * Gets the information needed to call an API on the given endpoint.
@@ -1653,22 +1977,20 @@ export class RecordsManager {
1653
1977
  let endpoint = event.endpoint;
1654
1978
  return this.getInfoForEndpoint(endpoint, authenticateIfNotLoggedIn);
1655
1979
  }
1656
- _publishUrl(recordsOrigin, path, queryParams = {}) {
1657
- return __awaiter(this, void 0, void 0, function* () {
1658
- let url = new URL(path, recordsOrigin);
1659
- for (let key in queryParams) {
1660
- const val = queryParams[key];
1661
- if (hasValue(val)) {
1662
- if (Array.isArray(val)) {
1663
- url.searchParams.set(key, val.join(','));
1664
- }
1665
- else {
1666
- url.searchParams.set(key, val);
1667
- }
1980
+ async _publishUrl(recordsOrigin, path, queryParams = {}) {
1981
+ let url = new URL(path, recordsOrigin);
1982
+ for (let key in queryParams) {
1983
+ const val = queryParams[key];
1984
+ if (hasValue(val)) {
1985
+ if (Array.isArray(val)) {
1986
+ url.searchParams.set(key, val.join(','));
1987
+ }
1988
+ else {
1989
+ url.searchParams.set(key, val);
1668
1990
  }
1669
1991
  }
1670
- return url.href;
1671
- });
1992
+ }
1993
+ return url.href;
1672
1994
  }
1673
1995
  }
1674
1996
  function getHash(buffer) {