@dxos/client-services 0.4.10-main.3040945 → 0.4.10-main.30a328e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/lib/browser/{chunk-WGCEYMNX.mjs → chunk-RCJRMCJI.mjs} +1407 -1026
  2. package/dist/lib/browser/chunk-RCJRMCJI.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +13 -3
  4. package/dist/lib/browser/index.mjs.map +1 -1
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/packlets/testing/index.mjs +133 -115
  7. package/dist/lib/browser/packlets/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-IQXG5CIB.cjs → chunk-OMVCNWC3.cjs} +1324 -1026
  9. package/dist/lib/node/chunk-OMVCNWC3.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +49 -39
  11. package/dist/lib/node/index.cjs.map +1 -1
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/packlets/testing/index.cjs +133 -118
  14. package/dist/lib/node/packlets/testing/index.cjs.map +3 -3
  15. package/dist/types/src/index.d.ts +1 -0
  16. package/dist/types/src/index.d.ts.map +1 -1
  17. package/dist/types/src/packlets/diagnostics/browser-diagnostics-broadcast.d.ts +5 -0
  18. package/dist/types/src/packlets/diagnostics/browser-diagnostics-broadcast.d.ts.map +1 -0
  19. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts +5 -0
  20. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts.map +1 -0
  21. package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts +15 -0
  22. package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts.map +1 -0
  23. package/dist/types/src/packlets/{services → diagnostics}/diagnostics.d.ts +1 -1
  24. package/dist/types/src/packlets/diagnostics/diagnostics.d.ts.map +1 -0
  25. package/dist/types/src/packlets/diagnostics/index.d.ts +4 -0
  26. package/dist/types/src/packlets/diagnostics/index.d.ts.map +1 -0
  27. package/dist/types/src/packlets/identity/identity-manager.d.ts.map +1 -1
  28. package/dist/types/src/packlets/indexing/util.d.ts +2 -1
  29. package/dist/types/src/packlets/indexing/util.d.ts.map +1 -1
  30. package/dist/types/src/packlets/invitations/device-invitation-protocol.d.ts +3 -1
  31. package/dist/types/src/packlets/invitations/device-invitation-protocol.d.ts.map +1 -1
  32. package/dist/types/src/packlets/invitations/index.d.ts +1 -0
  33. package/dist/types/src/packlets/invitations/index.d.ts.map +1 -1
  34. package/dist/types/src/packlets/invitations/invitation-extension.d.ts +1 -0
  35. package/dist/types/src/packlets/invitations/invitation-extension.d.ts.map +1 -1
  36. package/dist/types/src/packlets/invitations/invitation-protocol.d.ts +6 -1
  37. package/dist/types/src/packlets/invitations/invitation-protocol.d.ts.map +1 -1
  38. package/dist/types/src/packlets/invitations/invitations-handler.d.ts +8 -4
  39. package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
  40. package/dist/types/src/packlets/invitations/invitations-manager.d.ts +44 -0
  41. package/dist/types/src/packlets/invitations/invitations-manager.d.ts.map +1 -0
  42. package/dist/types/src/packlets/invitations/invitations-service.d.ts +7 -23
  43. package/dist/types/src/packlets/invitations/invitations-service.d.ts.map +1 -1
  44. package/dist/types/src/packlets/invitations/space-invitation-protocol.d.ts +2 -1
  45. package/dist/types/src/packlets/invitations/space-invitation-protocol.d.ts.map +1 -1
  46. package/dist/types/src/packlets/services/index.d.ts +1 -1
  47. package/dist/types/src/packlets/services/index.d.ts.map +1 -1
  48. package/dist/types/src/packlets/services/service-context.d.ts +2 -0
  49. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  50. package/dist/types/src/packlets/services/service-host.d.ts +5 -1
  51. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  52. package/dist/types/src/packlets/services/util.d.ts +1 -0
  53. package/dist/types/src/packlets/services/util.d.ts.map +1 -1
  54. package/dist/types/src/packlets/spaces/data-space-manager.d.ts +5 -1
  55. package/dist/types/src/packlets/spaces/data-space-manager.d.ts.map +1 -1
  56. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  57. package/dist/types/src/packlets/system/system-service.d.ts +1 -1
  58. package/dist/types/src/packlets/system/system-service.d.ts.map +1 -1
  59. package/dist/types/src/packlets/testing/invitation-utils.d.ts.map +1 -1
  60. package/dist/types/src/packlets/testing/test-builder.d.ts +6 -1
  61. package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
  62. package/dist/types/src/version.d.ts +1 -1
  63. package/package.json +35 -34
  64. package/src/index.ts +1 -0
  65. package/src/packlets/diagnostics/browser-diagnostics-broadcast.ts +94 -0
  66. package/src/packlets/diagnostics/diagnostics-broadcast.ts +20 -0
  67. package/src/packlets/diagnostics/diagnostics-collector.ts +65 -0
  68. package/src/packlets/{services → diagnostics}/diagnostics.ts +2 -2
  69. package/src/packlets/diagnostics/index.ts +7 -0
  70. package/src/packlets/identity/identity-manager.ts +1 -0
  71. package/src/packlets/identity/identity.test.ts +3 -0
  72. package/src/packlets/indexing/util.ts +15 -8
  73. package/src/packlets/invitations/device-invitation-protocol.ts +6 -1
  74. package/src/packlets/invitations/index.ts +1 -0
  75. package/src/packlets/invitations/invitation-extension.ts +28 -1
  76. package/src/packlets/invitations/invitation-protocol.ts +7 -1
  77. package/src/packlets/invitations/invitations-handler.ts +75 -96
  78. package/src/packlets/invitations/invitations-manager.ts +271 -0
  79. package/src/packlets/invitations/invitations-service.ts +23 -168
  80. package/src/packlets/invitations/space-invitation-protocol.ts +45 -3
  81. package/src/packlets/services/automerge-host.test.ts +10 -4
  82. package/src/packlets/services/index.ts +1 -1
  83. package/src/packlets/services/service-context.test.ts +4 -1
  84. package/src/packlets/services/service-context.ts +17 -3
  85. package/src/packlets/services/service-host.ts +34 -19
  86. package/src/packlets/services/util.ts +2 -0
  87. package/src/packlets/spaces/data-space-manager.test.ts +4 -4
  88. package/src/packlets/spaces/data-space-manager.ts +48 -2
  89. package/src/packlets/spaces/data-space.ts +1 -1
  90. package/src/packlets/storage/level.ts +1 -1
  91. package/src/packlets/system/system-service.ts +1 -1
  92. package/src/packlets/testing/invitation-utils.ts +100 -97
  93. package/src/packlets/testing/test-builder.ts +39 -5
  94. package/src/version.ts +1 -1
  95. package/dist/lib/browser/chunk-WGCEYMNX.mjs.map +0 -7
  96. package/dist/lib/node/chunk-IQXG5CIB.cjs.map +0 -7
  97. package/dist/types/src/packlets/services/diagnostics.d.ts.map +0 -1
@@ -1086,7 +1086,9 @@ var IdentityManager = class {
1086
1086
  C: (f, a) => f(...a)
1087
1087
  });
1088
1088
  },
1089
- memberKey: identityKey
1089
+ memberKey: identityKey,
1090
+ onDelegatedInvitationStatusChange: async () => {
1091
+ }
1090
1092
  });
1091
1093
  }
1092
1094
  };
@@ -1194,10 +1196,13 @@ var DeviceInvitationProtocol = class {
1194
1196
  kind: Invitation.Kind.DEVICE
1195
1197
  };
1196
1198
  }
