@dxos/client-services 0.4.10-main.b1e8dec → 0.4.10-main.b30eb88

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 (96) hide show
  1. package/dist/lib/browser/{chunk-BJNDCR72.mjs → chunk-BDY63S7K.mjs} +1290 -992
  2. package/dist/lib/browser/chunk-BDY63S7K.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +15 -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 +12 -5
  7. package/dist/lib/browser/packlets/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-DLKFCGSD.cjs → chunk-3LNVXTU2.cjs} +1118 -908
  9. package/dist/lib/node/chunk-3LNVXTU2.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +50 -38
  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 +16 -9
  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/indexing/util.d.ts +2 -1
  28. package/dist/types/src/packlets/indexing/util.d.ts.map +1 -1
  29. package/dist/types/src/packlets/invitations/index.d.ts +1 -0
  30. package/dist/types/src/packlets/invitations/index.d.ts.map +1 -1
  31. package/dist/types/src/packlets/invitations/invitation-extension.d.ts +1 -0
  32. package/dist/types/src/packlets/invitations/invitation-extension.d.ts.map +1 -1
  33. package/dist/types/src/packlets/invitations/invitations-handler.d.ts +4 -2
  34. package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
  35. package/dist/types/src/packlets/invitations/invitations-manager.d.ts +42 -0
  36. package/dist/types/src/packlets/invitations/invitations-manager.d.ts.map +1 -0
  37. package/dist/types/src/packlets/invitations/invitations-service.d.ts +7 -23
  38. package/dist/types/src/packlets/invitations/invitations-service.d.ts.map +1 -1
  39. package/dist/types/src/packlets/services/index.d.ts +1 -1
  40. package/dist/types/src/packlets/services/index.d.ts.map +1 -1
  41. package/dist/types/src/packlets/services/service-context.d.ts +9 -5
  42. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  43. package/dist/types/src/packlets/services/service-host.d.ts +6 -1
  44. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  45. package/dist/types/src/packlets/services/util.d.ts +1 -0
  46. package/dist/types/src/packlets/services/util.d.ts.map +1 -1
  47. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  48. package/dist/types/src/packlets/storage/index.d.ts +1 -0
  49. package/dist/types/src/packlets/storage/index.d.ts.map +1 -1
  50. package/dist/types/src/packlets/storage/level.d.ts +4 -0
  51. package/dist/types/src/packlets/storage/level.d.ts.map +1 -0
  52. package/dist/types/src/packlets/storage/storage.d.ts.map +1 -1
  53. package/dist/types/src/packlets/storage/util.d.ts +4 -0
  54. package/dist/types/src/packlets/storage/util.d.ts.map +1 -0
  55. package/dist/types/src/packlets/system/system-service.d.ts +1 -1
  56. package/dist/types/src/packlets/system/system-service.d.ts.map +1 -1
  57. package/dist/types/src/packlets/testing/test-builder.d.ts +4 -2
  58. package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
  59. package/dist/types/src/version.d.ts +1 -1
  60. package/package.json +36 -34
  61. package/src/index.ts +1 -0
  62. package/src/packlets/devices/devices-service.test.ts +1 -1
  63. package/src/packlets/diagnostics/browser-diagnostics-broadcast.ts +94 -0
  64. package/src/packlets/diagnostics/diagnostics-broadcast.ts +20 -0
  65. package/src/packlets/diagnostics/diagnostics-collector.ts +65 -0
  66. package/src/packlets/{services → diagnostics}/diagnostics.ts +2 -2
  67. package/src/packlets/diagnostics/index.ts +7 -0
  68. package/src/packlets/identity/identity-service.test.ts +1 -1
  69. package/src/packlets/indexing/util.ts +15 -8
  70. package/src/packlets/invitations/device-invitation-protocol.test.ts +1 -1
  71. package/src/packlets/invitations/index.ts +1 -0
  72. package/src/packlets/invitations/invitation-extension.ts +28 -1
  73. package/src/packlets/invitations/invitations-handler.ts +74 -34
  74. package/src/packlets/invitations/invitations-manager.ts +197 -0
  75. package/src/packlets/invitations/invitations-service.ts +21 -168
  76. package/src/packlets/network/network-service.test.ts +1 -1
  77. package/src/packlets/services/automerge-host.test.ts +10 -4
  78. package/src/packlets/services/index.ts +1 -1
  79. package/src/packlets/services/service-context.test.ts +9 -6
  80. package/src/packlets/services/service-context.ts +26 -8
  81. package/src/packlets/services/service-host.ts +61 -29
  82. package/src/packlets/services/service-registry.test.ts +1 -1
  83. package/src/packlets/services/util.ts +2 -0
  84. package/src/packlets/spaces/data-space-manager.test.ts +4 -4
  85. package/src/packlets/spaces/data-space.ts +1 -1
  86. package/src/packlets/spaces/spaces-service.test.ts +1 -1
  87. package/src/packlets/storage/index.ts +1 -0
  88. package/src/packlets/storage/level.ts +19 -0
  89. package/src/packlets/storage/storage.ts +3 -9
  90. package/src/packlets/storage/util.ts +19 -0
  91. package/src/packlets/system/system-service.ts +1 -1
  92. package/src/packlets/testing/test-builder.ts +23 -5
  93. package/src/version.ts +1 -1
  94. package/dist/lib/browser/chunk-BJNDCR72.mjs.map +0 -7
  95. package/dist/lib/node/chunk-DLKFCGSD.cjs.map +0 -7
  96. package/dist/types/src/packlets/services/diagnostics.d.ts.map +0 -1
@@ -1282,6 +1282,7 @@ import { PushStream, scheduleTask as scheduleTask2, TimeoutError, Trigger as Tri
1282
1282
  import { AuthenticatingInvitation, AUTHENTICATION_CODE_LENGTH, CancellableInvitation, INVITATION_TIMEOUT } from "@dxos/client-protocol";
1283
1283
  import { Context as Context5 } from "@dxos/context";
1284
1284
  import { generatePasscode } from "@dxos/credentials";
1285
+ import { createKeyPair, sign } from "@dxos/crypto";
1285
1286
  import { invariant as invariant6 } from "@dxos/invariant";
1286
1287
  import { PublicKey as PublicKey6 } from "@dxos/keys";
1287
1288
  import { log as log5 } from "@dxos/log";
@@ -1293,6 +1294,7 @@ import { AuthenticationResponse as AuthenticationResponse2 } from "@dxos/protoco
1293
1294
  // packages/sdk/client-services/src/packlets/invitations/invitation-extension.ts
1294
1295
  import { Trigger as Trigger2 } from "@dxos/async";
1295
1296
  import { cancelWithContext, Context as Context4 } from "@dxos/context";
1297
+ import { randomBytes, verify } from "@dxos/crypto";
1296
1298
  import { invariant as invariant5 } from "@dxos/invariant";
1297
1299
  import { PublicKey as PublicKey5 } from "@dxos/keys";
1298
1300
  import { log as log4 } from "@dxos/log";
@@ -1316,6 +1318,7 @@ var InvitationHostExtension = class extends RpcExtension {
1316
1318
  this._callbacks = _callbacks;
1317
1319
  this._ctx = new Context4();
1318
1320
  this._remoteOptionsTrigger = new Trigger2();
1321
+ this._challenge = void 0;
1319
1322
  this.invitation = void 0;
1320
1323
  this.guestProfile = void 0;
1321
1324
  this.authenticationPassed = false;
@@ -1330,7 +1333,7 @@ var InvitationHostExtension = class extends RpcExtension {
1330
1333
  options: async (options) => {
1331
1334
  invariant5(!this._remoteOptions, "Remote options already set.", {
1332
1335
  F: __dxlog_file6,
1333
- L: 87,
1336
+ L: 90,
1334
1337
  S: this,
1335
1338
  A: [
1336
1339
  "!this._remoteOptions",
@@ -1347,7 +1350,7 @@ var InvitationHostExtension = class extends RpcExtension {
1347
1350
  id: traceId
1348
1351
  }), {
1349
1352
  F: __dxlog_file6,
1350
- L: 96,
1353
+ L: 99,
1351
1354
  S: this,
1352
1355
  C: (f, a) => f(...a)
1353
1356
  });
@@ -1357,7 +1360,7 @@ var InvitationHostExtension = class extends RpcExtension {
1357
1360
  invitationId
1358
1361
  }, {
1359
1362
  F: __dxlog_file6,
1360
- L: 100,
1363
+ L: 103,
1361
1364
  S: this,
1362
1365
  C: (f, a) => f(...a)
1363
1366
  });
@@ -1371,7 +1374,7 @@ var InvitationHostExtension = class extends RpcExtension {
1371
1374
  guestProfile: profile
1372
1375
  }, {
1373
1376
  F: __dxlog_file6,
1374
- L: 109,
1377
+ L: 112,
1375
1378
  S: this,
1376
1379
  C: (f, a) => f(...a)
1377
1380
  });
@@ -1380,25 +1383,27 @@ var InvitationHostExtension = class extends RpcExtension {
1380
1383
  ...this.invitation,
1381
1384
  state: Invitation2.State.READY_FOR_AUTHENTICATION
1382
1385
  });
1386
+ this._challenge = this.invitation.authMethod === Invitation2.AuthMethod.KNOWN_PUBLIC_KEY ? randomBytes(32) : void 0;
1383
1387
  log4.trace("dxos.sdk.invitation-handler.host.introduce", trace3.end({
1384
1388
  id: traceId
1385
1389
  }), {
1386
1390
  F: __dxlog_file6,
1387
- L: 116,
1391
+ L: 122,
1388
1392
  S: this,
1389
1393
  C: (f, a) => f(...a)
1390
1394
  });
1391
1395
  return {
1392
- authMethod: this.invitation.authMethod
1396
+ authMethod: this.invitation.authMethod,
1397
+ challenge: this._challenge
1393
1398
  };
1394
1399
  },
1395
- authenticate: async ({ authCode: code }) => {
1400
+ authenticate: async ({ authCode: code, signedChallenge }) => {
1396
1401
  const traceId = PublicKey5.random().toHex();
1397
1402
  log4.trace("dxos.sdk.invitation-handler.host.authenticate", trace3.begin({
1398
1403
  id: traceId
1399
1404
  }), {
1400
1405
  F: __dxlog_file6,
1401
- L: 124,
1406
+ L: 131,
1402
1407
  S: this,
1403
1408
  C: (f, a) => f(...a)
1404
1409
  });
@@ -1406,14 +1411,14 @@ var InvitationHostExtension = class extends RpcExtension {
1406
1411
  authCode: code
1407
1412
  }, {
1408
1413
  F: __dxlog_file6,
1409
- L: 125,
1414
+ L: 132,
1410
1415
  S: this,
1411
1416
  C: (f, a) => f(...a)
1412
1417
  });
1413
1418
  let status = AuthenticationResponse.Status.OK;
1414
1419
  invariant5(this.invitation, "Invitation is not set.", {
1415
1420
  F: __dxlog_file6,
1416
- L: 128,
1421
+ L: 135,
1417
1422
  S: this,
1418
1423
  A: [
1419
1424
  "this.invitation",
@@ -1424,7 +1429,7 @@ var InvitationHostExtension = class extends RpcExtension {
1424
1429
  case Invitation2.AuthMethod.NONE: {
1425
1430
  log4("authentication not required", void 0, {
1426
1431
  F: __dxlog_file6,
1427
- L: 131,
1432
+ L: 138,
1428
1433
  S: this,
1429
1434
  C: (f, a) => f(...a)
1430
1435
  });
@@ -1444,12 +1449,25 @@ var InvitationHostExtension = class extends RpcExtension {
1444
1449
  }
1445
1450
  break;
1446
1451
  }
1452
+ case Invitation2.AuthMethod.KNOWN_PUBLIC_KEY: {
1453
+ if (!this.invitation.guestKeypair) {
1454
+ status = AuthenticationResponse.Status.INTERNAL_ERROR;
1455
+ break;
1456
+ }
1457
+ const isSignatureValid = this._challenge && verify(this._challenge, Buffer.from(signedChallenge ?? []), this.invitation.guestKeypair.publicKey.asBuffer());
1458
+ if (isSignatureValid) {
1459
+ this.authenticationPassed = true;
1460
+ } else {
1461
+ status = AuthenticationResponse.Status.INVALID_SIGNATURE;
1462
+ }
1463
+ break;
1464
+ }
1447
1465
  default: {
1448
1466
  log4.error("invalid authentication method", {
1449
1467
  authMethod: this.invitation.authMethod
1450
1468
  }, {
1451
1469
  F: __dxlog_file6,
1452
- L: 149,
1470
+ L: 176,
1453
1471
  S: this,
1454
1472
  C: (f, a) => f(...a)
1455
1473
  });
@@ -1464,7 +1482,7 @@ var InvitationHostExtension = class extends RpcExtension {
1464
1482
  }
1465
1483
  }), {
1466
1484
  F: __dxlog_file6,
1467
- L: 155,
1485
+ L: 182,
1468
1486
  S: this,
1469
1487
  C: (f, a) => f(...a)
1470
1488
  });
@@ -1478,14 +1496,14 @@ var InvitationHostExtension = class extends RpcExtension {
1478
1496
  id: traceId
1479
1497
  }), {
1480
1498
  F: __dxlog_file6,
1481
- L: 161,
1499
+ L: 188,
1482
1500
  S: this,
1483
1501
  C: (f, a) => f(...a)
1484
1502
  });
1485
1503
  try {
1486
1504
  invariant5(this.invitation, "Invitation is not set.", {
1487
1505
  F: __dxlog_file6,
1488
- L: 164,
1506
+ L: 191,
1489
1507
  S: this,
1490
1508
  A: [
1491
1509
  "this.invitation",
@@ -1500,7 +1518,7 @@ var InvitationHostExtension = class extends RpcExtension {
1500
1518
  id: traceId
1501
1519
  }), {
1502
1520
  F: __dxlog_file6,
1503
- L: 172,
1521
+ L: 199,
1504
1522
  S: this,
1505
1523
  C: (f, a) => f(...a)
1506
1524
  });
@@ -1557,7 +1575,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1557
1575
  options: async (options) => {
1558
1576
  invariant5(!this._remoteOptions, "Remote options already set.", {
1559
1577
  F: __dxlog_file6,
1560
- L: 239,
1578
+ L: 266,
1561
1579
  S: this,
1562
1580
  A: [
1563
1581
  "!this._remoteOptions",
@@ -1584,7 +1602,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1584
1602
  try {
1585
1603
  log4("begin options", void 0, {
1586
1604
  F: __dxlog_file6,
1587
- L: 260,
1605
+ L: 287,
1588
1606
  S: this,
1589
1607
  C: (f, a) => f(...a)
1590
1608
  });
@@ -1596,7 +1614,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1596
1614
  }));
1597
1615
  log4("end options", void 0, {
1598
1616
  F: __dxlog_file6,
1599
- L: 263,
1617
+ L: 290,
1600
1618
  S: this,
1601
1619
  C: (f, a) => f(...a)
1602
1620
  });
@@ -1610,7 +1628,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1610
1628
  } catch (err) {
1611
1629
  log4("openError", err, {
1612
1630
  F: __dxlog_file6,
1613
- L: 273,
1631
+ L: 300,
1614
1632
  S: this,
1615
1633
  C: (f, a) => f(...a)
1616
1634
  });
@@ -1620,7 +1638,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1620
1638
  async onClose() {
1621
1639
  log4("onClose", void 0, {
1622
1640
  F: __dxlog_file6,
1623
- L: 279,
1641
+ L: 306,
1624
1642
  S: this,
1625
1643
  C: (f, a) => f(...a)
1626
1644
  });
@@ -1639,11 +1657,11 @@ var InvitationsHandler = class {
1639
1657
  this._networkManager = _networkManager;
1640
1658
  }
1641
1659
  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 ?? {};
1660
+ 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 = options?.authMethod !== Invitation3.AuthMethod.KNOWN_PUBLIC_KEY, created = /* @__PURE__ */ new Date(), guestKeypair = void 0, lifetime = 86400, multiUse = false } = options ?? {};
1643
1661
  const authCode = options?.authCode ?? (authMethod === Invitation3.AuthMethod.SHARED_SECRET ? generatePasscode(AUTHENTICATION_CODE_LENGTH) : void 0);
1644
1662
  invariant6(protocol, void 0, {
1645
1663
  F: __dxlog_file7,
1646
- L: 84,
1664
+ L: 87,
1647
1665
  S: this,
1648
1666
  A: [
1649
1667
  "protocol",
@@ -1658,9 +1676,11 @@ var InvitationsHandler = class {
1658
1676
  swarmKey,
1659
1677
  authCode,
1660
1678
  timeout,
1661
- persistent,
1679
+ persistent: persistent && type !== Invitation3.Type.DELEGATED,
1680
+ guestKeypair: guestKeypair ?? (authMethod === Invitation3.AuthMethod.KNOWN_PUBLIC_KEY ? createAdmissionKeypair() : void 0),
1662
1681
  created,
1663
1682
  lifetime,
1683
+ multiUse,
1664
1684
  ...protocol.getInvitationContext()
1665
1685
  };
1666
1686
  const stream = new PushStream();
@@ -1675,7 +1695,7 @@ var InvitationsHandler = class {
1675
1695
  ...protocol.toJSON()
1676
1696
  }, {
1677
1697
  F: __dxlog_file7,
1678
- L: 109,
1698
+ L: 115,
1679
1699
  S: this,
1680
1700
  C: (f, a) => f(...a)
1681
1701
  });
@@ -1700,7 +1720,7 @@ var InvitationsHandler = class {
1700
1720
  const deviceKey = admissionRequest.device?.deviceKey ?? admissionRequest.space?.deviceKey;
1701
1721
  invariant6(deviceKey, void 0, {
1702
1722
  F: __dxlog_file7,
1703
- L: 130,
1723
+ L: 136,
1704
1724
  S: this,
1705
1725
  A: [
1706
1726
  "deviceKey",
@@ -1723,7 +1743,7 @@ var InvitationsHandler = class {
1723
1743
  id: traceId
1724
1744
  }), {
1725
1745
  F: __dxlog_file7,
1726
- L: 148,
1746
+ L: 154,
1727
1747
  S: this,
1728
1748
  C: (f, a) => f(...a)
1729
1749
  });
@@ -1731,7 +1751,7 @@ var InvitationsHandler = class {
1731
1751
  ...protocol.toJSON()
1732
1752
  }, {
1733
1753
  F: __dxlog_file7,
1734
- L: 149,
1754
+ L: 155,
1735
1755
  S: this,
1736
1756
  C: (f, a) => f(...a)
1737
1757
  });
@@ -1747,7 +1767,7 @@ var InvitationsHandler = class {
1747
1767
  ...protocol.toJSON()
1748
1768
  }, {
1749
1769
  F: __dxlog_file7,
1750
- L: 152,
1770
+ L: 158,
1751
1771
  S: this,
1752
1772
  C: (f, a) => f(...a)
1753
1773
  });
@@ -1759,7 +1779,7 @@ var InvitationsHandler = class {
1759
1779
  id: traceId
1760
1780
  }), {
1761
1781
  F: __dxlog_file7,
1762
- L: 154,
1782
+ L: 160,
1763
1783
  S: this,
1764
1784
  C: (f, a) => f(...a)
1765
1785
  });
@@ -1769,7 +1789,7 @@ var InvitationsHandler = class {
1769
1789
  ...protocol.toJSON()
1770
1790
  }, {
1771
1791
  F: __dxlog_file7,
1772
- L: 157,
1792
+ L: 163,
1773
1793
  S: this,
1774
1794
  C: (f, a) => f(...a)
1775
1795
  });
@@ -1780,7 +1800,7 @@ var InvitationsHandler = class {
1780
1800
  } else {
1781
1801
  log5.error("failed", err, {
1782
1802
  F: __dxlog_file7,
1783
- L: 160,
1803
+ L: 166,
1784
1804
  S: this,
1785
1805
  C: (f, a) => f(...a)
1786
1806
  });
@@ -1791,12 +1811,12 @@ var InvitationsHandler = class {
1791
1811
  error: err
1792
1812
  }), {
1793
1813
  F: __dxlog_file7,
1794
- L: 163,
1814
+ L: 169,
1795
1815
  S: this,
1796
1816
  C: (f, a) => f(...a)
1797
1817
  });
1798
1818
  } finally {
1799
- if (type !== Invitation3.Type.MULTIUSE) {
1819
+ if (!multiUse) {
1800
1820
  await swarmConnection.close();
1801
1821
  await ctx.dispose();
1802
1822
  }
@@ -1812,7 +1832,7 @@ var InvitationsHandler = class {
1812
1832
  ...protocol.toJSON()
1813
1833
  }, {
1814
1834
  F: __dxlog_file7,
1815
- L: 178,
1835
+ L: 184,
1816
1836
  S: this,
1817
1837
  C: (f, a) => f(...a)
1818
1838
  });
@@ -1823,7 +1843,7 @@ var InvitationsHandler = class {
1823
1843
  } else {
1824
1844
  log5.error("failed", err, {
1825
1845
  F: __dxlog_file7,
1826
- L: 181,
1846
+ L: 187,
1827
1847
  S: this,
1828
1848
  C: (f, a) => f(...a)
1829
1849
  });
@@ -1833,11 +1853,11 @@ var InvitationsHandler = class {
1833
1853
  });
1834
1854
  return extension;
1835
1855
  };
1836
- if (invitation.lifetime && invitation.created && invitation.lifetime !== 0) {
1856
+ if (invitation.lifetime && invitation.created) {
1837
1857
  if (invitation.created.getTime() + invitation.lifetime * 1e3 < Date.now()) {
1838
1858
  log5.warn("invitation has already expired", void 0, {
1839
1859
  F: __dxlog_file7,
1840
- L: 192,
1860
+ L: 198,
1841
1861
  S: this,
1842
1862
  C: (f, a) => f(...a)
1843
1863
  });
@@ -1888,7 +1908,7 @@ var InvitationsHandler = class {
1888
1908
  const { timeout = INVITATION_TIMEOUT } = invitation;
1889
1909
  invariant6(protocol, void 0, {
1890
1910
  F: __dxlog_file7,
1891
- L: 246,
1911
+ L: 252,
1892
1912
  S: this,
1893
1913
  A: [
1894
1914
  "protocol",
@@ -1898,7 +1918,7 @@ var InvitationsHandler = class {
1898
1918
  if (deviceProfile) {
1899
1919
  invariant6(invitation.kind === Invitation3.Kind.DEVICE, "deviceProfile provided for non-device invitation", {
1900
1920
  F: __dxlog_file7,
1901
- L: 250,
1921
+ L: 255,
1902
1922
  S: this,
1903
1923
  A: [
1904
1924
  "invitation.kind === Invitation.Kind.DEVICE",
@@ -1913,7 +1933,7 @@ var InvitationsHandler = class {
1913
1933
  const setState = (newData) => {
1914
1934
  invariant6(newData.state !== void 0, void 0, {
1915
1935
  F: __dxlog_file7,
1916
- L: 261,
1936
+ L: 266,
1917
1937
  S: this,
1918
1938
  A: [
1919
1939
  "newData.state !== undefined",
@@ -1933,7 +1953,7 @@ var InvitationsHandler = class {
1933
1953
  ...protocol.toJSON()
1934
1954
  }, {
1935
1955
  F: __dxlog_file7,
1936
- L: 269,
1956
+ L: 274,
1937
1957
  S: this,
1938
1958
  C: (f, a) => f(...a)
1939
1959
  });
@@ -1943,7 +1963,7 @@ var InvitationsHandler = class {
1943
1963
  } else {
1944
1964
  log5.warn("auth failed", err, {
1945
1965
  F: __dxlog_file7,
1946
- L: 272,
1966
+ L: 277,
1947
1967
  S: this,
1948
1968
  C: (f, a) => f(...a)
1949
1969
  });
@@ -1957,7 +1977,7 @@ var InvitationsHandler = class {
1957
1977
  ...protocol.toJSON()
1958
1978
  }, {
1959
1979
  F: __dxlog_file7,
1960
- L: 280,
1980
+ L: 285,
1961
1981
  S: this,
1962
1982
  C: (f, a) => f(...a)
1963
1983
  });
@@ -1972,7 +1992,7 @@ var InvitationsHandler = class {
1972
1992
  currentState
1973
1993
  }, {
1974
1994
  F: __dxlog_file7,
1975
- L: 290,
1995
+ L: 295,
1976
1996
  S: this,
1977
1997
  C: (f, a) => f(...a)
1978
1998
  });
@@ -1987,7 +2007,7 @@ var InvitationsHandler = class {
1987
2007
  id: traceId
1988
2008
  }), {
1989
2009
  F: __dxlog_file7,
1990
- L: 299,
2010
+ L: 304,
1991
2011
  S: this,
1992
2012
  C: (f, a) => f(...a)
1993
2013
  });
@@ -1999,7 +2019,7 @@ var InvitationsHandler = class {
1999
2019
  ...protocol.toJSON()
2000
2020
  }, {
2001
2021
  F: __dxlog_file7,
2002
- L: 307,
2022
+ L: 312,
2003
2023
  S: this,
2004
2024
  C: (f, a) => f(...a)
2005
2025
  });
@@ -2010,7 +2030,7 @@ var InvitationsHandler = class {
2010
2030
  ...protocol.toJSON()
2011
2031
  }, {
2012
2032
  F: __dxlog_file7,
2013
- L: 311,
2033
+ L: 316,
2014
2034
  S: this,
2015
2035
  C: (f, a) => f(...a)
2016
2036
  });
@@ -2020,62 +2040,28 @@ var InvitationsHandler = class {
2020
2040
  response: introductionResponse
2021
2041
  }, {
2022
2042
  F: __dxlog_file7,
2023
- L: 315,
2043
+ L: 320,
2024
2044
  S: this,
2025
2045
  C: (f, a) => f(...a)
2026
2046
  });
2027
2047
  invitation.authMethod = introductionResponse.authMethod;
2028
2048
  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) {
2049
+ switch (invitation.authMethod) {
2050
+ case Invitation3.AuthMethod.SHARED_SECRET:
2051
+ await this._handleGuestOtpAuth(extension, setState, authenticated, {
2052
+ timeout
2053
+ });
2054
+ break;
2055
+ case Invitation3.AuthMethod.KNOWN_PUBLIC_KEY:
2056
+ await this._handleGuestKpkAuth(extension, setState, invitation, introductionResponse);
2055
2057
  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
2058
  }
2073
2059
  }
2074
2060
  log5("request admission", {
2075
2061
  ...protocol.toJSON()
2076
2062
  }, {
2077
2063
  F: __dxlog_file7,
2078
- L: 344,
2064
+ L: 336,
2079
2065
  S: this,
2080
2066
  C: (f, a) => f(...a)
2081
2067
  });
@@ -2087,7 +2073,7 @@ var InvitationsHandler = class {
2087
2073
  ...protocol.toJSON()
2088
2074
  }, {
2089
2075
  F: __dxlog_file7,
2090
- L: 355,
2076
+ L: 347,
2091
2077
  S: this,
2092
2078
  C: (f, a) => f(...a)
2093
2079
  });
@@ -2100,7 +2086,7 @@ var InvitationsHandler = class {
2100
2086
  id: traceId
2101
2087
  }), {
2102
2088
  F: __dxlog_file7,
2103
- L: 357,
2089
+ L: 349,
2104
2090
  S: this,
2105
2091
  C: (f, a) => f(...a)
2106
2092
  });
@@ -2110,7 +2096,7 @@ var InvitationsHandler = class {
2110
2096
  ...protocol.toJSON()
2111
2097
  }, {
2112
2098
  F: __dxlog_file7,
2113
- L: 360,
2099
+ L: 352,
2114
2100
  S: this,
2115
2101
  C: (f, a) => f(...a)
2116
2102
  });
@@ -2120,7 +2106,7 @@ var InvitationsHandler = class {
2120
2106
  } else {
2121
2107
  log5("auth failed", err, {
2122
2108
  F: __dxlog_file7,
2123
- L: 363,
2109
+ L: 355,
2124
2110
  S: this,
2125
2111
  C: (f, a) => f(...a)
2126
2112
  });
@@ -2131,7 +2117,7 @@ var InvitationsHandler = class {
2131
2117
  error: err
2132
2118
  }), {
2133
2119
  F: __dxlog_file7,
2134
- L: 366,
2120
+ L: 358,
2135
2121
  S: this,
2136
2122
  C: (f, a) => f(...a)
2137
2123
  });
@@ -2149,7 +2135,7 @@ var InvitationsHandler = class {
2149
2135
  ...protocol.toJSON()
2150
2136
  }, {
2151
2137
  F: __dxlog_file7,
2152
- L: 377,
2138
+ L: 369,
2153
2139
  S: this,
2154
2140
  C: (f, a) => f(...a)
2155
2141
  });
@@ -2159,7 +2145,7 @@ var InvitationsHandler = class {
2159
2145
  } else {
2160
2146
  log5("auth failed", err, {
2161
2147
  F: __dxlog_file7,
2162
- L: 380,
2148
+ L: 372,
2163
2149
  S: this,
2164
2150
  C: (f, a) => f(...a)
2165
2151
  });
@@ -2176,7 +2162,7 @@ var InvitationsHandler = class {
2176
2162
  } else {
2177
2163
  invariant6(invitation.swarmKey, void 0, {
2178
2164
  F: __dxlog_file7,
2179
- L: 394,
2165
+ L: 386,
2180
2166
  S: this,
2181
2167
  A: [
2182
2168
  "invitation.swarmKey",
@@ -2214,206 +2200,115 @@ var InvitationsHandler = class {
2214
2200
  });
2215
2201
  return observable;
2216
2202
  }
2203
+ async _handleGuestOtpAuth(extension, setState, authenticated, options) {
2204
+ for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
2205
+ log5("guest waiting for authentication code...", void 0, {
2206
+ F: __dxlog_file7,
2207
+ L: 426,
2208
+ S: this,
2209
+ C: (f, a) => f(...a)
2210
+ });
2211
+ setState({
2212
+ state: Invitation3.State.READY_FOR_AUTHENTICATION
2213
+ });
2214
+ const authCode = await authenticated.wait(options);
2215
+ log5("sending authentication request", void 0, {
2216
+ F: __dxlog_file7,
2217
+ L: 430,
2218
+ S: this,
2219
+ C: (f, a) => f(...a)
2220
+ });
2221
+ setState({
2222
+ state: Invitation3.State.AUTHENTICATING
2223
+ });
2224
+ const response = await extension.rpc.InvitationHostService.authenticate({
2225
+ authCode
2226
+ });
2227
+ if (response.status === void 0 || response.status === AuthenticationResponse2.Status.OK) {
2228
+ break;
2229
+ }
2230
+ if (response.status === AuthenticationResponse2.Status.INVALID_OTP) {
2231
+ if (attempt === MAX_OTP_ATTEMPTS) {
2232
+ throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
2233
+ } else {
2234
+ log5("retrying invalid code", {
2235
+ attempt
2236
+ }, {
2237
+ F: __dxlog_file7,
2238
+ L: 441,
2239
+ S: this,
2240
+ C: (f, a) => f(...a)
2241
+ });
2242
+ authenticated.reset();
2243
+ }
2244
+ }
2245
+ }
2246
+ }
2247
+ async _handleGuestKpkAuth(extension, setState, invitation, introductionResponse) {
2248
+ if (invitation.guestKeypair?.privateKey == null) {
2249
+ throw new Error("keypair missing in the invitation");
2250
+ }
2251
+ if (introductionResponse.challenge == null) {
2252
+ throw new Error("challenge missing in the introduction");
2253
+ }
2254
+ log5("sending authentication request", void 0, {
2255
+ F: __dxlog_file7,
2256
+ L: 460,
2257
+ S: this,
2258
+ C: (f, a) => f(...a)
2259
+ });
2260
+ setState({
2261
+ state: Invitation3.State.AUTHENTICATING
2262
+ });
2263
+ const signature = sign(Buffer.from(introductionResponse.challenge), invitation.guestKeypair.privateKey);
2264
+ const response = await extension.rpc.InvitationHostService.authenticate({
2265
+ signedChallenge: signature
2266
+ });
2267
+ if (response.status !== AuthenticationResponse2.Status.OK) {
2268
+ throw new Error(`Authentication failed with code: ${response.status}`);
2269
+ }
2270
+ }
2217
2271
  };
2218
- var invitationExpired = (invitation) => {
2219
- return invitation.created && invitation.lifetime && invitation.lifetime !== 0 && invitation.created.getTime() + invitation.lifetime * 1e3 < Date.now();
2272
+ var createAdmissionKeypair = () => {
2273
+ const keypair = createKeyPair();
2274
+ return {
2275
+ publicKey: PublicKey6.from(keypair.publicKey),
2276
+ privateKey: keypair.secretKey
2277
+ };
2220
2278
  };
2221
2279
 
2222
2280
  // packages/sdk/client-services/src/packlets/invitations/invitations-service.ts
2223
- import { Event as Event3, scheduleTask as scheduleTask3 } from "@dxos/async";
2224
2281
  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";
2282
+ import { QueryInvitationsResponse } from "@dxos/protocols/proto/dxos/client/services";
2230
2283
  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;
2284
+ constructor(_invitationsManager) {
2285
+ this._invitationsManager = _invitationsManager;
2244
2286
  }
2245
2287
  // TODO(burdon): Guest/host label.
2246
2288
  getLoggingContext() {
2247
2289
  return {};
2248
2290
  }
2249
2291
  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
- }
2292
+ const invitation = this._invitationsManager.createInvitation(options);
2261
2293
  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
- });
2294
+ invitation.subscribe(next, close, close);
2288
2295
  });
2289
2296
  }
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
- }
2297
+ acceptInvitation(request) {
2298
+ const invitation = this._invitationsManager.acceptInvitation(request);
2337
2299
  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
- });
2300
+ invitation.subscribe(next, close, close);
2349
2301
  });