1197
- async admit(request) {
1199
+ async delegate(invitation) {
1200
+ throw new Error("delegation not supported");
1201
+ }
1202
+ async admit(_, request) {
1198
1203
  invariant4(request.device, void 0, {
1199
1204
  F: __dxlog_file5,
1200
- L: 37,
1205
+ L: 42,
1201
1206
  S: this,
1202
1207
  A: [
1203
1208
  "request.device",
@@ -1243,7 +1248,7 @@ var DeviceInvitationProtocol = class {
1243
1248
  async accept(response, request) {
1244
1249
  invariant4(response.device, void 0, {
1245
1250
  F: __dxlog_file5,
1246
- L: 82,
1251
+ L: 87,
1247
1252
  S: this,
1248
1253
  A: [
1249
1254
  "response.device",
@@ -1253,7 +1258,7 @@ var DeviceInvitationProtocol = class {
1253
1258
  const { identityKey, haloSpaceKey, genesisFeedKey, controlTimeframe } = response.device;
1254
1259
  invariant4(request.device, void 0, {
1255
1260
  F: __dxlog_file5,
1256
- L: 85,
1261
+ L: 90,
1257
1262
  S: this,
1258
1263
  A: [
1259
1264
  "request.device",
@@ -1279,9 +1284,9 @@ var DeviceInvitationProtocol = class {
1279
1284
 
1280
1285
  // packages/sdk/client-services/src/packlets/invitations/invitations-handler.ts
1281
1286
  import { PushStream, scheduleTask as scheduleTask2, TimeoutError, Trigger as Trigger3 } from "@dxos/async";
1282
- import { AuthenticatingInvitation, AUTHENTICATION_CODE_LENGTH, CancellableInvitation, INVITATION_TIMEOUT } from "@dxos/client-protocol";
1287
+ import { AuthenticatingInvitation, INVITATION_TIMEOUT } from "@dxos/client-protocol";
1283
1288
  import { Context as Context5 } from "@dxos/context";
1284
- import { generatePasscode } from "@dxos/credentials";
1289
+ import { createKeyPair, sign } from "@dxos/crypto";
1285
1290
  import { invariant as invariant6 } from "@dxos/invariant";
1286
1291
  import { PublicKey as PublicKey6 } from "@dxos/keys";
1287
1292
  import { log as log5 } from "@dxos/log";
@@ -1293,6 +1298,7 @@ import { AuthenticationResponse as AuthenticationResponse2 } from "@dxos/protoco
1293
1298
  // packages/sdk/client-services/src/packlets/invitations/invitation-extension.ts
1294
1299
  import { Trigger as Trigger2 } from "@dxos/async";
1295
1300
  import { cancelWithContext, Context as Context4 } from "@dxos/context";
1301
+ import { randomBytes, verify } from "@dxos/crypto";
1296
1302
  import { invariant as invariant5 } from "@dxos/invariant";
1297
1303
  import { PublicKey as PublicKey5 } from "@dxos/keys";
1298
1304
  import { log as log4 } from "@dxos/log";
@@ -1316,6 +1322,7 @@ var InvitationHostExtension = class extends RpcExtension {
1316
1322
  this._callbacks = _callbacks;
1317
1323
  this._ctx = new Context4();
1318
1324
  this._remoteOptionsTrigger = new Trigger2();
1325
+ this._challenge = void 0;
1319
1326
  this.invitation = void 0;
1320
1327
  this.guestProfile = void 0;
1321
1328
  this.authenticationPassed = false;
@@ -1330,7 +1337,7 @@ var InvitationHostExtension = class extends RpcExtension {
1330
1337
  options: async (options) => {
1331
1338
  invariant5(!this._remoteOptions, "Remote options already set.", {
1332
1339
  F: __dxlog_file6,
1333
- L: 87,
1340
+ L: 90,
1334
1341
  S: this,
1335
1342
  A: [
1336
1343
  "!this._remoteOptions",
@@ -1347,7 +1354,7 @@ var InvitationHostExtension = class extends RpcExtension {
1347
1354
  id: traceId
1348
1355
  }), {
1349
1356
  F: __dxlog_file6,
1350
- L: 96,
1357
+ L: 99,
1351
1358
  S: this,
1352
1359
  C: (f, a) => f(...a)
1353
1360
  });
@@ -1357,7 +1364,7 @@ var InvitationHostExtension = class extends RpcExtension {
1357
1364
  invitationId
1358
1365
  }, {
1359
1366
  F: __dxlog_file6,
1360
- L: 100,
1367
+ L: 103,
1361
1368
  S: this,
1362
1369
  C: (f, a) => f(...a)
1363
1370
  });
@@ -1371,7 +1378,7 @@ var InvitationHostExtension = class extends RpcExtension {
1371
1378
  guestProfile: profile
1372
1379
  }, {
1373
1380
  F: __dxlog_file6,
1374
- L: 109,
1381
+ L: 112,
1375
1382
  S: this,
1376
1383
  C: (f, a) => f(...a)
1377
1384
  });
@@ -1380,25 +1387,27 @@ var InvitationHostExtension = class extends RpcExtension {
1380
1387
  ...this.invitation,
1381
1388
  state: Invitation2.State.READY_FOR_AUTHENTICATION
1382
1389
  });
1390
+ this._challenge = this.invitation.authMethod === Invitation2.AuthMethod.KNOWN_PUBLIC_KEY ? randomBytes(32) : void 0;
1383
1391
  log4.trace("dxos.sdk.invitation-handler.host.introduce", trace3.end({
1384
1392
  id: traceId
1385
1393
  }), {
1386
1394
  F: __dxlog_file6,
1387
- L: 116,
1395
+ L: 122,
1388
1396
  S: this,
1389
1397
  C: (f, a) => f(...a)
1390
1398
  });
1391
1399
  return {
1392
- authMethod: this.invitation.authMethod
1400
+ authMethod: this.invitation.authMethod,
1401
+ challenge: this._challenge
1393
1402
  };
1394
1403
  },
1395
- authenticate: async ({ authCode: code }) => {
1404
+ authenticate: async ({ authCode: code, signedChallenge }) => {
1396
1405
  const traceId = PublicKey5.random().toHex();
1397
1406
  log4.trace("dxos.sdk.invitation-handler.host.authenticate", trace3.begin({
1398
1407
  id: traceId
1399
1408
  }), {
1400
1409
  F: __dxlog_file6,
1401
- L: 124,
1410
+ L: 131,
1402
1411
  S: this,
1403
1412
  C: (f, a) => f(...a)
1404
1413
  });
@@ -1406,14 +1415,14 @@ var InvitationHostExtension = class extends RpcExtension {
1406
1415
  authCode: code
1407
1416
  }, {
1408
1417
  F: __dxlog_file6,
1409
- L: 125,
1418
+ L: 132,
1410
1419
  S: this,
1411
1420
  C: (f, a) => f(...a)
1412
1421
  });
1413
1422
  let status = AuthenticationResponse.Status.OK;
1414
1423
  invariant5(this.invitation, "Invitation is not set.", {
1415
1424
  F: __dxlog_file6,
1416
- L: 128,
1425
+ L: 135,
1417
1426
  S: this,
1418
1427
  A: [
1419
1428
  "this.invitation",
@@ -1424,7 +1433,7 @@ var InvitationHostExtension = class extends RpcExtension {
1424
1433
  case Invitation2.AuthMethod.NONE: {
1425
1434
  log4("authentication not required", void 0, {
1426
1435
  F: __dxlog_file6,
1427
- L: 131,
1436
+ L: 138,
1428
1437
  S: this,
1429
1438
  C: (f, a) => f(...a)
1430
1439
  });
@@ -1444,12 +1453,25 @@ var InvitationHostExtension = class extends RpcExtension {
1444
1453
  }
1445
1454
  break;
1446
1455
  }
1456
+ case Invitation2.AuthMethod.KNOWN_PUBLIC_KEY: {
1457
+ if (!this.invitation.guestKeypair) {
1458
+ status = AuthenticationResponse.Status.INTERNAL_ERROR;
1459
+ break;
1460
+ }
1461
+ const isSignatureValid = this._challenge && verify(this._challenge, Buffer.from(signedChallenge ?? []), this.invitation.guestKeypair.publicKey.asBuffer());
1462
+ if (isSignatureValid) {
1463
+ this.authenticationPassed = true;
1464
+ } else {
1465
+ status = AuthenticationResponse.Status.INVALID_SIGNATURE;
1466
+ }
1467
+ break;
1468
+ }
1447
1469
  default: {
1448
1470
  log4.error("invalid authentication method", {
1449
1471
  authMethod: this.invitation.authMethod
1450
1472
  }, {
1451
1473
  F: __dxlog_file6,
1452
- L: 149,
1474
+ L: 176,
1453
1475
  S: this,
1454
1476
  C: (f, a) => f(...a)
1455
1477
  });
@@ -1464,7 +1486,7 @@ var InvitationHostExtension = class extends RpcExtension {
1464
1486
  }
1465
1487
  }), {
1466
1488
  F: __dxlog_file6,
1467
- L: 155,
1489
+ L: 182,
1468
1490
  S: this,
1469
1491
  C: (f, a) => f(...a)
1470
1492
  });
@@ -1478,14 +1500,14 @@ var InvitationHostExtension = class extends RpcExtension {
1478
1500
  id: traceId
1479
1501
  }), {
1480
1502
  F: __dxlog_file6,
1481
- L: 161,
1503
+ L: 188,
1482
1504
  S: this,
1483
1505
  C: (f, a) => f(...a)
1484
1506
  });
1485
1507
  try {
1486
1508
  invariant5(this.invitation, "Invitation is not set.", {
1487
1509
  F: __dxlog_file6,
1488
- L: 164,
1510
+ L: 191,
1489
1511
  S: this,
1490
1512
  A: [
1491
1513
  "this.invitation",
@@ -1500,7 +1522,7 @@ var InvitationHostExtension = class extends RpcExtension {
1500
1522
  id: traceId
1501
1523
  }), {
1502
1524
  F: __dxlog_file6,
1503
- L: 172,
1525
+ L: 199,
1504
1526
  S: this,
1505
1527
  C: (f, a) => f(...a)
1506
1528
  });
@@ -1557,7 +1579,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1557
1579
  options: async (options) => {
1558
1580
  invariant5(!this._remoteOptions, "Remote options already set.", {
1559
1581
  F: __dxlog_file6,
1560
- L: 239,
1582
+ L: 266,
1561
1583
  S: this,
1562
1584
  A: [
1563
1585
  "!this._remoteOptions",
@@ -1584,7 +1606,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1584
1606
  try {
1585
1607
  log4("begin options", void 0, {
1586
1608
  F: __dxlog_file6,
1587
- L: 260,
1609
+ L: 287,
1588
1610
  S: this,
1589
1611
  C: (f, a) => f(...a)
1590
1612
  });
@@ -1596,7 +1618,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1596
1618
  }));
1597
1619
  log4("end options", void 0, {
1598
1620
  F: __dxlog_file6,
1599
- L: 263,
1621
+ L: 290,
1600
1622
  S: this,
1601
1623
  C: (f, a) => f(...a)
1602
1624
  });
@@ -1610,7 +1632,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1610
1632
  } catch (err) {
1611
1633
  log4("openError", err, {
1612
1634
  F: __dxlog_file6,
1613
- L: 273,
1635
+ L: 300,
1614
1636
  S: this,
1615
1637
  C: (f, a) => f(...a)
1616
1638
  });
@@ -1620,7 +1642,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1620
1642
  async onClose() {
1621
1643
  log4("onClose", void 0, {
1622
1644
  F: __dxlog_file6,
1623
- L: 279,
1645
+ L: 306,
1624
1646
  S: this,
1625
1647
  C: (f, a) => f(...a)
1626
1648
  });
@@ -1638,49 +1660,7 @@ var InvitationsHandler = class {
1638
1660
  constructor(_networkManager) {
1639
1661
  this._networkManager = _networkManager;
1640
1662
  }
1641
- createInvitation(protocol, options) {
1642
- const { invitationId = PublicKey6.random().toHex(), type = Invitation3.Type.INTERACTIVE, authMethod = Invitation3.AuthMethod.SHARED_SECRET, state = Invitation3.State.INIT, timeout = INVITATION_TIMEOUT, swarmKey = PublicKey6.random(), persistent = true, created = /* @__PURE__ */ new Date(), lifetime = 86400 } = options ?? {};
1643
- const authCode = options?.authCode ?? (authMethod === Invitation3.AuthMethod.SHARED_SECRET ? generatePasscode(AUTHENTICATION_CODE_LENGTH) : void 0);
1644
- invariant6(protocol, void 0, {
1645
- F: __dxlog_file7,
1646
- L: 84,
1647
- S: this,
1648
- A: [
1649
- "protocol",
1650
- ""
1651
- ]
1652
- });
1653
- const invitation = {
1654
- invitationId,
1655
- type,
1656
- authMethod,
1657
- state,
1658
- swarmKey,
1659
- authCode,
1660
- timeout,
1661
- persistent,
1662
- created,
1663
- lifetime,
1664
- ...protocol.getInvitationContext()
1665
- };
1666
- const stream = new PushStream();
1667
- const ctx = new Context5({
1668
- onError: (err) => {
1669
- stream.error(err);
1670
- void ctx.dispose();
1671
- }
1672
- });
1673
- ctx.onDispose(() => {
1674
- log5("complete", {
1675
- ...protocol.toJSON()
1676
- }, {
1677
- F: __dxlog_file7,
1678
- L: 109,
1679
- S: this,
1680
- C: (f, a) => f(...a)
1681
- });
1682
- stream.complete();
1683
- });
1663
+ handleInvitationFlow(ctx, stream, protocol, invitation) {
1684
1664
  const createExtension = () => {
1685
1665
  const extension = new InvitationHostExtension({
1686
1666
  onStateUpdate: (invitation2) => {
@@ -1689,8 +1669,8 @@ var InvitationsHandler = class {
1689
1669
  state: Invitation3.State.READY_FOR_AUTHENTICATION
1690
1670
  });
1691
1671
  },
1692
- resolveInvitation: async ({ invitationId: invitationId2 }) => {
1693
- if (invitationId2 && invitationId2 !== invitation.invitationId) {
1672
+ resolveInvitation: async ({ invitationId }) => {
1673
+ if (invitationId && invitationId !== invitation.invitationId) {
1694
1674
  return void 0;
1695
1675
  }
1696
1676
  return invitation;
@@ -1700,14 +1680,14 @@ var InvitationsHandler = class {
1700
1680
  const deviceKey = admissionRequest.device?.deviceKey ?? admissionRequest.space?.deviceKey;
1701
1681
  invariant6(deviceKey, void 0, {
1702
1682
  F: __dxlog_file7,
1703
- L: 130,
1683
+ L: 87,
1704
1684
  S: this,
1705
1685
  A: [
1706
1686
  "deviceKey",
1707
1687
  ""
1708
1688
  ]
1709
1689
  });
1710
- const admissionResponse = await protocol.admit(admissionRequest, extension.guestProfile);
1690
+ const admissionResponse = await protocol.admit(invitation, admissionRequest, extension.guestProfile);
1711
1691
  extension.completedTrigger.wake(deviceKey);
1712
1692
  return admissionResponse;
1713
1693
  } catch (err) {
@@ -1723,7 +1703,7 @@ var InvitationsHandler = class {
1723
1703
  id: traceId
1724
1704
  }), {
1725
1705
  F: __dxlog_file7,
1726
- L: 148,
1706
+ L: 105,
1727
1707
  S: this,
1728
1708
  C: (f, a) => f(...a)
1729
1709
  });
@@ -1731,7 +1711,7 @@ var InvitationsHandler = class {
1731
1711
  ...protocol.toJSON()
1732
1712
  }, {
1733
1713
  F: __dxlog_file7,
1734
- L: 149,
1714
+ L: 106,
1735
1715
  S: this,
1736
1716
  C: (f, a) => f(...a)
1737
1717
  });
@@ -1740,14 +1720,14 @@ var InvitationsHandler = class {
1740
1720
  state: Invitation3.State.CONNECTED
1741
1721
  });
1742
1722
  const deviceKey = await extension.completedTrigger.wait({
1743
- timeout
1723
+ timeout: invitation.timeout
1744
1724
  });
1745
1725
  log5("admitted guest", {
1746
1726
  guest: deviceKey,
1747
1727
  ...protocol.toJSON()
1748
1728
  }, {
1749
1729
  F: __dxlog_file7,
1750
- L: 152,
1730
+ L: 109,
1751
1731
  S: this,
1752
1732
  C: (f, a) => f(...a)
1753
1733
  });
@@ -1759,7 +1739,7 @@ var InvitationsHandler = class {
1759
1739
  id: traceId
1760
1740
  }), {
1761
1741
  F: __dxlog_file7,
1762
- L: 154,
1742
+ L: 111,
1763
1743
  S: this,
1764
1744
  C: (f, a) => f(...a)
1765
1745
  });
@@ -1769,7 +1749,7 @@ var InvitationsHandler = class {
1769
1749
  ...protocol.toJSON()
1770
1750
  }, {
1771
1751
  F: __dxlog_file7,
1772
- L: 157,
1752
+ L: 114,
1773
1753
  S: this,
1774
1754
  C: (f, a) => f(...a)
1775
1755
  });
@@ -1780,7 +1760,7 @@ var InvitationsHandler = class {
1780
1760
  } else {
1781
1761
  log5.error("failed", err, {
1782
1762
  F: __dxlog_file7,
1783
- L: 160,
1763
+ L: 117,
1784
1764
  S: this,
1785
1765
  C: (f, a) => f(...a)
1786
1766
  });
@@ -1791,12 +1771,12 @@ var InvitationsHandler = class {
1791
1771
  error: err
1792
1772
  }), {
1793
1773
  F: __dxlog_file7,
1794
- L: 163,
1774
+ L: 120,
1795
1775
  S: this,
1796
1776
  C: (f, a) => f(...a)
1797
1777
  });
1798
1778
  } finally {
1799
- if (type !== Invitation3.Type.MULTIUSE) {
1779
+ if (!invitation.multiUse) {
1800
1780
  await swarmConnection.close();
1801
1781
  await ctx.dispose();
1802
1782
  }
@@ -1812,7 +1792,7 @@ var InvitationsHandler = class {
1812
1792
  ...protocol.toJSON()
1813
1793
  }, {
1814
1794
  F: __dxlog_file7,
1815
- L: 178,
1795
+ L: 135,
1816
1796
  S: this,
1817
1797
  C: (f, a) => f(...a)
1818
1798
  });
@@ -1823,7 +1803,7 @@ var InvitationsHandler = class {
1823
1803
  } else {
1824
1804
  log5.error("failed", err, {
1825
1805
  F: __dxlog_file7,
1826
- L: 181,
1806
+ L: 138,
1827
1807
  S: this,
1828
1808
  C: (f, a) => f(...a)
1829
1809
  });
@@ -1833,11 +1813,11 @@ var InvitationsHandler = class {
1833
1813
  });
1834
1814
  return extension;
1835
1815
  };
1836
- if (invitation.lifetime && invitation.created && invitation.lifetime !== 0) {
1816
+ if (invitation.lifetime && invitation.created) {
1837
1817
  if (invitation.created.getTime() + invitation.lifetime * 1e3 < Date.now()) {
1838
1818
  log5.warn("invitation has already expired", void 0, {
1839
1819
  F: __dxlog_file7,
1840
- L: 192,
1820
+ L: 149,
1841
1821
  S: this,
1842
1822
  C: (f, a) => f(...a)
1843
1823
  });
@@ -1871,24 +1851,12 @@ var InvitationsHandler = class {
1871
1851
  state: Invitation3.State.CONNECTING
1872
1852
  });
1873
1853
  });
1874
- const observable = new CancellableInvitation({
1875
- initialInvitation: invitation,
1876
- subscriber: stream.observable,
1877
- onCancel: async () => {
1878
- stream.next({
1879
- ...invitation,
1880
- state: Invitation3.State.CANCELLED
1881
- });
1882
- await ctx.dispose();
1883
- }
1884
- });
1885
- return observable;
1886
1854
  }
1887
1855
  acceptInvitation(protocol, invitation, deviceProfile) {
1888
1856
  const { timeout = INVITATION_TIMEOUT } = invitation;
1889
1857
  invariant6(protocol, void 0, {
1890
1858
  F: __dxlog_file7,
1891
- L: 246,
1859
+ L: 191,
1892
1860
  S: this,
1893
1861
  A: [
1894
1862
  "protocol",
@@ -1898,7 +1866,7 @@ var InvitationsHandler = class {
1898
1866
  if (deviceProfile) {
1899
1867
  invariant6(invitation.kind === Invitation3.Kind.DEVICE, "deviceProfile provided for non-device invitation", {
1900
1868
  F: __dxlog_file7,
1901
- L: 250,
1869
+ L: 194,
1902
1870
  S: this,
1903
1871
  A: [
1904
1872
  "invitation.kind === Invitation.Kind.DEVICE",
@@ -1913,7 +1881,7 @@ var InvitationsHandler = class {
1913
1881
  const setState = (newData) => {
1914
1882
  invariant6(newData.state !== void 0, void 0, {
1915
1883
  F: __dxlog_file7,
1916
- L: 261,
1884
+ L: 205,
1917
1885
  S: this,
1918
1886
  A: [
1919
1887
  "newData.state !== undefined",
@@ -1933,7 +1901,7 @@ var InvitationsHandler = class {
1933
1901
  ...protocol.toJSON()
1934
1902
  }, {
1935
1903
  F: __dxlog_file7,
1936
- L: 269,
1904
+ L: 213,
1937
1905
  S: this,
1938
1906
  C: (f, a) => f(...a)
1939
1907
  });
@@ -1943,7 +1911,7 @@ var InvitationsHandler = class {
1943
1911
  } else {
1944
1912
  log5.warn("auth failed", err, {
1945
1913
  F: __dxlog_file7,
1946
- L: 272,
1914
+ L: 216,
1947
1915
  S: this,
1948
1916
  C: (f, a) => f(...a)
1949
1917
  });
@@ -1957,7 +1925,7 @@ var InvitationsHandler = class {
1957
1925
  ...protocol.toJSON()
1958
1926
  }, {
1959
1927
  F: __dxlog_file7,
1960
- L: 280,
1928
+ L: 224,
1961
1929
  S: this,
1962
1930
  C: (f, a) => f(...a)
1963
1931
  });
@@ -1972,7 +1940,7 @@ var InvitationsHandler = class {
1972
1940
  currentState
1973
1941
  }, {
1974
1942
  F: __dxlog_file7,
1975
- L: 290,
1943
+ L: 234,
1976
1944
  S: this,
1977
1945
  C: (f, a) => f(...a)
1978
1946
  });
@@ -1987,7 +1955,7 @@ var InvitationsHandler = class {
1987
1955
  id: traceId
1988
1956
  }), {
1989
1957
  F: __dxlog_file7,
1990
- L: 299,
1958
+ L: 243,
1991
1959
  S: this,
1992
1960
  C: (f, a) => f(...a)
1993
1961
  });
@@ -1999,7 +1967,7 @@ var InvitationsHandler = class {
1999
1967
  ...protocol.toJSON()
2000
1968
  }, {
2001
1969
  F: __dxlog_file7,
2002
- L: 307,
1970
+ L: 251,
2003
1971
  S: this,
2004
1972
  C: (f, a) => f(...a)
2005
1973
  });
@@ -2010,7 +1978,7 @@ var InvitationsHandler = class {
2010
1978
  ...protocol.toJSON()
2011
1979
  }, {
2012
1980
  F: __dxlog_file7,
2013
- L: 311,
1981
+ L: 255,
2014
1982
  S: this,
2015
1983
  C: (f, a) => f(...a)
2016
1984
  });
@@ -2020,62 +1988,28 @@ var InvitationsHandler = class {
2020
1988
  response: introductionResponse
2021
1989
  }, {
2022
1990
  F: __dxlog_file7,
2023
- L: 315,
1991
+ L: 259,
2024
1992
  S: this,
2025
1993
  C: (f, a) => f(...a)
2026
1994
  });
2027
1995
  invitation.authMethod = introductionResponse.authMethod;
2028
1996
  if (isAuthenticationRequired(invitation)) {
2029
- for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
2030
- log5("guest waiting for authentication code...", void 0, {
2031
- F: __dxlog_file7,
2032
- L: 321,
2033
- S: this,
2034
- C: (f, a) => f(...a)
2035
- });
2036
- setState({
2037
- state: Invitation3.State.READY_FOR_AUTHENTICATION
2038
- });
2039
- const authCode = await authenticated.wait({
2040
- timeout
2041
- });
2042
- log5("sending authentication request", void 0, {
2043
- F: __dxlog_file7,
2044
- L: 325,
2045
- S: this,
2046
- C: (f, a) => f(...a)
2047
- });
2048
- setState({
2049
- state: Invitation3.State.AUTHENTICATING
2050
- });
2051
- const response = await extension.rpc.InvitationHostService.authenticate({
2052
- authCode
2053
- });
2054
- if (response.status === void 0 || response.status === AuthenticationResponse2.Status.OK) {
1997
+ switch (invitation.authMethod) {
1998
+ case Invitation3.AuthMethod.SHARED_SECRET:
1999
+ await this._handleGuestOtpAuth(extension, setState, authenticated, {
2000
+ timeout
2001
+ });
2002
+ break;
2003
+ case Invitation3.AuthMethod.KNOWN_PUBLIC_KEY:
2004
+ await this._handleGuestKpkAuth(extension, setState, invitation, introductionResponse);
2055
2005
  break;
2056
- }
2057
- if (response.status === AuthenticationResponse2.Status.INVALID_OTP) {
2058
- if (attempt === MAX_OTP_ATTEMPTS) {
2059
- throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
2060
- } else {
2061
- log5("retrying invalid code", {
2062
- attempt
2063
- }, {
2064
- F: __dxlog_file7,
2065
- L: 336,
2066
- S: this,
2067
- C: (f, a) => f(...a)
2068
- });
2069
- authenticated.reset();
2070
- }
2071
- }
2072
2006
  }
2073
2007
  }
2074
2008
  log5("request admission", {
2075
2009
  ...protocol.toJSON()
2076
2010
  }, {
2077
2011
  F: __dxlog_file7,
2078
- L: 344,
2012
+ L: 275,
2079
2013
  S: this,
2080
2014
  C: (f, a) => f(...a)
2081
2015
  });
@@ -2087,7 +2021,7 @@ var InvitationsHandler = class {
2087
2021
  ...protocol.toJSON()
2088
2022
  }, {
2089
2023
  F: __dxlog_file7,
2090
- L: 355,
2024
+ L: 286,
2091
2025
  S: this,
2092
2026
  C: (f, a) => f(...a)
2093
2027
  });
@@ -2100,7 +2034,7 @@ var InvitationsHandler = class {
2100
2034
  id: traceId
2101
2035
  }), {
2102
2036
  F: __dxlog_file7,
2103
- L: 357,
2037
+ L: 288,
2104
2038
  S: this,
2105
2039
  C: (f, a) => f(...a)
2106
2040
  });
@@ -2110,7 +2044,7 @@ var InvitationsHandler = class {
2110
2044
  ...protocol.toJSON()
2111
2045
  }, {
2112
2046
  F: __dxlog_file7,
2113
- L: 360,
2047
+ L: 291,
2114
2048
  S: this,
2115
2049
  C: (f, a) => f(...a)
2116
2050
  });
@@ -2120,7 +2054,7 @@ var InvitationsHandler = class {
2120
2054
  } else {
2121
2055
  log5("auth failed", err, {
2122
2056
  F: __dxlog_file7,
2123
- L: 363,
2057
+ L: 294,
2124
2058
  S: this,
2125
2059
  C: (f, a) => f(...a)
2126
2060
  });
@@ -2131,7 +2065,7 @@ var InvitationsHandler = class {
2131
2065
  error: err
2132
2066
  }), {
2133
2067
  F: __dxlog_file7,
2134
- L: 366,
2068
+ L: 297,
2135
2069
  S: this,
2136
2070
  C: (f, a) => f(...a)
2137
2071
  });
@@ -2149,7 +2083,7 @@ var InvitationsHandler = class {
2149
2083
  ...protocol.toJSON()
2150
2084
  }, {
2151
2085
  F: __dxlog_file7,
2152
- L: 377,
2086
+ L: 308,
2153
2087
  S: this,
2154
2088
  C: (f, a) => f(...a)
2155
2089
  });
@@ -2159,7 +2093,7 @@ var InvitationsHandler = class {
2159
2093
  } else {
2160
2094
  log5("auth failed", err, {
2161
2095
  F: __dxlog_file7,
2162
- L: 380,
2096
+ L: 311,
2163
2097
  S: this,
2164
2098
  C: (f, a) => f(...a)
2165
2099
  });
@@ -2176,7 +2110,7 @@ var InvitationsHandler = class {
2176
2110
  } else {
2177
2111
  invariant6(invitation.swarmKey, void 0, {
2178
2112
  F: __dxlog_file7,
2179
- L: 394,
2113
+ L: 325,
2180
2114
  S: this,
2181
2115
  A: [
2182
2116
  "invitation.swarmKey",
@@ -2214,206 +2148,114 @@ var InvitationsHandler = class {
2214
2148
  });
2215
2149
  return observable;
2216
2150
  }
2151
+ async _handleGuestOtpAuth(extension, setState, authenticated, options) {
2152
+ for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
2153
+ log5("guest waiting for authentication code...", void 0, {
2154
+ F: __dxlog_file7,
2155
+ L: 365,
2156
+ S: this,
2157
+ C: (f, a) => f(...a)
2158
+ });
2159
+ setState({
2160
+ state: Invitation3.State.READY_FOR_AUTHENTICATION
2161
+ });
2162
+ const authCode = await authenticated.wait(options);
2163
+ log5("sending authentication request", void 0, {
2164
+ F: __dxlog_file7,
2165
+ L: 369,
2166
+ S: this,
2167
+ C: (f, a) => f(...a)
2168
+ });
2169
+ setState({
2170
+ state: Invitation3.State.AUTHENTICATING
2171
+ });
2172
+ const response = await extension.rpc.InvitationHostService.authenticate({
2173
+ authCode
2174
+ });
2175
+ if (response.status === void 0 || response.status === AuthenticationResponse2.Status.OK) {
2176
+ break;
2177
+ }
2178
+ if (response.status === AuthenticationResponse2.Status.INVALID_OTP) {
2179
+ if (attempt === MAX_OTP_ATTEMPTS) {
2180
+ throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
2181
+ } else {
2182
+ log5("retrying invalid code", {
2183
+ attempt
2184
+ }, {
2185
+ F: __dxlog_file7,
2186
+ L: 380,
2187
+ S: this,
2188
+ C: (f, a) => f(...a)
2189
+ });
2190
+ authenticated.reset();
2191
+ }
2192
+ }
2193
+ }
2194
+ }
2195
+ async _handleGuestKpkAuth(extension, setState, invitation, introductionResponse) {
2196
+ if (invitation.guestKeypair?.privateKey == null) {
2197
+ throw new Error("keypair missing in the invitation");
2198
+ }
2199
+ if (introductionResponse.challenge == null) {
2200
+ throw new Error("challenge missing in the introduction");
2201
+ }
2202
+ log5("sending authentication request", void 0, {
2203
+ F: __dxlog_file7,
2204
+ L: 399,
2205
+ S: this,
2206
+ C: (f, a) => f(...a)
2207
+ });
2208
+ setState({
2209
+ state: Invitation3.State.AUTHENTICATING
2210
+ });
2211
+ const signature = sign(Buffer.from(introductionResponse.challenge), invitation.guestKeypair.privateKey);
2212
+ const response = await extension.rpc.InvitationHostService.authenticate({
2213
+ signedChallenge: signature
2214
+ });
2215
+ if (response.status !== AuthenticationResponse2.Status.OK) {
2216
+ throw new Error(`Authentication failed with code: ${response.status}`);
2217
+ }
2218
+ }
2217
2219
  };
2218
- var invitationExpired = (invitation) => {
2219
- return invitation.created && invitation.lifetime && invitation.lifetime !== 0 && invitation.created.getTime() + invitation.lifetime * 1e3 < Date.now();
2220
+ var createAdmissionKeypair = () => {
2221
+ const keypair = createKeyPair();
2222
+ return {
2223
+ publicKey: PublicKey6.from(keypair.publicKey),
2224
+ privateKey: keypair.secretKey
2225
+ };
2220
2226
  };
2221
2227
 
2222
2228
  // packages/sdk/client-services/src/packlets/invitations/invitations-service.ts
2223
- import { Event as Event3, scheduleTask as scheduleTask3 } from "@dxos/async";
2224
2229
  import { Stream as Stream8 } from "@dxos/codec-protobuf";
2225
- import { Context as Context6 } from "@dxos/context";
2226
- import { invariant as invariant7 } from "@dxos/invariant";
2227
- import { log as log6 } from "@dxos/log";
2228
- import { Invitation as Invitation4, QueryInvitationsResponse } from "@dxos/protocols/proto/dxos/client/services";
2229
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/invitations-service.ts";
2230
+ import { QueryInvitationsResponse } from "@dxos/protocols/proto/dxos/client/services";
2230
2231
  var InvitationsServiceImpl = class {
2231
- constructor(_invitationsHandler, _getHandler, _metadataStore) {
2232
- this._invitationsHandler = _invitationsHandler;
2233
- this._getHandler = _getHandler;
2234
- this._metadataStore = _metadataStore;
2235
- this._createInvitations = /* @__PURE__ */ new Map();
2236
- this._acceptInvitations = /* @__PURE__ */ new Map();
2237
- this._invitationCreated = new Event3();
2238
- this._invitationAccepted = new Event3();
2239
- this._removedCreated = new Event3();
2240
- this._removedAccepted = new Event3();
2241
- this._saved = new Event3();
2242
- this._persistentInvitationsLoadedEvent = new Event3();
2243
- this._persistentInvitationsLoaded = false;
2232
+ constructor(_invitationsManager) {
2233
+ this._invitationsManager = _invitationsManager;
2244
2234
  }
2245
2235
  // TODO(burdon): Guest/host label.
2246
2236
  getLoggingContext() {
2247
2237
  return {};
2248
2238
  }
2249
2239
  createInvitation(options) {
2250
- let invitation;
2251
- const savePersistentInvitationCtx = new Context6();
2252
- const existingInvitation = this._createInvitations.get(options.invitationId);
2253
- if (existingInvitation) {
2254
- invitation = existingInvitation;
2255
- } else {
2256
- const handler = this._getHandler(options);
2257
- invitation = this._invitationsHandler.createInvitation(handler, options);
2258
- this._createInvitations.set(invitation.get().invitationId, invitation);
2259
- this._invitationCreated.emit(invitation.get());
2260
- }
2261
2240
  return new Stream8(({ next, close }) => {
2262
- if (invitation.get().persistent) {
2263
- scheduleTask3(savePersistentInvitationCtx, async () => {
2264
- try {
2265
- await this._metadataStore.addInvitation(invitation.get());
2266
- this._saved.emit(invitation.get());
2267
- } catch (err) {
2268
- close(err);
2269
- }
2270
- });
2271
- }
2272
- invitation.subscribe((invitation2) => {
2273
- next(invitation2);
2274
- }, async (err) => {
2275
- await savePersistentInvitationCtx.dispose();
2276
- close(err);
2277
- }, async () => {
2278
- close();
2279
- if (invitation.get().persistent) {
2280
- await savePersistentInvitationCtx.dispose();
2281
- await this._metadataStore.removeInvitation(invitation.get().invitationId);
2282
- }
2283
- this._createInvitations.delete(invitation.get().invitationId);
2284
- if (invitation.get().type !== Invitation4.Type.MULTIUSE) {
2285
- this._removedCreated.emit(invitation.get());
2286
- }
2287
- });
2241
+ void this._invitationsManager.createInvitation(options).then((invitation) => invitation.subscribe(next, close, close)).catch(close);
2288
2242
  });
2289
2243
  }
2290
- async loadPersistentInvitations() {
2291
- const persistentInvitations = this._metadataStore.getInvitations();
2292
- const freshInvitations = persistentInvitations.filter(async (invitation) => !invitationExpired(invitation));
2293
- const cInvitations = freshInvitations.map((persistentInvitation) => {
2294
- invariant7(!this._createInvitations.get(persistentInvitation.invitationId), "invitation already exists", {
2295
- F: __dxlog_file8,
2296
- L: 109,
2297
- S: this,
2298
- A: [
2299
- "!this._createInvitations.get(persistentInvitation.invitationId)",
2300
- "'invitation already exists'"
2301
- ]
2302
- });
2303
- const handler = this._getHandler(persistentInvitation);
2304
- const invitation = this._invitationsHandler.createInvitation(handler, persistentInvitation);
2305
- this._createInvitations.set(invitation.get().invitationId, invitation);
2306
- this._invitationCreated.emit(invitation.get());
2307
- return persistentInvitation;
2308
- });
2309
- this._persistentInvitationsLoadedEvent.emit();
2310
- this._persistentInvitationsLoaded = true;
2311
- return {
2312
- invitations: cInvitations
2313
- };
2314
- }
2315
- acceptInvitation({ invitation: options, deviceProfile }) {
2316
- let invitation;
2317
- if (deviceProfile) {
2318
- invariant7(options.kind === Invitation4.Kind.DEVICE, "deviceProfile provided for non-device invitation", {
2319
- F: __dxlog_file8,
2320
- L: 127,
2321
- S: this,
2322
- A: [
2323
- "options.kind === Invitation.Kind.DEVICE",
2324
- "'deviceProfile provided for non-device invitation'"
2325
- ]
2326
- });
2327
- }
2328
- const existingInvitation = this._acceptInvitations.get(options.invitationId);
2329
- if (existingInvitation) {
2330
- invitation = existingInvitation;
2331
- } else {
2332
- const handler = this._getHandler(options);
2333
- invitation = this._invitationsHandler.acceptInvitation(handler, options, deviceProfile);
2334
- this._acceptInvitations.set(invitation.get().invitationId, invitation);
2335
- this._invitationAccepted.emit(invitation.get());
2336
- }
2244
+ acceptInvitation(request) {
2245
+ const invitation = this._invitationsManager.acceptInvitation(request);
2337
2246
  return new Stream8(({ next, close }) => {
2338
- invitation.subscribe((invitation2) => {
2339
- next(invitation2);
2340
- }, (err) => {
2341
- close(err);
2342
- }, () => {
2343
- close();
2344
- this._acceptInvitations.delete(invitation.get().invitationId);
2345
- if (invitation.get().type !== Invitation4.Type.MULTIUSE) {
2346
- this._removedAccepted.emit(invitation.get());
2347
- }
2348
- });
2247
+ invitation.subscribe(next, close, close);
2349
2248
  });
2350
2249
  }
2351
- async authenticate({ invitationId, authCode }) {
2352
- log6("authenticating...", void 0, {
2353
- F: __dxlog_file8,
2354
- L: 160,
2355
- S: this,
2356
- C: (f, a) => f(...a)
2357
- });
2358
- invariant7(invitationId, void 0, {
2359
- F: __dxlog_file8,
2360
- L: 161,
2361
- S: this,
2362
- A: [
2363
- "invitationId",
2364
- ""
2365
- ]
2366
- });
2367
- const observable = this._acceptInvitations.get(invitationId);
2368
- if (!observable) {
2369
- log6.warn("invalid invitation", {
2370
- invitationId
2371
- }, {
2372
- F: __dxlog_file8,
2373
- L: 164,
2374
- S: this,
2375
- C: (f, a) => f(...a)
2376
- });
2377
- } else {
2378
- await observable.authenticate(authCode);
2379
- }
2250
+ async authenticate(request) {
2251
+ return this._invitationsManager.authenticate(request);
2380
2252
  }
2381
- async cancelInvitation({ invitationId }) {
2382
- log6("cancelInvitation...", {
2383
- invitationId
2384
- }, {
2385
- F: __dxlog_file8,
2386
- L: 171,
2387
- S: this,
2388
- C: (f, a) => f(...a)
2389
- });
2390
- invariant7(invitationId, void 0, {
2391
- F: __dxlog_file8,
2392
- L: 172,
2393
- S: this,
2394
- A: [
2395
- "invitationId",
2396
- ""
2397
- ]
2398
- });
2399
- const created = this._createInvitations.get(invitationId);
2400
- const accepted = this._acceptInvitations.get(invitationId);
2401
- if (created) {
2402
- await created.cancel();
2403
- this._createInvitations.delete(invitationId);
2404
- this._removedCreated.emit(created.get());
2405
- if (created.get().persistent) {
2406
- await this._metadataStore.removeInvitation(created.get().invitationId);
2407
- }
2408
- } else if (accepted) {
2409
- await accepted.cancel();
2410
- this._acceptInvitations.delete(invitationId);
2411
- this._removedAccepted.emit(accepted.get());
2412
- }
2253
+ async cancelInvitation(request) {
2254
+ return this._invitationsManager.cancelInvitation(request);
2413
2255
  }
2414
2256
  queryInvitations() {
2415
2257
  return new Stream8(({ next, ctx }) => {
2416
- this._invitationCreated.on(ctx, (invitation) => {
2258
+ this._invitationsManager.invitationCreated.on(ctx, (invitation) => {
2417
2259
  next({
2418
2260
  action: QueryInvitationsResponse.Action.ADDED,
2419
2261
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2422,7 +2264,7 @@ var InvitationsServiceImpl = class {
2422
2264
  ]
2423
2265
  });
2424
2266
  });
2425
- this._invitationAccepted.on(ctx, (invitation) => {
2267
+ this._invitationsManager.invitationAccepted.on(ctx, (invitation) => {
2426
2268
  next({
2427
2269
  action: QueryInvitationsResponse.Action.ADDED,
2428
2270
  type: QueryInvitationsResponse.Type.ACCEPTED,
@@ -2431,7 +2273,7 @@ var InvitationsServiceImpl = class {
2431
2273
  ]
2432
2274
  });
2433
2275
  });
2434
- this._removedCreated.on(ctx, (invitation) => {
2276
+ this._invitationsManager.removedCreated.on(ctx, (invitation) => {
2435
2277
  next({
2436
2278
  action: QueryInvitationsResponse.Action.REMOVED,
2437
2279
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2440,7 +2282,7 @@ var InvitationsServiceImpl = class {
2440
2282
  ]
2441
2283
  });
2442
2284
  });
2443
- this._removedAccepted.on(ctx, (invitation) => {
2285
+ this._invitationsManager.removedAccepted.on(ctx, (invitation) => {
2444
2286
  next({
2445
2287
  action: QueryInvitationsResponse.Action.REMOVED,
2446
2288
  type: QueryInvitationsResponse.Type.ACCEPTED,
@@ -2449,7 +2291,7 @@ var InvitationsServiceImpl = class {
2449
2291
  ]
2450
2292
  });
2451
2293
  });
2452
- this._saved.on(ctx, (invitation) => {
2294
+ this._invitationsManager.saved.on(ctx, (invitation) => {
2453
2295
  next({
2454
2296
  action: QueryInvitationsResponse.Action.SAVED,
2455
2297
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2461,40 +2303,34 @@ var InvitationsServiceImpl = class {
2461
2303
  next({
2462
2304
  action: QueryInvitationsResponse.Action.ADDED,
2463
2305
  type: QueryInvitationsResponse.Type.CREATED,
2464
- invitations: Array.from(this._createInvitations.values()).map((invitation) => invitation.get()),
2306
+ invitations: this._invitationsManager.getCreatedInvitations(),
2465
2307
  existing: true
2466
2308
  });
2467
2309
  next({
2468
2310
  action: QueryInvitationsResponse.Action.ADDED,
2469
2311
  type: QueryInvitationsResponse.Type.ACCEPTED,
2470
- invitations: Array.from(this._acceptInvitations.values()).map((invitation) => invitation.get()),
2312
+ invitations: this._invitationsManager.getAcceptedInvitations(),
2471
2313
  existing: true
2472
2314
  });
2473
- if (this._persistentInvitationsLoaded) {
2315
+ this._invitationsManager.onPersistentInvitationsLoaded(ctx, () => {
2474
2316
  next({
2475
2317
  action: QueryInvitationsResponse.Action.LOAD_COMPLETE,
2476
2318
  type: QueryInvitationsResponse.Type.CREATED
2477
2319
  });
2478
- } else {
2479
- this._persistentInvitationsLoadedEvent.on(ctx, () => {
2480
- next({
2481
- action: QueryInvitationsResponse.Action.LOAD_COMPLETE,
2482
- type: QueryInvitationsResponse.Type.CREATED
2483
- });
2484
- });
2485
- }
2320
+ });
2486
2321
  });
2487
2322
  }
2488
2323
  };
2489
2324
 
2490
2325
  // packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts
2491
- import { createAdmissionCredentials, getCredentialAssertion } from "@dxos/credentials";
2326
+ import { createAdmissionCredentials, createDelegatedSpaceInvitationCredential, getCredentialAssertion } from "@dxos/credentials";
2492
2327
  import { writeMessages as writeMessages2 } from "@dxos/feed-store";
2493
- import { invariant as invariant8 } from "@dxos/invariant";
2494
- import { log as log7 } from "@dxos/log";
2328
+ import { invariant as invariant7 } from "@dxos/invariant";
2329
+ import { log as log6 } from "@dxos/log";
2495
2330
  import { AlreadyJoinedError as AlreadyJoinedError2 } from "@dxos/protocols";
2496
- import { Invitation as Invitation5 } from "@dxos/protocols/proto/dxos/client/services";
2497
- var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts";
2331
+ import { Invitation as Invitation4 } from "@dxos/protocols/proto/dxos/client/services";
2332
+ import { SpaceMember } from "@dxos/protocols/proto/dxos/halo/credentials";
2333
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts";
2498
2334
  var SpaceInvitationProtocol = class {
2499
2335
  constructor(_spaceManager, _signingContext, _keyring, _spaceKey) {
2500
2336
  this._spaceManager = _spaceManager;
@@ -2510,14 +2346,14 @@ var SpaceInvitationProtocol = class {
2510
2346
  }
2511
2347
  getInvitationContext() {
2512
2348
  return {
2513
- kind: Invitation5.Kind.SPACE,
2349
+ kind: Invitation4.Kind.SPACE,
2514
2350
  spaceKey: this._spaceKey
2515
2351
  };
2516
2352
  }
2517
- async admit(request, guestProfile) {
2518
- invariant8(this._spaceKey, void 0, {
2519
- F: __dxlog_file9,
2520
- L: 47,
2353
+ async admit(invitation, request, guestProfile) {
2354
+ invariant7(this._spaceKey, void 0, {
2355
+ F: __dxlog_file8,
2356
+ L: 55,
2521
2357
  S: this,
2522
2358
  A: [
2523
2359
  "this._spaceKey",
@@ -2525,18 +2361,18 @@ var SpaceInvitationProtocol = class {
2525
2361
  ]
2526
2362
  });
2527
2363
  const space = await this._spaceManager.spaces.get(this._spaceKey);
2528
- invariant8(space, void 0, {
2529
- F: __dxlog_file9,
2530
- L: 49,
2364
+ invariant7(space, void 0, {
2365
+ F: __dxlog_file8,
2366
+ L: 57,
2531
2367
  S: this,
2532
2368
  A: [
2533
2369
  "space",
2534
2370
  ""
2535
2371
  ]
2536
2372
  });
2537
- invariant8(request.space, void 0, {
2538
- F: __dxlog_file9,
2539
- L: 51,
2373
+ invariant7(request.space, void 0, {
2374
+ F: __dxlog_file8,
2375
+ L: 59,
2540
2376
  S: this,
2541
2377
  A: [
2542
2378
  "request.space",
@@ -2544,19 +2380,19 @@ var SpaceInvitationProtocol = class {
2544
2380
  ]
2545
2381
  });
2546
2382
  const { identityKey, deviceKey } = request.space;
2547
- log7("writing guest credentials", {
2383
+ log6("writing guest credentials", {
2548
2384
  host: this._signingContext.deviceKey,
2549
2385
  guest: deviceKey
2550
2386
  }, {
2551
- F: __dxlog_file9,
2552
- L: 54,
2387
+ F: __dxlog_file8,
2388
+ L: 62,
2553
2389
  S: this,
2554
2390
  C: (f, a) => f(...a)
2555
2391
  });
2556
- const credentials = await createAdmissionCredentials(this._signingContext.credentialSigner, identityKey, space.key, space.inner.genesisFeedKey, guestProfile);
2557
- invariant8(credentials[0].credential, void 0, {
2558
- F: __dxlog_file9,
2559
- L: 65,
2392
+ const credentials = await createAdmissionCredentials(this._signingContext.credentialSigner, identityKey, space.key, space.inner.genesisFeedKey, guestProfile, invitation.delegationCredentialId);
2393
+ invariant7(credentials[0].credential, void 0, {
2394
+ F: __dxlog_file8,
2395
+ L: 74,
2560
2396
  S: this,
2561
2397
  A: [
2562
2398
  "credentials[0].credential",
@@ -2564,9 +2400,9 @@ var SpaceInvitationProtocol = class {
2564
2400
  ]
2565
2401
  });
2566
2402
  const spaceMemberCredential = credentials[0].credential.credential;
2567
- invariant8(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
2568
- F: __dxlog_file9,
2569
- L: 67,
2403
+ invariant7(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
2404
+ F: __dxlog_file8,
2405
+ L: 76,
2570
2406
  S: this,
2571
2407
  A: [
2572
2408
  "getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember'",
@@ -2581,6 +2417,69 @@ var SpaceInvitationProtocol = class {
2581
2417
  }
2582
2418
  };
2583
2419
  }
2420
+ async delegate(invitation) {
2421
+ invariant7(this._spaceKey, void 0, {
2422
+ F: __dxlog_file8,
2423
+ L: 89,
2424
+ S: this,
2425
+ A: [
2426
+ "this._spaceKey",
2427
+ ""
2428
+ ]
2429
+ });
2430
+ const space = await this._spaceManager.spaces.get(this._spaceKey);
2431
+ invariant7(space, void 0, {
2432
+ F: __dxlog_file8,
2433
+ L: 91,
2434
+ S: this,
2435
+ A: [
2436
+ "space",
2437
+ ""
2438
+ ]
2439
+ });
2440
+ if (invitation.authMethod === Invitation4.AuthMethod.KNOWN_PUBLIC_KEY) {
2441
+ invariant7(invitation.guestKeypair?.publicKey, void 0, {
2442
+ F: __dxlog_file8,
2443
+ L: 93,
2444
+ S: this,
2445
+ A: [
2446
+ "invitation.guestKeypair?.publicKey",
2447
+ ""
2448
+ ]
2449
+ });
2450
+ }
2451
+ log6("writing delegate space invitation", {
2452
+ host: this._signingContext.deviceKey,
2453
+ id: invitation.invitationId
2454
+ }, {
2455
+ F: __dxlog_file8,
2456
+ L: 96,
2457
+ S: this,
2458
+ C: (f, a) => f(...a)
2459
+ });
2460
+ const credential = await createDelegatedSpaceInvitationCredential(this._signingContext.credentialSigner, space.key, {
2461
+ invitationId: invitation.invitationId,
2462
+ authMethod: invitation.authMethod,
2463
+ swarmKey: invitation.swarmKey,
2464
+ role: SpaceMember.Role.ADMIN,
2465
+ expiresOn: invitation.lifetime ? new Date((invitation.created?.getTime() ?? Date.now()) + invitation.lifetime) : void 0,
2466
+ multiUse: invitation.multiUse ?? false,
2467
+ guestKey: invitation.authMethod === Invitation4.AuthMethod.KNOWN_PUBLIC_KEY ? invitation.guestKeypair.publicKey : void 0
2468
+ });
2469
+ invariant7(credential.credential, void 0, {
2470
+ F: __dxlog_file8,
2471
+ L: 116,
2472
+ S: this,
2473
+ A: [
2474
+ "credential.credential",
2475
+ ""
2476
+ ]
2477
+ });
2478
+ await writeMessages2(space.inner.controlPipeline.writer, [
2479
+ credential
2480
+ ]);
2481
+ return credential.credential.credential.id;
2482
+ }
2584
2483
  checkInvitation(invitation) {
2585
2484
  if (invitation.spaceKey && this._spaceManager.spaces.has(invitation.spaceKey)) {
2586
2485
  return new AlreadyJoinedError2("Already joined space.");
@@ -2604,9 +2503,9 @@ var SpaceInvitationProtocol = class {
2604
2503
  };
2605
2504
  }
2606
2505
  async accept(response) {
2607
- invariant8(response.space, void 0, {
2608
- F: __dxlog_file9,
2609
- L: 107,
2506
+ invariant7(response.space, void 0, {
2507
+ F: __dxlog_file8,
2508
+ L: 149,
2610
2509
  S: this,
2611
2510
  A: [
2612
2511
  "response.space",
@@ -2615,18 +2514,18 @@ var SpaceInvitationProtocol = class {
2615
2514
  });
2616
2515
  const { credential, controlTimeframe, dataTimeframe } = response.space;
2617
2516
  const assertion = getCredentialAssertion(credential);
2618
- invariant8(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential", {
2619
- F: __dxlog_file9,
2620
- L: 110,
2517
+ invariant7(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential", {
2518
+ F: __dxlog_file8,
2519
+ L: 152,
2621
2520
  S: this,
2622
2521
  A: [
2623
2522
  "assertion['@type'] === 'dxos.halo.credentials.SpaceMember'",
2624
2523
  "'Invalid credential'"
2625
2524
  ]
2626
2525
  });
2627
- invariant8(credential.subject.id.equals(this._signingContext.identityKey), void 0, {
2628
- F: __dxlog_file9,
2629
- L: 111,
2526
+ invariant7(credential.subject.id.equals(this._signingContext.identityKey), void 0, {
2527
+ F: __dxlog_file8,
2528
+ L: 153,
2630
2529
  S: this,
2631
2530
  A: [
2632
2531
  "credential.subject.id.equals(this._signingContext.identityKey)",
@@ -2649,6 +2548,295 @@ var SpaceInvitationProtocol = class {
2649
2548
  }
2650
2549
  };
2651
2550
 
2551
+ // packages/sdk/client-services/src/packlets/invitations/invitations-manager.ts
2552
+ import { Event as Event3, PushStream as PushStream2 } from "@dxos/async";
2553
+ import { AUTHENTICATION_CODE_LENGTH, CancellableInvitation, INVITATION_TIMEOUT as INVITATION_TIMEOUT2 } from "@dxos/client-protocol";
2554
+ import { Context as Context6 } from "@dxos/context";
2555
+ import { generatePasscode } from "@dxos/credentials";
2556
+ import { hasInvitationExpired } from "@dxos/echo-pipeline";
2557
+ import { invariant as invariant8 } from "@dxos/invariant";
2558
+ import { PublicKey as PublicKey7 } from "@dxos/keys";
2559
+ import { log as log7 } from "@dxos/log";
2560
+ import { Invitation as Invitation5 } from "@dxos/protocols/proto/dxos/client/services";
2561
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/invitations-manager.ts";
2562
+ var InvitationsManager = class {
2563
+ constructor(_invitationsHandler, _getHandler, _metadataStore) {
2564
+ this._invitationsHandler = _invitationsHandler;
2565
+ this._getHandler = _getHandler;
2566
+ this._metadataStore = _metadataStore;
2567
+ this._createInvitations = /* @__PURE__ */ new Map();
2568
+ this._acceptInvitations = /* @__PURE__ */ new Map();
2569
+ this.invitationCreated = new Event3();
2570
+ this.invitationAccepted = new Event3();
2571
+ this.removedCreated = new Event3();
2572
+ this.removedAccepted = new Event3();
2573
+ this.saved = new Event3();
2574
+ this._persistentInvitationsLoadedEvent = new Event3();
2575
+ this._persistentInvitationsLoaded = false;
2576
+ }
2577
+ async createInvitation(options) {
2578
+ if (options.invitationId) {
2579
+ const existingInvitation = this._createInvitations.get(options.invitationId);
2580
+ if (existingInvitation) {
2581
+ return existingInvitation;
2582
+ }
2583
+ }
2584
+ const handler = this._getHandler(options);
2585
+ const invitation = this._createInvitation(handler, options);
2586
+ const { ctx, stream, observableInvitation } = this._createObservableInvitation(handler, invitation);
2587
+ this._createInvitations.set(invitation.invitationId, observableInvitation);
2588
+ this.invitationCreated.emit(invitation);
2589
+ this._onInvitationComplete(observableInvitation, async () => {
2590
+ this._createInvitations.delete(observableInvitation.get().invitationId);
2591
+ this.removedCreated.emit(observableInvitation.get());
2592
+ if (observableInvitation.get().persistent) {
2593
+ await this._safeDeleteInvitation(observableInvitation.get());
2594
+ }
2595
+ });
2596
+ try {
2597
+ await this._persistIfRequired(handler, stream, invitation);
2598
+ } catch (err) {
2599
+ log7.catch(err, void 0, {
2600
+ F: __dxlog_file9,
2601
+ L: 76,
2602
+ S: this,
2603
+ C: (f, a) => f(...a)
2604
+ });
2605
+ await observableInvitation.cancel();
2606
+ return observableInvitation;
2607
+ }
2608
+ this._invitationsHandler.handleInvitationFlow(ctx, stream, handler, observableInvitation.get());
2609
+ return observableInvitation;
2610
+ }
2611
+ async loadPersistentInvitations() {
2612
+ if (this._persistentInvitationsLoaded) {
2613
+ const invitations = this.getCreatedInvitations().filter((i) => i.persistent);
2614
+ return {
2615
+ invitations
2616
+ };
2617
+ }
2618
+ try {
2619
+ const persistentInvitations = this._metadataStore.getInvitations();
2620
+ const freshInvitations = persistentInvitations.filter((invitation) => !hasInvitationExpired(invitation));
2621
+ const loadTasks = freshInvitations.map((persistentInvitation) => {
2622
+ invariant8(!this._createInvitations.get(persistentInvitation.invitationId), "invitation already exists", {
2623
+ F: __dxlog_file9,
2624
+ L: 97,
2625
+ S: this,
2626
+ A: [
2627
+ "!this._createInvitations.get(persistentInvitation.invitationId)",
2628
+ "'invitation already exists'"
2629
+ ]
2630
+ });
2631
+ return this.createInvitation({
2632
+ ...persistentInvitation,
2633
+ persistent: false
2634
+ });
2635
+ });
2636
+ const cInvitations = await Promise.all(loadTasks);
2637
+ return {
2638
+ invitations: cInvitations.map((invitation) => invitation.get())
2639
+ };
2640
+ } catch (err) {
2641
+ log7.catch(err, void 0, {
2642
+ F: __dxlog_file9,
2643
+ L: 104,
2644
+ S: this,
2645
+ C: (f, a) => f(...a)
2646
+ });
2647
+ return {
2648
+ invitations: []
2649
+ };
2650
+ } finally {
2651
+ this._persistentInvitationsLoadedEvent.emit();
2652
+ this._persistentInvitationsLoaded = true;
2653
+ }
2654
+ }
2655
+ acceptInvitation(request) {
2656
+ const options = request.invitation;
2657
+ const existingInvitation = this._acceptInvitations.get(options.invitationId);
2658
+ if (existingInvitation) {
2659
+ return existingInvitation;
2660
+ }
2661
+ const handler = this._getHandler(options);
2662
+ const invitation = this._invitationsHandler.acceptInvitation(handler, options, request.deviceProfile);
2663
+ this._acceptInvitations.set(invitation.get().invitationId, invitation);
2664
+ this.invitationAccepted.emit(invitation.get());
2665
+ this._onInvitationComplete(invitation, () => {
2666
+ this._acceptInvitations.delete(invitation.get().invitationId);
2667
+ this.removedAccepted.emit(invitation.get());
2668
+ });
2669
+ return invitation;
2670
+ }
2671
+ async authenticate({ invitationId, authCode }) {
2672
+ log7("authenticating...", void 0, {
2673
+ F: __dxlog_file9,
2674
+ L: 133,
2675
+ S: this,
2676
+ C: (f, a) => f(...a)
2677
+ });
2678
+ invariant8(invitationId, void 0, {
2679
+ F: __dxlog_file9,
2680
+ L: 134,
2681
+ S: this,
2682
+ A: [
2683
+ "invitationId",
2684
+ ""
2685
+ ]
2686
+ });
2687
+ const observable = this._acceptInvitations.get(invitationId);
2688
+ if (!observable) {
2689
+ log7.warn("invalid invitation", {
2690
+ invitationId
2691
+ }, {
2692
+ F: __dxlog_file9,
2693
+ L: 137,
2694
+ S: this,
2695
+ C: (f, a) => f(...a)
2696
+ });
2697
+ } else {
2698
+ await observable.authenticate(authCode);
2699
+ }
2700
+ }
2701
+ async cancelInvitation({ invitationId }) {
2702
+ log7("cancelInvitation...", {
2703
+ invitationId
2704
+ }, {
2705
+ F: __dxlog_file9,
2706
+ L: 144,
2707
+ S: this,
2708
+ C: (f, a) => f(...a)
2709
+ });
2710
+ invariant8(invitationId, void 0, {
2711
+ F: __dxlog_file9,
2712
+ L: 145,
2713
+ S: this,
2714
+ A: [
2715
+ "invitationId",
2716
+ ""
2717
+ ]
2718
+ });
2719
+ const created = this._createInvitations.get(invitationId);
2720
+ if (created) {
2721
+ if (created.get().persistent) {
2722
+ await this._metadataStore.removeInvitation(invitationId);
2723
+ }
2724
+ await created.cancel();
2725
+ this._createInvitations.delete(invitationId);
2726
+ this.removedCreated.emit(created.get());
2727
+ return;
2728
+ }
2729
+ const accepted = this._acceptInvitations.get(invitationId);
2730
+ if (accepted) {
2731
+ await accepted.cancel();
2732
+ this._acceptInvitations.delete(invitationId);
2733
+ this.removedAccepted.emit(accepted.get());
2734
+ }
2735
+ }
2736
+ getCreatedInvitations() {
2737
+ return [
2738
+ ...this._createInvitations.values()
2739
+ ].map((i) => i.get());
2740
+ }
2741
+ getAcceptedInvitations() {
2742
+ return [
2743
+ ...this._acceptInvitations.values()
2744
+ ].map((i) => i.get());
2745
+ }
2746
+ onPersistentInvitationsLoaded(ctx, callback) {
2747
+ if (this._persistentInvitationsLoaded) {
2748
+ callback();
2749
+ } else {
2750
+ this._persistentInvitationsLoadedEvent.once(ctx, () => callback());
2751
+ }
2752
+ }
2753
+ _createInvitation(protocol, options) {
2754
+ const { invitationId = PublicKey7.random().toHex(), type = Invitation5.Type.INTERACTIVE, authMethod = Invitation5.AuthMethod.SHARED_SECRET, state = Invitation5.State.INIT, timeout = INVITATION_TIMEOUT2, swarmKey = PublicKey7.random(), persistent = options?.authMethod !== Invitation5.AuthMethod.KNOWN_PUBLIC_KEY, created = /* @__PURE__ */ new Date(), guestKeypair = void 0, lifetime = 86400, multiUse = false } = options ?? {};
2755
+ const authCode = options?.authCode ?? (authMethod === Invitation5.AuthMethod.SHARED_SECRET ? generatePasscode(AUTHENTICATION_CODE_LENGTH) : void 0);
2756
+ return {
2757
+ invitationId,
2758
+ type,
2759
+ authMethod,
2760
+ state,
2761
+ swarmKey,
2762
+ authCode,
2763
+ timeout,
2764
+ persistent: persistent && type !== Invitation5.Type.DELEGATED,
2765
+ guestKeypair: guestKeypair ?? (authMethod === Invitation5.AuthMethod.KNOWN_PUBLIC_KEY ? createAdmissionKeypair() : void 0),
2766
+ created,
2767
+ lifetime,
2768
+ multiUse,
2769
+ delegationCredentialId: options?.delegationCredentialId,
2770
+ ...protocol.getInvitationContext()
2771
+ };
2772
+ }
2773
+ _createObservableInvitation(handler, invitation) {
2774
+ const stream = new PushStream2();
2775
+ const ctx = new Context6({
2776
+ onError: (err) => {
2777
+ stream.error(err);
2778
+ void ctx.dispose();
2779
+ }
2780
+ });
2781
+ ctx.onDispose(() => {
2782
+ log7("complete", {
2783
+ ...handler.toJSON()
2784
+ }, {
2785
+ F: __dxlog_file9,
2786
+ L: 228,
2787
+ S: this,
2788
+ C: (f, a) => f(...a)
2789
+ });
2790
+ stream.complete();
2791
+ });
2792
+ const observableInvitation = new CancellableInvitation({
2793
+ initialInvitation: invitation,
2794
+ subscriber: stream.observable,
2795
+ onCancel: async () => {
2796
+ stream.next({
2797
+ ...invitation,
2798
+ state: Invitation5.State.CANCELLED
2799
+ });
2800
+ await ctx.dispose();
2801
+ }
2802
+ });
2803
+ return {
2804
+ ctx,
2805
+ stream,
2806
+ observableInvitation
2807
+ };
2808
+ }
2809
+ async _persistIfRequired(handler, changeStream, invitation) {
2810
+ if (invitation.type === Invitation5.Type.DELEGATED && invitation.delegationCredentialId == null) {
2811
+ const delegationCredentialId = await handler.delegate(invitation);
2812
+ changeStream.next({
2813
+ ...invitation,
2814
+ delegationCredentialId
2815
+ });
2816
+ } else if (invitation.persistent) {
2817
+ await this._metadataStore.addInvitation(invitation);
2818
+ this.saved.emit(invitation);
2819
+ }
2820
+ }
2821
+ async _safeDeleteInvitation(invitation) {
2822
+ try {
2823
+ await this._metadataStore.removeInvitation(invitation.invitationId);
2824
+ } catch (err) {
2825
+ log7.catch(err, void 0, {
2826
+ F: __dxlog_file9,
2827
+ L: 260,
2828
+ S: this,
2829
+ C: (f, a) => f(...a)
2830
+ });
2831
+ }
2832
+ }
2833
+ _onInvitationComplete(invitation, callback) {
2834
+ invitation.subscribe(() => {
2835
+ }, () => {
2836
+ }, callback);
2837
+ }
2838
+ };
2839
+
2652
2840
  // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
2653
2841
  import { Stream as Stream9 } from "@dxos/codec-protobuf";
2654
2842
  import { raise } from "@dxos/debug";
@@ -2730,222 +2918,72 @@ ClientRpcServer = _ts_decorate3([
2730
2918
  trace5.resource()
2731
2919
  ], ClientRpcServer);
2732
2920
 
2733
- // packages/sdk/client-services/src/packlets/services/diagnostics.ts
2734
- import { getFirstStreamValue } from "@dxos/codec-protobuf";
2735
- import { credentialTypeFilter } from "@dxos/credentials";
2736
- import { invariant as invariant9 } from "@dxos/invariant";
2737
- import { STORAGE_VERSION } from "@dxos/protocols";
2738
- import { SpaceMember } from "@dxos/protocols/proto/dxos/client/services";
2739
- import { TRACE_PROCESSOR } from "@dxos/tracing";
2921
+ // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2922
+ import { Event as Event6, asyncTimeout, scheduleTask as scheduleTask4, sleep as sleep2, synchronized, trackLeaks } from "@dxos/async";
2923
+ import { AUTH_TIMEOUT as AUTH_TIMEOUT2 } from "@dxos/client-protocol";
2924
+ import { cancelWithContext as cancelWithContext2, Context as Context8, ContextDisposedError } from "@dxos/context";
2925
+ import { timed, warnAfterTimeout } from "@dxos/debug";
2926
+ import { createMappedFeedWriter } from "@dxos/echo-pipeline";
2927
+ import { AutomergeDocumentLoaderImpl } from "@dxos/echo-pipeline";
2928
+ import { TYPE_PROPERTIES } from "@dxos/echo-schema";
2929
+ import { failedInvariant, invariant as invariant10 } from "@dxos/invariant";
2930
+ import { PublicKey as PublicKey9 } from "@dxos/keys";
2931
+ import { log as log9 } from "@dxos/log";
2932
+ import { CancelledError, SystemError } from "@dxos/protocols";
2933
+ import { SpaceState, CreateEpochRequest } from "@dxos/protocols/proto/dxos/client/services";
2934
+ import { AdmittedFeed as AdmittedFeed3 } from "@dxos/protocols/proto/dxos/halo/credentials";
2935
+ import { Timeframe as Timeframe2 } from "@dxos/timeframe";
2936
+ import { trace as trace6 } from "@dxos/tracing";
2937
+ import { ComplexSet as ComplexSet3, assignDeep } from "@dxos/util";
2740
2938
 
2741
- // packages/sdk/client-services/src/packlets/services/platform.ts
2742
- import { Platform } from "@dxos/protocols/proto/dxos/client/services";
2743
- var getPlatform = () => {
2744
- if (process.browser) {
2745
- if (typeof window !== "undefined") {
2746
- const { userAgent } = window.navigator;
2747
- return {
2748
- type: Platform.PLATFORM_TYPE.BROWSER,
2749
- userAgent,
2750
- uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1e3)
2751
- };
2752
- } else {
2753
- return {
2754
- type: Platform.PLATFORM_TYPE.SHARED_WORKER,
2755
- uptime: Math.floor((Date.now() - performance.timeOrigin) / 1e3)
2756
- };
2939
+ // packages/sdk/client-services/src/packlets/spaces/automerge-space-state.ts
2940
+ import { Event as Event4 } from "@dxos/async";
2941
+ import { checkCredentialType } from "@dxos/credentials";
2942
+ var AutomergeSpaceState = class {
2943
+ constructor(_onNewRoot) {
2944
+ this._onNewRoot = _onNewRoot;
2945
+ this.rootUrl = void 0;
2946
+ this.lastEpoch = void 0;
2947
+ this.onNewEpoch = new Event4();
2948
+ this._isProcessingRootDocs = false;
2949
+ }
2950
+ async processCredential(credential) {
2951
+ if (!checkCredentialType(credential, "dxos.halo.credentials.Epoch")) {
2952
+ return;
2757
2953
  }
2758
- } else {
2759
- const { platform: platform2, version, arch } = process;
2760
- return {
2761
- type: Platform.PLATFORM_TYPE.NODE,
2762
- platform: platform2,
2763
- arch,
2764
- runtime: version,
2765
- uptime: Math.floor(process.uptime()),
2766
- memory: process.memoryUsage()
2767
- };
2768
- }
2769
- };
2770
-
2771
- // packages/sdk/client-services/src/version.ts
2772
- var DXOS_VERSION = "0.4.10-main.3040945";
2773
-
2774
- // packages/sdk/client-services/src/packlets/services/diagnostics.ts
2775
- var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/diagnostics.ts";
2776
- var DEFAULT_TIMEOUT = 1e3;
2777
- var createDiagnostics = async (clientServices, serviceContext, config) => {
2778
- const diagnostics = {
2779
- created: (/* @__PURE__ */ new Date()).toISOString(),
2780
- platform: getPlatform(),
2781
- client: {
2782
- version: DXOS_VERSION,
2783
- storage: {
2784
- version: STORAGE_VERSION
2785
- }
2786
- },
2787
- trace: TRACE_PROCESSOR.getDiagnostics()
2788
- };
2789
- {
2790
- invariant9(clientServices.LoggingService, "SystemService is not available.", {
2791
- F: __dxlog_file10,
2792
- L: 108,
2793
- S: void 0,
2794
- A: [
2795
- "clientServices.LoggingService",
2796
- "'SystemService is not available.'"
2797
- ]
2798
- });
2799
- diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {
2800
- timeout: DEFAULT_TIMEOUT
2801
- }).catch(() => void 0);
2802
- }
2803
- if (typeof navigator !== "undefined" && navigator.storage) {
2804
- const map = /* @__PURE__ */ new Map();
2805
- const dir = await navigator.storage.getDirectory();
2806
- for await (const filename of dir?.keys()) {
2807
- const idx = filename.indexOf("-", filename.indexOf("-") + 1);
2808
- if (idx === -1) {
2809
- continue;
2810
- }
2811
- map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
2812
- }
2813
- diagnostics.storage = Array.from(map.entries()).sort((a, b) => b[1] - a[1]).map(([file, count]) => ({
2814
- file,
2815
- count
2816
- }));
2817
- }
2818
- const identity = serviceContext.identityManager.identity;
2819
- if (identity) {
2820
- diagnostics.identity = {
2821
- identityKey: identity.identityKey,
2822
- spaceKey: identity.space.key,
2823
- profile: identity.profileDocument
2824
- };
2825
- const { devices } = await getFirstStreamValue(clientServices.DevicesService.queryDevices(), {
2826
- timeout: DEFAULT_TIMEOUT
2827
- }).catch(() => void 0) ?? {};
2828
- diagnostics.devices = devices;
2829
- if (serviceContext.dataSpaceManager) {
2830
- diagnostics.spaces = await Promise.all(Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? []);
2831
- }
2832
- const { feeds = [] } = await getFirstStreamValue(clientServices.DevtoolsHost.subscribeToFeeds({}), {
2833
- timeout: DEFAULT_TIMEOUT
2834
- }).catch(() => void 0) ?? {};
2835
- diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({
2836
- feedKey,
2837
- bytes,
2838
- length
2839
- }));
2840
- const status = await getFirstStreamValue(clientServices.NetworkService.queryStatus(), {
2841
- timeout: DEFAULT_TIMEOUT
2842
- }).catch(() => void 0);
2843
- diagnostics.networkStatus = status;
2844
- diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;
2845
- }
2846
- diagnostics.config = config.values;
2847
- return diagnostics;
2848
- };
2849
- var getSpaceStats = async (space) => {
2850
- const stats = {
2851
- key: space.key,
2852
- metrics: space.metrics,
2853
- epochs: space.inner.spaceState.credentials.filter(credentialTypeFilter("dxos.halo.credentials.Epoch")).map((credential) => ({
2854
- ...credential.subject.assertion,
2855
- id: credential.id
2856
- })),
2857
- members: Array.from(space.inner.spaceState.members.values()).map((member) => ({
2858
- identity: {
2859
- identityKey: member.key,
2860
- profile: {
2861
- displayName: member.assertion.profile?.displayName
2862
- }
2863
- },
2864
- presence: space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0 ? SpaceMember.PresenceState.ONLINE : SpaceMember.PresenceState.OFFLINE
2865
- })),
2866
- pipeline: {
2867
- // TODO(burdon): Pick properties from credentials if needed.
2868
- currentEpoch: space.automergeSpaceState.lastEpoch,
2869
- appliedEpoch: space.automergeSpaceState.lastEpoch,
2870
- controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),
2871
- currentControlTimeframe: space.inner.controlPipeline.state.timeframe,
2872
- targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,
2873
- totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe
2874
- }
2875
- };
2876
- if (stats.metrics) {
2877
- const { open, ready } = stats.metrics;
2878
- stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();
2879
- }
2880
- return stats;
2881
- };
2882
-
2883
- // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2884
- import { Event as Event6, asyncTimeout, scheduleTask as scheduleTask5, sleep as sleep2, synchronized, trackLeaks } from "@dxos/async";
2885
- import { AUTH_TIMEOUT as AUTH_TIMEOUT2 } from "@dxos/client-protocol";
2886
- import { cancelWithContext as cancelWithContext2, Context as Context8, ContextDisposedError } from "@dxos/context";
2887
- import { timed, warnAfterTimeout } from "@dxos/debug";
2888
- import { TYPE_PROPERTIES } from "@dxos/echo-db";
2889
- import { createMappedFeedWriter } from "@dxos/echo-pipeline";
2890
- import { AutomergeDocumentLoaderImpl } from "@dxos/echo-pipeline";
2891
- import { failedInvariant, invariant as invariant11 } from "@dxos/invariant";
2892
- import { PublicKey as PublicKey8 } from "@dxos/keys";
2893
- import { log as log9 } from "@dxos/log";
2894
- import { CancelledError, SystemError } from "@dxos/protocols";
2895
- import { SpaceState, CreateEpochRequest } from "@dxos/protocols/proto/dxos/client/services";
2896
- import { AdmittedFeed as AdmittedFeed3 } from "@dxos/protocols/proto/dxos/halo/credentials";
2897
- import { Timeframe as Timeframe2 } from "@dxos/timeframe";
2898
- import { trace as trace6 } from "@dxos/tracing";
2899
- import { ComplexSet as ComplexSet3, assignDeep } from "@dxos/util";
2900
-
2901
- // packages/sdk/client-services/src/packlets/spaces/automerge-space-state.ts
2902
- import { Event as Event4 } from "@dxos/async";
2903
- import { checkCredentialType } from "@dxos/credentials";
2904
- var AutomergeSpaceState = class {
2905
- constructor(_onNewRoot) {
2906
- this._onNewRoot = _onNewRoot;
2907
- this.rootUrl = void 0;
2908
- this.lastEpoch = void 0;
2909
- this.onNewEpoch = new Event4();
2910
- this._isProcessingRootDocs = false;
2911
- }
2912
- async processCredential(credential) {
2913
- if (!checkCredentialType(credential, "dxos.halo.credentials.Epoch")) {
2914
- return;
2915
- }
2916
- this.lastEpoch = credential;
2917
- if (credential.subject.assertion.automergeRoot) {
2918
- this.rootUrl = credential.subject.assertion.automergeRoot;
2919
- if (this._isProcessingRootDocs) {
2920
- this._onNewRoot(this.rootUrl);
2921
- }
2922
- }
2923
- this.onNewEpoch.emit(credential);
2924
- }
2925
- startProcessingRootDocs() {
2926
- if (this._isProcessingRootDocs) {
2927
- return;
2928
- }
2929
- if (this.rootUrl) {
2930
- this._onNewRoot(this.rootUrl);
2931
- }
2932
- this._isProcessingRootDocs = true;
2933
- }
2934
- async ensureEpochInitialized() {
2935
- await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);
2954
+ this.lastEpoch = credential;
2955
+ if (credential.subject.assertion.automergeRoot) {
2956
+ this.rootUrl = credential.subject.assertion.automergeRoot;
2957
+ if (this._isProcessingRootDocs) {
2958
+ this._onNewRoot(this.rootUrl);
2959
+ }
2960
+ }
2961
+ this.onNewEpoch.emit(credential);
2962
+ }
2963
+ startProcessingRootDocs() {
2964
+ if (this._isProcessingRootDocs) {
2965
+ return;
2966
+ }
2967
+ if (this.rootUrl) {
2968
+ this._onNewRoot(this.rootUrl);
2969
+ }
2970
+ this._isProcessingRootDocs = true;
2971
+ }
2972
+ async ensureEpochInitialized() {
2973
+ await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);
2936
2974
  }
2937
2975
  };
2938
2976
 
2939
2977
  // packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts
2940
- import { DeferredTask, Event as Event5, scheduleTask as scheduleTask4, sleep, TimeoutError as TimeoutError2, Trigger as Trigger4 } from "@dxos/async";
2978
+ import { DeferredTask, Event as Event5, scheduleTask as scheduleTask3, sleep, TimeoutError as TimeoutError2, Trigger as Trigger4 } from "@dxos/async";
2941
2979
  import { Context as Context7, rejectOnDispose } from "@dxos/context";
2942
- import { invariant as invariant10 } from "@dxos/invariant";
2943
- import { PublicKey as PublicKey7 } from "@dxos/keys";
2980
+ import { invariant as invariant9 } from "@dxos/invariant";
2981
+ import { PublicKey as PublicKey8 } from "@dxos/keys";
2944
2982
  import { log as log8 } from "@dxos/log";
2945
2983
  import { schema as schema3 } from "@dxos/protocols";
2946
2984
  import { RpcExtension as RpcExtension2 } from "@dxos/teleport";
2947
2985
  import { ComplexMap as ComplexMap2, ComplexSet as ComplexSet2, entry } from "@dxos/util";
2948
- var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts";
2986
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts";
2949
2987
  var DEFAULT_RETRY_TIMEOUT = 1e3;
2950
2988
  var DEFAULT_SUCCESS_DELAY = 1e3;
2951
2989
  var DEFAULT_NOTARIZE_TIMEOUT = 1e4;
@@ -2955,8 +2993,8 @@ var NotarizationPlugin = class {
2955
2993
  this._ctx = new Context7();
2956
2994
  this._extensionOpened = new Event5();
2957
2995
  this._extensions = /* @__PURE__ */ new Set();
2958
- this._processedCredentials = new ComplexSet2(PublicKey7.hash);
2959
- this._processCredentialsTriggers = new ComplexMap2(PublicKey7.hash);
2996
+ this._processedCredentials = new ComplexSet2(PublicKey8.hash);
2997
+ this._processCredentialsTriggers = new ComplexMap2(PublicKey8.hash);
2960
2998
  }
2961
2999
  get hasWriter() {
2962
3000
  return !!this._writer;
@@ -2973,13 +3011,13 @@ var NotarizationPlugin = class {
2973
3011
  log8("notarize", {
2974
3012
  credentials
2975
3013
  }, {
2976
- F: __dxlog_file11,
3014
+ F: __dxlog_file10,
2977
3015
  L: 90,
2978
3016
  S: this,
2979
3017
  C: (f, a) => f(...a)
2980
3018
  });
2981
- invariant10(credentials.every((credential) => credential.id), "Credentials must have an id", {
2982
- F: __dxlog_file11,
3019
+ invariant9(credentials.every((credential) => credential.id), "Credentials must have an id", {
3020
+ F: __dxlog_file10,
2983
3021
  L: 91,
2984
3022
  S: this,
2985
3023
  A: [
@@ -2993,7 +3031,7 @@ var NotarizationPlugin = class {
2993
3031
  log8.warn("Notarization error", {
2994
3032
  err
2995
3033
  }, {
2996
- F: __dxlog_file11,
3034
+ F: __dxlog_file10,
2997
3035
  L: 99,
2998
3036
  S: this,
2999
3037
  C: (f, a) => f(...a)
@@ -3004,12 +3042,12 @@ var NotarizationPlugin = class {
3004
3042
  });
3005
3043
  opCtx?.onDispose(() => ctx.dispose());
3006
3044
  if (timeout !== 0) {
3007
- scheduleTask4(ctx, () => {
3045
+ scheduleTask3(ctx, () => {
3008
3046
  log8.warn("Notarization timeout", {
3009
3047
  timeout,
3010
3048
  peers: Array.from(this._extensions).map((extension) => extension.remotePeerId)
3011
3049
  }, {
3012
- F: __dxlog_file11,
3050
+ F: __dxlog_file10,
3013
3051
  L: 111,
3014
3052
  S: this,
3015
3053
  C: (f, a) => f(...a)
@@ -3032,13 +3070,13 @@ var NotarizationPlugin = class {
3032
3070
  log8.info("Exhausted all peers to notarize with", {
3033
3071
  retryIn: retryTimeout
3034
3072
  }, {
3035
- F: __dxlog_file11,
3073
+ F: __dxlog_file10,
3036
3074
  L: 136,
3037
3075
  S: this,
3038
3076
  C: (f, a) => f(...a)
3039
3077
  });
3040
3078
  peersTried.clear();
3041
- scheduleTask4(ctx, () => notarizeTask.schedule(), retryTimeout);
3079
+ scheduleTask3(ctx, () => notarizeTask.schedule(), retryTimeout);
3042
3080
  return;
3043
3081
  }
3044
3082
  peersTried.add(peer);
@@ -3046,7 +3084,7 @@ var NotarizationPlugin = class {
3046
3084
  peer: peer.localPeerId,
3047
3085
  credentialId: credentials.map((credential) => credential.id)
3048
3086
  }, {
3049
- F: __dxlog_file11,
3087
+ F: __dxlog_file10,
3050
3088
  L: 143,
3051
3089
  S: this,
3052
3090
  C: (f, a) => f(...a)
@@ -3055,7 +3093,7 @@ var NotarizationPlugin = class {
3055
3093
  credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id))
3056
3094
  });
3057
3095
  log8("success", void 0, {
3058
- F: __dxlog_file11,
3096
+ F: __dxlog_file10,
3059
3097
  L: 147,
3060
3098
  S: this,
3061
3099
  C: (f, a) => f(...a)
@@ -3064,7 +3102,7 @@ var NotarizationPlugin = class {
3064
3102
  } catch (err) {
3065
3103
  if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {
3066
3104
  log8.info("error notarizing (recoverable)", err, {
3067
- F: __dxlog_file11,
3105
+ F: __dxlog_file10,
3068
3106
  L: 151,
3069
3107
  S: this,
3070
3108
  C: (f, a) => f(...a)
@@ -3082,7 +3120,7 @@ var NotarizationPlugin = class {
3082
3120
  errors.wait()
3083
3121
  ]);
3084
3122
  log8("done", void 0, {
3085
- F: __dxlog_file11,
3123
+ F: __dxlog_file10,
3086
3124
  L: 162,
3087
3125
  S: this,
3088
3126
  C: (f, a) => f(...a)
@@ -3103,8 +3141,8 @@ var NotarizationPlugin = class {
3103
3141
  this._processCredentialsTriggers.delete(credential.id);
3104
3142
  }
3105
3143
  setWriter(writer) {
3106
- invariant10(!this._writer, "Writer already set.", {
3107
- F: __dxlog_file11,
3144
+ invariant9(!this._writer, "Writer already set.", {
3145
+ F: __dxlog_file10,
3108
3146
  L: 181,
3109
3147
  S: this,
3110
3148
  A: [
@@ -3128,8 +3166,8 @@ var NotarizationPlugin = class {
3128
3166
  throw new Error(WRITER_NOT_SET_ERROR_CODE);
3129
3167
  }
3130
3168
  for (const credential of request.credentials ?? []) {
3131
- invariant10(credential.id, "Credential must have an id", {
3132
- F: __dxlog_file11,
3169
+ invariant9(credential.id, "Credential must have an id", {
3170
+ F: __dxlog_file10,
3133
3171
  L: 200,
3134
3172
  S: this,
3135
3173
  A: [
@@ -3149,7 +3187,7 @@ var NotarizationPlugin = class {
3149
3187
  log8("extension opened", {
3150
3188
  peer: extension.localPeerId
3151
3189
  }, {
3152
- F: __dxlog_file11,
3190
+ F: __dxlog_file10,
3153
3191
  L: 211,
3154
3192
  S: this,
3155
3193
  C: (f, a) => f(...a)
@@ -3161,7 +3199,7 @@ var NotarizationPlugin = class {
3161
3199
  log8("extension closed", {
3162
3200
  peer: extension.localPeerId
3163
3201
  }, {
3164
- F: __dxlog_file11,
3202
+ F: __dxlog_file10,
3165
3203
  L: 216,
3166
3204
  S: this,
3167
3205
  C: (f, a) => f(...a)
@@ -3215,7 +3253,7 @@ function _ts_decorate4(decorators, target, key, desc) {
3215
3253
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3216
3254
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3217
3255
  }
3218
- var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space.ts";
3256
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space.ts";
3219
3257
  var DataSpace = class {
3220
3258
  constructor(params) {
3221
3259
  this._ctx = new Context8();
@@ -3241,7 +3279,7 @@ var DataSpace = class {
3241
3279
  this._callbacks = params.callbacks ?? {};
3242
3280
  this._automergeHost = params.automergeHost;
3243
3281
  this.authVerifier = new TrustedKeySetAuthVerifier({
3244
- trustedKeysProvider: () => new ComplexSet3(PublicKey8.hash, Array.from(this._inner.spaceState.members.values()).filter((member) => !member.removed).map((member) => member.key)),
3282
+ trustedKeysProvider: () => new ComplexSet3(PublicKey9.hash, Array.from(this._inner.spaceState.members.values()).filter((member) => !member.removed).map((member) => member.key)),
3245
3283
  update: this._inner.stateUpdate,
3246
3284
  authTimeout: AUTH_TIMEOUT2
3247
3285
  });
@@ -3250,7 +3288,7 @@ var DataSpace = class {
3250
3288
  log9("new state", {
3251
3289
  state: SpaceState[this._state]
3252
3290
  }, {
3253
- F: __dxlog_file12,
3291
+ F: __dxlog_file11,
3254
3292
  L: 140,
3255
3293
  S: this,
3256
3294
  C: (f, a) => f(...a)
@@ -3300,7 +3338,7 @@ var DataSpace = class {
3300
3338
  log9("new state", {
3301
3339
  state: SpaceState[this._state]
3302
3340
  }, {
3303
- F: __dxlog_file12,
3341
+ F: __dxlog_file11,
3304
3342
  L: 198,
3305
3343
  S: this,
3306
3344
  C: (f, a) => f(...a)
@@ -3318,7 +3356,7 @@ var DataSpace = class {
3318
3356
  log9("new state", {
3319
3357
  state: SpaceState[this._state]
3320
3358
  }, {
3321
- F: __dxlog_file12,
3359
+ F: __dxlog_file11,
3322
3360
  L: 212,
3323
3361
  S: this,
3324
3362
  C: (f, a) => f(...a)
@@ -3343,14 +3381,14 @@ var DataSpace = class {
3343
3381
  * Initialize the data pipeline in a separate task.
3344
3382
  */
3345
3383
  initializeDataPipelineAsync() {
3346
- scheduleTask5(this._ctx, async () => {
3384
+ scheduleTask4(this._ctx, async () => {
3347
3385
  try {
3348
3386
  this.metrics.pipelineInitBegin = /* @__PURE__ */ new Date();
3349
3387
  await this.initializeDataPipeline();
3350
3388
  } catch (err) {
3351
3389
  if (err instanceof CancelledError || err instanceof ContextDisposedError) {
3352
3390
  log9("data pipeline initialization cancelled", err, {
3353
- F: __dxlog_file12,
3391
+ F: __dxlog_file11,
3354
3392
  L: 245,
3355
3393
  S: this,
3356
3394
  C: (f, a) => f(...a)
@@ -3358,7 +3396,7 @@ var DataSpace = class {
3358
3396
  return;
3359
3397
  }
3360
3398
  log9.error("Error initializing data pipeline", err, {
3361
- F: __dxlog_file12,
3399
+ F: __dxlog_file11,
3362
3400
  L: 249,
3363
3401
  S: this,
3364
3402
  C: (f, a) => f(...a)
@@ -3367,7 +3405,7 @@ var DataSpace = class {
3367
3405
  log9("new state", {
3368
3406
  state: SpaceState[this._state]
3369
3407
  }, {
3370
- F: __dxlog_file12,
3408
+ F: __dxlog_file11,
3371
3409
  L: 251,
3372
3410
  S: this,
3373
3411
  C: (f, a) => f(...a)
@@ -3387,7 +3425,7 @@ var DataSpace = class {
3387
3425
  log9("new state", {
3388
3426
  state: SpaceState[this._state]
3389
3427
  }, {
3390
- F: __dxlog_file12,
3428
+ F: __dxlog_file11,
3391
3429
  L: 267,
3392
3430
  S: this,
3393
3431
  C: (f, a) => f(...a)
@@ -3397,7 +3435,7 @@ var DataSpace = class {
3397
3435
  this._automergeSpaceState.startProcessingRootDocs();
3398
3436
  await cancelWithContext2(this._ctx, this.automergeSpaceState.ensureEpochInitialized());
3399
3437
  log9("data pipeline ready", void 0, {
3400
- F: __dxlog_file12,
3438
+ F: __dxlog_file11,
3401
3439
  L: 279,
3402
3440
  S: this,
3403
3441
  C: (f, a) => f(...a)
@@ -3407,7 +3445,7 @@ var DataSpace = class {
3407
3445
  log9("new state", {
3408
3446
  state: SpaceState[this._state]
3409
3447
  }, {
3410
- F: __dxlog_file12,
3448
+ F: __dxlog_file11,
3411
3449
  L: 283,
3412
3450
  S: this,
3413
3451
  C: (f, a) => f(...a)
@@ -3423,7 +3461,7 @@ var DataSpace = class {
3423
3461
  this.metrics.controlPipelineReady = /* @__PURE__ */ new Date();
3424
3462
  await this._createWritableFeeds();
3425
3463
  log9("writable feeds created", void 0, {
3426
- F: __dxlog_file12,
3464
+ F: __dxlog_file11,
3427
3465
  L: 299,
3428
3466
  S: this,
3429
3467
  C: (f, a) => f(...a)
@@ -3486,7 +3524,7 @@ var DataSpace = class {
3486
3524
  space: this.key,
3487
3525
  rootUrl
3488
3526
  }, {
3489
- F: __dxlog_file12,
3527
+ F: __dxlog_file11,
3490
3528
  L: 365,
3491
3529
  S: this,
3492
3530
  C: (f, a) => f(...a)
@@ -3518,7 +3556,7 @@ var DataSpace = class {
3518
3556
  rootUrl,
3519
3557
  err
3520
3558
  }, {
3521
- F: __dxlog_file12,
3559
+ F: __dxlog_file11,
3522
3560
  L: 388,
3523
3561
  S: this,
3524
3562
  C: (f, a) => f(...a)
@@ -3572,8 +3610,8 @@ var DataSpace = class {
3572
3610
  const rootHandle = this._automergeHost.repo.find(currentRootUrl);
3573
3611
  await cancelWithContext2(this._ctx, asyncTimeout(rootHandle.whenReady(), 1e4));
3574
3612
  const newRoot = this._automergeHost.repo.create(rootHandle.docSync());
3575
- invariant11(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3576
- F: __dxlog_file12,
3613
+ invariant10(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3614
+ F: __dxlog_file11,
3577
3615
  L: 438,
3578
3616
  S: this,
3579
3617
  A: [
@@ -3592,7 +3630,7 @@ var DataSpace = class {
3592
3630
  case CreateEpochRequest.Migration.FRAGMENT_AUTOMERGE_ROOT:
3593
3631
  {
3594
3632
  log9.info("Fragmenting", void 0, {
3595
- F: __dxlog_file12,
3633
+ F: __dxlog_file11,
3596
3634
  L: 450,
3597
3635
  S: this,
3598
3636
  C: (f, a) => f(...a)
@@ -3603,8 +3641,8 @@ var DataSpace = class {
3603
3641
  const objects = Object.entries(rootHandle.docSync().objects);
3604
3642
  const properties = objects.find(([_, value]) => value.system.type?.itemId === TYPE_PROPERTIES);
3605
3643
  const otherObjects = objects.filter(([key]) => key !== properties?.[0]);
3606
- invariant11(properties, "Properties not found", {
3607
- F: __dxlog_file12,
3644
+ invariant10(properties, "Properties not found", {
3645
+ F: __dxlog_file11,
3608
3646
  L: 460,
3609
3647
  S: this,
3610
3648
  A: [
@@ -3619,8 +3657,8 @@ var DataSpace = class {
3619
3657
  ])
3620
3658
  };
3621
3659
  const newRoot = this._automergeHost.repo.create(newSpaceDoc);
3622
- invariant11(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3623
- F: __dxlog_file12,
3660
+ invariant10(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3661
+ F: __dxlog_file11,
3624
3662
  L: 465,
3625
3663
  S: this,
3626
3664
  A: [
@@ -3689,7 +3727,7 @@ var DataSpace = class {
3689
3727
  log9("new state", {
3690
3728
  state: SpaceState[this._state]
3691
3729
  }, {
3692
- F: __dxlog_file12,
3730
+ F: __dxlog_file11,
3693
3731
  L: 531,
3694
3732
  S: this,
3695
3733
  C: (f, a) => f(...a)
@@ -3747,11 +3785,11 @@ DataSpace = _ts_decorate4([
3747
3785
  import { Event as Event7, synchronized as synchronized2, trackLeaks as trackLeaks2 } from "@dxos/async";
3748
3786
  import { Context as Context9, cancelWithContext as cancelWithContext3 } from "@dxos/context";
3749
3787
  import { getCredentialAssertion as getCredentialAssertion2 } from "@dxos/credentials";
3750
- import { invariant as invariant12 } from "@dxos/invariant";
3751
- import { PublicKey as PublicKey9 } from "@dxos/keys";
3788
+ import { invariant as invariant11 } from "@dxos/invariant";
3789
+ import { PublicKey as PublicKey10 } from "@dxos/keys";
3752
3790
  import { log as log10 } from "@dxos/log";
3753
3791
  import { trace as trace7 } from "@dxos/protocols";
3754
- import { SpaceState as SpaceState2 } from "@dxos/protocols/proto/dxos/client/services";
3792
+ import { Invitation as Invitation6, SpaceState as SpaceState2 } from "@dxos/protocols/proto/dxos/client/services";
3755
3793
  import { Gossip as Gossip2, Presence as Presence2 } from "@dxos/teleport-extension-gossip";
3756
3794
  import { ComplexMap as ComplexMap3, deferFunction as deferFunction2, forEachAsync } from "@dxos/util";
3757
3795
 
@@ -3836,22 +3874,23 @@ function _ts_decorate5(decorators, target, key, desc) {
3836
3874
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3837
3875
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3838
3876
  }
3839
- var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts";
3877
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts";
3840
3878
  var PRESENCE_ANNOUNCE_INTERVAL = 1e4;
3841
3879
  var PRESENCE_OFFLINE_TIMEOUT = 2e4;
3842
3880
  var DataSpaceManager = class {
3843
- constructor(_spaceManager, _metadataStore, _keyring, _signingContext, _feedStore, _automergeHost, params) {
3881
+ constructor(_spaceManager, _metadataStore, _keyring, _signingContext, _feedStore, _automergeHost, _invitationsManager, params) {
3844
3882
  this._spaceManager = _spaceManager;
3845
3883
  this._metadataStore = _metadataStore;
3846
3884
  this._keyring = _keyring;
3847
3885
  this._signingContext = _signingContext;
3848
3886
  this._feedStore = _feedStore;
3849
3887
  this._automergeHost = _automergeHost;
3888
+ this._invitationsManager = _invitationsManager;
3850
3889
  this._ctx = new Context9();
3851
3890
  this.updated = new Event7();
3852
- this._spaces = new ComplexMap3(PublicKey9.hash);
3891
+ this._spaces = new ComplexMap3(PublicKey10.hash);
3853
3892
  this._isOpen = false;
3854
- this._instanceId = PublicKey9.random().toHex();
3893
+ this._instanceId = PublicKey10.random().toHex();
3855
3894
  const { spaceMemberPresenceAnnounceInterval = PRESENCE_ANNOUNCE_INTERVAL, spaceMemberPresenceOfflineTimeout = PRESENCE_OFFLINE_TIMEOUT } = params ?? {};
3856
3895
  this._spaceMemberPresenceAnnounceInterval = spaceMemberPresenceAnnounceInterval;
3857
3896
  this._spaceMemberPresenceOfflineTimeout = spaceMemberPresenceOfflineTimeout;
@@ -3862,24 +3901,24 @@ var DataSpaceManager = class {
3862
3901
  }
3863
3902
  async open() {
3864
3903
  log10("open", void 0, {
3865
- F: __dxlog_file13,
3866
- L: 98,
3904
+ F: __dxlog_file12,
3905
+ L: 101,
3867
3906
  S: this,
3868
3907
  C: (f, a) => f(...a)
3869
3908
  });
3870
3909
  log10.trace("dxos.echo.data-space-manager.open", trace7.begin({
3871
3910
  id: this._instanceId
3872
3911
  }), {
3873
- F: __dxlog_file13,
3874
- L: 99,
3912
+ F: __dxlog_file12,
3913
+ L: 102,
3875
3914
  S: this,
3876
3915
  C: (f, a) => f(...a)
3877
3916
  });
3878
3917
  log10("metadata loaded", {
3879
3918
  spaces: this._metadataStore.spaces.length
3880
3919
  }, {
3881
- F: __dxlog_file13,
3882
- L: 100,
3920
+ F: __dxlog_file12,
3921
+ L: 103,
3883
3922
  S: this,
3884
3923
  C: (f, a) => f(...a)
3885
3924
  });
@@ -3888,8 +3927,8 @@ var DataSpaceManager = class {
3888
3927
  log10("load space", {
3889
3928
  spaceMetadata
3890
3929
  }, {
3891
- F: __dxlog_file13,
3892
- L: 104,
3930
+ F: __dxlog_file12,
3931
+ L: 107,
3893
3932
  S: this,
3894
3933
  C: (f, a) => f(...a)
3895
3934
  });
@@ -3899,8 +3938,8 @@ var DataSpaceManager = class {
3899
3938
  spaceMetadata,
3900
3939
  err
3901
3940
  }, {
3902
- F: __dxlog_file13,
3903
- L: 107,
3941
+ F: __dxlog_file12,
3942
+ L: 110,
3904
3943
  S: this,
3905
3944
  C: (f, a) => f(...a)
3906
3945
  });
@@ -3916,16 +3955,16 @@ var DataSpaceManager = class {
3916
3955
  log10.trace("dxos.echo.data-space-manager.open", trace7.end({
3917
3956
  id: this._instanceId
3918
3957
  }), {
3919
- F: __dxlog_file13,
3920
- L: 120,
3958
+ F: __dxlog_file12,
3959
+ L: 123,
3921
3960
  S: this,
3922
3961
  C: (f, a) => f(...a)
3923
3962
  });
3924
3963
  }
3925
3964
  async close() {
3926
3965
  log10("close", void 0, {
3927
- F: __dxlog_file13,
3928
- L: 125,
3966
+ F: __dxlog_file12,
3967
+ L: 128,
3929
3968
  S: this,
3930
3969
  C: (f, a) => f(...a)
3931
3970
  });
@@ -3939,9 +3978,9 @@ var DataSpaceManager = class {
3939
3978
  * Creates a new space writing the genesis credentials to the control feed.
3940
3979
  */
3941
3980
  async createSpace() {
3942
- invariant12(this._isOpen, "Not open.", {
3943
- F: __dxlog_file13,
3944
- L: 138,
3981
+ invariant11(this._isOpen, "Not open.", {
3982
+ F: __dxlog_file12,
3983
+ L: 141,
3945
3984
  S: this,
3946
3985
  A: [
3947
3986
  "this._isOpen",
@@ -3961,8 +4000,8 @@ var DataSpaceManager = class {
3961
4000
  log10("creating space...", {
3962
4001
  spaceKey
3963
4002
  }, {
3964
- F: __dxlog_file13,
3965
- L: 150,
4003
+ F: __dxlog_file12,
4004
+ L: 153,
3966
4005
  S: this,
3967
4006
  C: (f, a) => f(...a)
3968
4007
  });
@@ -3976,9 +4015,9 @@ var DataSpaceManager = class {
3976
4015
  const credentials = await spaceGenesis(this._keyring, this._signingContext, space.inner, automergeRoot.url);
3977
4016
  await this._metadataStore.addSpace(metadata);
3978
4017
  const memberCredential = credentials[1];
3979
- invariant12(getCredentialAssertion2(memberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
3980
- F: __dxlog_file13,
3981
- L: 163,
4018
+ invariant11(getCredentialAssertion2(memberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
4019
+ F: __dxlog_file12,
4020
+ L: 166,
3982
4021
  S: this,
3983
4022
  A: [
3984
4023
  "getCredentialAssertion(memberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember'",
@@ -3995,23 +4034,23 @@ var DataSpaceManager = class {
3995
4034
  log10("accept space", {
3996
4035
  opts
3997
4036
  }, {
3998
- F: __dxlog_file13,
3999
- L: 175,
4037
+ F: __dxlog_file12,
4038
+ L: 178,
4000
4039
  S: this,
4001
4040
  C: (f, a) => f(...a)
4002
4041
  });
4003
- invariant12(this._isOpen, "Not open.", {
4004
- F: __dxlog_file13,
4005
- L: 176,
4042
+ invariant11(this._isOpen, "Not open.", {
4043
+ F: __dxlog_file12,
4044
+ L: 179,
4006
4045
  S: this,
4007
4046
  A: [
4008
4047
  "this._isOpen",
4009
4048
  "'Not open.'"
4010
4049
  ]
4011
4050
  });
4012
- invariant12(!this._spaces.has(opts.spaceKey), "Space already exists.", {
4013
- F: __dxlog_file13,
4014
- L: 177,
4051
+ invariant11(!this._spaces.has(opts.spaceKey), "Space already exists.", {
4052
+ F: __dxlog_file12,
4053
+ L: 180,
4015
4054
  S: this,
4016
4055
  A: [
4017
4056
  "!this._spaces.has(opts.spaceKey)",
@@ -4045,8 +4084,8 @@ var DataSpaceManager = class {
4045
4084
  log10("construct space", {
4046
4085
  metadata
4047
4086
  }, {
4048
- F: __dxlog_file13,
4049
- L: 210,
4087
+ F: __dxlog_file12,
4088
+ L: 213,
4050
4089
  S: this,
4051
4090
  C: (f, a) => f(...a)
4052
4091
  });
@@ -4083,13 +4122,16 @@ var DataSpaceManager = class {
4083
4122
  },
4084
4123
  onAuthFailure: () => {
4085
4124
  log10.warn("auth failure", void 0, {
4086
- F: __dxlog_file13,
4087
- L: 247,
4125
+ F: __dxlog_file12,
4126
+ L: 250,
4088
4127
  S: this,
4089
4128
  C: (f, a) => f(...a)
4090
4129
  });
4091
4130
  },
4092
- memberKey: this._signingContext.identityKey
4131
+ memberKey: this._signingContext.identityKey,
4132
+ onDelegatedInvitationStatusChange: (invitation, isActive) => {
4133
+ return this._handleInvitationStatusChange(dataSpace, invitation, isActive);
4134
+ }
4093
4135
  });
4094
4136
  controlFeed && await space.setControlFeed(controlFeed);
4095
4137
  dataFeed && await space.setDataFeed(dataFeed);
@@ -4107,8 +4149,8 @@ var DataSpaceManager = class {
4107
4149
  log10("before space ready", {
4108
4150
  space: space.key
4109
4151
  }, {
4110
- F: __dxlog_file13,
4111
- L: 265,
4152
+ F: __dxlog_file12,
4153
+ L: 271,
4112
4154
  S: this,
4113
4155
  C: (f, a) => f(...a)
4114
4156
  });
@@ -4118,12 +4160,15 @@ var DataSpaceManager = class {
4118
4160
  space: space.key,
4119
4161
  open: this._isOpen
4120
4162
  }, {
4121
- F: __dxlog_file13,
4122
- L: 268,
4163
+ F: __dxlog_file12,
4164
+ L: 274,
4123
4165
  S: this,
4124
4166
  C: (f, a) => f(...a)
4125
4167
  });
4126
4168
  if (this._isOpen) {
4169
+ await this._createDelegatedInvitations(dataSpace, [
4170
+ ...space.spaceState.invitations.entries()
4171
+ ]);
4127
4172
  this.updated.emit();
4128
4173
  }
4129
4174
  },
@@ -4131,8 +4176,8 @@ var DataSpaceManager = class {
4131
4176
  log10("before space close", {
4132
4177
  space: space.key
4133
4178
  }, {
4134
- F: __dxlog_file13,
4135
- L: 274,
4179
+ F: __dxlog_file12,
4180
+ L: 281,
4136
4181
  S: this,
4137
4182
  C: (f, a) => f(...a)
4138
4183
  });
@@ -4150,6 +4195,41 @@ var DataSpaceManager = class {
4150
4195
  this._spaces.set(metadata.key, dataSpace);
4151
4196
  return dataSpace;
4152
4197
  }
4198
+ async _handleInvitationStatusChange(dataSpace, delegatedInvitation, isActive) {
4199
+ if (dataSpace?.state !== SpaceState2.READY) {
4200
+ return;
4201
+ }
4202
+ if (isActive) {
4203
+ await this._createDelegatedInvitations(dataSpace, [
4204
+ [
4205
+ delegatedInvitation.credentialId,
4206
+ delegatedInvitation.invitation
4207
+ ]
4208
+ ]);
4209
+ } else {
4210
+ await this._invitationsManager.cancelInvitation(delegatedInvitation.invitation);
4211
+ }
4212
+ }
4213
+ async _createDelegatedInvitations(space, invitations) {
4214
+ const tasks = invitations.map(([credentialId, invitation]) => {
4215
+ return this._invitationsManager.createInvitation({
4216
+ type: Invitation6.Type.DELEGATED,
4217
+ kind: Invitation6.Kind.SPACE,
4218
+ spaceKey: space.key,
4219
+ authMethod: invitation.authMethod,
4220
+ invitationId: invitation.invitationId,
4221
+ swarmKey: invitation.swarmKey,
4222
+ guestKeypair: invitation.guestKey ? {
4223
+ publicKey: invitation.guestKey
4224
+ } : void 0,
4225
+ lifetime: invitation.expiresOn ? invitation.expiresOn.getTime() - Date.now() : void 0,
4226
+ multiUse: invitation.multiUse,
4227
+ delegationCredentialId: credentialId,
4228
+ persistent: false
4229
+ });
4230
+ });
4231
+ await Promise.all(tasks);
4232
+ }
4153
4233
  };
4154
4234
  _ts_decorate5([
4155
4235
  synchronized2
@@ -4168,14 +4248,14 @@ DataSpaceManager = _ts_decorate5([
4168
4248
  ], DataSpaceManager);
4169
4249
 
4170
4250
  // packages/sdk/client-services/src/packlets/spaces/spaces-service.ts
4171
- import { EventSubscriptions as EventSubscriptions2, UpdateScheduler, scheduleTask as scheduleTask6 } from "@dxos/async";
4251
+ import { EventSubscriptions as EventSubscriptions2, UpdateScheduler, scheduleTask as scheduleTask5 } from "@dxos/async";
4172
4252
  import { Stream as Stream10 } from "@dxos/codec-protobuf";
4173
4253
  import { raise as raise2 } from "@dxos/debug";
4174
- import { invariant as invariant13 } from "@dxos/invariant";
4254
+ import { invariant as invariant12 } from "@dxos/invariant";
4175
4255
  import { log as log11 } from "@dxos/log";
4176
4256
  import { ApiError, SpaceNotFoundError, encodeError } from "@dxos/protocols";
4177
4257
  import { SpaceMember as SpaceMember3, SpaceState as SpaceState3 } from "@dxos/protocols/proto/dxos/client/services";
4178
- var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/spaces-service.ts";
4258
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/spaces-service.ts";
4179
4259
  var SpacesServiceImpl = class {
4180
4260
  constructor(_identityManager, _spaceManager, _getDataSpaceManager) {
4181
4261
  this._identityManager = _identityManager;
@@ -4214,7 +4294,7 @@ var SpacesServiceImpl = class {
4214
4294
  log11("update", {
4215
4295
  spaces
4216
4296
  }, {
4217
- F: __dxlog_file14,
4297
+ F: __dxlog_file13,
4218
4298
  L: 77,
4219
4299
  S: this,
4220
4300
  C: (f, a) => f(...a)
@@ -4225,7 +4305,7 @@ var SpacesServiceImpl = class {
4225
4305
  }, {
4226
4306
  maxFrequency: false ? void 0 : 2
4227
4307
  });
4228
- scheduleTask6(ctx, async () => {
4308
+ scheduleTask5(ctx, async () => {
4229
4309
  const dataSpaceManager = await this._getDataSpaceManager();
4230
4310
  const subscriptions = new EventSubscriptions2();
4231
4311
  ctx.onDispose(() => subscriptions.clear());
@@ -4259,7 +4339,7 @@ var SpacesServiceImpl = class {
4259
4339
  }
4260
4340
  subscribeMessages({ spaceKey, channel }) {
4261
4341
  return new Stream10(({ ctx, next }) => {
4262
- scheduleTask6(ctx, async () => {
4342
+ scheduleTask5(ctx, async () => {
4263
4343
  const dataSpaceManager = await this._getDataSpaceManager();
4264
4344
  const space = dataSpaceManager.spaces.get(spaceKey) ?? raise2(new SpaceNotFoundError(spaceKey));
4265
4345
  const handle = space.listen(getChannelId(channel), (message) => {
@@ -4278,7 +4358,7 @@ var SpacesServiceImpl = class {
4278
4358
  }
4279
4359
  };
4280
4360
  ctx.onDispose(() => space.spaceState.removeCredentialProcessor(processor));
4281
- scheduleTask6(ctx, async () => {
4361
+ scheduleTask5(ctx, async () => {
4282
4362
  await space.spaceState.addCredentialProcessor(processor);
4283
4363
  if (noTail) {
4284
4364
  close();
@@ -4296,8 +4376,8 @@ var SpacesServiceImpl = class {
4296
4376
  }
4297
4377
  });
4298
4378
  } else {
4299
- invariant13(!credential.id, "Id on unsigned credentials is not allowed", {
4300
- F: __dxlog_file14,
4379
+ invariant12(!credential.id, "Id on unsigned credentials is not allowed", {
4380
+ F: __dxlog_file13,
4301
4381
  L: 164,
4302
4382
  S: this,
4303
4383
  A: [
@@ -4305,8 +4385,8 @@ var SpacesServiceImpl = class {
4305
4385
  "'Id on unsigned credentials is not allowed'"
4306
4386
  ]
4307
4387
  });
4308
- invariant13(this._identityManager.identity, "Identity is not available", {
4309
- F: __dxlog_file14,
4388
+ invariant12(this._identityManager.identity, "Identity is not available", {
4389
+ F: __dxlog_file13,
4310
4390
  L: 165,
4311
4391
  S: this,
4312
4392
  A: [
@@ -4315,8 +4395,8 @@ var SpacesServiceImpl = class {
4315
4395
  ]
4316
4396
  });
4317
4397
  const signer = this._identityManager.identity.getIdentityCredentialSigner();
4318
- invariant13(credential.issuer.equals(signer.getIssuer()), void 0, {
4319
- F: __dxlog_file14,
4398
+ invariant12(credential.issuer.equals(signer.getIssuer()), void 0, {
4399
+ F: __dxlog_file13,
4320
4400
  L: 167,
4321
4401
  S: this,
4322
4402
  A: [
@@ -4391,20 +4471,19 @@ import { getCredentialAssertion as getCredentialAssertion3 } from "@dxos/credent
4391
4471
  import { failUndefined as failUndefined2 } from "@dxos/debug";
4392
4472
  import { AutomergeHost, MetadataStore, SnapshotStore, SpaceManager, valueEncoding } from "@dxos/echo-pipeline";
4393
4473
  import { FeedFactory, FeedStore } from "@dxos/feed-store";
4394
- import { IndexMetadataStore, IndexStore, Indexer } from "@dxos/indexing";
4395
- import { invariant as invariant14 } from "@dxos/invariant";
4474
+ import { IndexMetadataStore, IndexStore, Indexer, createStorageCallbacks } from "@dxos/indexing";
4475
+ import { invariant as invariant13 } from "@dxos/invariant";
4396
4476
  import { Keyring } from "@dxos/keyring";
4397
- import { PublicKey as PublicKey10 } from "@dxos/keys";
4477
+ import { PublicKey as PublicKey11 } from "@dxos/keys";
4398
4478
  import { log as log12 } from "@dxos/log";
4399
- import { InvalidStorageVersionError, STORAGE_VERSION as STORAGE_VERSION2, trace as trace8 } from "@dxos/protocols";
4400
- import { Invitation as Invitation6 } from "@dxos/protocols/proto/dxos/client/services";
4479
+ import { InvalidStorageVersionError, STORAGE_VERSION, trace as trace8 } from "@dxos/protocols";
4480
+ import { Invitation as Invitation7 } from "@dxos/protocols/proto/dxos/client/services";
4401
4481
  import { BlobStore } from "@dxos/teleport-extension-object-sync";
4402
4482
  import { trace as Trace2 } from "@dxos/tracing";
4403
4483
  import { safeInstanceof } from "@dxos/util";
4404
4484
 
4405
4485
  // packages/sdk/client-services/src/packlets/indexing/util.ts
4406
4486
  import { getHeads } from "@dxos/automerge/automerge";
4407
- import { warnAfterTimeout as warnAfterTimeout2 } from "@dxos/debug";
4408
4487
  import { idCodec } from "@dxos/protocols";
4409
4488
  var createSelectedDocumentsIterator = (automergeHost) => (
4410
4489
  /**
@@ -4415,8 +4494,10 @@ var createSelectedDocumentsIterator = (automergeHost) => (
4415
4494
  async function* loadDocuments(ids) {
4416
4495
  for (const id of ids) {
4417
4496
  const { documentId, objectId } = idCodec.decode(id);
4418
- const handle = automergeHost.repo.find(documentId);
4419
- await warnAfterTimeout2(5e3, "to long to load doc", () => handle.whenReady());
4497
+ const handle = automergeHost.repo.handles[documentId] ?? automergeHost.repo.find(documentId);
4498
+ if (!handle.isReady()) {
4499
+ await handle.whenReady();
4500
+ }
4420
4501
  const doc = handle.docSync();
4421
4502
  const hash = getHeads(doc).join("");
4422
4503
  yield doc.objects?.[objectId] ? [
@@ -4441,7 +4522,9 @@ var createDocumentsIterator = (automergeHost) => (
4441
4522
  if (visited.has(handle.documentId)) {
4442
4523
  return;
4443
4524
  }
4444
- await warnAfterTimeout2(5e3, "to long to load doc", () => handle.whenReady());
4525
+ if (!handle.isReady()) {
4526
+ await handle.whenReady();
4527
+ }
4445
4528
  const doc = handle.docSync();
4446
4529
  const heads = getHeads(doc);
4447
4530
  if (doc.objects) {
@@ -4461,7 +4544,7 @@ var createDocumentsIterator = (automergeHost) => (
4461
4544
  if (visited.has(id)) {
4462
4545
  continue;
4463
4546
  }
4464
- const linkHandle = automergeHost.repo.find(id);
4547
+ const linkHandle = automergeHost.repo.handles[id] ?? automergeHost.repo.find(id);
4465
4548
  for await (const result of getObjectsFromHandle(linkHandle)) {
4466
4549
  yield result;
4467
4550
  }
@@ -4492,7 +4575,7 @@ function _ts_decorate6(decorators, target, key, desc) {
4492
4575
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4493
4576
  return c > 3 && r && Object.defineProperty(target, key, r), r;
4494
4577
  }
4495
- var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-context.ts";
4578
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-context.ts";
4496
4579
  var ServiceContext = class extends Resource {
4497
4580
  constructor(storage, level, networkManager, signalManager, _runtimeParams) {
4498
4581
  super();
@@ -4503,7 +4586,7 @@ var ServiceContext = class extends Resource {
4503
4586
  this._runtimeParams = _runtimeParams;
4504
4587
  this.initialized = new Trigger5();
4505
4588
  this._handlerFactories = /* @__PURE__ */ new Map();
4506
- this._instanceId = PublicKey10.random().toHex();
4589
+ this._instanceId = PublicKey11.random().toHex();
4507
4590
  this.metadataStore = new MetadataStore(storage.createDirectory("metadata"));
4508
4591
  this.snapshotStore = new SnapshotStore(storage.createDirectory("snapshots"));
4509
4592
  this.blobStore = new BlobStore(storage.createDirectory("blobs"));
@@ -4531,62 +4614,77 @@ var ServiceContext = class extends Resource {
4531
4614
  });
4532
4615
  this.automergeHost = new AutomergeHost({
4533
4616
  directory: storage.createDirectory("automerge"),
4534
- metadata: this.indexMetadata
4617
+ db: level.sublevel("automerge"),
4618
+ storageCallbacks: createStorageCallbacks({
4619
+ host: () => this.automergeHost,
4620
+ metadata: this.indexMetadata
4621
+ })
4535
4622
  });
4536
4623
  this.indexer = new Indexer({
4537
4624
  indexStore: new IndexStore({
4538
- directory: storage.createDirectory("index-store")
4625
+ db: level.sublevel("index-storage")
4539
4626
  }),
4540
4627
  metadataStore: this.indexMetadata,
4541
4628
  loadDocuments: createSelectedDocumentsIterator(this.automergeHost),
4542
4629
  getAllDocuments: createDocumentsIterator(this.automergeHost)
4543
4630
  });
4544
4631
  this.invitations = new InvitationsHandler(this.networkManager);
4545
- this._handlerFactories.set(Invitation6.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => this.identityManager.identity ?? failUndefined2(), this._acceptIdentity.bind(this)));
4632
+ this.invitationsManager = new InvitationsManager(this.invitations, (invitation) => this.getInvitationHandler(invitation), this.metadataStore);
4633
+ this._handlerFactories.set(Invitation7.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => this.identityManager.identity ?? failUndefined2(), this._acceptIdentity.bind(this)));
4546
4634
  }
4547
4635
  async _open(ctx) {
4548
4636
  await this._checkStorageVersion();
4549
4637
  log12("opening...", void 0, {
4550
- F: __dxlog_file15,
4551
- L: 156,
4638
+ F: __dxlog_file14,
4639
+ L: 164,
4552
4640
  S: this,
4553
4641
  C: (f, a) => f(...a)
4554
4642
  });
4555
4643
  log12.trace("dxos.sdk.service-context.open", trace8.begin({
4556
4644
  id: this._instanceId
4557
4645
  }), {
4558
- F: __dxlog_file15,
4559
- L: 157,
4646
+ F: __dxlog_file14,
4647
+ L: 165,
4560
4648
  S: this,
4561
4649
  C: (f, a) => f(...a)
4562
4650
  });
4563
4651
  await this.signalManager.open();
4564
4652
  await this.networkManager.open();
4653
+ await this.automergeHost.open();
4565
4654
  await this.metadataStore.load();
4566
4655
  await this.spaceManager.open();
4567
4656
  await this.identityManager.open(ctx);
4568
4657
  if (this.identityManager.identity) {
4569
4658
  await this._initialize(ctx);
4570
4659
  }
4571
- log12.trace("dxos.sdk.service-context.open", trace8.end({
4572
- id: this._instanceId
4573
- }), {
4574
- F: __dxlog_file15,
4575
- L: 167,
4660
+ const loadedInvitations = await this.invitationsManager.loadPersistentInvitations();
4661
+ log12("loaded persistent invitations", {
4662
+ count: loadedInvitations.invitations?.length
4663
+ }, {
4664
+ F: __dxlog_file14,
4665
+ L: 178,
4666
+ S: this,
4667
+ C: (f, a) => f(...a)
4668
+ });
4669
+ log12.trace("dxos.sdk.service-context.open", trace8.end({
4670
+ id: this._instanceId
4671
+ }), {
4672
+ F: __dxlog_file14,
4673
+ L: 180,
4576
4674
  S: this,
4577
4675
  C: (f, a) => f(...a)
4578
4676
  });
4579
4677
  log12("opened", void 0, {
4580
- F: __dxlog_file15,
4581
- L: 168,
4678
+ F: __dxlog_file14,
4679
+ L: 181,
4582
4680
  S: this,
4583
4681
  C: (f, a) => f(...a)
4584
4682
  });
4585
4683
  }
4586
4684
  async _close() {
4587
4685
  log12("closing...", void 0, {
4588
- F: __dxlog_file15,
4589
- L: 172,
4686
+ F: __dxlog_file14,
4687
+ L: 185,
4590
4688
  S: this,
4591
4689
  C: (f, a) => f(...a)
4592
4690
  });
@@ -4603,8 +4701,8 @@ var ServiceContext = class extends Resource {
4603
4701
  await this.metadataStore.close();
4604
4702
  await this.indexer.destroy();
4605
4703
  log12("closed", void 0, {
4606
- F: __dxlog_file15,
4607
- L: 185,
4704
+ F: __dxlog_file14,
4705
+ L: 198,
4608
4706
  S: this,
4609
4707
  C: (f, a) => f(...a)
4610
4708
  });
@@ -4616,9 +4714,9 @@ var ServiceContext = class extends Resource {
4616
4714
  }
4617
4715
  getInvitationHandler(invitation) {
4618
4716
  const factory = this._handlerFactories.get(invitation.kind);
4619
- invariant14(factory, `Unknown invitation kind: ${invitation.kind}`, {
4620
- F: __dxlog_file15,
4621
- L: 196,
4717
+ invariant13(factory, `Unknown invitation kind: ${invitation.kind}`, {
4718
+ F: __dxlog_file14,
4719
+ L: 209,
4622
4720
  S: this,
4623
4721
  A: [
4624
4722
  "factory",
@@ -4642,15 +4740,15 @@ var ServiceContext = class extends Resource {
4642
4740
  }
4643
4741
  async _checkStorageVersion() {
4644
4742
  await this.metadataStore.load();
4645
- if (this.metadataStore.version !== STORAGE_VERSION2) {
4646
- throw new InvalidStorageVersionError(STORAGE_VERSION2, this.metadataStore.version);
4743
+ if (this.metadataStore.version !== STORAGE_VERSION) {
4744
+ throw new InvalidStorageVersionError(STORAGE_VERSION, this.metadataStore.version);
4647
4745
  }
4648
4746
  }
4649
4747
  // Called when identity is created.
4650
4748
  async _initialize(ctx) {
4651
4749
  log12("initializing spaces...", void 0, {
4652
- F: __dxlog_file15,
4653
- L: 227,
4750
+ F: __dxlog_file14,
4751
+ L: 240,
4654
4752
  S: this,
4655
4753
  C: (f, a) => f(...a)
4656
4754
  });
@@ -4668,12 +4766,12 @@ var ServiceContext = class extends Resource {
4668
4766
  });
4669
4767
  }
4670
4768
  };
4671
- this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.keyring, signingContext, this.feedStore, this.automergeHost, this._runtimeParams);
4769
+ this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.keyring, signingContext, this.feedStore, this.automergeHost, this.invitationsManager, this._runtimeParams);
4672
4770
  await this.dataSpaceManager.open();
4673
- this._handlerFactories.set(Invitation6.Kind.SPACE, (invitation) => {
4674
- invariant14(this.dataSpaceManager, "dataSpaceManager not initialized yet", {
4675
- F: __dxlog_file15,
4676
- L: 251,
4771
+ this._handlerFactories.set(Invitation7.Kind.SPACE, (invitation) => {
4772
+ invariant13(this.dataSpaceManager, "dataSpaceManager not initialized yet", {
4773
+ F: __dxlog_file14,
4774
+ L: 265,
4677
4775
  S: this,
4678
4776
  A: [
4679
4777
  "this.dataSpaceManager",
@@ -4696,8 +4794,8 @@ var ServiceContext = class extends Resource {
4696
4794
  log12("dataSpaceManager not initialized yet, ignoring space admission", {
4697
4795
  details: assertion
4698
4796
  }, {
4699
- F: __dxlog_file15,
4700
- L: 267,
4797
+ F: __dxlog_file14,
4798
+ L: 281,
4701
4799
  S: this,
4702
4800
  C: (f, a) => f(...a)
4703
4801
  });
@@ -4707,8 +4805,8 @@ var ServiceContext = class extends Resource {
4707
4805
  log12("space already exists, ignoring space admission", {
4708
4806
  details: assertion
4709
4807
  }, {
4710
- F: __dxlog_file15,
4711
- L: 271,
4808
+ F: __dxlog_file14,
4809
+ L: 285,
4712
4810
  S: this,
4713
4811
  C: (f, a) => f(...a)
4714
4812
  });
@@ -4718,8 +4816,8 @@ var ServiceContext = class extends Resource {
4718
4816
  log12("accepting space recorded in halo", {
4719
4817
  details: assertion
4720
4818
  }, {
4721
- F: __dxlog_file15,
4722
- L: 276,
4819
+ F: __dxlog_file14,
4820
+ L: 290,
4723
4821
  S: this,
4724
4822
  C: (f, a) => f(...a)
4725
4823
  });
@@ -4729,8 +4827,8 @@ var ServiceContext = class extends Resource {
4729
4827
  });
4730
4828
  } catch (err) {
4731
4829
  log12.catch(err, void 0, {
4732
- F: __dxlog_file15,
4733
- L: 282,
4830
+ F: __dxlog_file14,
4831
+ L: 296,
4734
4832
  S: this,
4735
4833
  C: (f, a) => f(...a)
4736
4834
  });
@@ -4775,214 +4873,265 @@ var ServiceRegistry = class {
4775
4873
  }
4776
4874
  };
4777
4875
 
4778
- // packages/sdk/client-services/src/packlets/locks/browser.ts
4779
- import { asyncTimeout as asyncTimeout2, Trigger as Trigger6 } from "@dxos/async";
4780
- import { RESOURCE_LOCK_TIMEOUT } from "@dxos/client-protocol";
4781
- import { log as log13, logInfo } from "@dxos/log";
4782
- function _ts_decorate7(decorators, target, key, desc) {
4783
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4784
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4785
- r = Reflect.decorate(decorators, target, key, desc);
4786
- else
4787
- for (var i = decorators.length - 1; i >= 0; i--)
4788
- if (d = decorators[i])
4789
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4790
- return c > 3 && r && Object.defineProperty(target, key, r), r;
4791
- }
4792
- var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/locks/browser.ts";
4793
- var Message;
4794
- (function(Message2) {
4795
- Message2["ACQUIRING"] = "acquiring";
4796
- })(Message || (Message = {}));
4797
- var Lock = class {
4798
- constructor({ lockKey, onAcquire, onRelease }) {
4799
- this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
4800
- this._releaseTrigger = new Trigger6();
4801
- this._lockKey = lockKey;
4802
- this._onAcquire = onAcquire;
4803
- this._onRelease = onRelease;
4804
- this._broadcastChannel.onmessage = this._onMessage.bind(this);
4805
- }
4806
- get lockKey() {
4807
- return this._lockKey;
4808
- }
4809
- async acquire() {
4810
- this._broadcastChannel.postMessage({
4811
- message: "acquiring"
4812
- });
4813
- try {
4814
- log13("aquiring lock...", void 0, {
4815
- F: __dxlog_file16,
4816
- L: 42,
4817
- S: this,
4818
- C: (f, a) => f(...a)
4819
- });
4820
- await asyncTimeout2(this._requestLock(), RESOURCE_LOCK_TIMEOUT);
4821
- log13("acquired lock", void 0, {
4822
- F: __dxlog_file16,
4823
- L: 44,
4824
- S: this,
4825
- C: (f, a) => f(...a)
4826
- });
4827
- } catch {
4828
- log13("stealing lock...", void 0, {
4829
- F: __dxlog_file16,
4830
- L: 46,
4831
- S: this,
4832
- C: (f, a) => f(...a)
4833
- });
4834
- await this._requestLock(true);
4835
- log13("stolen lock", void 0, {
4836
- F: __dxlog_file16,
4837
- L: 48,
4838
- S: this,
4839
- C: (f, a) => f(...a)
4840
- });
4876
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts
4877
+ import { getFirstStreamValue } from "@dxos/codec-protobuf";
4878
+ import { credentialTypeFilter } from "@dxos/credentials";
4879
+ import { invariant as invariant14 } from "@dxos/invariant";
4880
+ import { STORAGE_VERSION as STORAGE_VERSION2 } from "@dxos/protocols";
4881
+ import { SpaceMember as SpaceMember4 } from "@dxos/protocols/proto/dxos/client/services";
4882
+ import { TRACE_PROCESSOR } from "@dxos/tracing";
4883
+
4884
+ // packages/sdk/client-services/src/version.ts
4885
+ var DXOS_VERSION = "0.4.10-main.30a328e";
4886
+
4887
+ // packages/sdk/client-services/src/packlets/services/platform.ts
4888
+ import { Platform } from "@dxos/protocols/proto/dxos/client/services";
4889
+ var getPlatform = () => {
4890
+ if (process.browser) {
4891
+ if (typeof window !== "undefined") {
4892
+ const { userAgent } = window.navigator;
4893
+ return {
4894
+ type: Platform.PLATFORM_TYPE.BROWSER,
4895
+ userAgent,
4896
+ uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1e3)
4897
+ };
4898
+ } else {
4899
+ return {
4900
+ type: Platform.PLATFORM_TYPE.SHARED_WORKER,
4901
+ uptime: Math.floor((Date.now() - performance.timeOrigin) / 1e3)
4902
+ };
4841
4903
  }
4904
+ } else {
4905
+ const { platform: platform2, version, arch } = process;
4906
+ return {
4907
+ type: Platform.PLATFORM_TYPE.NODE,
4908
+ platform: platform2,
4909
+ arch,
4910
+ runtime: version,
4911
+ uptime: Math.floor(process.uptime()),
4912
+ memory: process.memoryUsage()
4913
+ };
4842
4914
  }
4843
- async release() {
4844
- this._releaseTrigger.wake();
4915
+ };
4916
+
4917
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts
4918
+ var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts";
4919
+ var DEFAULT_TIMEOUT = 1e3;
4920
+ var createDiagnostics = async (clientServices, serviceContext, config) => {
4921
+ const diagnostics = {
4922
+ created: (/* @__PURE__ */ new Date()).toISOString(),
4923
+ platform: getPlatform(),
4924
+ client: {
4925
+ version: DXOS_VERSION,
4926
+ storage: {
4927
+ version: STORAGE_VERSION2
4928
+ }
4929
+ },
4930
+ trace: TRACE_PROCESSOR.getDiagnostics()
4931
+ };
4932
+ {
4933
+ invariant14(clientServices.LoggingService, "SystemService is not available.", {
4934
+ F: __dxlog_file15,
4935
+ L: 108,
4936
+ S: void 0,
4937
+ A: [
4938
+ "clientServices.LoggingService",
4939
+ "'SystemService is not available.'"
4940
+ ]
4941
+ });
4942
+ diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {
4943
+ timeout: DEFAULT_TIMEOUT
4944
+ }).catch(() => void 0);
4845
4945
  }
4846
- _onMessage(event) {
4847
- if (event.data.message === "acquiring") {
4848
- this._releaseTrigger.wake();
4946
+ if (typeof navigator !== "undefined" && navigator.storage) {
4947
+ const map = /* @__PURE__ */ new Map();
4948
+ const dir = await navigator.storage.getDirectory();
4949
+ for await (const filename of dir?.keys()) {
4950
+ const idx = filename.indexOf("-", filename.indexOf("-") + 1);
4951
+ if (idx === -1) {
4952
+ continue;
4953
+ }
4954
+ map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
4849
4955
  }
4956
+ diagnostics.storage = Array.from(map.entries()).sort((a, b) => b[1] - a[1]).map(([file, count]) => ({
4957
+ file,
4958
+ count
4959
+ }));
4850
4960
  }
4851
- async _requestLock(steal = false) {
4852
- log13("requesting lock...", {
4853
- steal
4854
- }, {
4855
- F: __dxlog_file16,
4856
- L: 63,
4857
- S: this,
4858
- C: (f, a) => f(...a)
4859
- });
4860
- const acquired = new Trigger6();
4861
- void navigator.locks.request(this._lockKey, {
4862
- steal
4863
- }, async () => {
4864
- await this._onAcquire?.();
4865
- acquired.wake();
4866
- this._releaseTrigger = new Trigger6();
4867
- await this._releaseTrigger.wait();
4868
- log13("releasing lock...", void 0, {
4869
- F: __dxlog_file16,
4870
- L: 72,
4871
- S: this,
4872
- C: (f, a) => f(...a)
4873
- });
4874
- await this._onRelease?.();
4875
- log13("released lock", void 0, {
4876
- F: __dxlog_file16,
4877
- L: 74,
4878
- S: this,
4879
- C: (f, a) => f(...a)
4880
- });
4881
- }).catch(async () => {
4882
- await this._onRelease?.();
4883
- });
4884
- await acquired.wait();
4885
- log13("recieved lock", {
4886
- steal
4887
- }, {
4888
- F: __dxlog_file16,
4889
- L: 81,
4890
- S: this,
4891
- C: (f, a) => f(...a)
4892
- });
4961
+ const identity = serviceContext.identityManager.identity;
4962
+ if (identity) {
4963
+ diagnostics.identity = {
4964
+ identityKey: identity.identityKey,
4965
+ spaceKey: identity.space.key,
4966
+ profile: identity.profileDocument
4967
+ };
4968
+ const { devices } = await getFirstStreamValue(clientServices.DevicesService.queryDevices(), {
4969
+ timeout: DEFAULT_TIMEOUT
4970
+ }).catch(() => void 0) ?? {};
4971
+ diagnostics.devices = devices;
4972
+ if (serviceContext.dataSpaceManager) {
4973
+ diagnostics.spaces = await Promise.all(Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? []);
4974
+ }
4975
+ const { feeds = [] } = await getFirstStreamValue(clientServices.DevtoolsHost.subscribeToFeeds({}), {
4976
+ timeout: DEFAULT_TIMEOUT
4977
+ }).catch(() => void 0) ?? {};
4978
+ diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({
4979
+ feedKey,
4980
+ bytes,
4981
+ length
4982
+ }));
4983
+ const status = await getFirstStreamValue(clientServices.NetworkService.queryStatus(), {
4984
+ timeout: DEFAULT_TIMEOUT
4985
+ }).catch(() => void 0);
4986
+ diagnostics.networkStatus = status;
4987
+ diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;
4893
4988
  }
4989
+ diagnostics.config = config.values;
4990
+ return diagnostics;
4894
4991
  };
4895
- _ts_decorate7([
4896
- logInfo
4897
- ], Lock.prototype, "lockKey", null);
4898
- var isLocked = (lockPath) => {
4899
- throw new Error("Not implemented");
4900
- };
4901
-
4902
- // packages/sdk/client-services/src/packlets/storage/storage.ts
4903
- import { InvalidConfigError } from "@dxos/protocols";
4904
- import { Runtime as Runtime2 } from "@dxos/protocols/proto/dxos/config";
4905
- import { createStorage, StorageType } from "@dxos/random-access-storage";
4906
-
4907
- // packages/sdk/client-services/src/packlets/storage/util.ts
4908
- import { DX_DATA } from "@dxos/client-protocol";
4909
- import { Runtime } from "@dxos/protocols/proto/dxos/config";
4910
- import { isNode as isNode2 } from "@dxos/util";
4911
- var getRootPath = (config) => {
4912
- const { dataRoot = isNode2() ? DX_DATA : "dxos/storage" } = config ?? {};
4913
- return `${dataRoot}/`;
4914
- };
4915
- var isPersistent = (config) => {
4916
- const { persistent = false } = config ?? {};
4917
- return config.dataStore !== void 0 && config.dataStore !== Runtime.Client.Storage.StorageDriver.RAM || persistent;
4992
+ var getSpaceStats = async (space) => {
4993
+ const stats = {
4994
+ key: space.key,
4995
+ metrics: space.metrics,
4996
+ epochs: space.inner.spaceState.credentials.filter(credentialTypeFilter("dxos.halo.credentials.Epoch")).map((credential) => ({
4997
+ ...credential.subject.assertion,
4998
+ id: credential.id
4999
+ })),
5000
+ members: Array.from(space.inner.spaceState.members.values()).map((member) => ({
5001
+ identity: {
5002
+ identityKey: member.key,
5003
+ profile: {
5004
+ displayName: member.assertion.profile?.displayName
5005
+ }
5006
+ },
5007
+ presence: space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0 ? SpaceMember4.PresenceState.ONLINE : SpaceMember4.PresenceState.OFFLINE
5008
+ })),
5009
+ pipeline: {
5010
+ // TODO(burdon): Pick properties from credentials if needed.
5011
+ currentEpoch: space.automergeSpaceState.lastEpoch,
5012
+ appliedEpoch: space.automergeSpaceState.lastEpoch,
5013
+ controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),
5014
+ currentControlTimeframe: space.inner.controlPipeline.state.timeframe,
5015
+ targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,
5016
+ totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe
5017
+ }
5018
+ };
5019
+ if (stats.metrics) {
5020
+ const { open, ready } = stats.metrics;
5021
+ stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();
5022
+ }
5023
+ return stats;
4918
5024
  };
4919
5025
 
4920
- // packages/sdk/client-services/src/packlets/storage/storage.ts
4921
- var StorageDriver = Runtime2.Client.Storage.StorageDriver;
4922
- var createStorageObjects = (config) => {
4923
- const { persistent = false, keyStore, dataStore } = config ?? {};
4924
- if (persistent && dataStore === StorageDriver.RAM) {
4925
- throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
4926
- }
4927
- if (!persistent && dataStore !== void 0 && dataStore !== StorageDriver.RAM) {
4928
- throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
4929
- }
4930
- if (persistent && keyStore === StorageDriver.RAM) {
4931
- throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
4932
- }
4933
- if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== void 0) {
4934
- throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
4935
- }
5026
+ // packages/sdk/client-services/src/packlets/diagnostics/browser-diagnostics-broadcast.ts
5027
+ import { Trigger as Trigger6 } from "@dxos/async";
5028
+ import { log as log13 } from "@dxos/log";
5029
+ var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/diagnostics/browser-diagnostics-broadcast.ts";
5030
+ var CHANNEL_NAME = "dxos.diagnostics.broadcast";
5031
+ var MessageType;
5032
+ (function(MessageType2) {
5033
+ MessageType2["PROBE"] = "probe";
5034
+ MessageType2["PROBE_ACK"] = "probe-ack";
5035
+ MessageType2["REQUEST_DIAGNOSTICS"] = "request-diagnostics";
5036
+ MessageType2["RECEIVE_DIAGNOSTICS"] = "receive-diagnostics";
5037
+ })(MessageType || (MessageType = {}));
5038
+ var createCollectDiagnosticsBroadcastSender = () => {
4936
5039
  return {
4937
- storage: createStorage({
4938
- type: persistent ? toStorageType(dataStore) : StorageType.RAM,
4939
- root: getRootPath(config)
4940
- })
5040
+ broadcastDiagnosticsRequest: async () => {
5041
+ let expectedResponse = "probe-ack";
5042
+ let channel;
5043
+ try {
5044
+ const trigger = new Trigger6();
5045
+ channel = new BroadcastChannel(CHANNEL_NAME);
5046
+ channel.onmessage = (msg) => {
5047
+ if (expectedResponse === msg.data.type) {
5048
+ trigger.wake(msg.data);
5049
+ }
5050
+ };
5051
+ channel.postMessage({
5052
+ type: "probe"
5053
+ });
5054
+ await trigger.wait({
5055
+ timeout: 200
5056
+ });
5057
+ expectedResponse = "receive-diagnostics";
5058
+ trigger.reset();
5059
+ channel.postMessage({
5060
+ type: "request-diagnostics"
5061
+ });
5062
+ const diagnostics = await trigger.wait({
5063
+ timeout: 5e3
5064
+ });
5065
+ return diagnostics.payload;
5066
+ } catch (e) {
5067
+ const errorDescription = e instanceof Error ? e.message : JSON.stringify(e);
5068
+ return {
5069
+ expectedResponse,
5070
+ errorDescription
5071
+ };
5072
+ } finally {
5073
+ safeClose(channel);
5074
+ }
5075
+ }
4941
5076
  };
4942
5077
  };
4943
- var toStorageType = (type) => {
4944
- switch (type) {
4945
- case void 0:
4946
- return void 0;
4947
- case StorageDriver.RAM:
4948
- return StorageType.RAM;
4949
- case StorageDriver.CHROME:
4950
- return StorageType.CHROME;
4951
- case StorageDriver.FIREFOX:
4952
- return StorageType.FIREFOX;
4953
- case StorageDriver.IDB:
4954
- return StorageType.IDB;
4955
- case StorageDriver.NODE:
4956
- return StorageType.NODE;
4957
- case StorageDriver.WEBFS:
4958
- return StorageType.WEBFS;
4959
- default:
4960
- throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
5078
+ var createCollectDiagnosticsBroadcastHandler = (systemService) => {
5079
+ let channel;
5080
+ return {
5081
+ start: () => {
5082
+ channel = new BroadcastChannel(CHANNEL_NAME);
5083
+ channel.onmessage = async (message) => {
5084
+ try {
5085
+ if (message.data.type === "probe") {
5086
+ channel?.postMessage({
5087
+ type: "probe-ack"
5088
+ });
5089
+ } else if (message.data.type === "request-diagnostics") {
5090
+ const diagnostics = await systemService.getDiagnostics({});
5091
+ channel?.postMessage({
5092
+ type: "receive-diagnostics",
5093
+ payload: diagnostics
5094
+ });
5095
+ }
5096
+ } catch (error) {
5097
+ log13.catch(error, void 0, {
5098
+ F: __dxlog_file16,
5099
+ L: 77,
5100
+ S: void 0,
5101
+ C: (f, a) => f(...a)
5102
+ });
5103
+ }
5104
+ };
5105
+ },
5106
+ stop: () => {
5107
+ safeClose(channel);
5108
+ channel = void 0;
5109
+ }
5110
+ };
5111
+ };
5112
+ var safeClose = (channel) => {
5113
+ try {
5114
+ channel?.close();
5115
+ } catch (e) {
4961
5116
  }
4962
5117
  };
4963
5118
 
4964
- // packages/sdk/client-services/src/packlets/storage/level.ts
4965
- import { Level } from "level";
4966
- import path from "@dxos/node-std/path";
4967
- import { PublicKey as PublicKey11 } from "@dxos/keys";
4968
- var createLevel = async (config) => {
4969
- const persistent = isPersistent(config);
4970
- const storagePath = persistent ? getRootPath(config) : path.join("tmp", "level", PublicKey11.random().toHex());
4971
- const level = new Level(storagePath);
4972
- await level.open();
4973
- return level;
4974
- };
5119
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
5120
+ import { ConfigResource } from "@dxos/config";
5121
+ import { GetDiagnosticsRequest as GetDiagnosticsRequest2 } from "@dxos/protocols/proto/dxos/client/services";
5122
+ import { TRACE_PROCESSOR as TRACE_PROCESSOR3 } from "@dxos/tracing";
5123
+ import { jsonKeyReplacer as jsonKeyReplacer2, nonNullable } from "@dxos/util";
4975
5124
 
4976
5125
  // packages/sdk/client-services/src/packlets/services/service-host.ts
4977
5126
  import { Event as Event9, synchronized as synchronized3 } from "@dxos/async";
4978
5127
  import { clientServiceBundle, defaultKey, Properties } from "@dxos/client-protocol";
4979
5128
  import { Context as Context11 } from "@dxos/context";
4980
5129
  import { DataServiceImpl, encodeReference } from "@dxos/echo-pipeline";
4981
- import * as E from "@dxos/echo-schema";
4982
- import { IndexServiceImpl } from "@dxos/indexing";
5130
+ import { getTypeReference } from "@dxos/echo-schema";
5131
+ import { QueryServiceImpl } from "@dxos/indexing";
4983
5132
  import { invariant as invariant16 } from "@dxos/invariant";
4984
- import { PublicKey as PublicKey13 } from "@dxos/keys";
4985
- import { log as log15 } from "@dxos/log";
5133
+ import { PublicKey as PublicKey14 } from "@dxos/keys";
5134
+ import { log as log16 } from "@dxos/log";
4986
5135
  import { WebsocketSignalManager } from "@dxos/messaging";
4987
5136
  import { NetworkManager, createSimplePeerTransportFactory } from "@dxos/network-manager";
4988
5137
  import { trace as trace9 } from "@dxos/protocols";
@@ -5073,11 +5222,135 @@ var DevicesServiceImpl = class {
5073
5222
  }
5074
5223
  };
5075
5224
 
5225
+ // packages/sdk/client-services/src/packlets/locks/browser.ts
5226
+ import { asyncTimeout as asyncTimeout2, Trigger as Trigger7 } from "@dxos/async";
5227
+ import { RESOURCE_LOCK_TIMEOUT } from "@dxos/client-protocol";
5228
+ import { log as log14, logInfo } from "@dxos/log";
5229
+ function _ts_decorate7(decorators, target, key, desc) {
5230
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5231
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
5232
+ r = Reflect.decorate(decorators, target, key, desc);
5233
+ else
5234
+ for (var i = decorators.length - 1; i >= 0; i--)
5235
+ if (d = decorators[i])
5236
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5237
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
5238
+ }
5239
+ var __dxlog_file18 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/locks/browser.ts";
5240
+ var Message;
5241
+ (function(Message2) {
5242
+ Message2["ACQUIRING"] = "acquiring";
5243
+ })(Message || (Message = {}));
5244
+ var Lock = class {
5245
+ constructor({ lockKey, onAcquire, onRelease }) {
5246
+ this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
5247
+ this._releaseTrigger = new Trigger7();
5248
+ this._lockKey = lockKey;
5249
+ this._onAcquire = onAcquire;
5250
+ this._onRelease = onRelease;
5251
+ this._broadcastChannel.onmessage = this._onMessage.bind(this);
5252
+ }
5253
+ get lockKey() {
5254
+ return this._lockKey;
5255
+ }
5256
+ async acquire() {
5257
+ this._broadcastChannel.postMessage({
5258
+ message: "acquiring"
5259
+ });
5260
+ try {
5261
+ log14("aquiring lock...", void 0, {
5262
+ F: __dxlog_file18,
5263
+ L: 42,
5264
+ S: this,
5265
+ C: (f, a) => f(...a)
5266
+ });
5267
+ await asyncTimeout2(this._requestLock(), RESOURCE_LOCK_TIMEOUT);
5268
+ log14("acquired lock", void 0, {
5269
+ F: __dxlog_file18,
5270
+ L: 44,
5271
+ S: this,
5272
+ C: (f, a) => f(...a)
5273
+ });
5274
+ } catch {
5275
+ log14("stealing lock...", void 0, {
5276
+ F: __dxlog_file18,
5277
+ L: 46,
5278
+ S: this,
5279
+ C: (f, a) => f(...a)
5280
+ });
5281
+ await this._requestLock(true);
5282
+ log14("stolen lock", void 0, {
5283
+ F: __dxlog_file18,
5284
+ L: 48,
5285
+ S: this,
5286
+ C: (f, a) => f(...a)
5287
+ });
5288
+ }
5289
+ }
5290
+ async release() {
5291
+ this._releaseTrigger.wake();
5292
+ }
5293
+ _onMessage(event) {
5294
+ if (event.data.message === "acquiring") {
5295
+ this._releaseTrigger.wake();
5296
+ }
5297
+ }
5298
+ async _requestLock(steal = false) {
5299
+ log14("requesting lock...", {
5300
+ steal
5301
+ }, {
5302
+ F: __dxlog_file18,
5303
+ L: 63,
5304
+ S: this,
5305
+ C: (f, a) => f(...a)
5306
+ });
5307
+ const acquired = new Trigger7();
5308
+ void navigator.locks.request(this._lockKey, {
5309
+ steal
5310
+ }, async () => {
5311
+ await this._onAcquire?.();
5312
+ acquired.wake();
5313
+ this._releaseTrigger = new Trigger7();
5314
+ await this._releaseTrigger.wait();
5315
+ log14("releasing lock...", void 0, {
5316
+ F: __dxlog_file18,
5317
+ L: 72,
5318
+ S: this,
5319
+ C: (f, a) => f(...a)
5320
+ });
5321
+ await this._onRelease?.();
5322
+ log14("released lock", void 0, {
5323
+ F: __dxlog_file18,
5324
+ L: 74,
5325
+ S: this,
5326
+ C: (f, a) => f(...a)
5327
+ });
5328
+ }).catch(async () => {
5329
+ await this._onRelease?.();
5330
+ });
5331
+ await acquired.wait();
5332
+ log14("recieved lock", {
5333
+ steal
5334
+ }, {
5335
+ F: __dxlog_file18,
5336
+ L: 81,
5337
+ S: this,
5338
+ C: (f, a) => f(...a)
5339
+ });
5340
+ }
5341
+ };
5342
+ _ts_decorate7([
5343
+ logInfo
5344
+ ], Lock.prototype, "lockKey", null);
5345
+ var isLocked = (lockPath) => {
5346
+ throw new Error("Not implemented");
5347
+ };
5348
+
5076
5349
  // packages/sdk/client-services/src/packlets/logging/logging-service.ts
5077
5350
  import { Event as Event8 } from "@dxos/async";
5078
5351
  import { Stream as Stream12 } from "@dxos/codec-protobuf";
5079
5352
  import { PublicKey as PublicKey12 } from "@dxos/keys";
5080
- import { getContextFromEntry, log as log14 } from "@dxos/log";
5353
+ import { getContextFromEntry, log as log15 } from "@dxos/log";
5081
5354
  import { QueryLogsRequest } from "@dxos/protocols/proto/dxos/client/services";
5082
5355
  import { getDebugName, jsonify, numericalValues, tracer } from "@dxos/util";
5083
5356
  var LoggingServiceImpl = class {
@@ -5090,11 +5363,11 @@ var LoggingServiceImpl = class {
5090
5363
  };
5091
5364
  }
5092
5365
  async open() {
5093
- log14.runtimeConfig.processors.push(this._logProcessor);
5366
+ log15.runtimeConfig.processors.push(this._logProcessor);
5094
5367
  }
5095
5368
  async close() {
5096
- const index = log14.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
5097
- log14.runtimeConfig.processors.splice(index, 1);
5369
+ const index = log15.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
5370
+ log15.runtimeConfig.processors.splice(index, 1);
5098
5371
  }
5099
5372
  async controlMetrics({ reset, record }) {
5100
5373
  if (reset) {
@@ -5230,6 +5503,80 @@ var NetworkServiceImpl = class {
5230
5503
  }
5231
5504
  };
5232
5505
 
5506
+ // packages/sdk/client-services/src/packlets/storage/storage.ts
5507
+ import { InvalidConfigError } from "@dxos/protocols";
5508
+ import { Runtime as Runtime2 } from "@dxos/protocols/proto/dxos/config";
5509
+ import { createStorage, StorageType } from "@dxos/random-access-storage";
5510
+
5511
+ // packages/sdk/client-services/src/packlets/storage/util.ts
5512
+ import { DX_DATA } from "@dxos/client-protocol";
5513
+ import { Runtime } from "@dxos/protocols/proto/dxos/config";
5514
+ import { isNode as isNode2 } from "@dxos/util";
5515
+ var getRootPath = (config) => {
5516
+ const { dataRoot = isNode2() ? DX_DATA : "dxos/storage" } = config ?? {};
5517
+ return `${dataRoot}/`;
5518
+ };
5519
+ var isPersistent = (config) => {
5520
+ const { persistent = false } = config ?? {};
5521
+ return config.dataStore !== void 0 && config.dataStore !== Runtime.Client.Storage.StorageDriver.RAM || persistent;
5522
+ };
5523
+
5524
+ // packages/sdk/client-services/src/packlets/storage/storage.ts
5525
+ var StorageDriver = Runtime2.Client.Storage.StorageDriver;
5526
+ var createStorageObjects = (config) => {
5527
+ const { persistent = false, keyStore, dataStore } = config ?? {};
5528
+ if (persistent && dataStore === StorageDriver.RAM) {
5529
+ throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
5530
+ }
5531
+ if (!persistent && dataStore !== void 0 && dataStore !== StorageDriver.RAM) {
5532
+ throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
5533
+ }
5534
+ if (persistent && keyStore === StorageDriver.RAM) {
5535
+ throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
5536
+ }
5537
+ if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== void 0) {
5538
+ throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
5539
+ }
5540
+ return {
5541
+ storage: createStorage({
5542
+ type: persistent ? toStorageType(dataStore) : StorageType.RAM,
5543
+ root: getRootPath(config)
5544
+ })
5545
+ };
5546
+ };
5547
+ var toStorageType = (type) => {
5548
+ switch (type) {
5549
+ case void 0:
5550
+ return void 0;
5551
+ case StorageDriver.RAM:
5552
+ return StorageType.RAM;
5553
+ case StorageDriver.CHROME:
5554
+ return StorageType.CHROME;
5555
+ case StorageDriver.FIREFOX:
5556
+ return StorageType.FIREFOX;
5557
+ case StorageDriver.IDB:
5558
+ return StorageType.IDB;
5559
+ case StorageDriver.NODE:
5560
+ return StorageType.NODE;
5561
+ case StorageDriver.WEBFS:
5562
+ return StorageType.WEBFS;
5563
+ default:
5564
+ throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
5565
+ }
5566
+ };
5567
+
5568
+ // packages/sdk/client-services/src/packlets/storage/level.ts
5569
+ import { Level } from "level";
5570
+ import path from "@dxos/node-std/path";
5571
+ import { PublicKey as PublicKey13 } from "@dxos/keys";
5572
+ var createLevel = async (config) => {
5573
+ const persistent = isPersistent(config);
5574
+ const storagePath = persistent ? path.join(getRootPath(config), "level") : `/tmp/dxos-${PublicKey13.random().toHex()}`;
5575
+ const level = new Level(storagePath);
5576
+ await level.open();
5577
+ return level;
5578
+ };
5579
+
5233
5580
  // packages/sdk/client-services/src/packlets/system/system-service.ts
5234
5581
  import { Stream as Stream14 } from "@dxos/codec-protobuf";
5235
5582
  import { GetDiagnosticsRequest } from "@dxos/protocols/proto/dxos/client/services";
@@ -5298,13 +5645,14 @@ function _ts_decorate8(decorators, target, key, desc) {
5298
5645
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5299
5646
  return c > 3 && r && Object.defineProperty(target, key, r), r;
5300
5647
  }
5301
- var __dxlog_file18 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-host.ts";
5648
+ var __dxlog_file19 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-host.ts";
5302
5649
  var ClientServicesHost = class {
5303
5650
  constructor({
5304
5651
  config,
5305
5652
  transportFactory,
5306
5653
  signalManager,
5307
5654
  storage,
5655
+ level,
5308
5656
  // TODO(wittjosiah): Turn this on by default.
5309
5657
  lockKey,
5310
5658
  callbacks,
@@ -5315,6 +5663,7 @@ var ClientServicesHost = class {
5315
5663
  this._opening = false;
5316
5664
  this._open = false;
5317
5665
  this._storage = storage;
5666
+ this._level = level;
5318
5667
  this._callbacks = callbacks;
5319
5668
  this._runtimeParams = runtimeParams;
5320
5669
  if (config) {
@@ -5353,6 +5702,7 @@ var ClientServicesHost = class {
5353
5702
  await this.reset();
5354
5703
  }
5355
5704
  });
5705
+ this.diagnosticsBroadcastHandler = createCollectDiagnosticsBroadcastHandler(this._systemService);
5356
5706
  this._loggingService = new LoggingServiceImpl();
5357
5707
  this._serviceRegistry = new ServiceRegistry(clientServiceBundle, {
5358
5708
  SystemService: this._systemService,
@@ -5384,24 +5734,24 @@ var ClientServicesHost = class {
5384
5734
  */
5385
5735
  initialize({ config, ...options }) {
5386
5736
  invariant16(!this._open, "service host is open", {
5387
- F: __dxlog_file18,
5388
- L: 182,
5737
+ F: __dxlog_file19,
5738
+ L: 198,
5389
5739
  S: this,
5390
5740
  A: [
5391
5741
  "!this._open",
5392
5742
  "'service host is open'"
5393
5743
  ]
5394
5744
  });
5395
- log15("initializing...", void 0, {
5396
- F: __dxlog_file18,
5397
- L: 183,
5745
+ log16("initializing...", void 0, {
5746
+ F: __dxlog_file19,
5747
+ L: 199,
5398
5748
  S: this,
5399
5749
  C: (f, a) => f(...a)
5400
5750
  });
5401
5751
  if (config) {
5402
5752
  invariant16(!this._config, "config already set", {
5403
- F: __dxlog_file18,
5404
- L: 186,
5753
+ F: __dxlog_file19,
5754
+ L: 202,
5405
5755
  S: this,
5406
5756
  A: [
5407
5757
  "!this._config",
@@ -5414,9 +5764,9 @@ var ClientServicesHost = class {
5414
5764
  }
5415
5765
  }
5416
5766
  if (!options.signalManager) {
5417
- log15.warn("running signaling without telemetry metadata.", void 0, {
5418
- F: __dxlog_file18,
5419
- L: 194,
5767
+ log16.warn("running signaling without telemetry metadata.", void 0, {
5768
+ F: __dxlog_file19,
5769
+ L: 210,
5420
5770
  S: this,
5421
5771
  C: (f, a) => f(...a)
5422
5772
  });
@@ -5426,8 +5776,8 @@ var ClientServicesHost = class {
5426
5776
  }), signalManager = new WebsocketSignalManager(this._config?.get("runtime.services.signaling") ?? []) } = options;
5427
5777
  this._signalManager = signalManager;
5428
5778
  invariant16(!this._networkManager, "network manager already set", {
5429
- F: __dxlog_file18,
5430
- L: 205,
5779
+ F: __dxlog_file19,
5780
+ L: 221,
5431
5781
  S: this,
5432
5782
  A: [
5433
5783
  "!this._networkManager",
@@ -5439,9 +5789,9 @@ var ClientServicesHost = class {
5439
5789
  transportFactory,
5440
5790
  signalManager
5441
5791
  });
5442
- log15("initialized", void 0, {
5443
- F: __dxlog_file18,
5444
- L: 212,
5792
+ log16("initialized", void 0, {
5793
+ F: __dxlog_file19,
5794
+ L: 228,
5445
5795
  S: this,
5446
5796
  C: (f, a) => f(...a)
5447
5797
  });
@@ -5450,18 +5800,18 @@ var ClientServicesHost = class {
5450
5800
  if (this._open) {
5451
5801
  return;
5452
5802
  }
5453
- const traceId = PublicKey13.random().toHex();
5454
- log15.trace("dxos.client-services.host.open", trace9.begin({
5803
+ const traceId = PublicKey14.random().toHex();
5804
+ log16.trace("dxos.client-services.host.open", trace9.begin({
5455
5805
  id: traceId
5456
5806
  }), {
5457
- F: __dxlog_file18,
5458
- L: 223,
5807
+ F: __dxlog_file19,
5808
+ L: 239,
5459
5809
  S: this,
5460
5810
  C: (f, a) => f(...a)
5461
5811
  });
5462
5812
  invariant16(this._config, "config not set", {
5463
- F: __dxlog_file18,
5464
- L: 225,
5813
+ F: __dxlog_file19,
5814
+ L: 241,
5465
5815
  S: this,
5466
5816
  A: [
5467
5817
  "this._config",
@@ -5469,8 +5819,8 @@ var ClientServicesHost = class {
5469
5819
  ]
5470
5820
  });
5471
5821
  invariant16(this._storage, "storage not set", {
5472
- F: __dxlog_file18,
5473
- L: 226,
5822
+ F: __dxlog_file19,
5823
+ L: 242,
5474
5824
  S: this,
5475
5825
  A: [
5476
5826
  "this._storage",
@@ -5478,8 +5828,8 @@ var ClientServicesHost = class {
5478
5828
  ]
5479
5829
  });
5480
5830
  invariant16(this._signalManager, "signal manager not set", {
5481
- F: __dxlog_file18,
5482
- L: 227,
5831
+ F: __dxlog_file19,
5832
+ L: 243,
5483
5833
  S: this,
5484
5834
  A: [
5485
5835
  "this._signalManager",
@@ -5487,8 +5837,8 @@ var ClientServicesHost = class {
5487
5837
  ]
5488
5838
  });
5489
5839
  invariant16(this._networkManager, "network manager not set", {
5490
- F: __dxlog_file18,
5491
- L: 228,
5840
+ F: __dxlog_file19,
5841
+ L: 244,
5492
5842
  S: this,
5493
5843
  A: [
5494
5844
  "this._networkManager",
@@ -5496,34 +5846,37 @@ var ClientServicesHost = class {
5496
5846
  ]
5497
5847
  });
5498
5848
  this._opening = true;
5499
- log15("opening...", {
5849
+ log16("opening...", {
5500
5850
  lockKey: this._resourceLock?.lockKey
5501
5851
  }, {
5502
- F: __dxlog_file18,
5503
- L: 231,
5852
+ F: __dxlog_file19,
5853
+ L: 247,
5504
5854
  S: this,
5505
5855
  C: (f, a) => f(...a)
5506
5856
  });
5507
5857
  if (!this._level) {
5508
5858
  this._level = await createLevel(this._config.get("runtime.client.storage", {}));
5509
5859
  }
5860
+ await this._level.open();
5510
5861
  await this._resourceLock?.acquire();
5511
5862
  await this._loggingService.open();
5512
5863
  this._serviceContext = new ServiceContext(this._storage, this._level, this._networkManager, this._signalManager, this._runtimeParams);
5864
+ this._queryService = new QueryServiceImpl({
5865
+ indexer: this._serviceContext.indexer,
5866
+ automergeHost: this._serviceContext.automergeHost
5867
+ });
5868
+ await this._queryService.open(ctx);
5513
5869
  this._serviceRegistry.setServices({
5514
5870
  SystemService: this._systemService,
5515
5871
  IdentityService: new IdentityServiceImpl((params) => this._createIdentity(params), this._serviceContext.identityManager, this._serviceContext.keyring, (profile) => this._serviceContext.broadcastProfileUpdate(profile)),
5516
- InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitations, (invitation) => this._serviceContext.getInvitationHandler(invitation), this._serviceContext.metadataStore),
5872
+ InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitationsManager),
5517
5873
  DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
5518
5874
  SpacesService: new SpacesServiceImpl(this._serviceContext.identityManager, this._serviceContext.spaceManager, async () => {
5519
5875
  await this._serviceContext.initialized.wait();
5520
5876
  return this._serviceContext.dataSpaceManager;
5521
5877
  }),
5522
5878
  DataService: new DataServiceImpl(this._serviceContext.automergeHost),
5523
- IndexService: new IndexServiceImpl({
5524
- indexer: this._serviceContext.indexer,
5525
- automergeHost: this._serviceContext.automergeHost
5526
- }),
5879
+ QueryService: this._queryService,
5527
5880
  NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager, this._serviceContext.signalManager),
5528
5881
  LoggingService: this._loggingService,
5529
5882
  TracingService: this._tracingService,
@@ -5535,24 +5888,6 @@ var ClientServicesHost = class {
5535
5888
  })
5536
5889
  });
5537
5890
  await this._serviceContext.open(ctx);
5538
- invariant16(this.serviceRegistry.services.InvitationsService, void 0, {
5539
- F: __dxlog_file18,
5540
- L: 297,
5541
- S: this,
5542
- A: [
5543
- "this.serviceRegistry.services.InvitationsService",
5544
- ""
5545
- ]
5546
- });
5547
- const loadedInvitations = await this.serviceRegistry.services.InvitationsService.loadPersistentInvitations();
5548
- log15("loaded persistent invitations", {
5549
- count: loadedInvitations.invitations?.length
5550
- }, {
5551
- F: __dxlog_file18,
5552
- L: 300,
5553
- S: this,
5554
- C: (f, a) => f(...a)
5555
- });
5556
5891
  const devtoolsProxy = this._config?.get("runtime.client.devtoolsProxy");
5557
5892
  if (devtoolsProxy) {
5558
5893
  this._devtoolsProxy = new WebsocketRpcClient({
@@ -5563,23 +5898,24 @@ var ClientServicesHost = class {
5563
5898
  });
5564
5899
  void this._devtoolsProxy.open();
5565
5900
  }
5901
+ this.diagnosticsBroadcastHandler.start();
5566
5902
  this._opening = false;
5567
5903
  this._open = true;
5568
5904
  this._statusUpdate.emit();
5569
5905
  const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;
5570
- log15("opened", {
5906
+ log16("opened", {
5571
5907
  deviceKey
5572
5908
  }, {
5573
- F: __dxlog_file18,
5574
- L: 317,
5909
+ F: __dxlog_file19,
5910
+ L: 330,
5575
5911
  S: this,
5576
5912
  C: (f, a) => f(...a)
5577
5913
  });
5578
- log15.trace("dxos.client-services.host.open", trace9.end({
5914
+ log16.trace("dxos.client-services.host.open", trace9.end({
5579
5915
  id: traceId
5580
5916
  }), {
5581
- F: __dxlog_file18,
5582
- L: 318,
5917
+ F: __dxlog_file19,
5918
+ L: 331,
5583
5919
  S: this,
5584
5920
  C: (f, a) => f(...a)
5585
5921
  });
@@ -5589,61 +5925,63 @@ var ClientServicesHost = class {
5589
5925
  return;
5590
5926
  }
5591
5927
  const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;
5592
- log15("closing...", {
5928
+ log16("closing...", {
5593
5929
  deviceKey
5594
5930
  }, {
5595
- F: __dxlog_file18,
5596
- L: 329,
5931
+ F: __dxlog_file19,
5932
+ L: 342,
5597
5933
  S: this,
5598
5934
  C: (f, a) => f(...a)
5599
5935
  });
5936
+ this.diagnosticsBroadcastHandler.stop();
5600
5937
  await this._devtoolsProxy?.close();
5601
5938
  this._serviceRegistry.setServices({
5602
5939
  SystemService: this._systemService
5603
5940
  });
5604
5941
  await this._loggingService.close();
5942
+ await this._queryService.close();
5605
5943
  await this._serviceContext.close();
5606
5944
  await this._level?.close();
5607
5945
  this._open = false;
5608
5946
  this._statusUpdate.emit();
5609
- log15("closed", {
5947
+ log16("closed", {
5610
5948
  deviceKey
5611
5949
  }, {
5612
- F: __dxlog_file18,
5613
- L: 337,
5950
+ F: __dxlog_file19,
5951
+ L: 352,
5614
5952
  S: this,
5615
5953
  C: (f, a) => f(...a)
5616
5954
  });
5617
5955
  }
5618
5956
  async reset() {
5619
- const traceId = PublicKey13.random().toHex();
5620
- log15.trace("dxos.sdk.client-services-host.reset", trace9.begin({
5957
+ const traceId = PublicKey14.random().toHex();
5958
+ log16.trace("dxos.sdk.client-services-host.reset", trace9.begin({
5621
5959
  id: traceId
5622
5960
  }), {
5623
- F: __dxlog_file18,
5624
- L: 342,
5961
+ F: __dxlog_file19,
5962
+ L: 357,
5625
5963
  S: this,
5626
5964
  C: (f, a) => f(...a)
5627
5965
  });
5628
- log15("resetting...", void 0, {
5629
- F: __dxlog_file18,
5630
- L: 344,
5966
+ log16("resetting...", void 0, {
5967
+ F: __dxlog_file19,
5968
+ L: 359,
5631
5969
  S: this,
5632
5970
  C: (f, a) => f(...a)
5633
5971
  });
5634
5972
  await this._serviceContext?.close();
5635
5973
  await this._storage.reset();
5636
- log15("reset", void 0, {
5637
- F: __dxlog_file18,
5638
- L: 347,
5974
+ log16("reset", void 0, {
5975
+ F: __dxlog_file19,
5976
+ L: 362,
5639
5977
  S: this,
5640
5978
  C: (f, a) => f(...a)
5641
5979
  });
5642
- log15.trace("dxos.sdk.client-services-host.reset", trace9.end({
5980
+ log16.trace("dxos.sdk.client-services-host.reset", trace9.end({
5643
5981
  id: traceId
5644
5982
  }), {
5645
- F: __dxlog_file18,
5646
- L: 348,
5983
+ F: __dxlog_file19,
5984
+ L: 363,
5647
5985
  S: this,
5648
5986
  C: (f, a) => f(...a)
5649
5987
  });
@@ -5655,8 +5993,8 @@ var ClientServicesHost = class {
5655
5993
  const space = await this._serviceContext.dataSpaceManager.createSpace();
5656
5994
  const automergeIndex = space.automergeSpaceState.rootUrl;
5657
5995
  invariant16(automergeIndex, void 0, {
5658
- F: __dxlog_file18,
5659
- L: 360,
5996
+ F: __dxlog_file19,
5997
+ L: 375,
5660
5998
  S: this,
5661
5999
  A: [
5662
6000
  "automergeIndex",
@@ -5667,7 +6005,7 @@ var ClientServicesHost = class {
5667
6005
  await document.whenReady();
5668
6006
  const properties = {
5669
6007
  system: {
5670
- type: encodeReference(E.getTypeReference(Properties))
6008
+ type: encodeReference(getTypeReference(Properties))
5671
6009
  },
5672
6010
  data: {
5673
6011
  [defaultKey]: identity.identityKey.toHex()
@@ -5676,7 +6014,7 @@ var ClientServicesHost = class {
5676
6014
  keys: []
5677
6015
  }
5678
6016
  };
5679
- const propertiesId = PublicKey13.random().toHex();
6017
+ const propertiesId = PublicKey14.random().toHex();
5680
6018
  document.change((doc) => {
5681
6019
  assignDeep2(doc, [
5682
6020
  "objects",
@@ -5705,6 +6043,44 @@ ClientServicesHost = _ts_decorate8([
5705
6043
  Trace3.resource()
5706
6044
  ], ClientServicesHost);
5707
6045
 
6046
+ // packages/sdk/client-services/src/packlets/services/util.ts
6047
+ import { PublicKey as PublicKey15 } from "@dxos/keys";
6048
+ import { humanize } from "@dxos/util";
6049
+ var ClientServicesProviderResource = Symbol.for("dxos.resource.ClientServices");
6050
+
6051
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
6052
+ var DiagnosticsCollector = class {
6053
+ static {
6054
+ this.broadcastSender = createCollectDiagnosticsBroadcastSender();
6055
+ }
6056
+ static async collect(config = findConfigs(), services = findSystemServiceProvider(), options = {}) {
6057
+ const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics({
6058
+ keys: options.humanize ? GetDiagnosticsRequest2.KEY_OPTION.HUMANIZE : options.truncate ? GetDiagnosticsRequest2.KEY_OPTION.TRUNCATE : void 0
6059
+ });
6060
+ const clientDiagnostics = {
6061
+ config,
6062
+ trace: TRACE_PROCESSOR3.getDiagnostics()
6063
+ };
6064
+ const diagnostics = serviceDiagnostics != null ? {
6065
+ client: clientDiagnostics,
6066
+ services: serviceDiagnostics
6067
+ } : {
6068
+ client: clientDiagnostics,
6069
+ broadcast: await this.broadcastSender.broadcastDiagnosticsRequest()
6070
+ };
6071
+ return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer2(options)));
6072
+ }
6073
+ };
6074
+ var findSystemServiceProvider = () => {
6075
+ const serviceProviders = TRACE_PROCESSOR3.findByAnnotation(ClientServicesProviderResource);
6076
+ const providerResource = serviceProviders.find((r) => r.instance.deref()?.services?.SystemService != null);
6077
+ return providerResource?.instance?.deref() ?? null;
6078
+ };
6079
+ var findConfigs = () => {
6080
+ const configs = TRACE_PROCESSOR3.findByAnnotation(ConfigResource);
6081
+ return configs.map((r) => r.instance.deref()).filter(nonNullable);
6082
+ };
6083
+
5708
6084
  export {
5709
6085
  Buffer,
5710
6086
  subscribeToFeeds,
@@ -5724,20 +6100,25 @@ export {
5724
6100
  IdentityServiceImpl,
5725
6101
  DeviceInvitationProtocol,
5726
6102
  InvitationsHandler,
5727
- invitationExpired,
6103
+ createAdmissionKeypair,
5728
6104
  InvitationsServiceImpl,
5729
6105
  SpaceInvitationProtocol,
6106
+ InvitationsManager,
5730
6107
  ClientRpcServer,
5731
- createDiagnostics,
5732
6108
  DataSpace,
5733
6109
  DataSpaceManager,
5734
6110
  SpacesServiceImpl,
5735
6111
  ServiceContext,
5736
6112
  ServiceRegistry,
6113
+ createDiagnostics,
6114
+ createCollectDiagnosticsBroadcastSender,
6115
+ createCollectDiagnosticsBroadcastHandler,
6116
+ DiagnosticsCollector,
5737
6117
  Lock,
5738
6118
  isLocked,
5739
6119
  createStorageObjects,
5740
6120
  createLevel,
5741
- ClientServicesHost
6121
+ ClientServicesHost,
6122
+ ClientServicesProviderResource
5742
6123
  };
5743
- //# sourceMappingURL=chunk-WGCEYMNX.mjs.map
6124
+ //# sourceMappingURL=chunk-RCJRMCJI.mjs.map