2350
2302
  }
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
- }
2303
+ async authenticate(request) {
2304
+ return this._invitationsManager.authenticate(request);
2380
2305
  }
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
- }
2306
+ async cancelInvitation(request) {
2307
+ return this._invitationsManager.cancelInvitation(request);
2413
2308
  }
2414
2309
  queryInvitations() {
2415
2310
  return new Stream8(({ next, ctx }) => {
2416
- this._invitationCreated.on(ctx, (invitation) => {
2311
+ this._invitationsManager.invitationCreated.on(ctx, (invitation) => {
2417
2312
  next({
2418
2313
  action: QueryInvitationsResponse.Action.ADDED,
2419
2314
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2422,7 +2317,7 @@ var InvitationsServiceImpl = class {
2422
2317
  ]
2423
2318
  });
2424
2319
  });
2425
- this._invitationAccepted.on(ctx, (invitation) => {
2320
+ this._invitationsManager.invitationAccepted.on(ctx, (invitation) => {
2426
2321
  next({
2427
2322
  action: QueryInvitationsResponse.Action.ADDED,
2428
2323
  type: QueryInvitationsResponse.Type.ACCEPTED,
@@ -2431,7 +2326,7 @@ var InvitationsServiceImpl = class {
2431
2326
  ]
2432
2327
  });
2433
2328
  });
2434
- this._removedCreated.on(ctx, (invitation) => {
2329
+ this._invitationsManager.removedCreated.on(ctx, (invitation) => {
2435
2330
  next({
2436
2331
  action: QueryInvitationsResponse.Action.REMOVED,
2437
2332
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2440,7 +2335,7 @@ var InvitationsServiceImpl = class {
2440
2335
  ]
2441
2336
  });
2442
2337
  });
2443
- this._removedAccepted.on(ctx, (invitation) => {
2338
+ this._invitationsManager.removedAccepted.on(ctx, (invitation) => {
2444
2339
  next({
2445
2340
  action: QueryInvitationsResponse.Action.REMOVED,
2446
2341
  type: QueryInvitationsResponse.Type.ACCEPTED,
@@ -2449,7 +2344,7 @@ var InvitationsServiceImpl = class {
2449
2344
  ]
2450
2345
  });
2451
2346
  });
2452
- this._saved.on(ctx, (invitation) => {
2347
+ this._invitationsManager.saved.on(ctx, (invitation) => {
2453
2348
  next({
2454
2349
  action: QueryInvitationsResponse.Action.SAVED,
2455
2350
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2461,28 +2356,21 @@ var InvitationsServiceImpl = class {
2461
2356
  next({
2462
2357
  action: QueryInvitationsResponse.Action.ADDED,
2463
2358
  type: QueryInvitationsResponse.Type.CREATED,
2464
- invitations: Array.from(this._createInvitations.values()).map((invitation) => invitation.get()),
2359
+ invitations: this._invitationsManager.getCreatedInvitations(),
2465
2360
  existing: true
2466
2361
  });
2467
2362
  next({
2468
2363
  action: QueryInvitationsResponse.Action.ADDED,
2469
2364
  type: QueryInvitationsResponse.Type.ACCEPTED,
2470
- invitations: Array.from(this._acceptInvitations.values()).map((invitation) => invitation.get()),
2365
+ invitations: this._invitationsManager.getAcceptedInvitations(),
2471
2366
  existing: true
2472
2367
  });
2473
- if (this._persistentInvitationsLoaded) {
2368
+ this._invitationsManager.onPersistentInvitationsLoaded(ctx, () => {
2474
2369
  next({
2475
2370
  action: QueryInvitationsResponse.Action.LOAD_COMPLETE,
2476
2371
  type: QueryInvitationsResponse.Type.CREATED
2477
2372
  });
2478
- } else {
2479
- this._persistentInvitationsLoadedEvent.on(ctx, () => {
2480
- next({
2481
- action: QueryInvitationsResponse.Action.LOAD_COMPLETE,
2482
- type: QueryInvitationsResponse.Type.CREATED
2483
- });
2484
- });
2485
- }
2373
+ });
2486
2374
  });
2487
2375
  }
2488
2376
  };
@@ -2490,11 +2378,11 @@ var InvitationsServiceImpl = class {
2490
2378
  // packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts
2491
2379
  import { createAdmissionCredentials, getCredentialAssertion } from "@dxos/credentials";
2492
2380
  import { writeMessages as writeMessages2 } from "@dxos/feed-store";
2493
- import { invariant as invariant8 } from "@dxos/invariant";
2494
- import { log as log7 } from "@dxos/log";
2381
+ import { invariant as invariant7 } from "@dxos/invariant";
2382
+ import { log as log6 } from "@dxos/log";
2495
2383
  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";
2384
+ import { Invitation as Invitation4 } from "@dxos/protocols/proto/dxos/client/services";
2385
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts";
2498
2386
  var SpaceInvitationProtocol = class {
2499
2387
  constructor(_spaceManager, _signingContext, _keyring, _spaceKey) {
2500
2388
  this._spaceManager = _spaceManager;
@@ -2510,13 +2398,13 @@ var SpaceInvitationProtocol = class {
2510
2398
  }
2511
2399
  getInvitationContext() {
2512
2400
  return {
2513
- kind: Invitation5.Kind.SPACE,
2401
+ kind: Invitation4.Kind.SPACE,
2514
2402
  spaceKey: this._spaceKey
2515
2403
  };
2516
2404
  }
2517
2405
  async admit(request, guestProfile) {
2518
- invariant8(this._spaceKey, void 0, {
2519
- F: __dxlog_file9,
2406
+ invariant7(this._spaceKey, void 0, {
2407
+ F: __dxlog_file8,
2520
2408
  L: 47,
2521
2409
  S: this,
2522
2410
  A: [
@@ -2525,8 +2413,8 @@ var SpaceInvitationProtocol = class {
2525
2413
  ]
2526
2414
  });
2527
2415
  const space = await this._spaceManager.spaces.get(this._spaceKey);
2528
- invariant8(space, void 0, {
2529
- F: __dxlog_file9,
2416
+ invariant7(space, void 0, {
2417
+ F: __dxlog_file8,
2530
2418
  L: 49,
2531
2419
  S: this,
2532
2420
  A: [
@@ -2534,8 +2422,8 @@ var SpaceInvitationProtocol = class {
2534
2422
  ""
2535
2423
  ]
2536
2424
  });
2537
- invariant8(request.space, void 0, {
2538
- F: __dxlog_file9,
2425
+ invariant7(request.space, void 0, {
2426
+ F: __dxlog_file8,
2539
2427
  L: 51,
2540
2428
  S: this,
2541
2429
  A: [
@@ -2544,18 +2432,18 @@ var SpaceInvitationProtocol = class {
2544
2432
  ]
2545
2433
  });
2546
2434
  const { identityKey, deviceKey } = request.space;
2547
- log7("writing guest credentials", {
2435
+ log6("writing guest credentials", {
2548
2436
  host: this._signingContext.deviceKey,
2549
2437
  guest: deviceKey
2550
2438
  }, {
2551
- F: __dxlog_file9,
2439
+ F: __dxlog_file8,
2552
2440
  L: 54,
2553
2441
  S: this,
2554
2442
  C: (f, a) => f(...a)
2555
2443
  });
2556
2444
  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,
2445
+ invariant7(credentials[0].credential, void 0, {
2446
+ F: __dxlog_file8,
2559
2447
  L: 65,
2560
2448
  S: this,
2561
2449
  A: [
@@ -2564,8 +2452,8 @@ var SpaceInvitationProtocol = class {
2564
2452
  ]
2565
2453
  });
2566
2454
  const spaceMemberCredential = credentials[0].credential.credential;
2567
- invariant8(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
2568
- F: __dxlog_file9,
2455
+ invariant7(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
2456
+ F: __dxlog_file8,
2569
2457
  L: 67,
2570
2458
  S: this,
2571
2459
  A: [
@@ -2604,8 +2492,8 @@ var SpaceInvitationProtocol = class {
2604
2492
  };
2605
2493
  }
2606
2494
  async accept(response) {
2607
- invariant8(response.space, void 0, {
2608
- F: __dxlog_file9,
2495
+ invariant7(response.space, void 0, {
2496
+ F: __dxlog_file8,
2609
2497
  L: 107,
2610
2498
  S: this,
2611
2499
  A: [
@@ -2615,8 +2503,8 @@ var SpaceInvitationProtocol = class {
2615
2503
  });
2616
2504
  const { credential, controlTimeframe, dataTimeframe } = response.space;
2617
2505
  const assertion = getCredentialAssertion(credential);
2618
- invariant8(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential", {
2619
- F: __dxlog_file9,
2506
+ invariant7(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential", {
2507
+ F: __dxlog_file8,
2620
2508
  L: 110,
2621
2509
  S: this,
2622
2510
  A: [
@@ -2624,8 +2512,8 @@ var SpaceInvitationProtocol = class {
2624
2512
  "'Invalid credential'"
2625
2513
  ]
2626
2514
  });
2627
- invariant8(credential.subject.id.equals(this._signingContext.identityKey), void 0, {
2628
- F: __dxlog_file9,
2515
+ invariant7(credential.subject.id.equals(this._signingContext.identityKey), void 0, {
2516
+ F: __dxlog_file8,
2629
2517
  L: 111,
2630
2518
  S: this,
2631
2519
  A: [
@@ -2649,310 +2537,381 @@ var SpaceInvitationProtocol = class {
2649
2537
  }
2650
2538
  };
2651
2539
 
2652
- // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
2653
- import { Stream as Stream9 } from "@dxos/codec-protobuf";
2654
- import { raise } from "@dxos/debug";
2655
- import { parseMethodName, RpcPeer } from "@dxos/rpc";
2656
- import { MapCounter, trace as trace5 } from "@dxos/tracing";
2657
- function _ts_decorate3(decorators, target, key, desc) {
2658
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2659
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2660
- r = Reflect.decorate(decorators, target, key, desc);
2661
- else
2662
- for (var i = decorators.length - 1; i >= 0; i--)
2663
- if (d = decorators[i])
2664
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2665
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2666
- }
2667
- var ClientRpcServer = class {
2668
- constructor(params) {
2669
- this._handlerCache = /* @__PURE__ */ new Map();
2670
- this._callMetrics = new MapCounter();
2671
- const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
2672
- this._handleCall = handleCall;
2673
- this._handleStream = handleStream;
2674
- this._serviceRegistry = serviceRegistry;
2675
- this._rpcPeer = new RpcPeer({
2676
- ...rpcOptions,
2677
- callHandler: (method, params2) => {
2678
- const [serviceName, methodName] = parseMethodName(method);
2679
- const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
2680
- this._callMetrics.inc(`${serviceName}.${methodName} request`);
2681
- if (this._handleCall) {
2682
- return this._handleCall(methodName, params2, handler);
2683
- } else {
2684
- return handler(methodName, params2);
2685
- }
2686
- },
2687
- streamHandler: (method, params2) => {
2688
- const [serviceName, methodName] = parseMethodName(method);
2689
- const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
2690
- this._callMetrics.inc(`${serviceName}.${methodName} request stream`);
2691
- if (this._handleStream) {
2692
- return Stream9.map(Stream9.unwrapPromise(this._handleStream(methodName, params2, handler)), (data) => {
2693
- this._callMetrics.inc(`${serviceName}.${methodName} response stream`);
2694
- return data;
2695
- });
2696
- } else {
2697
- return handler(methodName, params2);
2698
- }
2540
+ // packages/sdk/client-services/src/packlets/invitations/invitations-manager.ts
2541
+ import { Event as Event3 } from "@dxos/async";
2542
+ import { hasInvitationExpired } from "@dxos/echo-pipeline";
2543
+ import { invariant as invariant8 } from "@dxos/invariant";
2544
+ import { log as log7 } from "@dxos/log";
2545
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/invitations-manager.ts";
2546
+ var InvitationsManager = class {
2547
+ constructor(_invitationsHandler, _getHandler, _metadataStore) {
2548
+ this._invitationsHandler = _invitationsHandler;
2549
+ this._getHandler = _getHandler;
2550
+ this._metadataStore = _metadataStore;
2551
+ this._createInvitations = /* @__PURE__ */ new Map();
2552
+ this._acceptInvitations = /* @__PURE__ */ new Map();
2553
+ this.invitationCreated = new Event3();
2554
+ this.invitationAccepted = new Event3();
2555
+ this.removedCreated = new Event3();
2556
+ this.removedAccepted = new Event3();
2557
+ this.saved = new Event3();
2558
+ this._persistentInvitationsLoadedEvent = new Event3();
2559
+ this._persistentInvitationsLoaded = false;
2560
+ }
2561
+ createInvitation(options) {
2562
+ const existingInvitation = this._createInvitations.get(options.invitationId);
2563
+ if (existingInvitation) {
2564
+ return existingInvitation;
2565
+ }
2566
+ const handler = this._getHandler(options);
2567
+ const invitation = this._invitationsHandler.createInvitation(handler, options);
2568
+ this._createInvitations.set(invitation.get().invitationId, invitation);
2569
+ this.invitationCreated.emit(invitation.get());
2570
+ const saveInvitationTask = invitation.get().persistent ? this._safePersistInBackground(invitation) : Promise.resolve();
2571
+ this._onInvitationComplete(invitation, async () => {
2572
+ this._createInvitations.delete(invitation.get().invitationId);
2573
+ this.removedCreated.emit(invitation.get());
2574
+ if (invitation.get().persistent) {
2575
+ await saveInvitationTask;
2576
+ await this._safeDeleteInvitation(invitation.get());
2699
2577
  }
2700
2578
  });
2579
+ return invitation;
2701
2580
  }
2702
- get _services() {
2703
- return Object.keys(this._serviceRegistry.services);
2704
- }
2705
- async open() {
2706
- await this._rpcPeer.open();
2707
- }
2708
- async close() {
2709
- await this._rpcPeer.close();
2710
- }
2711
- _getServiceHandler(serviceName) {
2712
- if (!this._handlerCache.has(serviceName)) {
2713
- const [key, descriptor] = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName) ?? raise(new Error(`Service not available: ${serviceName}`));
2714
- const service = this._serviceRegistry.services[key];
2715
- if (!service) {
2716
- throw new Error(`Service not available: ${serviceName}`);
2717
- }
2718
- this._handlerCache.set(serviceName, descriptor.createServer(service));
2581
+ async loadPersistentInvitations() {
2582
+ if (this._persistentInvitationsLoaded) {
2583
+ const invitations = this.getCreatedInvitations().filter((i) => i.persistent);
2584
+ return {
2585
+ invitations
2586
+ };
2719
2587
  }
2720
- return this._handlerCache.get(serviceName);
2721
- }
2722
- };
2723
- _ts_decorate3([
2724
- trace5.metricsCounter()
2725
- ], ClientRpcServer.prototype, "_callMetrics", void 0);
2726
- _ts_decorate3([
2727
- trace5.info()
2728
- ], ClientRpcServer.prototype, "_services", null);
2729
- ClientRpcServer = _ts_decorate3([
2730
- trace5.resource()
2731
- ], ClientRpcServer);
2732
-
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";
2740
-
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;
2588
+ try {
2589
+ const persistentInvitations = this._metadataStore.getInvitations();
2590
+ const freshInvitations = persistentInvitations.filter((invitation) => !hasInvitationExpired(invitation));
2591
+ const cInvitations = freshInvitations.map((persistentInvitation) => {
2592
+ invariant8(!this._createInvitations.get(persistentInvitation.invitationId), "invitation already exists", {
2593
+ F: __dxlog_file9,
2594
+ L: 82,
2595
+ S: this,
2596
+ A: [
2597
+ "!this._createInvitations.get(persistentInvitation.invitationId)",
2598
+ "'invitation already exists'"
2599
+ ]
2600
+ });
2601
+ return this.createInvitation({
2602
+ ...persistentInvitation,
2603
+ persistent: false
2604
+ }).get();
2605
+ });
2747
2606
  return {
2748
- type: Platform.PLATFORM_TYPE.BROWSER,
2749
- userAgent,
2750
- uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1e3)
2607
+ invitations: cInvitations
2751
2608
  };
2752
- } else {
2609
+ } catch (err) {
2610
+ log7.catch(err, void 0, {
2611
+ F: __dxlog_file9,
2612
+ L: 88,
2613
+ S: this,
2614
+ C: (f, a) => f(...a)
2615
+ });
2753
2616
  return {
2754
- type: Platform.PLATFORM_TYPE.SHARED_WORKER,
2755
- uptime: Math.floor((Date.now() - performance.timeOrigin) / 1e3)
2617
+ invitations: []
2756
2618
  };
2619
+ } finally {
2620
+ this._persistentInvitationsLoadedEvent.emit();
2621
+ this._persistentInvitationsLoaded = true;
2757
2622
  }
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
2623
  }
2769
- };
2770
-
2771
- // packages/sdk/client-services/src/version.ts
2772
- var DXOS_VERSION = "0.4.10-main.b1e8dec";
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,
2624
+ acceptInvitation(request) {
2625
+ const options = request.invitation;
2626
+ const existingInvitation = this._acceptInvitations.get(options.invitationId);
2627
+ if (existingInvitation) {
2628
+ return existingInvitation;
2629
+ }
2630
+ const handler = this._getHandler(options);
2631
+ const invitation = this._invitationsHandler.acceptInvitation(handler, options, request.deviceProfile);
2632
+ this._acceptInvitations.set(invitation.get().invitationId, invitation);
2633
+ this.invitationAccepted.emit(invitation.get());
2634
+ this._onInvitationComplete(invitation, () => {
2635
+ this._acceptInvitations.delete(invitation.get().invitationId);
2636
+ this.removedAccepted.emit(invitation.get());
2637
+ });
2638
+ return invitation;
2639
+ }
2640
+ async authenticate({ invitationId, authCode }) {
2641
+ log7("authenticating...", void 0, {
2642
+ F: __dxlog_file9,
2643
+ L: 117,
2644
+ S: this,
2645
+ C: (f, a) => f(...a)
2646
+ });
2647
+ invariant8(invitationId, void 0, {
2648
+ F: __dxlog_file9,
2649
+ L: 118,
2650
+ S: this,
2794
2651
  A: [
2795
- "clientServices.LoggingService",
2796
- "'SystemService is not available.'"
2652
+ "invitationId",
2653
+ ""
2797
2654
  ]
2798
2655
  });
2799
- diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {
2800
- timeout: DEFAULT_TIMEOUT
2801
- }).catch(() => void 0);
2656
+ const observable = this._acceptInvitations.get(invitationId);
2657
+ if (!observable) {
2658
+ log7.warn("invalid invitation", {
2659
+ invitationId
2660
+ }, {
2661
+ F: __dxlog_file9,
2662
+ L: 121,
2663
+ S: this,
2664
+ C: (f, a) => f(...a)
2665
+ });
2666
+ } else {
2667
+ await observable.authenticate(authCode);
2668
+ }
2802
2669
  }
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;
2670
+ async cancelInvitation({ invitationId }) {
2671
+ log7("cancelInvitation...", {
2672
+ invitationId
2673
+ }, {
2674
+ F: __dxlog_file9,
2675
+ L: 128,
2676
+ S: this,
2677
+ C: (f, a) => f(...a)
2678
+ });
2679
+ invariant8(invitationId, void 0, {
2680
+ F: __dxlog_file9,
2681
+ L: 129,
2682
+ S: this,
2683
+ A: [
2684
+ "invitationId",
2685
+ ""
2686
+ ]
2687
+ });
2688
+ const created = this._createInvitations.get(invitationId);
2689
+ if (created) {
2690
+ if (created.get().persistent) {
2691
+ await this._metadataStore.removeInvitation(invitationId);
2810
2692
  }
2811
- map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
2693
+ await created.cancel();
2694
+ this._createInvitations.delete(invitationId);
2695
+ this.removedCreated.emit(created.get());
2696
+ return;
2812
2697
  }
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)) ?? []);
2698
+ const accepted = this._acceptInvitations.get(invitationId);
2699
+ if (accepted) {
2700
+ await accepted.cancel();
2701
+ this._acceptInvitations.delete(invitationId);
2702
+ this.removedAccepted.emit(accepted.get());
2831
2703
  }
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
2704
  }
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();
2705
+ getCreatedInvitations() {
2706
+ return [
2707
+ ...this._createInvitations.values()
2708
+ ].map((i) => i.get());
2879
2709
  }
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;
2710
+ getAcceptedInvitations() {
2711
+ return [
2712
+ ...this._acceptInvitations.values()
2713
+ ].map((i) => i.get());
2911
2714
  }
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
- }
2715
+ onPersistentInvitationsLoaded(ctx, callback) {
2716
+ if (this._persistentInvitationsLoaded) {
2717
+ callback();
2718
+ } else {
2719
+ this._persistentInvitationsLoadedEvent.once(ctx, () => callback());
2922
2720
  }
2923
- this.onNewEpoch.emit(credential);
2924
2721
  }
2925
- startProcessingRootDocs() {
2926
- if (this._isProcessingRootDocs) {
2927
- return;
2928
- }
2929
- if (this.rootUrl) {
2930
- this._onNewRoot(this.rootUrl);
2722
+ _safePersistInBackground(invitation) {
2723
+ return new Promise((resolve) => {
2724
+ setTimeout(async () => {
2725
+ try {
2726
+ await this._metadataStore.addInvitation(invitation.get());
2727
+ this.saved.emit(invitation.get());
2728
+ } catch (err) {
2729
+ log7.catch(err, void 0, {
2730
+ F: __dxlog_file9,
2731
+ L: 173,
2732
+ S: this,
2733
+ C: (f, a) => f(...a)
2734
+ });
2735
+ await invitation.cancel();
2736
+ } finally {
2737
+ resolve();
2738
+ }
2739
+ });
2740
+ });
2741
+ }
2742
+ async _safeDeleteInvitation(invitation) {
2743
+ try {
2744
+ await this._metadataStore.removeInvitation(invitation.invitationId);
2745
+ } catch (err) {
2746
+ log7.catch(err, void 0, {
2747
+ F: __dxlog_file9,
2748
+ L: 186,
2749
+ S: this,
2750
+ C: (f, a) => f(...a)
2751
+ });
2931
2752
  }
2932
- this._isProcessingRootDocs = true;
2933
2753
  }
2934
- async ensureEpochInitialized() {
2935
- await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);
2754
+ _onInvitationComplete(invitation, callback) {
2755
+ invitation.subscribe(() => {
2756
+ }, () => {
2757
+ }, callback);
2936
2758
  }
2937
2759
  };
2938
2760
 
2939
- // 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";
2941
- import { Context as Context7, rejectOnDispose } from "@dxos/context";
2942
- import { invariant as invariant10 } from "@dxos/invariant";
2943
- import { PublicKey as PublicKey7 } from "@dxos/keys";
2944
- import { log as log8 } from "@dxos/log";
2761
+ // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
2762
+ import { Stream as Stream9 } from "@dxos/codec-protobuf";
2763
+ import { raise } from "@dxos/debug";
2764
+ import { parseMethodName, RpcPeer } from "@dxos/rpc";
2765
+ import { MapCounter, trace as trace5 } from "@dxos/tracing";
2766
+ function _ts_decorate3(decorators, target, key, desc) {
2767
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2768
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2769
+ r = Reflect.decorate(decorators, target, key, desc);
2770
+ else
2771
+ for (var i = decorators.length - 1; i >= 0; i--)
2772
+ if (d = decorators[i])
2773
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2774
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2775
+ }
2776
+ var ClientRpcServer = class {
2777
+ constructor(params) {
2778
+ this._handlerCache = /* @__PURE__ */ new Map();
2779
+ this._callMetrics = new MapCounter();
2780
+ const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
2781
+ this._handleCall = handleCall;
2782
+ this._handleStream = handleStream;
2783
+ this._serviceRegistry = serviceRegistry;
2784
+ this._rpcPeer = new RpcPeer({
2785
+ ...rpcOptions,
2786
+ callHandler: (method, params2) => {
2787
+ const [serviceName, methodName] = parseMethodName(method);
2788
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
2789
+ this._callMetrics.inc(`${serviceName}.${methodName} request`);
2790
+ if (this._handleCall) {
2791
+ return this._handleCall(methodName, params2, handler);
2792
+ } else {
2793
+ return handler(methodName, params2);
2794
+ }
2795
+ },
2796
+ streamHandler: (method, params2) => {
2797
+ const [serviceName, methodName] = parseMethodName(method);
2798
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
2799
+ this._callMetrics.inc(`${serviceName}.${methodName} request stream`);
2800
+ if (this._handleStream) {
2801
+ return Stream9.map(Stream9.unwrapPromise(this._handleStream(methodName, params2, handler)), (data) => {
2802
+ this._callMetrics.inc(`${serviceName}.${methodName} response stream`);
2803
+ return data;
2804
+ });
2805
+ } else {
2806
+ return handler(methodName, params2);
2807
+ }
2808
+ }
2809
+ });
2810
+ }
2811
+ get _services() {
2812
+ return Object.keys(this._serviceRegistry.services);
2813
+ }
2814
+ async open() {
2815
+ await this._rpcPeer.open();
2816
+ }
2817
+ async close() {
2818
+ await this._rpcPeer.close();
2819
+ }
2820
+ _getServiceHandler(serviceName) {
2821
+ if (!this._handlerCache.has(serviceName)) {
2822
+ const [key, descriptor] = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName) ?? raise(new Error(`Service not available: ${serviceName}`));
2823
+ const service = this._serviceRegistry.services[key];
2824
+ if (!service) {
2825
+ throw new Error(`Service not available: ${serviceName}`);
2826
+ }
2827
+ this._handlerCache.set(serviceName, descriptor.createServer(service));
2828
+ }
2829
+ return this._handlerCache.get(serviceName);
2830
+ }
2831
+ };
2832
+ _ts_decorate3([
2833
+ trace5.metricsCounter()
2834
+ ], ClientRpcServer.prototype, "_callMetrics", void 0);
2835
+ _ts_decorate3([
2836
+ trace5.info()
2837
+ ], ClientRpcServer.prototype, "_services", null);
2838
+ ClientRpcServer = _ts_decorate3([
2839
+ trace5.resource()
2840
+ ], ClientRpcServer);
2841
+
2842
+ // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2843
+ import { Event as Event6, asyncTimeout, scheduleTask as scheduleTask4, sleep as sleep2, synchronized, trackLeaks } from "@dxos/async";
2844
+ import { AUTH_TIMEOUT as AUTH_TIMEOUT2 } from "@dxos/client-protocol";
2845
+ import { cancelWithContext as cancelWithContext2, Context as Context7, ContextDisposedError } from "@dxos/context";
2846
+ import { timed, warnAfterTimeout } from "@dxos/debug";
2847
+ import { createMappedFeedWriter } from "@dxos/echo-pipeline";
2848
+ import { AutomergeDocumentLoaderImpl } from "@dxos/echo-pipeline";
2849
+ import { TYPE_PROPERTIES } from "@dxos/echo-schema";
2850
+ import { failedInvariant, invariant as invariant10 } from "@dxos/invariant";
2851
+ import { PublicKey as PublicKey8 } from "@dxos/keys";
2852
+ import { log as log9 } from "@dxos/log";
2853
+ import { CancelledError, SystemError } from "@dxos/protocols";
2854
+ import { SpaceState, CreateEpochRequest } from "@dxos/protocols/proto/dxos/client/services";
2855
+ import { AdmittedFeed as AdmittedFeed3 } from "@dxos/protocols/proto/dxos/halo/credentials";
2856
+ import { Timeframe as Timeframe2 } from "@dxos/timeframe";
2857
+ import { trace as trace6 } from "@dxos/tracing";
2858
+ import { ComplexSet as ComplexSet3, assignDeep } from "@dxos/util";
2859
+
2860
+ // packages/sdk/client-services/src/packlets/spaces/automerge-space-state.ts
2861
+ import { Event as Event4 } from "@dxos/async";
2862
+ import { checkCredentialType } from "@dxos/credentials";
2863
+ var AutomergeSpaceState = class {
2864
+ constructor(_onNewRoot) {
2865
+ this._onNewRoot = _onNewRoot;
2866
+ this.rootUrl = void 0;
2867
+ this.lastEpoch = void 0;
2868
+ this.onNewEpoch = new Event4();
2869
+ this._isProcessingRootDocs = false;
2870
+ }
2871
+ async processCredential(credential) {
2872
+ if (!checkCredentialType(credential, "dxos.halo.credentials.Epoch")) {
2873
+ return;
2874
+ }
2875
+ this.lastEpoch = credential;
2876
+ if (credential.subject.assertion.automergeRoot) {
2877
+ this.rootUrl = credential.subject.assertion.automergeRoot;
2878
+ if (this._isProcessingRootDocs) {
2879
+ this._onNewRoot(this.rootUrl);
2880
+ }
2881
+ }
2882
+ this.onNewEpoch.emit(credential);
2883
+ }
2884
+ startProcessingRootDocs() {
2885
+ if (this._isProcessingRootDocs) {
2886
+ return;
2887
+ }
2888
+ if (this.rootUrl) {
2889
+ this._onNewRoot(this.rootUrl);
2890
+ }
2891
+ this._isProcessingRootDocs = true;
2892
+ }
2893
+ async ensureEpochInitialized() {
2894
+ await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);
2895
+ }
2896
+ };
2897
+
2898
+ // packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts
2899
+ import { DeferredTask, Event as Event5, scheduleTask as scheduleTask3, sleep, TimeoutError as TimeoutError2, Trigger as Trigger4 } from "@dxos/async";
2900
+ import { Context as Context6, rejectOnDispose } from "@dxos/context";
2901
+ import { invariant as invariant9 } from "@dxos/invariant";
2902
+ import { PublicKey as PublicKey7 } from "@dxos/keys";
2903
+ import { log as log8 } from "@dxos/log";
2945
2904
  import { schema as schema3 } from "@dxos/protocols";
2946
2905
  import { RpcExtension as RpcExtension2 } from "@dxos/teleport";
2947
2906
  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";
2907
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts";
2949
2908
  var DEFAULT_RETRY_TIMEOUT = 1e3;
2950
2909
  var DEFAULT_SUCCESS_DELAY = 1e3;
2951
2910
  var DEFAULT_NOTARIZE_TIMEOUT = 1e4;
2952
2911
  var WRITER_NOT_SET_ERROR_CODE = "WRITER_NOT_SET";
2953
2912
  var NotarizationPlugin = class {
2954
2913
  constructor() {
2955
- this._ctx = new Context7();
2914
+ this._ctx = new Context6();
2956
2915
  this._extensionOpened = new Event5();
2957
2916
  this._extensions = /* @__PURE__ */ new Set();
2958
2917
  this._processedCredentials = new ComplexSet2(PublicKey7.hash);
@@ -2973,13 +2932,13 @@ var NotarizationPlugin = class {
2973
2932
  log8("notarize", {
2974
2933
  credentials
2975
2934
  }, {
2976
- F: __dxlog_file11,
2935
+ F: __dxlog_file10,
2977
2936
  L: 90,
2978
2937
  S: this,
2979
2938
  C: (f, a) => f(...a)
2980
2939
  });
2981
- invariant10(credentials.every((credential) => credential.id), "Credentials must have an id", {
2982
- F: __dxlog_file11,
2940
+ invariant9(credentials.every((credential) => credential.id), "Credentials must have an id", {
2941
+ F: __dxlog_file10,
2983
2942
  L: 91,
2984
2943
  S: this,
2985
2944
  A: [
@@ -2993,7 +2952,7 @@ var NotarizationPlugin = class {
2993
2952
  log8.warn("Notarization error", {
2994
2953
  err
2995
2954
  }, {
2996
- F: __dxlog_file11,
2955
+ F: __dxlog_file10,
2997
2956
  L: 99,
2998
2957
  S: this,
2999
2958
  C: (f, a) => f(...a)
@@ -3004,12 +2963,12 @@ var NotarizationPlugin = class {
3004
2963
  });
3005
2964
  opCtx?.onDispose(() => ctx.dispose());
3006
2965
  if (timeout !== 0) {
3007
- scheduleTask4(ctx, () => {
2966
+ scheduleTask3(ctx, () => {
3008
2967
  log8.warn("Notarization timeout", {
3009
2968
  timeout,
3010
2969
  peers: Array.from(this._extensions).map((extension) => extension.remotePeerId)
3011
2970
  }, {
3012
- F: __dxlog_file11,
2971
+ F: __dxlog_file10,
3013
2972
  L: 111,
3014
2973
  S: this,
3015
2974
  C: (f, a) => f(...a)
@@ -3032,13 +2991,13 @@ var NotarizationPlugin = class {
3032
2991
  log8.info("Exhausted all peers to notarize with", {
3033
2992
  retryIn: retryTimeout
3034
2993
  }, {
3035
- F: __dxlog_file11,
2994
+ F: __dxlog_file10,
3036
2995
  L: 136,
3037
2996
  S: this,
3038
2997
  C: (f, a) => f(...a)
3039
2998
  });
3040
2999
  peersTried.clear();
3041
- scheduleTask4(ctx, () => notarizeTask.schedule(), retryTimeout);
3000
+ scheduleTask3(ctx, () => notarizeTask.schedule(), retryTimeout);
3042
3001
  return;
3043
3002
  }
3044
3003
  peersTried.add(peer);
@@ -3046,7 +3005,7 @@ var NotarizationPlugin = class {
3046
3005
  peer: peer.localPeerId,
3047
3006
  credentialId: credentials.map((credential) => credential.id)
3048
3007
  }, {
3049
- F: __dxlog_file11,
3008
+ F: __dxlog_file10,
3050
3009
  L: 143,
3051
3010
  S: this,
3052
3011
  C: (f, a) => f(...a)
@@ -3055,7 +3014,7 @@ var NotarizationPlugin = class {
3055
3014
  credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id))
3056
3015
  });
3057
3016
  log8("success", void 0, {
3058
- F: __dxlog_file11,
3017
+ F: __dxlog_file10,
3059
3018
  L: 147,
3060
3019
  S: this,
3061
3020
  C: (f, a) => f(...a)
@@ -3064,7 +3023,7 @@ var NotarizationPlugin = class {
3064
3023
  } catch (err) {
3065
3024
  if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {
3066
3025
  log8.info("error notarizing (recoverable)", err, {
3067
- F: __dxlog_file11,
3026
+ F: __dxlog_file10,
3068
3027
  L: 151,
3069
3028
  S: this,
3070
3029
  C: (f, a) => f(...a)
@@ -3082,7 +3041,7 @@ var NotarizationPlugin = class {
3082
3041
  errors.wait()
3083
3042
  ]);
3084
3043
  log8("done", void 0, {
3085
- F: __dxlog_file11,
3044
+ F: __dxlog_file10,
3086
3045
  L: 162,
3087
3046
  S: this,
3088
3047
  C: (f, a) => f(...a)
@@ -3103,8 +3062,8 @@ var NotarizationPlugin = class {
3103
3062
  this._processCredentialsTriggers.delete(credential.id);
3104
3063
  }
3105
3064
  setWriter(writer) {
3106
- invariant10(!this._writer, "Writer already set.", {
3107
- F: __dxlog_file11,
3065
+ invariant9(!this._writer, "Writer already set.", {
3066
+ F: __dxlog_file10,
3108
3067
  L: 181,
3109
3068
  S: this,
3110
3069
  A: [
@@ -3128,8 +3087,8 @@ var NotarizationPlugin = class {
3128
3087
  throw new Error(WRITER_NOT_SET_ERROR_CODE);
3129
3088
  }
3130
3089
  for (const credential of request.credentials ?? []) {
3131
- invariant10(credential.id, "Credential must have an id", {
3132
- F: __dxlog_file11,
3090
+ invariant9(credential.id, "Credential must have an id", {
3091
+ F: __dxlog_file10,
3133
3092
  L: 200,
3134
3093
  S: this,
3135
3094
  A: [
@@ -3149,7 +3108,7 @@ var NotarizationPlugin = class {
3149
3108
  log8("extension opened", {
3150
3109
  peer: extension.localPeerId
3151
3110
  }, {
3152
- F: __dxlog_file11,
3111
+ F: __dxlog_file10,
3153
3112
  L: 211,
3154
3113
  S: this,
3155
3114
  C: (f, a) => f(...a)
@@ -3161,7 +3120,7 @@ var NotarizationPlugin = class {
3161
3120
  log8("extension closed", {
3162
3121
  peer: extension.localPeerId
3163
3122
  }, {
3164
- F: __dxlog_file11,
3123
+ F: __dxlog_file10,
3165
3124
  L: 216,
3166
3125
  S: this,
3167
3126
  C: (f, a) => f(...a)
@@ -3215,10 +3174,10 @@ function _ts_decorate4(decorators, target, key, desc) {
3215
3174
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3216
3175
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3217
3176
  }
3218
- var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space.ts";
3177
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space.ts";
3219
3178
  var DataSpace = class {
3220
3179
  constructor(params) {
3221
- this._ctx = new Context8();
3180
+ this._ctx = new Context7();
3222
3181
  this._notarizationPlugin = new NotarizationPlugin();
3223
3182
  this._cache = void 0;
3224
3183
  // TODO(dmaretskyi): Move into Space?
@@ -3250,7 +3209,7 @@ var DataSpace = class {
3250
3209
  log9("new state", {
3251
3210
  state: SpaceState[this._state]
3252
3211
  }, {
3253
- F: __dxlog_file12,
3212
+ F: __dxlog_file11,
3254
3213
  L: 140,
3255
3214
  S: this,
3256
3215
  C: (f, a) => f(...a)
@@ -3295,12 +3254,12 @@ var DataSpace = class {
3295
3254
  await this._notarizationPlugin.open();
3296
3255
  await this._inner.spaceState.addCredentialProcessor(this._notarizationPlugin);
3297
3256
  await this._inner.spaceState.addCredentialProcessor(this._automergeSpaceState);
3298
- await this._inner.open(new Context8());
3257
+ await this._inner.open(new Context7());
3299
3258
  this._state = SpaceState.CONTROL_ONLY;
3300
3259
  log9("new state", {
3301
3260
  state: SpaceState[this._state]
3302
3261
  }, {
3303
- F: __dxlog_file12,
3262
+ F: __dxlog_file11,
3304
3263
  L: 198,
3305
3264
  S: this,
3306
3265
  C: (f, a) => f(...a)
@@ -3318,13 +3277,13 @@ var DataSpace = class {
3318
3277
  log9("new state", {
3319
3278
  state: SpaceState[this._state]
3320
3279
  }, {
3321
- F: __dxlog_file12,
3280
+ F: __dxlog_file11,
3322
3281
  L: 212,
3323
3282
  S: this,
3324
3283
  C: (f, a) => f(...a)
3325
3284
  });
3326
3285
  await this._ctx.dispose();
3327
- this._ctx = new Context8();
3286
+ this._ctx = new Context7();
3328
3287
  await this.authVerifier.close();
3329
3288
  await this._inner.close();
3330
3289
  await this._inner.spaceState.removeCredentialProcessor(this._automergeSpaceState);
@@ -3343,14 +3302,14 @@ var DataSpace = class {
3343
3302
  * Initialize the data pipeline in a separate task.
3344
3303
  */
3345
3304
  initializeDataPipelineAsync() {
3346
- scheduleTask5(this._ctx, async () => {
3305
+ scheduleTask4(this._ctx, async () => {
3347
3306
  try {
3348
3307
  this.metrics.pipelineInitBegin = /* @__PURE__ */ new Date();
3349
3308
  await this.initializeDataPipeline();
3350
3309
  } catch (err) {
3351
3310
  if (err instanceof CancelledError || err instanceof ContextDisposedError) {
3352
3311
  log9("data pipeline initialization cancelled", err, {
3353
- F: __dxlog_file12,
3312
+ F: __dxlog_file11,
3354
3313
  L: 245,
3355
3314
  S: this,
3356
3315
  C: (f, a) => f(...a)
@@ -3358,7 +3317,7 @@ var DataSpace = class {
3358
3317
  return;
3359
3318
  }
3360
3319
  log9.error("Error initializing data pipeline", err, {
3361
- F: __dxlog_file12,
3320
+ F: __dxlog_file11,
3362
3321
  L: 249,
3363
3322
  S: this,
3364
3323
  C: (f, a) => f(...a)
@@ -3367,7 +3326,7 @@ var DataSpace = class {
3367
3326
  log9("new state", {
3368
3327
  state: SpaceState[this._state]
3369
3328
  }, {
3370
- F: __dxlog_file12,
3329
+ F: __dxlog_file11,
3371
3330
  L: 251,
3372
3331
  S: this,
3373
3332
  C: (f, a) => f(...a)
@@ -3387,7 +3346,7 @@ var DataSpace = class {
3387
3346
  log9("new state", {
3388
3347
  state: SpaceState[this._state]
3389
3348
  }, {
3390
- F: __dxlog_file12,
3349
+ F: __dxlog_file11,
3391
3350
  L: 267,
3392
3351
  S: this,
3393
3352
  C: (f, a) => f(...a)
@@ -3397,7 +3356,7 @@ var DataSpace = class {
3397
3356
  this._automergeSpaceState.startProcessingRootDocs();
3398
3357
  await cancelWithContext2(this._ctx, this.automergeSpaceState.ensureEpochInitialized());
3399
3358
  log9("data pipeline ready", void 0, {
3400
- F: __dxlog_file12,
3359
+ F: __dxlog_file11,
3401
3360
  L: 279,
3402
3361
  S: this,
3403
3362
  C: (f, a) => f(...a)
@@ -3407,7 +3366,7 @@ var DataSpace = class {
3407
3366
  log9("new state", {
3408
3367
  state: SpaceState[this._state]
3409
3368
  }, {
3410
- F: __dxlog_file12,
3369
+ F: __dxlog_file11,
3411
3370
  L: 283,
3412
3371
  S: this,
3413
3372
  C: (f, a) => f(...a)
@@ -3423,7 +3382,7 @@ var DataSpace = class {
3423
3382
  this.metrics.controlPipelineReady = /* @__PURE__ */ new Date();
3424
3383
  await this._createWritableFeeds();
3425
3384
  log9("writable feeds created", void 0, {
3426
- F: __dxlog_file12,
3385
+ F: __dxlog_file11,
3427
3386
  L: 299,
3428
3387
  S: this,
3429
3388
  C: (f, a) => f(...a)
@@ -3486,7 +3445,7 @@ var DataSpace = class {
3486
3445
  space: this.key,
3487
3446
  rootUrl
3488
3447
  }, {
3489
- F: __dxlog_file12,
3448
+ F: __dxlog_file11,
3490
3449
  L: 365,
3491
3450
  S: this,
3492
3451
  C: (f, a) => f(...a)
@@ -3518,7 +3477,7 @@ var DataSpace = class {
3518
3477
  rootUrl,
3519
3478
  err
3520
3479
  }, {
3521
- F: __dxlog_file12,
3480
+ F: __dxlog_file11,
3522
3481
  L: 388,
3523
3482
  S: this,
3524
3483
  C: (f, a) => f(...a)
@@ -3572,8 +3531,8 @@ var DataSpace = class {
3572
3531
  const rootHandle = this._automergeHost.repo.find(currentRootUrl);
3573
3532
  await cancelWithContext2(this._ctx, asyncTimeout(rootHandle.whenReady(), 1e4));
3574
3533
  const newRoot = this._automergeHost.repo.create(rootHandle.docSync());
3575
- invariant11(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3576
- F: __dxlog_file12,
3534
+ invariant10(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3535
+ F: __dxlog_file11,
3577
3536
  L: 438,
3578
3537
  S: this,
3579
3538
  A: [
@@ -3592,7 +3551,7 @@ var DataSpace = class {
3592
3551
  case CreateEpochRequest.Migration.FRAGMENT_AUTOMERGE_ROOT:
3593
3552
  {
3594
3553
  log9.info("Fragmenting", void 0, {
3595
- F: __dxlog_file12,
3554
+ F: __dxlog_file11,
3596
3555
  L: 450,
3597
3556
  S: this,
3598
3557
  C: (f, a) => f(...a)
@@ -3603,8 +3562,8 @@ var DataSpace = class {
3603
3562
  const objects = Object.entries(rootHandle.docSync().objects);
3604
3563
  const properties = objects.find(([_, value]) => value.system.type?.itemId === TYPE_PROPERTIES);
3605
3564
  const otherObjects = objects.filter(([key]) => key !== properties?.[0]);
3606
- invariant11(properties, "Properties not found", {
3607
- F: __dxlog_file12,
3565
+ invariant10(properties, "Properties not found", {
3566
+ F: __dxlog_file11,
3608
3567
  L: 460,
3609
3568
  S: this,
3610
3569
  A: [
@@ -3619,8 +3578,8 @@ var DataSpace = class {
3619
3578
  ])
3620
3579
  };
3621
3580
  const newRoot = this._automergeHost.repo.create(newSpaceDoc);
3622
- invariant11(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3623
- F: __dxlog_file12,
3581
+ invariant10(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3582
+ F: __dxlog_file11,
3624
3583
  L: 465,
3625
3584
  S: this,
3626
3585
  A: [
@@ -3689,7 +3648,7 @@ var DataSpace = class {
3689
3648
  log9("new state", {
3690
3649
  state: SpaceState[this._state]
3691
3650
  }, {
3692
- F: __dxlog_file12,
3651
+ F: __dxlog_file11,
3693
3652
  L: 531,
3694
3653
  S: this,
3695
3654
  C: (f, a) => f(...a)
@@ -3745,9 +3704,9 @@ DataSpace = _ts_decorate4([
3745
3704
 
3746
3705
  // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
3747
3706
  import { Event as Event7, synchronized as synchronized2, trackLeaks as trackLeaks2 } from "@dxos/async";
3748
- import { Context as Context9, cancelWithContext as cancelWithContext3 } from "@dxos/context";
3707
+ import { Context as Context8, cancelWithContext as cancelWithContext3 } from "@dxos/context";
3749
3708
  import { getCredentialAssertion as getCredentialAssertion2 } from "@dxos/credentials";
3750
- import { invariant as invariant12 } from "@dxos/invariant";
3709
+ import { invariant as invariant11 } from "@dxos/invariant";
3751
3710
  import { PublicKey as PublicKey9 } from "@dxos/keys";
3752
3711
  import { log as log10 } from "@dxos/log";
3753
3712
  import { trace as trace7 } from "@dxos/protocols";
@@ -3758,7 +3717,7 @@ import { ComplexMap as ComplexMap3, deferFunction as deferFunction2, forEachAsyn
3758
3717
  // packages/sdk/client-services/src/packlets/spaces/genesis.ts
3759
3718
  import { createCredential } from "@dxos/credentials";
3760
3719
  import { failUndefined } from "@dxos/debug";
3761
- import { AdmittedFeed as AdmittedFeed4, SpaceMember as SpaceMember2 } from "@dxos/protocols/proto/dxos/halo/credentials";
3720
+ import { AdmittedFeed as AdmittedFeed4, SpaceMember } from "@dxos/protocols/proto/dxos/halo/credentials";
3762
3721
  import { Timeframe as Timeframe3 } from "@dxos/timeframe";
3763
3722
  var spaceGenesis = async (keyring, signingContext, space, automergeRoot) => {
3764
3723
  const credentials = [
@@ -3778,7 +3737,7 @@ var spaceGenesis = async (keyring, signingContext, space, automergeRoot) => {
3778
3737
  assertion: {
3779
3738
  "@type": "dxos.halo.credentials.SpaceMember",
3780
3739
  spaceKey: space.key,
3781
- role: SpaceMember2.Role.ADMIN,
3740
+ role: SpaceMember.Role.ADMIN,
3782
3741
  profile: signingContext.getProfile(),
3783
3742
  genesisFeedKey: space.controlFeedKey ?? failUndefined()
3784
3743
  }
@@ -3836,7 +3795,7 @@ function _ts_decorate5(decorators, target, key, desc) {
3836
3795
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3837
3796
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3838
3797
  }
3839
- var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts";
3798
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts";
3840
3799
  var PRESENCE_ANNOUNCE_INTERVAL = 1e4;
3841
3800
  var PRESENCE_OFFLINE_TIMEOUT = 2e4;
3842
3801
  var DataSpaceManager = class {
@@ -3847,7 +3806,7 @@ var DataSpaceManager = class {
3847
3806
  this._signingContext = _signingContext;
3848
3807
  this._feedStore = _feedStore;
3849
3808
  this._automergeHost = _automergeHost;
3850
- this._ctx = new Context9();
3809
+ this._ctx = new Context8();
3851
3810
  this.updated = new Event7();
3852
3811
  this._spaces = new ComplexMap3(PublicKey9.hash);
3853
3812
  this._isOpen = false;
@@ -3862,7 +3821,7 @@ var DataSpaceManager = class {
3862
3821
  }
3863
3822
  async open() {
3864
3823
  log10("open", void 0, {
3865
- F: __dxlog_file13,
3824
+ F: __dxlog_file12,
3866
3825
  L: 98,
3867
3826
  S: this,
3868
3827
  C: (f, a) => f(...a)
@@ -3870,7 +3829,7 @@ var DataSpaceManager = class {
3870
3829
  log10.trace("dxos.echo.data-space-manager.open", trace7.begin({
3871
3830
  id: this._instanceId
3872
3831
  }), {
3873
- F: __dxlog_file13,
3832
+ F: __dxlog_file12,
3874
3833
  L: 99,
3875
3834
  S: this,
3876
3835
  C: (f, a) => f(...a)
@@ -3878,7 +3837,7 @@ var DataSpaceManager = class {
3878
3837
  log10("metadata loaded", {
3879
3838
  spaces: this._metadataStore.spaces.length
3880
3839
  }, {
3881
- F: __dxlog_file13,
3840
+ F: __dxlog_file12,
3882
3841
  L: 100,
3883
3842
  S: this,
3884
3843
  C: (f, a) => f(...a)
@@ -3888,7 +3847,7 @@ var DataSpaceManager = class {
3888
3847
  log10("load space", {
3889
3848
  spaceMetadata
3890
3849
  }, {
3891
- F: __dxlog_file13,
3850
+ F: __dxlog_file12,
3892
3851
  L: 104,
3893
3852
  S: this,
3894
3853
  C: (f, a) => f(...a)
@@ -3899,7 +3858,7 @@ var DataSpaceManager = class {
3899
3858
  spaceMetadata,
3900
3859
  err
3901
3860
  }, {
3902
- F: __dxlog_file13,
3861
+ F: __dxlog_file12,
3903
3862
  L: 107,
3904
3863
  S: this,
3905
3864
  C: (f, a) => f(...a)
@@ -3916,7 +3875,7 @@ var DataSpaceManager = class {
3916
3875
  log10.trace("dxos.echo.data-space-manager.open", trace7.end({
3917
3876
  id: this._instanceId
3918
3877
  }), {
3919
- F: __dxlog_file13,
3878
+ F: __dxlog_file12,
3920
3879
  L: 120,
3921
3880
  S: this,
3922
3881
  C: (f, a) => f(...a)
@@ -3924,7 +3883,7 @@ var DataSpaceManager = class {
3924
3883
  }
3925
3884
  async close() {
3926
3885
  log10("close", void 0, {
3927
- F: __dxlog_file13,
3886
+ F: __dxlog_file12,
3928
3887
  L: 125,
3929
3888
  S: this,
3930
3889
  C: (f, a) => f(...a)
@@ -3939,8 +3898,8 @@ var DataSpaceManager = class {
3939
3898
  * Creates a new space writing the genesis credentials to the control feed.
3940
3899
  */
3941
3900
  async createSpace() {
3942
- invariant12(this._isOpen, "Not open.", {
3943
- F: __dxlog_file13,
3901
+ invariant11(this._isOpen, "Not open.", {
3902
+ F: __dxlog_file12,
3944
3903
  L: 138,
3945
3904
  S: this,
3946
3905
  A: [
@@ -3961,7 +3920,7 @@ var DataSpaceManager = class {
3961
3920
  log10("creating space...", {
3962
3921
  spaceKey
3963
3922
  }, {
3964
- F: __dxlog_file13,
3923
+ F: __dxlog_file12,
3965
3924
  L: 150,
3966
3925
  S: this,
3967
3926
  C: (f, a) => f(...a)
@@ -3976,8 +3935,8 @@ var DataSpaceManager = class {
3976
3935
  const credentials = await spaceGenesis(this._keyring, this._signingContext, space.inner, automergeRoot.url);
3977
3936
  await this._metadataStore.addSpace(metadata);
3978
3937
  const memberCredential = credentials[1];
3979
- invariant12(getCredentialAssertion2(memberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
3980
- F: __dxlog_file13,
3938
+ invariant11(getCredentialAssertion2(memberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
3939
+ F: __dxlog_file12,
3981
3940
  L: 163,
3982
3941
  S: this,
3983
3942
  A: [
@@ -3995,13 +3954,13 @@ var DataSpaceManager = class {
3995
3954
  log10("accept space", {
3996
3955
  opts
3997
3956
  }, {
3998
- F: __dxlog_file13,
3957
+ F: __dxlog_file12,
3999
3958
  L: 175,
4000
3959
  S: this,
4001
3960
  C: (f, a) => f(...a)
4002
3961
  });
4003
- invariant12(this._isOpen, "Not open.", {
4004
- F: __dxlog_file13,
3962
+ invariant11(this._isOpen, "Not open.", {
3963
+ F: __dxlog_file12,
4005
3964
  L: 176,
4006
3965
  S: this,
4007
3966
  A: [
@@ -4009,8 +3968,8 @@ var DataSpaceManager = class {
4009
3968
  "'Not open.'"
4010
3969
  ]
4011
3970
  });
4012
- invariant12(!this._spaces.has(opts.spaceKey), "Space already exists.", {
4013
- F: __dxlog_file13,
3971
+ invariant11(!this._spaces.has(opts.spaceKey), "Space already exists.", {
3972
+ F: __dxlog_file12,
4014
3973
  L: 177,
4015
3974
  S: this,
4016
3975
  A: [
@@ -4045,7 +4004,7 @@ var DataSpaceManager = class {
4045
4004
  log10("construct space", {
4046
4005
  metadata
4047
4006
  }, {
4048
- F: __dxlog_file13,
4007
+ F: __dxlog_file12,
4049
4008
  L: 210,
4050
4009
  S: this,
4051
4010
  C: (f, a) => f(...a)
@@ -4083,7 +4042,7 @@ var DataSpaceManager = class {
4083
4042
  },
4084
4043
  onAuthFailure: () => {
4085
4044
  log10.warn("auth failure", void 0, {
4086
- F: __dxlog_file13,
4045
+ F: __dxlog_file12,
4087
4046
  L: 247,
4088
4047
  S: this,
4089
4048
  C: (f, a) => f(...a)
@@ -4107,7 +4066,7 @@ var DataSpaceManager = class {
4107
4066
  log10("before space ready", {
4108
4067
  space: space.key
4109
4068
  }, {
4110
- F: __dxlog_file13,
4069
+ F: __dxlog_file12,
4111
4070
  L: 265,
4112
4071
  S: this,
4113
4072
  C: (f, a) => f(...a)
@@ -4118,7 +4077,7 @@ var DataSpaceManager = class {
4118
4077
  space: space.key,
4119
4078
  open: this._isOpen
4120
4079
  }, {
4121
- F: __dxlog_file13,
4080
+ F: __dxlog_file12,
4122
4081
  L: 268,
4123
4082
  S: this,
4124
4083
  C: (f, a) => f(...a)
@@ -4131,7 +4090,7 @@ var DataSpaceManager = class {
4131
4090
  log10("before space close", {
4132
4091
  space: space.key
4133
4092
  }, {
4134
- F: __dxlog_file13,
4093
+ F: __dxlog_file12,
4135
4094
  L: 274,
4136
4095
  S: this,
4137
4096
  C: (f, a) => f(...a)
@@ -4168,14 +4127,14 @@ DataSpaceManager = _ts_decorate5([
4168
4127
  ], DataSpaceManager);
4169
4128
 
4170
4129
  // packages/sdk/client-services/src/packlets/spaces/spaces-service.ts
4171
- import { EventSubscriptions as EventSubscriptions2, UpdateScheduler, scheduleTask as scheduleTask6 } from "@dxos/async";
4130
+ import { EventSubscriptions as EventSubscriptions2, UpdateScheduler, scheduleTask as scheduleTask5 } from "@dxos/async";
4172
4131
  import { Stream as Stream10 } from "@dxos/codec-protobuf";
4173
4132
  import { raise as raise2 } from "@dxos/debug";
4174
- import { invariant as invariant13 } from "@dxos/invariant";
4133
+ import { invariant as invariant12 } from "@dxos/invariant";
4175
4134
  import { log as log11 } from "@dxos/log";
4176
4135
  import { ApiError, SpaceNotFoundError, encodeError } from "@dxos/protocols";
4177
- 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";
4136
+ import { SpaceMember as SpaceMember2, SpaceState as SpaceState3 } from "@dxos/protocols/proto/dxos/client/services";
4137
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/spaces-service.ts";
4179
4138
  var SpacesServiceImpl = class {
4180
4139
  constructor(_identityManager, _spaceManager, _getDataSpaceManager) {
4181
4140
  this._identityManager = _identityManager;
@@ -4214,7 +4173,7 @@ var SpacesServiceImpl = class {
4214
4173
  log11("update", {
4215
4174
  spaces
4216
4175
  }, {
4217
- F: __dxlog_file14,
4176
+ F: __dxlog_file13,
4218
4177
  L: 77,
4219
4178
  S: this,
4220
4179
  C: (f, a) => f(...a)
@@ -4225,7 +4184,7 @@ var SpacesServiceImpl = class {
4225
4184
  }, {
4226
4185
  maxFrequency: false ? void 0 : 2
4227
4186
  });
4228
- scheduleTask6(ctx, async () => {
4187
+ scheduleTask5(ctx, async () => {
4229
4188
  const dataSpaceManager = await this._getDataSpaceManager();
4230
4189
  const subscriptions = new EventSubscriptions2();
4231
4190
  ctx.onDispose(() => subscriptions.clear());
@@ -4259,7 +4218,7 @@ var SpacesServiceImpl = class {
4259
4218
  }
4260
4219
  subscribeMessages({ spaceKey, channel }) {
4261
4220
  return new Stream10(({ ctx, next }) => {
4262
- scheduleTask6(ctx, async () => {
4221
+ scheduleTask5(ctx, async () => {
4263
4222
  const dataSpaceManager = await this._getDataSpaceManager();
4264
4223
  const space = dataSpaceManager.spaces.get(spaceKey) ?? raise2(new SpaceNotFoundError(spaceKey));
4265
4224
  const handle = space.listen(getChannelId(channel), (message) => {
@@ -4278,7 +4237,7 @@ var SpacesServiceImpl = class {
4278
4237
  }
4279
4238
  };
4280
4239
  ctx.onDispose(() => space.spaceState.removeCredentialProcessor(processor));
4281
- scheduleTask6(ctx, async () => {
4240
+ scheduleTask5(ctx, async () => {
4282
4241
  await space.spaceState.addCredentialProcessor(processor);
4283
4242
  if (noTail) {
4284
4243
  close();
@@ -4296,8 +4255,8 @@ var SpacesServiceImpl = class {
4296
4255
  }
4297
4256
  });
4298
4257
  } else {
4299
- invariant13(!credential.id, "Id on unsigned credentials is not allowed", {
4300
- F: __dxlog_file14,
4258
+ invariant12(!credential.id, "Id on unsigned credentials is not allowed", {
4259
+ F: __dxlog_file13,
4301
4260
  L: 164,
4302
4261
  S: this,
4303
4262
  A: [
@@ -4305,8 +4264,8 @@ var SpacesServiceImpl = class {
4305
4264
  "'Id on unsigned credentials is not allowed'"
4306
4265
  ]
4307
4266
  });
4308
- invariant13(this._identityManager.identity, "Identity is not available", {
4309
- F: __dxlog_file14,
4267
+ invariant12(this._identityManager.identity, "Identity is not available", {
4268
+ F: __dxlog_file13,
4310
4269
  L: 165,
4311
4270
  S: this,
4312
4271
  A: [
@@ -4315,8 +4274,8 @@ var SpacesServiceImpl = class {
4315
4274
  ]
4316
4275
  });
4317
4276
  const signer = this._identityManager.identity.getIdentityCredentialSigner();
4318
- invariant13(credential.issuer.equals(signer.getIssuer()), void 0, {
4319
- F: __dxlog_file14,
4277
+ invariant12(credential.issuer.equals(signer.getIssuer()), void 0, {
4278
+ F: __dxlog_file13,
4320
4279
  L: 167,
4321
4280
  S: this,
4322
4281
  A: [
@@ -4372,7 +4331,7 @@ var SpacesServiceImpl = class {
4372
4331
  identityKey: member.key,
4373
4332
  profile: member.profile ?? {}
4374
4333
  },
4375
- presence: member.removed ? SpaceMember3.PresenceState.REMOVED : isMe || peers.length > 0 ? SpaceMember3.PresenceState.ONLINE : SpaceMember3.PresenceState.OFFLINE,
4334
+ presence: member.removed ? SpaceMember2.PresenceState.REMOVED : isMe || peers.length > 0 ? SpaceMember2.PresenceState.ONLINE : SpaceMember2.PresenceState.OFFLINE,
4376
4335
  peerStates: peers
4377
4336
  };
4378
4337
  }),
@@ -4386,25 +4345,24 @@ var getChannelId = (channel) => `user-channel/${channel}`;
4386
4345
 
4387
4346
  // packages/sdk/client-services/src/packlets/services/service-context.ts
4388
4347
  import { Trigger as Trigger5 } from "@dxos/async";
4389
- import { Context as Context10 } from "@dxos/context";
4348
+ import { Context as Context9, Resource } from "@dxos/context";
4390
4349
  import { getCredentialAssertion as getCredentialAssertion3 } from "@dxos/credentials";
4391
4350
  import { failUndefined as failUndefined2 } from "@dxos/debug";
4392
4351
  import { AutomergeHost, MetadataStore, SnapshotStore, SpaceManager, valueEncoding } from "@dxos/echo-pipeline";
4393
4352
  import { FeedFactory, FeedStore } from "@dxos/feed-store";
4394
- import { IndexMetadataStore, IndexStore, Indexer } from "@dxos/indexing";
4395
- import { invariant as invariant14 } from "@dxos/invariant";
4353
+ import { IndexMetadataStore, IndexStore, Indexer, createStorageCallbacks } from "@dxos/indexing";
4354
+ import { invariant as invariant13 } from "@dxos/invariant";
4396
4355
  import { Keyring } from "@dxos/keyring";
4397
4356
  import { PublicKey as PublicKey10 } from "@dxos/keys";
4398
4357
  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";
4358
+ import { InvalidStorageVersionError, STORAGE_VERSION, trace as trace8 } from "@dxos/protocols";
4359
+ import { Invitation as Invitation5 } from "@dxos/protocols/proto/dxos/client/services";
4401
4360
  import { BlobStore } from "@dxos/teleport-extension-object-sync";
4402
4361
  import { trace as Trace2 } from "@dxos/tracing";
4403
4362
  import { safeInstanceof } from "@dxos/util";
4404
4363
 
4405
4364
  // packages/sdk/client-services/src/packlets/indexing/util.ts
4406
4365
  import { getHeads } from "@dxos/automerge/automerge";
4407
- import { warnAfterTimeout as warnAfterTimeout2 } from "@dxos/debug";
4408
4366
  import { idCodec } from "@dxos/protocols";
4409
4367
  var createSelectedDocumentsIterator = (automergeHost) => (
4410
4368
  /**
@@ -4415,8 +4373,10 @@ var createSelectedDocumentsIterator = (automergeHost) => (
4415
4373
  async function* loadDocuments(ids) {
4416
4374
  for (const id of ids) {
4417
4375
  const { documentId, objectId } = idCodec.decode(id);
4418
- const handle = automergeHost.repo.find(documentId);
4419
- await warnAfterTimeout2(5e3, "to long to load doc", () => handle.whenReady());
4376
+ const handle = automergeHost.repo.handles[documentId] ?? automergeHost.repo.find(documentId);
4377
+ if (!handle.isReady()) {
4378
+ await handle.whenReady();
4379
+ }
4420
4380
  const doc = handle.docSync();
4421
4381
  const hash = getHeads(doc).join("");
4422
4382
  yield doc.objects?.[objectId] ? [
@@ -4441,7 +4401,9 @@ var createDocumentsIterator = (automergeHost) => (
4441
4401
  if (visited.has(handle.documentId)) {
4442
4402
  return;
4443
4403
  }
4444
- await warnAfterTimeout2(5e3, "to long to load doc", () => handle.whenReady());
4404
+ if (!handle.isReady()) {
4405
+ await handle.whenReady();
4406
+ }
4445
4407
  const doc = handle.docSync();
4446
4408
  const heads = getHeads(doc);
4447
4409
  if (doc.objects) {
@@ -4461,7 +4423,7 @@ var createDocumentsIterator = (automergeHost) => (
4461
4423
  if (visited.has(id)) {
4462
4424
  continue;
4463
4425
  }
4464
- const linkHandle = automergeHost.repo.find(id);
4426
+ const linkHandle = automergeHost.repo.handles[id] ?? automergeHost.repo.find(id);
4465
4427
  for await (const result of getObjectsFromHandle(linkHandle)) {
4466
4428
  yield result;
4467
4429
  }
@@ -4492,10 +4454,12 @@ function _ts_decorate6(decorators, target, key, desc) {
4492
4454
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4493
4455
  return c > 3 && r && Object.defineProperty(target, key, r), r;
4494
4456
  }
4495
- var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-context.ts";
4496
- var ServiceContext = class {
4497
- constructor(storage, networkManager, signalManager, _runtimeParams) {
4457
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-context.ts";
4458
+ var ServiceContext = class extends Resource {
4459
+ constructor(storage, level, networkManager, signalManager, _runtimeParams) {
4460
+ super();
4498
4461
  this.storage = storage;
4462
+ this.level = level;
4499
4463
  this.networkManager = networkManager;
4500
4464
  this.signalManager = signalManager;
4501
4465
  this._runtimeParams = _runtimeParams;
@@ -4525,66 +4489,81 @@ var ServiceContext = class {
4525
4489
  });
4526
4490
  this.identityManager = new IdentityManager(this.metadataStore, this.keyring, this.feedStore, this.spaceManager, this._runtimeParams);
4527
4491
  this.indexMetadata = new IndexMetadataStore({
4528
- directory: storage.createDirectory("index-metadata")
4492
+ db: level.sublevel("index-metadata")
4529
4493
  });
4530
4494
  this.automergeHost = new AutomergeHost({
4531
4495
  directory: storage.createDirectory("automerge"),
4532
- metadata: this.indexMetadata
4496
+ db: level.sublevel("automerge"),
4497
+ storageCallbacks: createStorageCallbacks({
4498
+ host: () => this.automergeHost,
4499
+ metadata: this.indexMetadata
4500
+ })
4533
4501
  });
4534
4502
  this.indexer = new Indexer({
4535
4503
  indexStore: new IndexStore({
4536
- directory: storage.createDirectory("index-store")
4504
+ db: level.sublevel("index-storage")
4537
4505
  }),
4538
4506
  metadataStore: this.indexMetadata,
4539
4507
  loadDocuments: createSelectedDocumentsIterator(this.automergeHost),
4540
4508
  getAllDocuments: createDocumentsIterator(this.automergeHost)
4541
4509
  });
4542
4510
  this.invitations = new InvitationsHandler(this.networkManager);
4543
- this._handlerFactories.set(Invitation6.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => this.identityManager.identity ?? failUndefined2(), this._acceptIdentity.bind(this)));
4511
+ this.invitationsManager = new InvitationsManager(this.invitations, (invitation) => this.getInvitationHandler(invitation), this.metadataStore);
4512
+ this._handlerFactories.set(Invitation5.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => this.identityManager.identity ?? failUndefined2(), this._acceptIdentity.bind(this)));
4544
4513
  }
4545
- async open(ctx) {
4514
+ async _open(ctx) {
4546
4515
  await this._checkStorageVersion();
4547
4516
  log12("opening...", void 0, {
4548
- F: __dxlog_file15,
4549
- L: 151,
4517
+ F: __dxlog_file14,
4518
+ L: 164,
4550
4519
  S: this,
4551
4520
  C: (f, a) => f(...a)
4552
4521
  });
4553
4522
  log12.trace("dxos.sdk.service-context.open", trace8.begin({
4554
4523
  id: this._instanceId
4555
4524
  }), {
4556
- F: __dxlog_file15,
4557
- L: 152,
4525
+ F: __dxlog_file14,
4526
+ L: 165,
4558
4527
  S: this,
4559
4528
  C: (f, a) => f(...a)
4560
4529
  });
4561
4530
  await this.signalManager.open();
4562
4531
  await this.networkManager.open();
4532
+ await this.automergeHost.open();
4563
4533
  await this.metadataStore.load();
4564
4534
  await this.spaceManager.open();
4565
4535
  await this.identityManager.open(ctx);
4566
4536
  if (this.identityManager.identity) {
4567
4537
  await this._initialize(ctx);
4568
4538
  }
4539
+ const loadedInvitations = await this.invitationsManager.loadPersistentInvitations();
4540
+ log12("loaded persistent invitations", {
4541
+ count: loadedInvitations.invitations?.length
4542
+ }, {
4543
+ F: __dxlog_file14,
4544
+ L: 178,
4545
+ S: this,
4546
+ C: (f, a) => f(...a)
4547
+ });
4569
4548
  log12.trace("dxos.sdk.service-context.open", trace8.end({
4570
4549
  id: this._instanceId
4571
4550
  }), {
4572
- F: __dxlog_file15,
4573
- L: 162,
4551
+ F: __dxlog_file14,
4552
+ L: 180,
4574
4553
  S: this,
4575
4554
  C: (f, a) => f(...a)
4576
4555
  });
4577
4556
  log12("opened", void 0, {
4578
- F: __dxlog_file15,
4579
- L: 163,
4557
+ F: __dxlog_file14,
4558
+ L: 181,
4580
4559
  S: this,
4581
4560
  C: (f, a) => f(...a)
4582
4561
  });
4583
4562
  }
4584
- async close() {
4563
+ async _close() {
4585
4564
  log12("closing...", void 0, {
4586
- F: __dxlog_file15,
4587
- L: 167,
4565
+ F: __dxlog_file14,
4566
+ L: 185,
4588
4567
  S: this,
4589
4568
  C: (f, a) => f(...a)
4590
4569
  });
@@ -4601,22 +4580,22 @@ var ServiceContext = class {
4601
4580
  await this.metadataStore.close();
4602
4581
  await this.indexer.destroy();
4603
4582
  log12("closed", void 0, {
4604
- F: __dxlog_file15,
4605
- L: 180,
4583
+ F: __dxlog_file14,
4584
+ L: 198,
4606
4585
  S: this,
4607
4586
  C: (f, a) => f(...a)
4608
4587
  });
4609
4588
  }
4610
4589
  async createIdentity(params = {}) {
4611
4590
  const identity = await this.identityManager.createIdentity(params);
4612
- await this._initialize(new Context10());
4591
+ await this._initialize(new Context9());
4613
4592
  return identity;
4614
4593
  }
4615
4594
  getInvitationHandler(invitation) {
4616
4595
  const factory = this._handlerFactories.get(invitation.kind);
4617
- invariant14(factory, `Unknown invitation kind: ${invitation.kind}`, {
4618
- F: __dxlog_file15,
4619
- L: 191,
4596
+ invariant13(factory, `Unknown invitation kind: ${invitation.kind}`, {
4597
+ F: __dxlog_file14,
4598
+ L: 209,
4620
4599
  S: this,
4621
4600
  A: [
4622
4601
  "factory",
@@ -4635,20 +4614,20 @@ var ServiceContext = class {
4635
4614
  }
4636
4615
  async _acceptIdentity(params) {
4637
4616
  const identity = await this.identityManager.acceptIdentity(params);
4638
- await this._initialize(new Context10());
4617
+ await this._initialize(new Context9());
4639
4618
  return identity;
4640
4619
  }
4641
4620
  async _checkStorageVersion() {
4642
4621
  await this.metadataStore.load();
4643
- if (this.metadataStore.version !== STORAGE_VERSION2) {
4644
- throw new InvalidStorageVersionError(STORAGE_VERSION2, this.metadataStore.version);
4622
+ if (this.metadataStore.version !== STORAGE_VERSION) {
4623
+ throw new InvalidStorageVersionError(STORAGE_VERSION, this.metadataStore.version);
4645
4624
  }
4646
4625
  }
4647
4626
  // Called when identity is created.
4648
4627
  async _initialize(ctx) {
4649
4628
  log12("initializing spaces...", void 0, {
4650
- F: __dxlog_file15,
4651
- L: 222,
4629
+ F: __dxlog_file14,
4630
+ L: 240,
4652
4631
  S: this,
4653
4632
  C: (f, a) => f(...a)
4654
4633
  });
@@ -4668,10 +4647,10 @@ var ServiceContext = class {
4668
4647
  };
4669
4648
  this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.keyring, signingContext, this.feedStore, this.automergeHost, this._runtimeParams);
4670
4649
  await this.dataSpaceManager.open();
4671
- this._handlerFactories.set(Invitation6.Kind.SPACE, (invitation) => {
4672
- invariant14(this.dataSpaceManager, "dataSpaceManager not initialized yet", {
4673
- F: __dxlog_file15,
4674
- L: 246,
4650
+ this._handlerFactories.set(Invitation5.Kind.SPACE, (invitation) => {
4651
+ invariant13(this.dataSpaceManager, "dataSpaceManager not initialized yet", {
4652
+ F: __dxlog_file14,
4653
+ L: 264,
4675
4654
  S: this,
4676
4655
  A: [
4677
4656
  "this.dataSpaceManager",
@@ -4694,8 +4673,8 @@ var ServiceContext = class {
4694
4673
  log12("dataSpaceManager not initialized yet, ignoring space admission", {
4695
4674
  details: assertion
4696
4675
  }, {
4697
- F: __dxlog_file15,
4698
- L: 262,
4676
+ F: __dxlog_file14,
4677
+ L: 280,
4699
4678
  S: this,
4700
4679
  C: (f, a) => f(...a)
4701
4680
  });
@@ -4705,8 +4684,8 @@ var ServiceContext = class {
4705
4684
  log12("space already exists, ignoring space admission", {
4706
4685
  details: assertion
4707
4686
  }, {
4708
- F: __dxlog_file15,
4709
- L: 266,
4687
+ F: __dxlog_file14,
4688
+ L: 284,
4710
4689
  S: this,
4711
4690
  C: (f, a) => f(...a)
4712
4691
  });
@@ -4716,8 +4695,8 @@ var ServiceContext = class {
4716
4695
  log12("accepting space recorded in halo", {
4717
4696
  details: assertion
4718
4697
  }, {
4719
- F: __dxlog_file15,
4720
- L: 271,
4698
+ F: __dxlog_file14,
4699
+ L: 289,
4721
4700
  S: this,
4722
4701
  C: (f, a) => f(...a)
4723
4702
  });
@@ -4727,8 +4706,8 @@ var ServiceContext = class {
4727
4706
  });
4728
4707
  } catch (err) {
4729
4708
  log12.catch(err, void 0, {
4730
- F: __dxlog_file15,
4731
- L: 277,
4709
+ F: __dxlog_file14,
4710
+ L: 295,
4732
4711
  S: this,
4733
4712
  C: (f, a) => f(...a)
4734
4713
  });
@@ -4740,7 +4719,7 @@ var ServiceContext = class {
4740
4719
  };
4741
4720
  _ts_decorate6([
4742
4721
  Trace2.span()
4743
- ], ServiceContext.prototype, "open", null);
4722
+ ], ServiceContext.prototype, "_open", null);
4744
4723
  _ts_decorate6([
4745
4724
  Trace2.span()
4746
4725
  ], ServiceContext.prototype, "_initialize", null);
@@ -4773,190 +4752,265 @@ var ServiceRegistry = class {
4773
4752
  }
4774
4753
  };
4775
4754
 
4776
- // packages/sdk/client-services/src/packlets/locks/browser.ts
4777
- import { asyncTimeout as asyncTimeout2, Trigger as Trigger6 } from "@dxos/async";
4778
- import { RESOURCE_LOCK_TIMEOUT } from "@dxos/client-protocol";
4779
- import { log as log13, logInfo } from "@dxos/log";
4780
- function _ts_decorate7(decorators, target, key, desc) {
4781
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4782
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4783
- r = Reflect.decorate(decorators, target, key, desc);
4784
- else
4785
- for (var i = decorators.length - 1; i >= 0; i--)
4786
- if (d = decorators[i])
4787
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4788
- return c > 3 && r && Object.defineProperty(target, key, r), r;
4789
- }
4790
- var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/locks/browser.ts";
4791
- var Message;
4792
- (function(Message2) {
4793
- Message2["ACQUIRING"] = "acquiring";
4794
- })(Message || (Message = {}));
4795
- var Lock = class {
4796
- constructor({ lockKey, onAcquire, onRelease }) {
4797
- this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
4798
- this._releaseTrigger = new Trigger6();
4799
- this._lockKey = lockKey;
4800
- this._onAcquire = onAcquire;
4801
- this._onRelease = onRelease;
4802
- this._broadcastChannel.onmessage = this._onMessage.bind(this);
4803
- }
4804
- get lockKey() {
4805
- return this._lockKey;
4806
- }
4807
- async acquire() {
4808
- this._broadcastChannel.postMessage({
4809
- message: "acquiring"
4810
- });
4811
- try {
4812
- log13("aquiring lock...", void 0, {
4813
- F: __dxlog_file16,
4814
- L: 42,
4815
- S: this,
4816
- C: (f, a) => f(...a)
4817
- });
4818
- await asyncTimeout2(this._requestLock(), RESOURCE_LOCK_TIMEOUT);
4819
- log13("acquired lock", void 0, {
4820
- F: __dxlog_file16,
4821
- L: 44,
4822
- S: this,
4823
- C: (f, a) => f(...a)
4824
- });
4825
- } catch {
4826
- log13("stealing lock...", void 0, {
4827
- F: __dxlog_file16,
4828
- L: 46,
4829
- S: this,
4830
- C: (f, a) => f(...a)
4831
- });
4832
- await this._requestLock(true);
4833
- log13("stolen lock", void 0, {
4834
- F: __dxlog_file16,
4835
- L: 48,
4836
- S: this,
4837
- C: (f, a) => f(...a)
4838
- });
4755
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts
4756
+ import { getFirstStreamValue } from "@dxos/codec-protobuf";
4757
+ import { credentialTypeFilter } from "@dxos/credentials";
4758
+ import { invariant as invariant14 } from "@dxos/invariant";
4759
+ import { STORAGE_VERSION as STORAGE_VERSION2 } from "@dxos/protocols";
4760
+ import { SpaceMember as SpaceMember3 } from "@dxos/protocols/proto/dxos/client/services";
4761
+ import { TRACE_PROCESSOR } from "@dxos/tracing";
4762
+
4763
+ // packages/sdk/client-services/src/version.ts
4764
+ var DXOS_VERSION = "0.4.10-main.b30eb88";
4765
+
4766
+ // packages/sdk/client-services/src/packlets/services/platform.ts
4767
+ import { Platform } from "@dxos/protocols/proto/dxos/client/services";
4768
+ var getPlatform = () => {
4769
+ if (process.browser) {
4770
+ if (typeof window !== "undefined") {
4771
+ const { userAgent } = window.navigator;
4772
+ return {
4773
+ type: Platform.PLATFORM_TYPE.BROWSER,
4774
+ userAgent,
4775
+ uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1e3)
4776
+ };
4777
+ } else {
4778
+ return {
4779
+ type: Platform.PLATFORM_TYPE.SHARED_WORKER,
4780
+ uptime: Math.floor((Date.now() - performance.timeOrigin) / 1e3)
4781
+ };
4839
4782
  }
4783
+ } else {
4784
+ const { platform: platform2, version, arch } = process;
4785
+ return {
4786
+ type: Platform.PLATFORM_TYPE.NODE,
4787
+ platform: platform2,
4788
+ arch,
4789
+ runtime: version,
4790
+ uptime: Math.floor(process.uptime()),
4791
+ memory: process.memoryUsage()
4792
+ };
4840
4793
  }
4841
- async release() {
4842
- this._releaseTrigger.wake();
4794
+ };
4795
+
4796
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts
4797
+ var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts";
4798
+ var DEFAULT_TIMEOUT = 1e3;
4799
+ var createDiagnostics = async (clientServices, serviceContext, config) => {
4800
+ const diagnostics = {
4801
+ created: (/* @__PURE__ */ new Date()).toISOString(),
4802
+ platform: getPlatform(),
4803
+ client: {
4804
+ version: DXOS_VERSION,
4805
+ storage: {
4806
+ version: STORAGE_VERSION2
4807
+ }
4808
+ },
4809
+ trace: TRACE_PROCESSOR.getDiagnostics()
4810
+ };
4811
+ {
4812
+ invariant14(clientServices.LoggingService, "SystemService is not available.", {
4813
+ F: __dxlog_file15,
4814
+ L: 108,
4815
+ S: void 0,
4816
+ A: [
4817
+ "clientServices.LoggingService",
4818
+ "'SystemService is not available.'"
4819
+ ]
4820
+ });
4821
+ diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {
4822
+ timeout: DEFAULT_TIMEOUT
4823
+ }).catch(() => void 0);
4843
4824
  }
4844
- _onMessage(event) {
4845
- if (event.data.message === "acquiring") {
4846
- this._releaseTrigger.wake();
4825
+ if (typeof navigator !== "undefined" && navigator.storage) {
4826
+ const map = /* @__PURE__ */ new Map();
4827
+ const dir = await navigator.storage.getDirectory();
4828
+ for await (const filename of dir?.keys()) {
4829
+ const idx = filename.indexOf("-", filename.indexOf("-") + 1);
4830
+ if (idx === -1) {
4831
+ continue;
4832
+ }
4833
+ map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
4847
4834
  }
4835
+ diagnostics.storage = Array.from(map.entries()).sort((a, b) => b[1] - a[1]).map(([file, count]) => ({
4836
+ file,
4837
+ count
4838
+ }));
4848
4839
  }
4849
- async _requestLock(steal = false) {
4850
- log13("requesting lock...", {
4851
- steal
4852
- }, {
4853
- F: __dxlog_file16,
4854
- L: 63,
4855
- S: this,
4856
- C: (f, a) => f(...a)
4857
- });
4858
- const acquired = new Trigger6();
4859
- void navigator.locks.request(this._lockKey, {
4860
- steal
4861
- }, async () => {
4862
- await this._onAcquire?.();
4863
- acquired.wake();
4864
- this._releaseTrigger = new Trigger6();
4865
- await this._releaseTrigger.wait();
4866
- log13("releasing lock...", void 0, {
4867
- F: __dxlog_file16,
4868
- L: 72,
4869
- S: this,
4870
- C: (f, a) => f(...a)
4871
- });
4872
- await this._onRelease?.();
4873
- log13("released lock", void 0, {
4874
- F: __dxlog_file16,
4875
- L: 74,
4876
- S: this,
4877
- C: (f, a) => f(...a)
4878
- });
4879
- }).catch(async () => {
4880
- await this._onRelease?.();
4881
- });
4882
- await acquired.wait();
4883
- log13("recieved lock", {
4884
- steal
4885
- }, {
4886
- F: __dxlog_file16,
4887
- L: 81,
4888
- S: this,
4889
- C: (f, a) => f(...a)
4890
- });
4840
+ const identity = serviceContext.identityManager.identity;
4841
+ if (identity) {
4842
+ diagnostics.identity = {
4843
+ identityKey: identity.identityKey,
4844
+ spaceKey: identity.space.key,
4845
+ profile: identity.profileDocument
4846
+ };
4847
+ const { devices } = await getFirstStreamValue(clientServices.DevicesService.queryDevices(), {
4848
+ timeout: DEFAULT_TIMEOUT
4849
+ }).catch(() => void 0) ?? {};
4850
+ diagnostics.devices = devices;
4851
+ if (serviceContext.dataSpaceManager) {
4852
+ diagnostics.spaces = await Promise.all(Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? []);
4853
+ }
4854
+ const { feeds = [] } = await getFirstStreamValue(clientServices.DevtoolsHost.subscribeToFeeds({}), {
4855
+ timeout: DEFAULT_TIMEOUT
4856
+ }).catch(() => void 0) ?? {};
4857
+ diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({
4858
+ feedKey,
4859
+ bytes,
4860
+ length
4861
+ }));
4862
+ const status = await getFirstStreamValue(clientServices.NetworkService.queryStatus(), {
4863
+ timeout: DEFAULT_TIMEOUT
4864
+ }).catch(() => void 0);
4865
+ diagnostics.networkStatus = status;
4866
+ diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;
4891
4867
  }
4868
+ diagnostics.config = config.values;
4869
+ return diagnostics;
4892
4870
  };
4893
- _ts_decorate7([
4894
- logInfo
4895
- ], Lock.prototype, "lockKey", null);
4896
- var isLocked = (lockPath) => {
4897
- throw new Error("Not implemented");
4871
+ var getSpaceStats = async (space) => {
4872
+ const stats = {
4873
+ key: space.key,
4874
+ metrics: space.metrics,
4875
+ epochs: space.inner.spaceState.credentials.filter(credentialTypeFilter("dxos.halo.credentials.Epoch")).map((credential) => ({
4876
+ ...credential.subject.assertion,
4877
+ id: credential.id
4878
+ })),
4879
+ members: Array.from(space.inner.spaceState.members.values()).map((member) => ({
4880
+ identity: {
4881
+ identityKey: member.key,
4882
+ profile: {
4883
+ displayName: member.assertion.profile?.displayName
4884
+ }
4885
+ },
4886
+ presence: space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0 ? SpaceMember3.PresenceState.ONLINE : SpaceMember3.PresenceState.OFFLINE
4887
+ })),
4888
+ pipeline: {
4889
+ // TODO(burdon): Pick properties from credentials if needed.
4890
+ currentEpoch: space.automergeSpaceState.lastEpoch,
4891
+ appliedEpoch: space.automergeSpaceState.lastEpoch,
4892
+ controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),
4893
+ currentControlTimeframe: space.inner.controlPipeline.state.timeframe,
4894
+ targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,
4895
+ totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe
4896
+ }
4897
+ };
4898
+ if (stats.metrics) {
4899
+ const { open, ready } = stats.metrics;
4900
+ stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();
4901
+ }
4902
+ return stats;
4898
4903
  };
4899
4904
 
4900
- // packages/sdk/client-services/src/packlets/storage/storage.ts
4901
- import { DX_DATA } from "@dxos/client-protocol";
4902
- import { InvalidConfigError } from "@dxos/protocols";
4903
- import { Runtime } from "@dxos/protocols/proto/dxos/config";
4904
- import { createStorage, StorageType } from "@dxos/random-access-storage";
4905
- import { isNode as isNode2 } from "@dxos/util";
4906
- var StorageDriver = Runtime.Client.Storage.StorageDriver;
4907
- var createStorageObjects = (config) => {
4908
- const { persistent = false, keyStore, dataStore, dataRoot = isNode2() ? DX_DATA : "dxos/storage" } = config ?? {};
4909
- if (persistent && dataStore === StorageDriver.RAM) {
4910
- throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
4911
- }
4912
- if (!persistent && dataStore !== void 0 && dataStore !== StorageDriver.RAM) {
4913
- throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
4914
- }
4915
- if (persistent && keyStore === StorageDriver.RAM) {
4916
- throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
4917
- }
4918
- if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== void 0) {
4919
- throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
4920
- }
4905
+ // packages/sdk/client-services/src/packlets/diagnostics/browser-diagnostics-broadcast.ts
4906
+ import { Trigger as Trigger6 } from "@dxos/async";
4907
+ import { log as log13 } from "@dxos/log";
4908
+ var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/diagnostics/browser-diagnostics-broadcast.ts";
4909
+ var CHANNEL_NAME = "dxos.diagnostics.broadcast";
4910
+ var MessageType;
4911
+ (function(MessageType2) {
4912
+ MessageType2["PROBE"] = "probe";
4913
+ MessageType2["PROBE_ACK"] = "probe-ack";
4914
+ MessageType2["REQUEST_DIAGNOSTICS"] = "request-diagnostics";
4915
+ MessageType2["RECEIVE_DIAGNOSTICS"] = "receive-diagnostics";
4916
+ })(MessageType || (MessageType = {}));
4917
+ var createCollectDiagnosticsBroadcastSender = () => {
4921
4918
  return {
4922
- storage: createStorage({
4923
- type: persistent ? toStorageType(dataStore) : StorageType.RAM,
4924
- root: `${dataRoot}/`
4925
- })
4919
+ broadcastDiagnosticsRequest: async () => {
4920
+ let expectedResponse = "probe-ack";
4921
+ let channel;
4922
+ try {
4923
+ const trigger = new Trigger6();
4924
+ channel = new BroadcastChannel(CHANNEL_NAME);
4925
+ channel.onmessage = (msg) => {
4926
+ if (expectedResponse === msg.data.type) {
4927
+ trigger.wake(msg.data);
4928
+ }
4929
+ };
4930
+ channel.postMessage({
4931
+ type: "probe"
4932
+ });
4933
+ await trigger.wait({
4934
+ timeout: 200
4935
+ });
4936
+ expectedResponse = "receive-diagnostics";
4937
+ trigger.reset();
4938
+ channel.postMessage({
4939
+ type: "request-diagnostics"
4940
+ });
4941
+ const diagnostics = await trigger.wait({
4942
+ timeout: 5e3
4943
+ });
4944
+ return diagnostics.payload;
4945
+ } catch (e) {
4946
+ const errorDescription = e instanceof Error ? e.message : JSON.stringify(e);
4947
+ return {
4948
+ expectedResponse,
4949
+ errorDescription
4950
+ };
4951
+ } finally {
4952
+ safeClose(channel);
4953
+ }
4954
+ }
4955
+ };
4956
+ };
4957
+ var createCollectDiagnosticsBroadcastHandler = (systemService) => {
4958
+ let channel;
4959
+ return {
4960
+ start: () => {
4961
+ channel = new BroadcastChannel(CHANNEL_NAME);
4962
+ channel.onmessage = async (message) => {
4963
+ try {
4964
+ if (message.data.type === "probe") {
4965
+ channel?.postMessage({
4966
+ type: "probe-ack"
4967
+ });
4968
+ } else if (message.data.type === "request-diagnostics") {
4969
+ const diagnostics = await systemService.getDiagnostics({});
4970
+ channel?.postMessage({
4971
+ type: "receive-diagnostics",
4972
+ payload: diagnostics
4973
+ });
4974
+ }
4975
+ } catch (error) {
4976
+ log13.catch(error, void 0, {
4977
+ F: __dxlog_file16,
4978
+ L: 77,
4979
+ S: void 0,
4980
+ C: (f, a) => f(...a)
4981
+ });
4982
+ }
4983
+ };
4984
+ },
4985
+ stop: () => {
4986
+ safeClose(channel);
4987
+ channel = void 0;
4988
+ }
4926
4989
  };
4927
4990
  };
4928
- var toStorageType = (type) => {
4929
- switch (type) {
4930
- case void 0:
4931
- return void 0;
4932
- case StorageDriver.RAM:
4933
- return StorageType.RAM;
4934
- case StorageDriver.CHROME:
4935
- return StorageType.CHROME;
4936
- case StorageDriver.FIREFOX:
4937
- return StorageType.FIREFOX;
4938
- case StorageDriver.IDB:
4939
- return StorageType.IDB;
4940
- case StorageDriver.NODE:
4941
- return StorageType.NODE;
4942
- case StorageDriver.WEBFS:
4943
- return StorageType.WEBFS;
4944
- default:
4945
- throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
4991
+ var safeClose = (channel) => {
4992
+ try {
4993
+ channel?.close();
4994
+ } catch (e) {
4946
4995
  }
4947
4996
  };
4948
4997
 
4998
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
4999
+ import { ConfigResource } from "@dxos/config";
5000
+ import { GetDiagnosticsRequest as GetDiagnosticsRequest2 } from "@dxos/protocols/proto/dxos/client/services";
5001
+ import { TRACE_PROCESSOR as TRACE_PROCESSOR3 } from "@dxos/tracing";
5002
+ import { jsonKeyReplacer as jsonKeyReplacer2, nonNullable } from "@dxos/util";
5003
+
4949
5004
  // packages/sdk/client-services/src/packlets/services/service-host.ts
4950
- import { Event as Event9, sleep as sleep3, synchronized as synchronized3 } from "@dxos/async";
4951
- import { clientServiceBundle, defaultKey, PropertiesSchema } from "@dxos/client-protocol";
4952
- import { Context as Context11 } from "@dxos/context";
4953
- import { DataServiceImpl } from "@dxos/echo-pipeline";
4954
- import * as E from "@dxos/echo-schema";
4955
- import { createRawObjectDoc } from "@dxos/echo-schema";
4956
- import { IndexServiceImpl } from "@dxos/indexing";
5005
+ import { Event as Event9, synchronized as synchronized3 } from "@dxos/async";
5006
+ import { clientServiceBundle, defaultKey, Properties } from "@dxos/client-protocol";
5007
+ import { Context as Context10 } from "@dxos/context";
5008
+ import { DataServiceImpl, encodeReference } from "@dxos/echo-pipeline";
5009
+ import { getTypeReference } from "@dxos/echo-schema";
5010
+ import { QueryServiceImpl } from "@dxos/indexing";
4957
5011
  import { invariant as invariant16 } from "@dxos/invariant";
4958
- import { PublicKey as PublicKey12 } from "@dxos/keys";
4959
- import { log as log15 } from "@dxos/log";
5012
+ import { PublicKey as PublicKey13 } from "@dxos/keys";
5013
+ import { log as log16 } from "@dxos/log";
4960
5014
  import { WebsocketSignalManager } from "@dxos/messaging";
4961
5015
  import { NetworkManager, createSimplePeerTransportFactory } from "@dxos/network-manager";
4962
5016
  import { trace as trace9 } from "@dxos/protocols";
@@ -5047,11 +5101,135 @@ var DevicesServiceImpl = class {
5047
5101
  }
5048
5102
  };
5049
5103
 
5104
+ // packages/sdk/client-services/src/packlets/locks/browser.ts
5105
+ import { asyncTimeout as asyncTimeout2, Trigger as Trigger7 } from "@dxos/async";
5106
+ import { RESOURCE_LOCK_TIMEOUT } from "@dxos/client-protocol";
5107
+ import { log as log14, logInfo } from "@dxos/log";
5108
+ function _ts_decorate7(decorators, target, key, desc) {
5109
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5110
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
5111
+ r = Reflect.decorate(decorators, target, key, desc);
5112
+ else
5113
+ for (var i = decorators.length - 1; i >= 0; i--)
5114
+ if (d = decorators[i])
5115
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5116
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
5117
+ }
5118
+ var __dxlog_file18 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/locks/browser.ts";
5119
+ var Message;
5120
+ (function(Message2) {
5121
+ Message2["ACQUIRING"] = "acquiring";
5122
+ })(Message || (Message = {}));
5123
+ var Lock = class {
5124
+ constructor({ lockKey, onAcquire, onRelease }) {
5125
+ this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
5126
+ this._releaseTrigger = new Trigger7();
5127
+ this._lockKey = lockKey;
5128
+ this._onAcquire = onAcquire;
5129
+ this._onRelease = onRelease;
5130
+ this._broadcastChannel.onmessage = this._onMessage.bind(this);
5131
+ }
5132
+ get lockKey() {
5133
+ return this._lockKey;
5134
+ }
5135
+ async acquire() {
5136
+ this._broadcastChannel.postMessage({
5137
+ message: "acquiring"
5138
+ });
5139
+ try {
5140
+ log14("aquiring lock...", void 0, {
5141
+ F: __dxlog_file18,
5142
+ L: 42,
5143
+ S: this,
5144
+ C: (f, a) => f(...a)
5145
+ });
5146
+ await asyncTimeout2(this._requestLock(), RESOURCE_LOCK_TIMEOUT);
5147
+ log14("acquired lock", void 0, {
5148
+ F: __dxlog_file18,
5149
+ L: 44,
5150
+ S: this,
5151
+ C: (f, a) => f(...a)
5152
+ });
5153
+ } catch {
5154
+ log14("stealing lock...", void 0, {
5155
+ F: __dxlog_file18,
5156
+ L: 46,
5157
+ S: this,
5158
+ C: (f, a) => f(...a)
5159
+ });
5160
+ await this._requestLock(true);
5161
+ log14("stolen lock", void 0, {
5162
+ F: __dxlog_file18,
5163
+ L: 48,
5164
+ S: this,
5165
+ C: (f, a) => f(...a)
5166
+ });
5167
+ }
5168
+ }
5169
+ async release() {
5170
+ this._releaseTrigger.wake();
5171
+ }
5172
+ _onMessage(event) {
5173
+ if (event.data.message === "acquiring") {
5174
+ this._releaseTrigger.wake();
5175
+ }
5176
+ }
5177
+ async _requestLock(steal = false) {
5178
+ log14("requesting lock...", {
5179
+ steal
5180
+ }, {
5181
+ F: __dxlog_file18,
5182
+ L: 63,
5183
+ S: this,
5184
+ C: (f, a) => f(...a)
5185
+ });
5186
+ const acquired = new Trigger7();
5187
+ void navigator.locks.request(this._lockKey, {
5188
+ steal
5189
+ }, async () => {
5190
+ await this._onAcquire?.();
5191
+ acquired.wake();
5192
+ this._releaseTrigger = new Trigger7();
5193
+ await this._releaseTrigger.wait();
5194
+ log14("releasing lock...", void 0, {
5195
+ F: __dxlog_file18,
5196
+ L: 72,
5197
+ S: this,
5198
+ C: (f, a) => f(...a)
5199
+ });
5200
+ await this._onRelease?.();
5201
+ log14("released lock", void 0, {
5202
+ F: __dxlog_file18,
5203
+ L: 74,
5204
+ S: this,
5205
+ C: (f, a) => f(...a)
5206
+ });
5207
+ }).catch(async () => {
5208
+ await this._onRelease?.();
5209
+ });
5210
+ await acquired.wait();
5211
+ log14("recieved lock", {
5212
+ steal
5213
+ }, {
5214
+ F: __dxlog_file18,
5215
+ L: 81,
5216
+ S: this,
5217
+ C: (f, a) => f(...a)
5218
+ });
5219
+ }
5220
+ };
5221
+ _ts_decorate7([
5222
+ logInfo
5223
+ ], Lock.prototype, "lockKey", null);
5224
+ var isLocked = (lockPath) => {
5225
+ throw new Error("Not implemented");
5226
+ };
5227
+
5050
5228
  // packages/sdk/client-services/src/packlets/logging/logging-service.ts
5051
5229
  import { Event as Event8 } from "@dxos/async";
5052
5230
  import { Stream as Stream12 } from "@dxos/codec-protobuf";
5053
5231
  import { PublicKey as PublicKey11 } from "@dxos/keys";
5054
- import { getContextFromEntry, log as log14 } from "@dxos/log";
5232
+ import { getContextFromEntry, log as log15 } from "@dxos/log";
5055
5233
  import { QueryLogsRequest } from "@dxos/protocols/proto/dxos/client/services";
5056
5234
  import { getDebugName, jsonify, numericalValues, tracer } from "@dxos/util";
5057
5235
  var LoggingServiceImpl = class {
@@ -5064,11 +5242,11 @@ var LoggingServiceImpl = class {
5064
5242
  };
5065
5243
  }
5066
5244
  async open() {
5067
- log14.runtimeConfig.processors.push(this._logProcessor);
5245
+ log15.runtimeConfig.processors.push(this._logProcessor);
5068
5246
  }
5069
5247
  async close() {
5070
- const index = log14.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
5071
- log14.runtimeConfig.processors.splice(index, 1);
5248
+ const index = log15.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
5249
+ log15.runtimeConfig.processors.splice(index, 1);
5072
5250
  }
5073
5251
  async controlMetrics({ reset, record }) {
5074
5252
  if (reset) {
@@ -5153,12 +5331,12 @@ var LoggingServiceImpl = class {
5153
5331
  });
5154
5332
  }
5155
5333
  };
5156
- var matchFilter = (filter, level, path, options) => {
5334
+ var matchFilter = (filter, level, path2, options) => {
5157
5335
  switch (options) {
5158
5336
  case QueryLogsRequest.MatchingOptions.INCLUSIVE:
5159
- return level >= filter.level && (!filter.pattern || path.includes(filter.pattern));
5337
+ return level >= filter.level && (!filter.pattern || path2.includes(filter.pattern));
5160
5338
  case QueryLogsRequest.MatchingOptions.EXPLICIT:
5161
- return level === filter.level && (!filter.pattern || path.includes(filter.pattern));
5339
+ return level === filter.level && (!filter.pattern || path2.includes(filter.pattern));
5162
5340
  }
5163
5341
  };
5164
5342
  var shouldLog = (entry2, request) => {
@@ -5204,6 +5382,80 @@ var NetworkServiceImpl = class {
5204
5382
  }
5205
5383
  };
5206
5384
 
5385
+ // packages/sdk/client-services/src/packlets/storage/storage.ts
5386
+ import { InvalidConfigError } from "@dxos/protocols";
5387
+ import { Runtime as Runtime2 } from "@dxos/protocols/proto/dxos/config";
5388
+ import { createStorage, StorageType } from "@dxos/random-access-storage";
5389
+
5390
+ // packages/sdk/client-services/src/packlets/storage/util.ts
5391
+ import { DX_DATA } from "@dxos/client-protocol";
5392
+ import { Runtime } from "@dxos/protocols/proto/dxos/config";
5393
+ import { isNode as isNode2 } from "@dxos/util";
5394
+ var getRootPath = (config) => {
5395
+ const { dataRoot = isNode2() ? DX_DATA : "dxos/storage" } = config ?? {};
5396
+ return `${dataRoot}/`;
5397
+ };
5398
+ var isPersistent = (config) => {
5399
+ const { persistent = false } = config ?? {};
5400
+ return config.dataStore !== void 0 && config.dataStore !== Runtime.Client.Storage.StorageDriver.RAM || persistent;
5401
+ };
5402
+
5403
+ // packages/sdk/client-services/src/packlets/storage/storage.ts
5404
+ var StorageDriver = Runtime2.Client.Storage.StorageDriver;
5405
+ var createStorageObjects = (config) => {
5406
+ const { persistent = false, keyStore, dataStore } = config ?? {};
5407
+ if (persistent && dataStore === StorageDriver.RAM) {
5408
+ throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
5409
+ }
5410
+ if (!persistent && dataStore !== void 0 && dataStore !== StorageDriver.RAM) {
5411
+ throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
5412
+ }
5413
+ if (persistent && keyStore === StorageDriver.RAM) {
5414
+ throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
5415
+ }
5416
+ if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== void 0) {
5417
+ throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
5418
+ }
5419
+ return {
5420
+ storage: createStorage({
5421
+ type: persistent ? toStorageType(dataStore) : StorageType.RAM,
5422
+ root: getRootPath(config)
5423
+ })
5424
+ };
5425
+ };
5426
+ var toStorageType = (type) => {
5427
+ switch (type) {
5428
+ case void 0:
5429
+ return void 0;
5430
+ case StorageDriver.RAM:
5431
+ return StorageType.RAM;
5432
+ case StorageDriver.CHROME:
5433
+ return StorageType.CHROME;
5434
+ case StorageDriver.FIREFOX:
5435
+ return StorageType.FIREFOX;
5436
+ case StorageDriver.IDB:
5437
+ return StorageType.IDB;
5438
+ case StorageDriver.NODE:
5439
+ return StorageType.NODE;
5440
+ case StorageDriver.WEBFS:
5441
+ return StorageType.WEBFS;
5442
+ default:
5443
+ throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
5444
+ }
5445
+ };
5446
+
5447
+ // packages/sdk/client-services/src/packlets/storage/level.ts
5448
+ import { Level } from "level";
5449
+ import path from "@dxos/node-std/path";
5450
+ import { PublicKey as PublicKey12 } from "@dxos/keys";
5451
+ var createLevel = async (config) => {
5452
+ const persistent = isPersistent(config);
5453
+ const storagePath = persistent ? path.join(getRootPath(config), "level") : `/tmp/dxos-${PublicKey12.random().toHex()}`;
5454
+ const level = new Level(storagePath);
5455
+ await level.open();
5456
+ return level;
5457
+ };
5458
+
5207
5459
  // packages/sdk/client-services/src/packlets/system/system-service.ts
5208
5460
  import { Stream as Stream14 } from "@dxos/codec-protobuf";
5209
5461
  import { GetDiagnosticsRequest } from "@dxos/protocols/proto/dxos/client/services";
@@ -5272,13 +5524,14 @@ function _ts_decorate8(decorators, target, key, desc) {
5272
5524
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5273
5525
  return c > 3 && r && Object.defineProperty(target, key, r), r;
5274
5526
  }
5275
- var __dxlog_file18 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-host.ts";
5527
+ var __dxlog_file19 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-host.ts";
5276
5528
  var ClientServicesHost = class {
5277
5529
  constructor({
5278
5530
  config,
5279
5531
  transportFactory,
5280
5532
  signalManager,
5281
5533
  storage,
5534
+ level,
5282
5535
  // TODO(wittjosiah): Turn this on by default.
5283
5536
  lockKey,
5284
5537
  callbacks,
@@ -5289,6 +5542,7 @@ var ClientServicesHost = class {
5289
5542
  this._opening = false;
5290
5543
  this._open = false;
5291
5544
  this._storage = storage;
5545
+ this._level = level;
5292
5546
  this._callbacks = callbacks;
5293
5547
  this._runtimeParams = runtimeParams;
5294
5548
  if (config) {
@@ -5303,7 +5557,7 @@ var ClientServicesHost = class {
5303
5557
  lockKey,
5304
5558
  onAcquire: () => {
5305
5559
  if (!this._opening) {
5306
- void this.open(new Context11());
5560
+ void this.open(new Context10());
5307
5561
  }
5308
5562
  },
5309
5563
  onRelease: () => this.close()
@@ -5327,6 +5581,7 @@ var ClientServicesHost = class {
5327
5581
  await this.reset();
5328
5582
  }
5329
5583
  });
5584
+ this.diagnosticsBroadcastHandler = createCollectDiagnosticsBroadcastHandler(this._systemService);
5330
5585
  this._loggingService = new LoggingServiceImpl();
5331
5586
  this._serviceRegistry = new ServiceRegistry(clientServiceBundle, {
5332
5587
  SystemService: this._systemService,
@@ -5358,24 +5613,24 @@ var ClientServicesHost = class {
5358
5613
  */
5359
5614
  initialize({ config, ...options }) {
5360
5615
  invariant16(!this._open, "service host is open", {
5361
- F: __dxlog_file18,
5362
- L: 180,
5616
+ F: __dxlog_file19,
5617
+ L: 198,
5363
5618
  S: this,
5364
5619
  A: [
5365
5620
  "!this._open",
5366
5621
  "'service host is open'"
5367
5622
  ]
5368
5623
  });
5369
- log15("initializing...", void 0, {
5370
- F: __dxlog_file18,
5371
- L: 181,
5624
+ log16("initializing...", void 0, {
5625
+ F: __dxlog_file19,
5626
+ L: 199,
5372
5627
  S: this,
5373
5628
  C: (f, a) => f(...a)
5374
5629
  });
5375
5630
  if (config) {
5376
5631
  invariant16(!this._config, "config already set", {
5377
- F: __dxlog_file18,
5378
- L: 184,
5632
+ F: __dxlog_file19,
5633
+ L: 202,
5379
5634
  S: this,
5380
5635
  A: [
5381
5636
  "!this._config",
@@ -5388,9 +5643,9 @@ var ClientServicesHost = class {
5388
5643
  }
5389
5644
  }
5390
5645
  if (!options.signalManager) {
5391
- log15.warn("running signaling without telemetry metadata.", void 0, {
5392
- F: __dxlog_file18,
5393
- L: 192,
5646
+ log16.warn("running signaling without telemetry metadata.", void 0, {
5647
+ F: __dxlog_file19,
5648
+ L: 210,
5394
5649
  S: this,
5395
5650
  C: (f, a) => f(...a)
5396
5651
  });
@@ -5400,8 +5655,8 @@ var ClientServicesHost = class {
5400
5655
  }), signalManager = new WebsocketSignalManager(this._config?.get("runtime.services.signaling") ?? []) } = options;
5401
5656
  this._signalManager = signalManager;
5402
5657
  invariant16(!this._networkManager, "network manager already set", {
5403
- F: __dxlog_file18,
5404
- L: 203,
5658
+ F: __dxlog_file19,
5659
+ L: 221,
5405
5660
  S: this,
5406
5661
  A: [
5407
5662
  "!this._networkManager",
@@ -5413,9 +5668,9 @@ var ClientServicesHost = class {
5413
5668
  transportFactory,
5414
5669
  signalManager
5415
5670
  });
5416
- log15("initialized", void 0, {
5417
- F: __dxlog_file18,
5418
- L: 210,
5671
+ log16("initialized", void 0, {
5672
+ F: __dxlog_file19,
5673
+ L: 228,
5419
5674
  S: this,
5420
5675
  C: (f, a) => f(...a)
5421
5676
  });
@@ -5424,18 +5679,18 @@ var ClientServicesHost = class {
5424
5679
  if (this._open) {
5425
5680
  return;
5426
5681
  }
5427
- const traceId = PublicKey12.random().toHex();
5428
- log15.trace("dxos.client-services.host.open", trace9.begin({
5682
+ const traceId = PublicKey13.random().toHex();
5683
+ log16.trace("dxos.client-services.host.open", trace9.begin({
5429
5684
  id: traceId
5430
5685
  }), {
5431
- F: __dxlog_file18,
5432
- L: 221,
5686
+ F: __dxlog_file19,
5687
+ L: 239,
5433
5688
  S: this,
5434
5689
  C: (f, a) => f(...a)
5435
5690
  });
5436
5691
  invariant16(this._config, "config not set", {
5437
- F: __dxlog_file18,
5438
- L: 223,
5692
+ F: __dxlog_file19,
5693
+ L: 241,
5439
5694
  S: this,
5440
5695
  A: [
5441
5696
  "this._config",
@@ -5443,8 +5698,8 @@ var ClientServicesHost = class {
5443
5698
  ]
5444
5699
  });
5445
5700
  invariant16(this._storage, "storage not set", {
5446
- F: __dxlog_file18,
5447
- L: 224,
5701
+ F: __dxlog_file19,
5702
+ L: 242,
5448
5703
  S: this,
5449
5704
  A: [
5450
5705
  "this._storage",
@@ -5452,8 +5707,8 @@ var ClientServicesHost = class {
5452
5707
  ]
5453
5708
  });
5454
5709
  invariant16(this._signalManager, "signal manager not set", {
5455
- F: __dxlog_file18,
5456
- L: 225,
5710
+ F: __dxlog_file19,
5711
+ L: 243,
5457
5712
  S: this,
5458
5713
  A: [
5459
5714
  "this._signalManager",
@@ -5461,8 +5716,8 @@ var ClientServicesHost = class {
5461
5716
  ]
5462
5717
  });
5463
5718
  invariant16(this._networkManager, "network manager not set", {
5464
- F: __dxlog_file18,
5465
- L: 226,
5719
+ F: __dxlog_file19,
5720
+ L: 244,
5466
5721
  S: this,
5467
5722
  A: [
5468
5723
  "this._networkManager",
@@ -5470,31 +5725,37 @@ var ClientServicesHost = class {
5470
5725
  ]
5471
5726
  });
5472
5727
  this._opening = true;
5473
- log15("opening...", {
5728
+ log16("opening...", {
5474
5729
  lockKey: this._resourceLock?.lockKey
5475
5730
  }, {
5476
- F: __dxlog_file18,
5477
- L: 229,
5731
+ F: __dxlog_file19,
5732
+ L: 247,
5478
5733
  S: this,
5479
5734
  C: (f, a) => f(...a)
5480
5735
  });
5736
+ if (!this._level) {
5737
+ this._level = await createLevel(this._config.get("runtime.client.storage", {}));
5738
+ }
5739
+ await this._level.open();
5481
5740
  await this._resourceLock?.acquire();
5482
5741
  await this._loggingService.open();
5483
- this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._signalManager, this._runtimeParams);
5742
+ this._serviceContext = new ServiceContext(this._storage, this._level, this._networkManager, this._signalManager, this._runtimeParams);
5743
+ this._queryService = new QueryServiceImpl({
5744
+ indexer: this._serviceContext.indexer,
5745
+ automergeHost: this._serviceContext.automergeHost
5746
+ });
5747
+ await this._queryService.open(ctx);
5484
5748
  this._serviceRegistry.setServices({
5485
5749
  SystemService: this._systemService,
5486
5750
  IdentityService: new IdentityServiceImpl((params) => this._createIdentity(params), this._serviceContext.identityManager, this._serviceContext.keyring, (profile) => this._serviceContext.broadcastProfileUpdate(profile)),
5487
- InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitations, (invitation) => this._serviceContext.getInvitationHandler(invitation), this._serviceContext.metadataStore),
5751
+ InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitationsManager),
5488
5752
  DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
5489
5753
  SpacesService: new SpacesServiceImpl(this._serviceContext.identityManager, this._serviceContext.spaceManager, async () => {
5490
5754
  await this._serviceContext.initialized.wait();
5491
5755
  return this._serviceContext.dataSpaceManager;
5492
5756
  }),
5493
5757
  DataService: new DataServiceImpl(this._serviceContext.automergeHost),
5494
- IndexService: new IndexServiceImpl({
5495
- indexer: this._serviceContext.indexer,
5496
- automergeHost: this._serviceContext.automergeHost
5497
- }),
5758
+ QueryService: this._queryService,
5498
5759
  NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager, this._serviceContext.signalManager),
5499
5760
  LoggingService: this._loggingService,
5500
5761
  TracingService: this._tracingService,
@@ -5506,24 +5767,6 @@ var ClientServicesHost = class {
5506
5767
  })
5507
5768
  });
5508
5769
  await this._serviceContext.open(ctx);
5509
- invariant16(this.serviceRegistry.services.InvitationsService, void 0, {
5510
- F: __dxlog_file18,
5511
- L: 290,
5512
- S: this,
5513
- A: [
5514
- "this.serviceRegistry.services.InvitationsService",
5515
- ""
5516
- ]
5517
- });
5518
- const loadedInvitations = await this.serviceRegistry.services.InvitationsService.loadPersistentInvitations();
5519
- log15("loaded persistent invitations", {
5520
- count: loadedInvitations.invitations?.length
5521
- }, {
5522
- F: __dxlog_file18,
5523
- L: 293,
5524
- S: this,
5525
- C: (f, a) => f(...a)
5526
- });
5527
5770
  const devtoolsProxy = this._config?.get("runtime.client.devtoolsProxy");
5528
5771
  if (devtoolsProxy) {
5529
5772
  this._devtoolsProxy = new WebsocketRpcClient({
@@ -5534,23 +5777,24 @@ var ClientServicesHost = class {
5534
5777
  });
5535
5778
  void this._devtoolsProxy.open();
5536
5779
  }
5780
+ this.diagnosticsBroadcastHandler.start();
5537
5781
  this._opening = false;
5538
5782
  this._open = true;
5539
5783
  this._statusUpdate.emit();
5540
5784
  const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;
5541
- log15("opened", {
5785
+ log16("opened", {
5542
5786
  deviceKey
5543
5787
  }, {
5544
- F: __dxlog_file18,
5545
- L: 310,
5788
+ F: __dxlog_file19,
5789
+ L: 330,
5546
5790
  S: this,
5547
5791
  C: (f, a) => f(...a)
5548
5792
  });
5549
- log15.trace("dxos.client-services.host.open", trace9.end({
5793
+ log16.trace("dxos.client-services.host.open", trace9.end({
5550
5794
  id: traceId
5551
5795
  }), {
5552
- F: __dxlog_file18,
5553
- L: 311,
5796
+ F: __dxlog_file19,
5797
+ L: 331,
5554
5798
  S: this,
5555
5799
  C: (f, a) => f(...a)
5556
5800
  });
@@ -5560,60 +5804,63 @@ var ClientServicesHost = class {
5560
5804
  return;
5561
5805
  }
5562
5806
  const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;
5563
- log15("closing...", {
5807
+ log16("closing...", {
5564
5808
  deviceKey
5565
5809
  }, {
5566
- F: __dxlog_file18,
5567
- L: 322,
5810
+ F: __dxlog_file19,
5811
+ L: 342,
5568
5812
  S: this,
5569
5813
  C: (f, a) => f(...a)
5570
5814
  });
5815
+ this.diagnosticsBroadcastHandler.stop();
5571
5816
  await this._devtoolsProxy?.close();
5572
5817
  this._serviceRegistry.setServices({
5573
5818
  SystemService: this._systemService
5574
5819
  });
5575
5820
  await this._loggingService.close();
5821
+ await this._queryService.close();
5576
5822
  await this._serviceContext.close();
5823
+ await this._level?.close();
5577
5824
  this._open = false;
5578
5825
  this._statusUpdate.emit();
5579
- log15("closed", {
5826
+ log16("closed", {
5580
5827
  deviceKey
5581
5828
  }, {
5582
- F: __dxlog_file18,
5583
- L: 329,
5829
+ F: __dxlog_file19,
5830
+ L: 352,
5584
5831
  S: this,
5585
5832
  C: (f, a) => f(...a)
5586
5833
  });
5587
5834
  }
5588
5835
  async reset() {
5589
- const traceId = PublicKey12.random().toHex();
5590
- log15.trace("dxos.sdk.client-services-host.reset", trace9.begin({
5836
+ const traceId = PublicKey13.random().toHex();
5837
+ log16.trace("dxos.sdk.client-services-host.reset", trace9.begin({
5591
5838
  id: traceId
5592
5839
  }), {
5593
- F: __dxlog_file18,
5594
- L: 334,
5840
+ F: __dxlog_file19,
5841
+ L: 357,
5595
5842
  S: this,
5596
5843
  C: (f, a) => f(...a)
5597
5844
  });
5598
- log15("resetting...", void 0, {
5599
- F: __dxlog_file18,
5600
- L: 336,
5845
+ log16("resetting...", void 0, {
5846
+ F: __dxlog_file19,
5847
+ L: 359,
5601
5848
  S: this,
5602
5849
  C: (f, a) => f(...a)
5603
5850
  });
5604
5851
  await this._serviceContext?.close();
5605
5852
  await this._storage.reset();
5606
- log15("reset", void 0, {
5607
- F: __dxlog_file18,
5608
- L: 339,
5853
+ log16("reset", void 0, {
5854
+ F: __dxlog_file19,
5855
+ L: 362,
5609
5856
  S: this,
5610
5857
  C: (f, a) => f(...a)
5611
5858
  });
5612
- log15.trace("dxos.sdk.client-services-host.reset", trace9.end({
5859
+ log16.trace("dxos.sdk.client-services-host.reset", trace9.end({
5613
5860
  id: traceId
5614
5861
  }), {
5615
- F: __dxlog_file18,
5616
- L: 340,
5862
+ F: __dxlog_file19,
5863
+ L: 363,
5617
5864
  S: this,
5618
5865
  C: (f, a) => f(...a)
5619
5866
  });
@@ -5625,8 +5872,8 @@ var ClientServicesHost = class {
5625
5872
  const space = await this._serviceContext.dataSpaceManager.createSpace();
5626
5873
  const automergeIndex = space.automergeSpaceState.rootUrl;
5627
5874
  invariant16(automergeIndex, void 0, {
5628
- F: __dxlog_file18,
5629
- L: 352,
5875
+ F: __dxlog_file19,
5876
+ L: 375,
5630
5877
  S: this,
5631
5878
  A: [
5632
5879
  "automergeIndex",
@@ -5635,18 +5882,25 @@ var ClientServicesHost = class {
5635
5882
  });
5636
5883
  const document = await this._serviceContext.automergeHost.repo.find(automergeIndex);
5637
5884
  await document.whenReady();
5638
- const objectDocument = createRawObjectDoc({
5639
- [defaultKey]: identity.identityKey.toHex()
5640
- }, {
5641
- type: E.getTypeReference(PropertiesSchema)
5642
- });
5885
+ const properties = {
5886
+ system: {
5887
+ type: encodeReference(getTypeReference(Properties))
5888
+ },
5889
+ data: {
5890
+ [defaultKey]: identity.identityKey.toHex()
5891
+ },
5892
+ meta: {
5893
+ keys: []
5894
+ }
5895
+ };
5896
+ const propertiesId = PublicKey13.random().toHex();
5643
5897
  document.change((doc) => {
5644
5898
  assignDeep2(doc, [
5645
5899
  "objects",
5646
- objectDocument.id
5647
- ], objectDocument.handle.docSync());
5900
+ propertiesId
5901
+ ], properties);
5648
5902
  });
5649
- await sleep3(200);
5903
+ await this._serviceContext.automergeHost.repo.flush();
5650
5904
  return identity;
5651
5905
  }
5652
5906
  };
@@ -5668,6 +5922,44 @@ ClientServicesHost = _ts_decorate8([
5668
5922
  Trace3.resource()
5669
5923
  ], ClientServicesHost);
5670
5924
 
5925
+ // packages/sdk/client-services/src/packlets/services/util.ts
5926
+ import { PublicKey as PublicKey14 } from "@dxos/keys";
5927
+ import { humanize } from "@dxos/util";
5928
+ var ClientServicesProviderResource = Symbol.for("dxos.resource.ClientServices");
5929
+
5930
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
5931
+ var DiagnosticsCollector = class {
5932
+ static {
5933
+ this.broadcastSender = createCollectDiagnosticsBroadcastSender();
5934
+ }
5935
+ static async collect(config = findConfigs(), services = findSystemServiceProvider(), options = {}) {
5936
+ const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics({
5937
+ keys: options.humanize ? GetDiagnosticsRequest2.KEY_OPTION.HUMANIZE : options.truncate ? GetDiagnosticsRequest2.KEY_OPTION.TRUNCATE : void 0
5938
+ });
5939
+ const clientDiagnostics = {
5940
+ config,
5941
+ trace: TRACE_PROCESSOR3.getDiagnostics()
5942
+ };
5943
+ const diagnostics = serviceDiagnostics != null ? {
5944
+ client: clientDiagnostics,
5945
+ services: serviceDiagnostics
5946
+ } : {
5947
+ client: clientDiagnostics,
5948
+ broadcast: await this.broadcastSender.broadcastDiagnosticsRequest()
5949
+ };
5950
+ return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer2(options)));
5951
+ }
5952
+ };
5953
+ var findSystemServiceProvider = () => {
5954
+ const serviceProviders = TRACE_PROCESSOR3.findByAnnotation(ClientServicesProviderResource);
5955
+ const providerResource = serviceProviders.find((r) => r.instance.deref()?.services?.SystemService != null);
5956
+ return providerResource?.instance?.deref() ?? null;
5957
+ };
5958
+ var findConfigs = () => {
5959
+ const configs = TRACE_PROCESSOR3.findByAnnotation(ConfigResource);
5960
+ return configs.map((r) => r.instance.deref()).filter(nonNullable);
5961
+ };
5962
+
5671
5963
  export {
5672
5964
  Buffer,
5673
5965
  subscribeToFeeds,
@@ -5687,19 +5979,25 @@ export {
5687
5979
  IdentityServiceImpl,
5688
5980
  DeviceInvitationProtocol,
5689
5981
  InvitationsHandler,
5690
- invitationExpired,
5982
+ createAdmissionKeypair,
5691
5983
  InvitationsServiceImpl,
5692
5984
  SpaceInvitationProtocol,
5985
+ InvitationsManager,
5693
5986
  ClientRpcServer,
5694
- createDiagnostics,
5695
5987
  DataSpace,
5696
5988
  DataSpaceManager,
5697
5989
  SpacesServiceImpl,
5698
5990
  ServiceContext,
5699
5991
  ServiceRegistry,
5992
+ createDiagnostics,
5993
+ createCollectDiagnosticsBroadcastSender,
5994
+ createCollectDiagnosticsBroadcastHandler,
5995
+ DiagnosticsCollector,
5700
5996
  Lock,
5701
5997
  isLocked,
5702
5998
  createStorageObjects,
5703
- ClientServicesHost
5999
+ createLevel,
6000
+ ClientServicesHost,
6001
+ ClientServicesProviderResource
5704
6002
  };
5705
- //# sourceMappingURL=chunk-BJNDCR72.mjs.map
6003
+ //# sourceMappingURL=chunk-BDY63S7K.mjs.map