@dxos/edge-client 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (50) hide show
  1. package/dist/lib/{browser/chunk-IKP53CBQ.mjs → neutral/chunk-ZIQ5T3A7.mjs} +20 -83
  2. package/dist/lib/{browser/chunk-IKP53CBQ.mjs.map → neutral/chunk-ZIQ5T3A7.mjs.map} +2 -2
  3. package/dist/lib/{browser → neutral}/edge-ws-muxer.mjs +1 -1
  4. package/dist/lib/{browser → neutral}/index.mjs +365 -439
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/lib/{browser → neutral}/testing/index.mjs +6 -31
  8. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  9. package/dist/types/src/auth.d.ts.map +1 -1
  10. package/dist/types/src/edge-client.d.ts +5 -2
  11. package/dist/types/src/edge-client.d.ts.map +1 -1
  12. package/dist/types/src/edge-http-client.d.ts +61 -30
  13. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  14. package/dist/types/src/edge-identity.d.ts.map +1 -1
  15. package/dist/types/src/edge-ws-connection.d.ts +20 -0
  16. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  17. package/dist/types/src/edge-ws-muxer.d.ts.map +1 -1
  18. package/dist/types/src/errors.d.ts.map +1 -1
  19. package/dist/types/src/http-client.d.ts +10 -7
  20. package/dist/types/src/http-client.d.ts.map +1 -1
  21. package/dist/types/src/protocol.d.ts +1 -1
  22. package/dist/types/src/protocol.d.ts.map +1 -1
  23. package/dist/types/src/testing/test-server.d.ts.map +1 -1
  24. package/dist/types/src/testing/test-utils.d.ts +3 -3
  25. package/dist/types/src/testing/test-utils.d.ts.map +1 -1
  26. package/dist/types/src/utils.d.ts +1 -1
  27. package/dist/types/src/utils.d.ts.map +1 -1
  28. package/dist/types/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +28 -31
  30. package/src/edge-client.test.ts +20 -15
  31. package/src/edge-client.ts +55 -8
  32. package/src/edge-http-client.test.ts +3 -2
  33. package/src/edge-http-client.ts +207 -78
  34. package/src/edge-ws-connection.ts +120 -6
  35. package/src/http-client.test.ts +9 -6
  36. package/src/http-client.ts +18 -8
  37. package/src/testing/test-utils.ts +7 -7
  38. package/dist/lib/browser/index.mjs.map +0 -7
  39. package/dist/lib/browser/meta.json +0 -1
  40. package/dist/lib/browser/testing/index.mjs.map +0 -7
  41. package/dist/lib/node-esm/chunk-DR5YNW5K.mjs +0 -332
  42. package/dist/lib/node-esm/chunk-DR5YNW5K.mjs.map +0 -7
  43. package/dist/lib/node-esm/edge-ws-muxer.mjs +0 -12
  44. package/dist/lib/node-esm/edge-ws-muxer.mjs.map +0 -7
  45. package/dist/lib/node-esm/index.mjs +0 -1251
  46. package/dist/lib/node-esm/index.mjs.map +0 -7
  47. package/dist/lib/node-esm/meta.json +0 -1
  48. package/dist/lib/node-esm/testing/index.mjs +0 -186
  49. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  50. /package/dist/lib/{browser → neutral}/edge-ws-muxer.mjs.map +0 -0
@@ -32,9 +32,25 @@ export class EdgeWsConnection extends Resource {
32
32
  private _wsMuxer: WebSocketMuxer | undefined;
33
33
  private _lastReceivedMessageTimestamp = Date.now();
34
34
 
35
+ private _openTimestamp: number | undefined;
36
+
37
+ // Latency tracking.
38
+ private _pingTimestamp: number | undefined;
39
+ private _rtt = 0;
40
+
41
+ // Rate tracking with sliding window.
42
+ private _uploadRate = 0;
43
+ private _downloadRate = 0;
44
+ private readonly _rateWindow = 10000; // 10 second sliding window.
45
+ private readonly _rateUpdateInterval = 1000; // Update rates every second.
46
+ private _bytesSamples: Array<{ timestamp: number; sent: number; received: number }> = [];
47
+
48
+ private _messagesSent = 0;
49
+ private _messagesReceived = 0;
50
+
35
51
  constructor(
36
52
  private readonly _identity: EdgeIdentity,
37
- private readonly _connectionInfo: { url: URL; protocolHeader?: string },
53
+ private readonly _connectionInfo: { url: URL; protocolHeader?: string; headers?: Record<string, string> },
38
54
  private readonly _callbacks: EdgeWsConnectionCallbacks,
39
55
  ) {
40
56
  super();
@@ -49,10 +65,35 @@ export class EdgeWsConnection extends Resource {
49
65
  };
50
66
  }
51
67
 
68
+ public get rtt(): number {
69
+ return this._rtt;
70
+ }
71
+
72
+ public get uptime(): number {
73
+ return this._openTimestamp ? (Date.now() - this._openTimestamp) / 1000 : 0;
74
+ }
75
+
76
+ public get uploadRate(): number {
77
+ return this._uploadRate;
78
+ }
79
+
80
+ public get downloadRate(): number {
81
+ return this._downloadRate;
82
+ }
83
+
84
+ public get messagesSent(): number {
85
+ return this._messagesSent;
86
+ }
87
+
88
+ public get messagesReceived(): number {
89
+ return this._messagesReceived;
90
+ }
91
+
52
92
  public send(message: Message): void {
53
93
  invariant(this._ws);
54
94
  invariant(this._wsMuxer);
55
95
  log('sending...', { peerKey: this._identity.peerKey, payload: protocol.getPayloadType(message) });
96
+ this._messagesSent++;
56
97
  if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {
57
98
  const binary = buf.toBinary(MessageSchema, message);
58
99
  if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {
@@ -63,8 +104,12 @@ export class EdgeWsConnection extends Resource {
63
104
  });
64
105
  return;
65
106
  }
107
+ this._recordBytes(binary.byteLength, 0);
66
108
  this._ws.send(binary);
67
109
  } else {
110
+ // For muxer, we need to track the size of the message being sent.
111
+ const binary = buf.toBinary(MessageSchema, message);
112
+ this._recordBytes(binary.byteLength, 0);
68
113
  this._wsMuxer.send(message).catch((e) => log.catch(e));
69
114
  }
70
115
  }
@@ -76,6 +121,7 @@ export class EdgeWsConnection extends Resource {
76
121
  this._connectionInfo.protocolHeader
77
122
  ? [...baseProtocols, this._connectionInfo.protocolHeader]
78
123
  : [...baseProtocols],
124
+ this._connectionInfo.headers ? { headers: this._connectionInfo.headers } : undefined,
79
125
  );
80
126
  const muxer = new WebSocketMuxer(this._ws);
81
127
  this._wsMuxer = muxer;
@@ -83,20 +129,22 @@ export class EdgeWsConnection extends Resource {
83
129
  this._ws.onopen = () => {
84
130
  if (this.isOpen) {
85
131
  log('connected');
132
+ this._openTimestamp = Date.now();
86
133
  this._callbacks.onConnected();
87
134
  this._scheduleHeartbeats();
135
+ this._scheduleRateCalculation();
88
136
  } else {
89
137
  log.verbose('connected after becoming inactive', { currentIdentity: this._identity });
90
138
  }
91
139
  };
92
- this._ws.onclose = (event) => {
140
+ this._ws.onclose = (event: WebSocket.CloseEvent) => {
93
141
  if (this.isOpen) {
94
- log.warn('disconnected while being open', { code: event.code, reason: event.reason });
142
+ log.warn('server disconnected', { code: event.code, reason: event.reason });
95
143
  this._callbacks.onRestartRequired();
96
144
  muxer.destroy();
97
145
  }
98
146
  };
99
- this._ws.onerror = (event) => {
147
+ this._ws.onerror = (event: WebSocket.ErrorEvent) => {
100
148
  if (this.isOpen) {
101
149
  log.warn('edge connection socket error', { error: event.error, info: event.message });
102
150
  this._callbacks.onRestartRequired();
@@ -107,21 +155,29 @@ export class EdgeWsConnection extends Resource {
107
155
  /**
108
156
  * https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data
109
157
  */
110
- this._ws.onmessage = async (event) => {
158
+ this._ws.onmessage = async (event: WebSocket.MessageEvent) => {
111
159
  if (!this.isOpen) {
112
160
  log.verbose('message ignored on closed connection', { event: event.type });
113
161
  return;
114
162
  }
115
163
  this._lastReceivedMessageTimestamp = Date.now();
116
164
  if (event.data === '__pong__') {
165
+ // Calculate latency.
166
+ if (this._pingTimestamp) {
167
+ this._rtt = Date.now() - this._pingTimestamp;
168
+ this._pingTimestamp = undefined;
169
+ }
117
170
  this._rescheduleHeartbeatTimeout();
118
171
  return;
119
172
  }
120
173
  const bytes = await toUint8Array(event.data);
174
+ this._recordBytes(0, bytes.byteLength);
121
175
  if (!this.isOpen) {
122
176
  return;
123
177
  }
124
178
 
179
+ this._messagesReceived++;
180
+
125
181
  const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0)
126
182
  ? buf.fromBinary(MessageSchema, bytes)
127
183
  : muxer.receiveData(bytes);
@@ -145,7 +201,7 @@ export class EdgeWsConnection extends Resource {
145
201
  if (err instanceof Error && err.message.includes('WebSocket is closed before the connection is established.')) {
146
202
  return;
147
203
  }
148
- log.warn('Error closing websocket', { err });
204
+ log.warn('error closing websocket', { err });
149
205
  }
150
206
  }
151
207
 
@@ -156,10 +212,12 @@ export class EdgeWsConnection extends Resource {
156
212
  async () => {
157
213
  // TODO(mykola): use RFC6455 ping/pong once implemented in the browser?
158
214
  // Cloudflare's worker responds to this `without interrupting hibernation`. https://developers.cloudflare.com/durable-objects/api/websockets/#setwebsocketautoresponse
215
+ this._pingTimestamp = Date.now();
159
216
  this._ws?.send('__ping__');
160
217
  },
161
218
  SIGNAL_KEEPALIVE_INTERVAL,
162
219
  );
220
+ this._pingTimestamp = Date.now();
163
221
  this._ws.send('__ping__');
164
222
  this._rescheduleHeartbeatTimeout();
165
223
  }
@@ -187,4 +245,60 @@ export class EdgeWsConnection extends Resource {
187
245
  SIGNAL_KEEPALIVE_TIMEOUT,
188
246
  );
189
247
  }
248
+
249
+ private _recordBytes(sent: number, received: number): void {
250
+ const now = Date.now();
251
+
252
+ // Find if we have a sample for the current second.
253
+ const currentSecond = Math.floor(now / 1000) * 1000;
254
+ const existingSample = this._bytesSamples.find((s) => Math.floor(s.timestamp / 1000) * 1000 === currentSecond);
255
+
256
+ if (existingSample) {
257
+ existingSample.sent += sent;
258
+ existingSample.received += received;
259
+ } else {
260
+ this._bytesSamples.push({ timestamp: now, sent, received });
261
+ }
262
+ }
263
+
264
+ private _scheduleRateCalculation(): void {
265
+ scheduleTaskInterval(
266
+ this._ctx,
267
+ async () => {
268
+ this._calculateRates();
269
+ },
270
+ this._rateUpdateInterval,
271
+ );
272
+ // Calculate initial rates.
273
+ this._calculateRates();
274
+ }
275
+
276
+ private _calculateRates(): void {
277
+ const now = Date.now();
278
+ const cutoff = now - this._rateWindow;
279
+
280
+ // Remove old samples.
281
+ this._bytesSamples = this._bytesSamples.filter((s) => s.timestamp > cutoff);
282
+
283
+ if (this._bytesSamples.length === 0) {
284
+ this._uploadRate = 0;
285
+ this._downloadRate = 0;
286
+ return;
287
+ }
288
+
289
+ // Calculate total bytes and time span.
290
+ let totalSent = 0;
291
+ let totalReceived = 0;
292
+ const oldestTimestamp = Math.min(...this._bytesSamples.map((s) => s.timestamp));
293
+ const timeSpan = (now - oldestTimestamp) / 1000; // Convert to seconds.
294
+
295
+ for (const sample of this._bytesSamples) {
296
+ totalSent += sample.sent;
297
+ totalReceived += sample.received;
298
+ }
299
+
300
+ // Calculate rates (bytes per second).
301
+ this._uploadRate = timeSpan > 0 ? Math.round(totalSent / timeSpan) : 0;
302
+ this._downloadRate = timeSpan > 0 ? Math.round(totalReceived / timeSpan) : 0;
303
+ }
190
304
  }
@@ -2,10 +2,13 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { FetchHttpClient, HttpClient } from '@effect/platform';
6
- import { Effect, pipe } from 'effect';
5
+ import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
6
+ import * as HttpClient from '@effect/platform/HttpClient';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Function from 'effect/Function';
7
9
  import { afterEach, beforeEach, describe, it } from 'vitest';
8
10
 
11
+ import { runAndForwardErrors } from '@dxos/effect';
9
12
  import { invariant } from '@dxos/invariant';
10
13
 
11
14
  import { HttpConfig, withLogging, withRetry, withRetryConfig } from './http-client';
@@ -30,24 +33,24 @@ describe('HttpClient', () => {
30
33
  invariant(server);
31
34
 
32
35
  {
33
- const result = await pipe(
36
+ const result = await Function.pipe(
34
37
  withRetry(HttpClient.get(server.url)),
35
38
  Effect.provide(FetchHttpClient.layer),
36
39
  Effect.withSpan('EdgeHttpClient'),
37
- Effect.runPromise,
40
+ runAndForwardErrors,
38
41
  );
39
42
  expect(result).toMatchObject({ success: true, data: { value: 100 } });
40
43
  }
41
44
 
42
45
  {
43
- const result = await pipe(
46
+ const result = await Function.pipe(
44
47
  HttpClient.get(server.url),
45
48
  withLogging,
46
49
  withRetryConfig,
47
50
  Effect.provide(FetchHttpClient.layer),
48
51
  Effect.provide(HttpConfig.default), // TODO(burdon): Swap out to mock.
49
52
  Effect.withSpan('EdgeHttpClient'), // TODO(burdon): OTEL.
50
- Effect.runPromise,
53
+ runAndForwardErrors,
51
54
  );
52
55
  expect(result).toMatchObject({ success: true, data: { value: 100 } });
53
56
  }
@@ -2,10 +2,14 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type HttpClient } from '@effect/platform';
6
- import { type HttpClientError } from '@effect/platform/HttpClientError';
7
- import { type HttpClientResponse } from '@effect/platform/HttpClientResponse';
8
- import { Context, Duration, Effect, Layer, Schedule } from 'effect';
5
+ import type * as HttpClient from '@effect/platform/HttpClient';
6
+ import type * as HttpClientError from '@effect/platform/HttpClientError';
7
+ import type * as HttpClientResponse from '@effect/platform/HttpClientResponse';
8
+ import * as Context from 'effect/Context';
9
+ import * as Duration from 'effect/Duration';
10
+ import * as Effect from 'effect/Effect';
11
+ import * as Layer from 'effect/Layer';
12
+ import * as Schedule from 'effect/Schedule';
9
13
 
10
14
  import { log } from '@dxos/log';
11
15
 
@@ -28,7 +32,7 @@ export class HttpConfig extends Context.Tag('HttpConfig')<HttpConfig, RetryOptio
28
32
 
29
33
  // HOC pattern.
30
34
  export const withRetry = (
31
- effect: Effect.Effect<HttpClientResponse, HttpClientError, HttpClient.HttpClient>,
35
+ effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError, HttpClient.HttpClient>,
32
36
  {
33
37
  timeout = Duration.millis(1_000),
34
38
  retryBaseDelay = Duration.millis(1_000),
@@ -48,14 +52,20 @@ export const withRetry = (
48
52
  );
49
53
  };
50
54
 
51
- export const withRetryConfig = (effect: Effect.Effect<HttpClientResponse, HttpClientError, HttpClient.HttpClient>) =>
55
+ export const withRetryConfig = (
56
+ effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError, HttpClient.HttpClient>,
57
+ ) =>
52
58
  Effect.gen(function* () {
53
59
  const config = yield* HttpConfig;
54
60
  return yield* withRetry(effect, config);
55
61
  });
56
62
 
57
- export const withLogging = <A extends HttpClientResponse, E, R>(effect: Effect.Effect<A, E, R>) =>
58
- effect.pipe(Effect.tap((res) => log.info('response', { status: res.status })));
63
+ export const withLogging = <A extends HttpClientResponse.HttpClientResponse, E, R>(effect: Effect.Effect<A, E, R>) =>
64
+ effect.pipe(
65
+ Effect.tap((res) => {
66
+ log.info('response', { status: res.status });
67
+ }),
68
+ );
59
69
 
60
70
  /**
61
71
  *
@@ -16,13 +16,13 @@ import { toUint8Array } from '../protocol';
16
16
 
17
17
  export const DEFAULT_PORT = 8080;
18
18
 
19
- type TestEdgeWsServerParams = {
19
+ type TestEdgeWsServerProps = {
20
20
  admitConnection?: Trigger;
21
21
  payloadDecoder?: (payload: Uint8Array) => any;
22
22
  messageHandler?: (payload: any) => Promise<Uint8Array | undefined>;
23
23
  };
24
24
 
25
- export const createTestEdgeWsServer = async (port = DEFAULT_PORT, params?: TestEdgeWsServerParams) => {
25
+ export const createTestEdgeWsServer = async (port = DEFAULT_PORT, params?: TestEdgeWsServerProps) => {
26
26
  const wsServer = new WebSocket.Server({
27
27
  port,
28
28
  verifyClient: createConnectionDelayHandler(params),
@@ -36,11 +36,11 @@ export const createTestEdgeWsServer = async (port = DEFAULT_PORT, params?: TestE
36
36
  const closeTrigger = new Trigger();
37
37
  const sendResponseMessage = createResponseSender(() => connection!.muxer);
38
38
 
39
- wsServer.on('connection', (ws) => {
39
+ wsServer.on('connection', (ws: WebSocket) => {
40
40
  const muxer = new WebSocketMuxer(ws);
41
41
  connection = { ws, muxer };
42
- ws.on('error', (err) => log.catch(err));
43
- ws.on('message', async (data) => {
42
+ ws.on('error', (err: Error) => log.catch(err));
43
+ ws.on('message', async (data: any) => {
44
44
  if (String(data) === '__ping__') {
45
45
  ws.send('__pong__');
46
46
  return;
@@ -86,7 +86,7 @@ export const createTestEdgeWsServer = async (port = DEFAULT_PORT, params?: TestE
86
86
  };
87
87
  };
88
88
 
89
- const createConnectionDelayHandler = (params: TestEdgeWsServerParams | undefined) => {
89
+ const createConnectionDelayHandler = (params: TestEdgeWsServerProps | undefined) => {
90
90
  return (_: any, callback: (admit: boolean) => void) => {
91
91
  if (params?.admitConnection) {
92
92
  log('delaying edge connection admission');
@@ -116,7 +116,7 @@ const createResponseSender = (connection: () => WebSocketMuxer) => {
116
116
  };
117
117
  };
118
118
 
119
- const decodePayload = async (request: Message, params: TestEdgeWsServerParams | undefined) => {
119
+ const decodePayload = async (request: Message, params: TestEdgeWsServerProps | undefined) => {
120
120
  const requestPayload = params?.payloadDecoder
121
121
  ? params.payloadDecoder(request.payload!.value!)
122
122
  : protocol.getPayload(request, TextMessageSchema);
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/index.ts", "../../../src/auth.ts", "../../../src/edge-client.ts", "../../../src/edge-identity.ts", "../../../src/edge-ws-connection.ts", "../../../src/errors.ts", "../../../src/utils.ts", "../../../src/edge-http-client.ts", "../../../src/http-client.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nexport * from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nexport * from './auth';\nexport * from './defs';\nexport * from './edge-client';\nexport * from './errors';\nexport * from './protocol';\nexport * from './edge-http-client';\nexport * from './edge-identity';\nexport * from './edge-ws-muxer';\nexport * from './http-client';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { createCredential, signPresentation } from '@dxos/credentials';\nimport { type Signer } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { type Chain, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport type { EdgeIdentity } from './edge-identity';\n\n/**\n * Edge identity backed by a device key without a credential chain.\n */\nexport const createDeviceEdgeIdentity = async (signer: Signer, key: PublicKey): Promise<EdgeIdentity> => {\n return {\n identityKey: key.toHex(),\n peerKey: key.toHex(),\n presentCredentials: async ({ challenge }) => {\n return signPresentation({\n presentation: {\n credentials: [\n // Verifier requires at least one credential in the presentation to establish the subject.\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: key,\n subject: key,\n signer,\n }),\n ],\n },\n signer,\n signerKey: key,\n nonce: challenge,\n });\n },\n };\n};\n\n/**\n * Edge identity backed by a chain of credentials.\n */\nexport const createChainEdgeIdentity = async (\n signer: Signer,\n identityKey: PublicKey,\n peerKey: PublicKey,\n chain: Chain | undefined,\n credentials: Credential[],\n): Promise<EdgeIdentity> => {\n const credentialsToSign =\n credentials.length > 0\n ? credentials\n : [\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: identityKey,\n subject: identityKey,\n signer,\n chain,\n signingKey: peerKey,\n }),\n ];\n\n return {\n identityKey: identityKey.toHex(),\n peerKey: peerKey.toHex(),\n presentCredentials: async ({ challenge }) => {\n // TODO: make chain required after device invitation flow update release\n invariant(chain);\n return signPresentation({\n presentation: {\n credentials: credentialsToSign,\n },\n signer,\n nonce: challenge,\n signerKey: peerKey,\n chain,\n });\n },\n };\n};\n\n/**\n * Edge identity backed by a random ephemeral key without HALO.\n */\nexport const createEphemeralEdgeIdentity = async (): Promise<EdgeIdentity> => {\n const keyring = new Keyring();\n const key = await keyring.createKey();\n return createDeviceEdgeIdentity(keyring, key);\n};\n\n/**\n * Creates a HALO chain of credentials to act as an edge identity.\n */\nexport const createTestHaloEdgeIdentity = async (\n signer: Signer,\n identityKey: PublicKey,\n deviceKey: PublicKey,\n): Promise<EdgeIdentity> => {\n const deviceAdmission = await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n deviceKey,\n identityKey,\n },\n issuer: identityKey,\n subject: deviceKey,\n signer,\n });\n return createChainEdgeIdentity(signer, identityKey, deviceKey, { credential: deviceAdmission }, [\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: identityKey,\n subject: identityKey,\n signer,\n }),\n ]);\n};\n\nexport const createStubEdgeIdentity = (): EdgeIdentity => {\n const identityKey = PublicKey.random();\n const deviceKey = PublicKey.random();\n return {\n identityKey: identityKey.toHex(),\n peerKey: deviceKey.toHex(),\n presentCredentials: async () => {\n throw new Error('Stub identity does not support authentication.');\n },\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event, PersistentLifecycle, Trigger, TriggerState, scheduleMicroTask } from '@dxos/async';\nimport { type Lifecycle, Resource } from '@dxos/context';\nimport { log, logInfo } from '@dxos/log';\nimport { type Message } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport { EdgeStatus } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { protocol } from './defs';\nimport { type EdgeIdentity, handleAuthChallenge } from './edge-identity';\nimport { EdgeWsConnection } from './edge-ws-connection';\nimport { EdgeConnectionClosedError, EdgeIdentityChangedError } from './errors';\nimport { type Protocol } from './protocol';\nimport { getEdgeUrlWithProtocol } from './utils';\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport type MessageListener = (message: Message) => void;\nexport type ReconnectListener = () => void;\n\nexport type MessengerConfig = {\n socketEndpoint: string;\n timeout?: number;\n protocol?: Protocol;\n disableAuth?: boolean;\n};\n\nexport interface EdgeConnection extends Required<Lifecycle> {\n statusChanged: Event<EdgeStatus>;\n get info(): any;\n get identityKey(): string;\n get peerKey(): string;\n get isOpen(): boolean;\n get status(): EdgeStatus;\n setIdentity(identity: EdgeIdentity): void;\n send(message: Message): Promise<void>;\n onMessage(listener: MessageListener): () => void;\n onReconnected(listener: ReconnectListener): () => void;\n}\n\n/**\n * Messenger client for EDGE:\n * - While open, uses PersistentLifecycle to keep an open EdgeWsConnection, reconnecting on failures.\n * - Manages identity and re-create EdgeWsConnection when identity changes.\n * - Dispatches connection state and message notifications.\n */\nexport class EdgeClient extends Resource implements EdgeConnection {\n public readonly statusChanged = new Event<EdgeStatus>();\n\n private readonly _persistentLifecycle = new PersistentLifecycle<EdgeWsConnection>({\n start: async () => this._connect(),\n stop: async (state: EdgeWsConnection) => this._disconnect(state),\n });\n\n private readonly _messageListeners = new Set<MessageListener>();\n private readonly _reconnectListeners = new Set<ReconnectListener>();\n private readonly _baseWsUrl: string;\n private readonly _baseHttpUrl: string;\n private _currentConnection?: EdgeWsConnection = undefined;\n private _ready = new Trigger();\n\n constructor(\n private _identity: EdgeIdentity,\n private readonly _config: MessengerConfig,\n ) {\n super();\n this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'ws');\n this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'http');\n }\n\n @logInfo\n public get info() {\n return {\n open: this.isOpen,\n status: this.status,\n identity: this._identity.identityKey,\n device: this._identity.peerKey,\n };\n }\n\n get status() {\n return Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED\n ? EdgeStatus.CONNECTED\n : EdgeStatus.NOT_CONNECTED;\n }\n\n get identityKey() {\n return this._identity.identityKey;\n }\n\n get peerKey() {\n return this._identity.peerKey;\n }\n\n setIdentity(identity: EdgeIdentity) {\n if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {\n log('Edge identity changed', { identity, oldIdentity: this._identity });\n this._identity = identity;\n this._closeCurrentConnection(new EdgeIdentityChangedError());\n void this._persistentLifecycle.scheduleRestart();\n }\n }\n\n /**\n * Send message.\n * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.\n */\n public async send(message: Message) {\n if (this._ready.state !== TriggerState.RESOLVED) {\n log('waiting for websocket');\n await this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT });\n }\n\n if (!this._currentConnection) {\n throw new EdgeConnectionClosedError();\n }\n\n if (\n message.source &&\n (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)\n ) {\n throw new EdgeIdentityChangedError();\n }\n\n this._currentConnection.send(message);\n }\n\n public onMessage(listener: MessageListener) {\n this._messageListeners.add(listener);\n return () => this._messageListeners.delete(listener);\n }\n\n public onReconnected(listener: () => void) {\n this._reconnectListeners.add(listener);\n if (this._ready.state === TriggerState.RESOLVED) {\n // Microtask so that listener is always called asynchronously, no matter the state of the ready trigger\n // at the moment of registration.\n scheduleMicroTask(this._ctx, () => {\n if (this._reconnectListeners.has(listener)) {\n try {\n listener();\n } catch (error) {\n log.catch(error);\n }\n }\n });\n }\n\n return () => this._reconnectListeners.delete(listener);\n }\n\n /**\n * Open connection to messaging service.\n */\n protected override async _open(): Promise<void> {\n log('opening...', { info: this.info });\n this._persistentLifecycle.open().catch((err) => {\n log.warn('Error while opening connection', { err });\n });\n }\n\n /**\n * Close connection and free resources.\n */\n protected override async _close(): Promise<void> {\n log('closing...', { peerKey: this._identity.peerKey });\n this._closeCurrentConnection();\n await this._persistentLifecycle.close();\n }\n\n private async _connect(): Promise<EdgeWsConnection | undefined> {\n if (this._ctx.disposed) {\n return undefined;\n }\n\n const identity = this._identity;\n const path = `/ws/${identity.identityKey}/${identity.peerKey}`;\n const protocolHeader = this._config.disableAuth ? undefined : await this._createAuthHeader(path);\n if (this._identity !== identity) {\n log('identity changed during auth header request');\n return undefined;\n }\n\n const restartRequired = new Trigger();\n const url = new URL(path, this._baseWsUrl);\n log('Opening websocket', { url: url.toString(), protocolHeader });\n const connection = new EdgeWsConnection(\n identity,\n { url, protocolHeader },\n {\n onConnected: () => {\n if (this._isActive(connection)) {\n this._ready.wake();\n this._notifyReconnected();\n } else {\n log.verbose('connected callback ignored, because connection is not active');\n }\n },\n onRestartRequired: () => {\n if (this._isActive(connection)) {\n this._closeCurrentConnection();\n void this._persistentLifecycle.scheduleRestart();\n } else {\n log.verbose('restart requested by inactive connection');\n }\n restartRequired.wake();\n },\n onMessage: (message) => {\n if (this._isActive(connection)) {\n this._notifyMessageReceived(message);\n } else {\n log.verbose('ignored a message on inactive connection', {\n from: message.source,\n type: message.payload?.typeUrl,\n });\n }\n },\n },\n );\n this._currentConnection = connection;\n\n await connection.open();\n // Race with restartRequired so that restart is not blocked by _connect execution.\n // Wait on ready to attempt a reconnect if it times out.\n await Promise.race([this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT }), restartRequired]);\n return connection;\n }\n\n private async _disconnect(state: EdgeWsConnection): Promise<void> {\n await state.close();\n this.statusChanged.emit(this.status);\n }\n\n private _closeCurrentConnection(error: Error = new EdgeConnectionClosedError()): void {\n this._currentConnection = undefined;\n this._ready.throw(error);\n this._ready.reset();\n this.statusChanged.emit(this.status);\n }\n\n private _notifyReconnected(): void {\n this.statusChanged.emit(this.status);\n for (const listener of this._reconnectListeners) {\n try {\n listener();\n } catch (err) {\n log.error('ws reconnect listener failed', { err });\n }\n }\n }\n\n private _notifyMessageReceived(message: Message): void {\n for (const listener of this._messageListeners) {\n try {\n listener(message);\n } catch (err) {\n log.error('ws incoming message processing failed', { err, payload: protocol.getPayloadType(message) });\n }\n }\n }\n\n private async _createAuthHeader(path: string): Promise<string | undefined> {\n const httpUrl = new URL(path, this._baseHttpUrl);\n httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), 'http');\n const response = await fetch(httpUrl, { method: 'GET' });\n if (response.status === 401) {\n return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));\n } else {\n log.warn('no auth challenge from edge', { status: response.status, statusText: response.statusText });\n return undefined;\n }\n }\n\n private _isActive = (connection: EdgeWsConnection) => connection === this._currentConnection;\n}\n\nconst encodePresentationWsAuthHeader = (encodedPresentation: Uint8Array): string => {\n // '=' and '/' characters are not allowed in the WebSocket subprotocol header.\n const encodedToken = Buffer.from(encodedPresentation).toString('base64').replace(/=*$/, '').replaceAll('/', '|');\n return `base64url.bearer.authorization.dxos.org.${encodedToken}`;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Presentation } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nexport interface EdgeIdentity {\n peerKey: string;\n identityKey: string;\n /**\n * Returns credential presentation issued by the identity key.\n * Presentation must have the provided challenge.\n * Presentation may include ServiceAccess credentials.\n */\n presentCredentials({ challenge }: { challenge: Uint8Array }): Promise<Presentation>;\n}\n\nexport const handleAuthChallenge = async (failedResponse: Response, identity: EdgeIdentity): Promise<Uint8Array> => {\n invariant(failedResponse.status === 401);\n\n const headerValue = failedResponse.headers.get('Www-Authenticate');\n invariant(headerValue?.startsWith('VerifiablePresentation challenge='));\n\n const challenge = headerValue?.slice('VerifiablePresentation challenge='.length);\n invariant(challenge);\n\n const presentation = await identity.presentCredentials({ challenge: Buffer.from(challenge, 'base64') });\n return schema.getCodecForType('dxos.halo.credentials.Presentation').encode(presentation);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'isomorphic-ws';\n\nimport { scheduleTask, scheduleTaskInterval } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log, logInfo } from '@dxos/log';\nimport { EdgeWebsocketProtocol } from '@dxos/protocols';\nimport { buf } from '@dxos/protocols/buf';\nimport { type Message, MessageSchema } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nimport { protocol } from './defs';\nimport { type EdgeIdentity } from './edge-identity';\nimport { CLOUDFLARE_MESSAGE_MAX_BYTES, WebSocketMuxer } from './edge-ws-muxer';\nimport { toUint8Array } from './protocol';\n\nconst SIGNAL_KEEPALIVE_INTERVAL = 4_000;\nconst SIGNAL_KEEPALIVE_TIMEOUT = 12_000;\n\nexport type EdgeWsConnectionCallbacks = {\n onConnected: () => void;\n onMessage: (message: Message) => void;\n onRestartRequired: () => void;\n};\n\nexport class EdgeWsConnection extends Resource {\n private _inactivityTimeoutCtx: Context | undefined;\n private _ws: WebSocket | undefined;\n private _wsMuxer: WebSocketMuxer | undefined;\n private _lastReceivedMessageTimestamp = Date.now();\n\n constructor(\n private readonly _identity: EdgeIdentity,\n private readonly _connectionInfo: { url: URL; protocolHeader?: string },\n private readonly _callbacks: EdgeWsConnectionCallbacks,\n ) {\n super();\n }\n\n @logInfo\n public get info() {\n return {\n open: this.isOpen,\n identity: this._identity.identityKey,\n device: this._identity.peerKey,\n };\n }\n\n public send(message: Message): void {\n invariant(this._ws);\n invariant(this._wsMuxer);\n log('sending...', { peerKey: this._identity.peerKey, payload: protocol.getPayloadType(message) });\n if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {\n const binary = buf.toBinary(MessageSchema, message);\n if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {\n log.error('Message dropped because it was too large (>1MB).', {\n byteLength: binary.byteLength,\n serviceId: message.serviceId,\n payload: protocol.getPayloadType(message),\n });\n return;\n }\n this._ws.send(binary);\n } else {\n this._wsMuxer.send(message).catch((e) => log.catch(e));\n }\n }\n\n protected override async _open(): Promise<void> {\n const baseProtocols = [...Object.values(EdgeWebsocketProtocol)];\n this._ws = new WebSocket(\n this._connectionInfo.url.toString(),\n this._connectionInfo.protocolHeader\n ? [...baseProtocols, this._connectionInfo.protocolHeader]\n : [...baseProtocols],\n );\n const muxer = new WebSocketMuxer(this._ws);\n this._wsMuxer = muxer;\n\n this._ws.onopen = () => {\n if (this.isOpen) {\n log('connected');\n this._callbacks.onConnected();\n this._scheduleHeartbeats();\n } else {\n log.verbose('connected after becoming inactive', { currentIdentity: this._identity });\n }\n };\n this._ws.onclose = (event) => {\n if (this.isOpen) {\n log.warn('disconnected while being open', { code: event.code, reason: event.reason });\n this._callbacks.onRestartRequired();\n muxer.destroy();\n }\n };\n this._ws.onerror = (event) => {\n if (this.isOpen) {\n log.warn('edge connection socket error', { error: event.error, info: event.message });\n this._callbacks.onRestartRequired();\n } else {\n log.verbose('error ignored on closed connection', { error: event.error });\n }\n };\n /**\n * https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data\n */\n this._ws.onmessage = async (event) => {\n if (!this.isOpen) {\n log.verbose('message ignored on closed connection', { event: event.type });\n return;\n }\n this._lastReceivedMessageTimestamp = Date.now();\n if (event.data === '__pong__') {\n this._rescheduleHeartbeatTimeout();\n return;\n }\n const bytes = await toUint8Array(event.data);\n if (!this.isOpen) {\n return;\n }\n\n const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0)\n ? buf.fromBinary(MessageSchema, bytes)\n : muxer.receiveData(bytes);\n\n if (message) {\n log('received', { from: message.source, payload: protocol.getPayloadType(message) });\n this._callbacks.onMessage(message);\n }\n };\n }\n\n protected override async _close(): Promise<void> {\n void this._inactivityTimeoutCtx?.dispose().catch(() => {});\n\n try {\n this._ws?.close();\n this._ws = undefined;\n this._wsMuxer?.destroy();\n this._wsMuxer = undefined;\n } catch (err) {\n if (err instanceof Error && err.message.includes('WebSocket is closed before the connection is established.')) {\n return;\n }\n log.warn('Error closing websocket', { err });\n }\n }\n\n private _scheduleHeartbeats(): void {\n invariant(this._ws);\n scheduleTaskInterval(\n this._ctx,\n async () => {\n // TODO(mykola): use RFC6455 ping/pong once implemented in the browser?\n // Cloudflare's worker responds to this `without interrupting hibernation`. https://developers.cloudflare.com/durable-objects/api/websockets/#setwebsocketautoresponse\n this._ws?.send('__ping__');\n },\n SIGNAL_KEEPALIVE_INTERVAL,\n );\n this._ws.send('__ping__');\n this._rescheduleHeartbeatTimeout();\n }\n\n private _rescheduleHeartbeatTimeout(): void {\n if (!this.isOpen) {\n return;\n }\n void this._inactivityTimeoutCtx?.dispose();\n this._inactivityTimeoutCtx = new Context();\n scheduleTask(\n this._inactivityTimeoutCtx,\n () => {\n if (this.isOpen) {\n if (Date.now() - this._lastReceivedMessageTimestamp > SIGNAL_KEEPALIVE_TIMEOUT) {\n log.warn('restart due to inactivity timeout', {\n lastReceivedMessageTimestamp: this._lastReceivedMessageTimestamp,\n });\n this._callbacks.onRestartRequired();\n } else {\n this._rescheduleHeartbeatTimeout();\n }\n }\n },\n SIGNAL_KEEPALIVE_TIMEOUT,\n );\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport class EdgeConnectionClosedError extends Error {\n constructor() {\n super('Edge connection closed.');\n }\n}\n\nexport class EdgeIdentityChangedError extends Error {\n constructor() {\n super('Edge identity changed.');\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const getEdgeUrlWithProtocol = (baseUrl: string, protocol: 'http' | 'ws') => {\n const isSecure = baseUrl.startsWith('https') || baseUrl.startsWith('wss');\n const url = new URL(baseUrl);\n url.protocol = protocol + (isSecure ? 's' : '');\n return url.toString();\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { FetchHttpClient, HttpClient } from '@effect/platform';\nimport { Effect, pipe } from 'effect';\n\nimport { sleep } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n type CreateAgentRequestBody,\n type CreateAgentResponseBody,\n type CreateSpaceRequest,\n type CreateSpaceResponseBody,\n EdgeAuthChallengeError,\n EdgeCallFailedError,\n type EdgeHttpResponse,\n type EdgeStatus,\n type ExecuteWorkflowResponseBody,\n type ExportBundleRequest,\n type ExportBundleResponse,\n type GetAgentStatusResponseBody,\n type GetNotarizationResponseBody,\n type ImportBundleRequest,\n type InitiateOAuthFlowRequest,\n type InitiateOAuthFlowResponse,\n type JoinSpaceRequest,\n type JoinSpaceResponseBody,\n type ObjectId,\n type PostNotarizationRequestBody,\n type QueryResult,\n type QueueQuery,\n type RecoverIdentityRequest,\n type RecoverIdentityResponseBody,\n type UploadFunctionRequest,\n type UploadFunctionResponseBody,\n} from '@dxos/protocols';\nimport { createUrl } from '@dxos/util';\n\nimport { type EdgeIdentity, handleAuthChallenge } from './edge-identity';\nimport { HttpConfig, encodeAuthHeader, withLogging, withRetryConfig } from './http-client';\nimport { getEdgeUrlWithProtocol } from './utils';\n\nconst DEFAULT_RETRY_TIMEOUT = 1500;\nconst DEFAULT_RETRY_JITTER = 500;\nconst DEFAULT_MAX_RETRIES_COUNT = 3;\nconst WARNING_BODY_SIZE = 10 * 1024 * 1024; // 10MB\n\nexport type RetryConfig = {\n /**\n * A number of call retries, not counting the initial request.\n */\n count: number;\n /**\n * Delay before retries in ms.\n */\n timeout?: number;\n /**\n * A random amount of time before retrying to help prevent large bursts of requests.\n */\n jitter?: number;\n};\n\ntype EdgeHttpRequestArgs = {\n method: string;\n context?: Context;\n retry?: RetryConfig;\n body?: any;\n /**\n * @default true\n */\n json?: boolean;\n\n /**\n * Do not expect a standard EDGE JSON response with a `success` field.\n */\n rawResponse?: boolean;\n};\n\nexport type EdgeHttpGetArgs = Pick<EdgeHttpRequestArgs, 'context' | 'retry'>;\nexport type EdgeHttpPostArgs = Pick<EdgeHttpRequestArgs, 'context' | 'retry' | 'body'>;\n\nexport class EdgeHttpClient {\n private readonly _baseUrl: string;\n\n private _edgeIdentity: EdgeIdentity | undefined;\n\n /**\n * Auth header is cached until receiving the next 401 from EDGE, at which point it gets refreshed.\n */\n private _authHeader: string | undefined;\n\n constructor(baseUrl: string) {\n this._baseUrl = getEdgeUrlWithProtocol(baseUrl, 'http');\n log('created', { url: this._baseUrl });\n }\n\n get baseUrl() {\n return this._baseUrl;\n }\n\n setIdentity(identity: EdgeIdentity): void {\n if (this._edgeIdentity?.identityKey !== identity.identityKey || this._edgeIdentity?.peerKey !== identity.peerKey) {\n this._edgeIdentity = identity;\n this._authHeader = undefined;\n }\n }\n\n //\n // Status\n //\n\n public async getStatus(args?: EdgeHttpGetArgs): Promise<EdgeStatus> {\n return this._call(new URL('/status', this.baseUrl), { ...args, method: 'GET' });\n }\n\n //\n // Agents\n //\n\n public createAgent(body: CreateAgentRequestBody, args?: EdgeHttpGetArgs): Promise<CreateAgentResponseBody> {\n return this._call(new URL('/agents/create', this.baseUrl), { ...args, method: 'POST', body });\n }\n\n public getAgentStatus(\n request: { ownerIdentityKey: PublicKey },\n args?: EdgeHttpGetArgs,\n ): Promise<GetAgentStatusResponseBody> {\n return this._call(new URL(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, this.baseUrl), {\n ...args,\n method: 'GET',\n });\n }\n\n //\n // Credentials\n //\n\n public getCredentialsForNotarization(spaceId: SpaceId, args?: EdgeHttpGetArgs): Promise<GetNotarizationResponseBody> {\n return this._call(new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), { ...args, method: 'GET' });\n }\n\n public async notarizeCredentials(\n spaceId: SpaceId,\n body: PostNotarizationRequestBody,\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n await this._call(new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), { ...args, body, method: 'POST' });\n }\n\n //\n // Identity\n //\n\n public async recoverIdentity(\n body: RecoverIdentityRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<RecoverIdentityResponseBody> {\n return this._call(new URL('/identity/recover', this.baseUrl), { ...args, body, method: 'POST' });\n }\n\n //\n // Invitations\n //\n\n public async joinSpaceByInvitation(\n spaceId: SpaceId,\n body: JoinSpaceRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<JoinSpaceResponseBody> {\n return this._call(new URL(`/spaces/${spaceId}/join`, this.baseUrl), { ...args, body, method: 'POST' });\n }\n\n //\n // OAuth and credentials\n //\n\n public async initiateOAuthFlow(\n body: InitiateOAuthFlowRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<InitiateOAuthFlowResponse> {\n return this._call(new URL('/oauth/initiate', this.baseUrl), { ...args, body, method: 'POST' });\n }\n\n //\n // Spaces\n //\n\n async createSpace(body: CreateSpaceRequest, args?: EdgeHttpGetArgs): Promise<CreateSpaceResponseBody> {\n return this._call(new URL('/spaces/create', this.baseUrl), { ...args, body, method: 'POST' });\n }\n\n //\n // Queues\n //\n\n public async queryQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n query: QueueQuery,\n args?: EdgeHttpGetArgs,\n ): Promise<QueryResult> {\n const { queueId } = query;\n return this._call(\n createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query`, this.baseUrl), {\n after: query.after,\n before: query.before,\n limit: query.limit,\n reverse: query.reverse,\n objectIds: query.objectIds?.join(','),\n }),\n {\n ...args,\n method: 'GET',\n },\n );\n }\n\n public async insertIntoQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n queueId: ObjectId,\n objects: unknown[],\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {\n ...args,\n body: { objects },\n method: 'POST',\n });\n }\n\n public async deleteFromQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n queueId: ObjectId,\n objectIds: ObjectId[],\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(\n createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {\n ids: objectIds.join(','),\n }),\n {\n ...args,\n method: 'DELETE',\n },\n );\n }\n\n //\n // Functions\n //\n\n public async uploadFunction(\n pathParts: { functionId?: string },\n body: UploadFunctionRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<UploadFunctionResponseBody> {\n const formData = new FormData();\n formData.append('name', body.name ?? '');\n formData.append('version', body.version);\n formData.append('ownerPublicKey', body.ownerPublicKey);\n formData.append('entryPoint', body.entryPoint);\n for (const [filename, content] of Object.entries(body.assets)) {\n formData.append(\n 'assets',\n new Blob([content as Uint8Array<ArrayBuffer>], { type: getFileMimeType(filename) }),\n filename,\n );\n }\n\n const path = ['functions', ...(pathParts.functionId ? [pathParts.functionId] : [])].join('/');\n return this._call(new URL(path, this.baseUrl), {\n ...args,\n body: formData,\n method: 'PUT',\n json: false,\n });\n }\n\n public async listFunctions(args?: EdgeHttpGetArgs): Promise<any> {\n return this._call(new URL('/functions', this.baseUrl), { ...args, method: 'GET' });\n }\n\n public async invokeFunction(\n params: {\n functionId: string;\n version?: string;\n spaceId?: SpaceId;\n cpuTimeLimit?: number;\n subrequestsLimit?: number;\n },\n input: unknown,\n args?: EdgeHttpGetArgs,\n ): Promise<any> {\n const url = new URL(`/functions/${params.functionId}`, this.baseUrl);\n if (params.version) {\n url.searchParams.set('version', params.version);\n }\n if (params.spaceId) {\n url.searchParams.set('spaceId', params.spaceId.toString());\n }\n if (params.cpuTimeLimit) {\n url.searchParams.set('cpuTimeLimit', params.cpuTimeLimit.toString());\n }\n if (params.subrequestsLimit) {\n url.searchParams.set('subrequestsLimit', params.subrequestsLimit.toString());\n }\n\n return this._call(url, {\n ...args,\n body: input,\n method: 'POST',\n rawResponse: true,\n });\n }\n\n //\n // Workflows\n //\n\n public async executeWorkflow(\n spaceId: SpaceId,\n graphId: ObjectId,\n input: any,\n args?: EdgeHttpGetArgs,\n ): Promise<ExecuteWorkflowResponseBody> {\n return this._call(new URL(`/workflows/${spaceId}/${graphId}`, this.baseUrl), {\n ...args,\n body: input,\n method: 'POST',\n });\n }\n\n //\n // Triggers\n //\n\n public async getCronTriggers(spaceId: SpaceId) {\n return this._call(new URL(`/test/functions/${spaceId}/triggers/crons`, this.baseUrl), { method: 'GET' });\n }\n\n //\n // Import/Export space.\n //\n\n public async importBundle(\n spaceId: SpaceId, //\n body: ImportBundleRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(new URL(`/spaces/${spaceId}/import`, this.baseUrl), { ...args, body, method: 'PUT' });\n }\n\n public async exportBundle(\n spaceId: SpaceId,\n body: ExportBundleRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<ExportBundleResponse> {\n return this._call(new URL(`/spaces/${spaceId}/export`, this.baseUrl), {\n ...args,\n body,\n method: 'POST',\n });\n }\n\n //\n // Internal\n //\n\n private async _fetch<T>(url: URL, args: EdgeHttpRequestArgs): Promise<T> {\n return pipe(\n HttpClient.get(url),\n withLogging,\n withRetryConfig,\n Effect.provide(FetchHttpClient.layer),\n Effect.provide(HttpConfig.default),\n Effect.withSpan('EdgeHttpClient'),\n Effect.runPromise,\n ) as T;\n }\n\n // TODO(burdon): Refactor with effect (see edge-http-client.test.ts).\n private async _call<T>(url: URL, args: EdgeHttpRequestArgs): Promise<T> {\n const shouldRetry = createRetryHandler(args);\n const requestContext = args.context ?? new Context();\n log('fetch', { url, request: args.body });\n\n let handledAuth = false;\n while (true) {\n let processingError: EdgeCallFailedError | undefined = undefined;\n let retryAfterHeaderValue: number = Number.NaN;\n try {\n const request = createRequest(args, this._authHeader);\n const response = await fetch(url, request);\n retryAfterHeaderValue = Number(response.headers.get('Retry-After'));\n if (response.ok) {\n const body = (await response.json()) as EdgeHttpResponse<T>;\n\n if (args.rawResponse) {\n return body as any;\n }\n\n if (!('success' in body)) {\n return body;\n }\n\n if (body.success) {\n return body.data;\n }\n\n log.warn('unsuccessful edge response', { url, body });\n if (body.errorData?.type === 'auth_challenge' && typeof body.errorData?.challenge === 'string') {\n processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);\n } else if (body.errorData) {\n processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);\n }\n } else if (response.status === 401 && !handledAuth) {\n this._authHeader = await this._handleUnauthorized(response);\n handledAuth = true;\n continue;\n } else {\n processingError = await EdgeCallFailedError.fromHttpFailure(response);\n }\n } catch (error: any) {\n processingError = EdgeCallFailedError.fromProcessingFailureCause(error);\n }\n\n if (processingError?.isRetryable && (await shouldRetry(requestContext, retryAfterHeaderValue))) {\n log('retrying edge request', { url, processingError });\n } else {\n throw processingError!;\n }\n }\n }\n\n private async _handleUnauthorized(response: Response): Promise<string> {\n if (!this._edgeIdentity) {\n log.warn('unauthorized response received before identity was set');\n throw await EdgeCallFailedError.fromHttpFailure(response);\n }\n\n const challenge = await handleAuthChallenge(response, this._edgeIdentity);\n return encodeAuthHeader(challenge);\n }\n}\n\nconst createRequest = (\n { method, body, json = true }: EdgeHttpRequestArgs,\n authHeader: string | undefined,\n): RequestInit => {\n let requestBody: BodyInit | undefined;\n const headers: HeadersInit = {};\n\n if (json) {\n requestBody = body && JSON.stringify(body);\n headers['Content-Type'] = 'application/json';\n } else {\n requestBody = body;\n }\n\n if (typeof requestBody === 'string' && requestBody.length > WARNING_BODY_SIZE) {\n log.warn('Request with large body', { bodySize: requestBody.length });\n }\n\n if (authHeader) {\n headers['Authorization'] = authHeader;\n }\n\n return {\n method,\n body: requestBody,\n headers,\n };\n};\n\n/**\n * @deprecated\n */\nconst createRetryHandler = ({ retry }: EdgeHttpRequestArgs) => {\n if (!retry || retry.count < 1) {\n return async () => false;\n }\n\n let retries = 0;\n const maxRetries = retry.count ?? DEFAULT_MAX_RETRIES_COUNT;\n const baseTimeout = retry.timeout ?? DEFAULT_RETRY_TIMEOUT;\n const jitter = retry.jitter ?? DEFAULT_RETRY_JITTER;\n return async (ctx: Context, retryAfter: number) => {\n if (++retries > maxRetries || ctx.disposed) {\n return false;\n }\n\n if (retryAfter) {\n await sleep(retryAfter);\n } else {\n const timeout = baseTimeout + Math.random() * jitter;\n await sleep(timeout);\n }\n\n return true;\n };\n};\n\nconst getFileMimeType = (filename: string) =>\n ['.js', '.mjs'].some((codeExtension) => filename.endsWith(codeExtension))\n ? 'application/javascript+module'\n : filename.endsWith('.wasm')\n ? 'application/wasm'\n : 'application/octet-stream';\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type HttpClient } from '@effect/platform';\nimport { type HttpClientError } from '@effect/platform/HttpClientError';\nimport { type HttpClientResponse } from '@effect/platform/HttpClientResponse';\nimport { Context, Duration, Effect, Layer, Schedule } from 'effect';\n\nimport { log } from '@dxos/log';\n\n// TODO(burdon): Factor out.\n\nexport type RetryOptions = {\n timeout: Duration.Duration;\n retryTimes: number;\n retryBaseDelay: Duration.Duration;\n};\n\n// Layer pattern.\nexport class HttpConfig extends Context.Tag('HttpConfig')<HttpConfig, RetryOptions>() {\n static default = Layer.succeed(HttpConfig, {\n timeout: Duration.millis(1_000),\n retryTimes: 3,\n retryBaseDelay: Duration.millis(1_000),\n });\n}\n\n// HOC pattern.\nexport const withRetry = (\n effect: Effect.Effect<HttpClientResponse, HttpClientError, HttpClient.HttpClient>,\n {\n timeout = Duration.millis(1_000),\n retryBaseDelay = Duration.millis(1_000),\n retryTimes = 3,\n }: Partial<RetryOptions> = {},\n) => {\n return effect.pipe(\n Effect.flatMap((res) =>\n // Treat 500 errors as retryable?\n res.status === 500 ? Effect.fail(new Error(res.status.toString())) : res.json,\n ),\n Effect.timeout(timeout),\n Effect.retry({\n schedule: Schedule.exponential(retryBaseDelay).pipe(Schedule.jittered),\n times: retryTimes,\n }),\n );\n};\n\nexport const withRetryConfig = (effect: Effect.Effect<HttpClientResponse, HttpClientError, HttpClient.HttpClient>) =>\n Effect.gen(function* () {\n const config = yield* HttpConfig;\n return yield* withRetry(effect, config);\n });\n\nexport const withLogging = <A extends HttpClientResponse, E, R>(effect: Effect.Effect<A, E, R>) =>\n effect.pipe(Effect.tap((res) => log.info('response', { status: res.status })));\n\n/**\n *\n */\n// TODO(burdon): Document.\nexport const encodeAuthHeader = (challenge: Uint8Array) => {\n const encodedChallenge = Buffer.from(challenge).toString('base64');\n return `VerifiablePresentation pb;base64,${encodedChallenge}`;\n};\n"],
5
- "mappings": ";;;;;;;;;;;AAIA,cAAc;;;ACAd,SAASA,kBAAkBC,wBAAwB;AAEnD,SAASC,iBAAiB;AAC1B,SAASC,eAAe;AACxB,SAASC,iBAAiB;;AAQnB,IAAMC,2BAA2B,OAAOC,QAAgBC,QAAAA;AAC7D,SAAO;IACLC,aAAaD,IAAIE,MAAK;IACtBC,SAASH,IAAIE,MAAK;IAClBE,oBAAoB,OAAO,EAAEC,UAAS,MAAE;AACtC,aAAOX,iBAAiB;QACtBY,cAAc;UACZC,aAAa;;YAEX,MAAMd,iBAAiB;cACrBe,WAAW;gBACT,SAAS;cACX;cACAC,QAAQT;cACRU,SAASV;cACTD;YACF,CAAA;;QAEJ;QACAA;QACAY,WAAWX;QACXY,OAAOP;MACT,CAAA;IACF;EACF;AACF;AAKO,IAAMQ,0BAA0B,OACrCd,QACAE,aACAE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AAuB,CAAC;AAE9B,MAAI7C,MAAM;AACRkE,kBAAchH,QAAQiH,KAAKC,UAAUlH,IAAAA;AACrC2F,YAAQ,cAAA,IAAkB;EAC5B,OAAO;AACLqB,kBAAchH;EAChB;AAEA,MAAI,OAAOgH,gBAAgB,YAAYA,YAAYG,SAASpI,mBAAmB;AAC7EmG,IAAAA,KAAIa,KAAK,2BAA2B;MAAEqB,UAAUJ,YAAYG;IAAO,GAAA;;;;;;EACrE;AAEA,MAAIJ,YAAY;AACdpB,YAAQ,eAAA,IAAmBoB;EAC7B;AAEA,SAAO;IACLjH;IACAE,MAAMgH;IACNrB;EACF;AACF;AAKA,IAAMb,qBAAqB,CAAC,EAAEuC,MAAK,MAAuB;AACxD,MAAI,CAACA,SAASA,MAAMC,QAAQ,GAAG;AAC7B,WAAO,YAAY;EACrB;AAEA,MAAIC,UAAU;AACd,QAAMC,aAAaH,MAAMC,SAASxI;AAClC,QAAM2I,cAAcJ,MAAMK,WAAW9I;AACrC,QAAM+I,SAASN,MAAMM,UAAU9I;AAC/B,SAAO,OAAO+I,KAAcC,eAAAA;AAC1B,QAAI,EAAEN,UAAUC,cAAcI,IAAIE,UAAU;AAC1C,aAAO;IACT;AAEA,QAAID,YAAY;AACd,YAAME,MAAMF,UAAAA;IACd,OAAO;AACL,YAAMH,UAAUD,cAAcO,KAAKC,OAAM,IAAKN;AAC9C,YAAMI,MAAML,OAAAA;IACd;AAEA,WAAO;EACT;AACF;AAEA,IAAM/E,kBAAkB,CAACP,aACvB;EAAC;EAAO;EAAQ8F,KAAK,CAACC,kBAAkB/F,SAASgG,SAASD,aAAAA,CAAAA,IACtD,kCACA/F,SAASgG,SAAS,OAAA,IAChB,qBACA;",
6
- "names": ["createCredential", "signPresentation", "invariant", "Keyring", "PublicKey", "createDeviceEdgeIdentity", "signer", "key", "identityKey", "toHex", "peerKey", "presentCredentials", "challenge", "presentation", "credentials", "assertion", "issuer", "subject", "signerKey", "nonce", "createChainEdgeIdentity", "chain", "credentialsToSign", "length", "signingKey", "createEphemeralEdgeIdentity", "keyring", "createKey", "createTestHaloEdgeIdentity", "deviceKey", "deviceAdmission", "credential", "createStubEdgeIdentity", "random", "Error", "Event", "PersistentLifecycle", "Trigger", "TriggerState", "scheduleMicroTask", "Resource", "log", "logInfo", "EdgeStatus", "invariant", "schema", "handleAuthChallenge", "failedResponse", "identity", "status", "headerValue", "headers", "get", "startsWith", "challenge", "slice", "length", "presentation", "presentCredentials", "Buffer", "from", "getCodecForType", "encode", "WebSocket", "scheduleTask", "scheduleTaskInterval", "Context", "Resource", "invariant", "log", "logInfo", "EdgeWebsocketProtocol", "buf", "MessageSchema", "SIGNAL_KEEPALIVE_INTERVAL", "SIGNAL_KEEPALIVE_TIMEOUT", "EdgeWsConnection", "Resource", "info", "open", "isOpen", "identity", "_identity", "identityKey", "device", "peerKey", "send", "message", "invariant", "_ws", "_wsMuxer", "log", "payload", "protocol", "getPayloadType", "includes", "EdgeWebsocketProtocol", "V0", "binary", "buf", "toBinary", "MessageSchema", "length", "CLOUDFLARE_MESSAGE_MAX_BYTES", "error", "byteLength", "serviceId", "catch", "e", "_open", "baseProtocols", "Object", "values", "WebSocket", "_connectionInfo", "url", "toString", "protocolHeader", "muxer", "WebSocketMuxer", "onopen", "_callbacks", "onConnected", "_scheduleHeartbeats", "verbose", "currentIdentity", "onclose", "event", "warn", "code", "reason", "onRestartRequired", "destroy", "onerror", "onmessage", "type", "_lastReceivedMessageTimestamp", "Date", "now", "data", "_rescheduleHeartbeatTimeout", "bytes", "toUint8Array", "fromBinary", "receiveData", "from", "source", "onMessage", "_close", "_inactivityTimeoutCtx", "dispose", "close", "undefined", "err", "Error", "scheduleTaskInterval", "_ctx", "Context", "scheduleTask", "lastReceivedMessageTimestamp", "EdgeConnectionClosedError", "Error", "EdgeIdentityChangedError", "getEdgeUrlWithProtocol", "baseUrl", "protocol", "isSecure", "startsWith", "url", "URL", "toString", "DEFAULT_TIMEOUT", "EdgeClient", "Resource", "info", "open", "isOpen", "status", "identity", "_identity", "identityKey", "device", "peerKey", "Boolean", "_currentConnection", "_ready", "state", "TriggerState", "RESOLVED", "EdgeStatus", "CONNECTED", "NOT_CONNECTED", "setIdentity", "log", "oldIdentity", "_closeCurrentConnection", "EdgeIdentityChangedError", "_persistentLifecycle", "scheduleRestart", "send", "message", "wait", "timeout", "_config", "EdgeConnectionClosedError", "source", "onMessage", "listener", "_messageListeners", "add", "delete", "onReconnected", "_reconnectListeners", "scheduleMicroTask", "_ctx", "has", "error", "catch", "_open", "err", "warn", "_close", "close", "_connect", "disposed", "undefined", "path", "protocolHeader", "disableAuth", "_createAuthHeader", "restartRequired", "Trigger", "url", "URL", "_baseWsUrl", "toString", "connection", "EdgeWsConnection", "onConnected", "_isActive", "wake", "_notifyReconnected", "verbose", "onRestartRequired", "_notifyMessageReceived", "from", "type", "payload", "typeUrl", "Promise", "race", "_disconnect", "statusChanged", "emit", "throw", "reset", "protocol", "getPayloadType", "httpUrl", "_baseHttpUrl", "getEdgeUrlWithProtocol", "response", "fetch", "method", "encodePresentationWsAuthHeader", "handleAuthChallenge", "statusText", "_define_property", "Event", "PersistentLifecycle", "start", "stop", "Set", "socketEndpoint", "encodedPresentation", "encodedToken", "Buffer", "replace", "replaceAll", "FetchHttpClient", "HttpClient", "Effect", "pipe", "sleep", "Context", "log", "EdgeAuthChallengeError", "EdgeCallFailedError", "createUrl", "Context", "Duration", "Effect", "Layer", "Schedule", "log", "HttpConfig", "Tag", "_define_property", "default", "succeed", "timeout", "millis", "retryTimes", "retryBaseDelay", "withRetry", "effect", "pipe", "flatMap", "res", "status", "fail", "Error", "toString", "json", "retry", "schedule", "exponential", "jittered", "times", "withRetryConfig", "gen", "config", "withLogging", "tap", "info", "encodeAuthHeader", "challenge", "encodedChallenge", "Buffer", "from", "DEFAULT_RETRY_TIMEOUT", "DEFAULT_RETRY_JITTER", "DEFAULT_MAX_RETRIES_COUNT", "WARNING_BODY_SIZE", "EdgeHttpClient", "baseUrl", "_baseUrl", "setIdentity", "identity", "_edgeIdentity", "identityKey", "peerKey", "_authHeader", "undefined", "getStatus", "args", "_call", "URL", "method", "createAgent", "body", "getAgentStatus", "request", "ownerIdentityKey", "toHex", "getCredentialsForNotarization", "spaceId", "notarizeCredentials", "recoverIdentity", "joinSpaceByInvitation", "initiateOAuthFlow", "createSpace", "queryQueue", "subspaceTag", "query", "queueId", "createUrl", "after", "before", "limit", "reverse", "objectIds", "join", "insertIntoQueue", "objects", "deleteFromQueue", "ids", "uploadFunction", "pathParts", "formData", "FormData", "append", "name", "version", "ownerPublicKey", "entryPoint", "filename", "content", "Object", "entries", "assets", "Blob", "type", "getFileMimeType", "path", "functionId", "json", "listFunctions", "invokeFunction", "params", "input", "url", "searchParams", "set", "toString", "cpuTimeLimit", "subrequestsLimit", "rawResponse", "executeWorkflow", "graphId", "getCronTriggers", "importBundle", "exportBundle", "_fetch", "pipe", "HttpClient", "get", "withLogging", "withRetryConfig", "Effect", "provide", "FetchHttpClient", "layer", "HttpConfig", "default", "withSpan", "runPromise", "shouldRetry", "createRetryHandler", "requestContext", "context", "Context", "log", "handledAuth", "processingError", "retryAfterHeaderValue", "Number", "NaN", "createRequest", "response", "fetch", "headers", "ok", "success", "data", "warn", "errorData", "challenge", "EdgeAuthChallengeError", "EdgeCallFailedError", "fromUnsuccessfulResponse", "status", "_handleUnauthorized", "fromHttpFailure", "error", "fromProcessingFailureCause", "isRetryable", "handleAuthChallenge", "encodeAuthHeader", "_define_property", "getEdgeUrlWithProtocol", "authHeader", "requestBody", "JSON", "stringify", "length", "bodySize", "retry", "count", "retries", "maxRetries", "baseTimeout", "timeout", "jitter", "ctx", "retryAfter", "disposed", "sleep", "Math", "random", "some", "codeExtension", "endsWith"]
7
- }
@@ -1 +0,0 @@
1
- {"inputs":{"src/protocol.ts":{"bytes":10506,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/defs.ts":{"bytes":1550,"imports":[{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"src/protocol.ts","kind":"import-statement","original":"./protocol"}],"format":"esm"},"src/edge-ws-muxer.ts":{"bytes":24722,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"src/defs.ts","kind":"import-statement","original":"./defs"}],"format":"esm"},"src/auth.ts":{"bytes":12117,"imports":[{"path":"@dxos/credentials","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keyring","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true}],"format":"esm"},"src/edge-identity.ts":{"bytes":3976,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true}],"format":"esm"},"src/edge-ws-connection.ts":{"bytes":26028,"imports":[{"path":"isomorphic-ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"src/defs.ts","kind":"import-statement","original":"./defs"},{"path":"src/edge-ws-muxer.ts","kind":"import-statement","original":"./edge-ws-muxer"},{"path":"src/protocol.ts","kind":"import-statement","original":"./protocol"}],"format":"esm"},"src/errors.ts":{"bytes":1188,"imports":[],"format":"esm"},"src/utils.ts":{"bytes":1398,"imports":[],"format":"esm"},"src/edge-client.ts":{"bytes":35764,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/client/services","kind":"import-statement","external":true},{"path":"src/defs.ts","kind":"import-statement","original":"./defs"},{"path":"src/edge-identity.ts","kind":"import-statement","original":"./edge-identity"},{"path":"src/edge-ws-connection.ts","kind":"import-statement","original":"./edge-ws-connection"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"src/utils.ts","kind":"import-statement","original":"./utils"}],"format":"esm"},"src/http-client.ts":{"bytes":7059,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/edge-http-client.ts":{"bytes":47533,"imports":[{"path":"@effect/platform","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"src/edge-identity.ts","kind":"import-statement","original":"./edge-identity"},{"path":"src/http-client.ts","kind":"import-statement","original":"./http-client"},{"path":"src/utils.ts","kind":"import-statement","original":"./utils"}],"format":"esm"},"src/index.ts":{"bytes":1375,"imports":[{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"src/auth.ts","kind":"import-statement","original":"./auth"},{"path":"src/defs.ts","kind":"import-statement","original":"./defs"},{"path":"src/edge-client.ts","kind":"import-statement","original":"./edge-client"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"src/protocol.ts","kind":"import-statement","original":"./protocol"},{"path":"src/edge-http-client.ts","kind":"import-statement","original":"./edge-http-client"},{"path":"src/edge-identity.ts","kind":"import-statement","original":"./edge-identity"},{"path":"src/edge-ws-muxer.ts","kind":"import-statement","original":"./edge-ws-muxer"},{"path":"src/http-client.ts","kind":"import-statement","original":"./http-client"}],"format":"esm"},"src/testing/test-server.ts":{"bytes":4545,"imports":[{"path":"@dxos/node-std/http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/testing/test-utils.ts":{"bytes":13985,"imports":[{"path":"isomorphic-ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"src/defs.ts","kind":"import-statement","original":"../defs"},{"path":"src/edge-ws-muxer.ts","kind":"import-statement","original":"../edge-ws-muxer"},{"path":"src/protocol.ts","kind":"import-statement","original":"../protocol"}],"format":"esm"},"src/testing/index.ts":{"bytes":570,"imports":[{"path":"src/testing/test-server.ts","kind":"import-statement","original":"./test-server"},{"path":"src/testing/test-utils.ts","kind":"import-statement","original":"./test-utils"}],"format":"esm"}},"outputs":{"dist/lib/browser/edge-ws-muxer.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"dist/lib/browser/edge-ws-muxer.mjs":{"imports":[{"path":"dist/lib/browser/chunk-IKP53CBQ.mjs","kind":"import-statement"}],"exports":["CLOUDFLARE_MESSAGE_MAX_BYTES","CLOUDFLARE_RPC_MAX_BYTES","WebSocketMuxer"],"entryPoint":"src/edge-ws-muxer.ts","inputs":{},"bytes":249},"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":65162},"dist/lib/browser/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-IKP53CBQ.mjs","kind":"import-statement"},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"@dxos/credentials","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keyring","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/client/services","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"isomorphic-ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"@effect/platform","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["CLOUDFLARE_MESSAGE_MAX_BYTES","CLOUDFLARE_RPC_MAX_BYTES","EdgeClient","EdgeConnectionClosedError","EdgeHttpClient","EdgeIdentityChangedError","HttpConfig","Protocol","WebSocketMuxer","createChainEdgeIdentity","createDeviceEdgeIdentity","createEphemeralEdgeIdentity","createStubEdgeIdentity","createTestHaloEdgeIdentity","encodeAuthHeader","getTypename","handleAuthChallenge","protocol","toUint8Array","withLogging","withRetry","withRetryConfig"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":60},"src/auth.ts":{"bytesInOutput":2963},"src/edge-client.ts":{"bytesInOutput":10154},"src/edge-identity.ts":{"bytesInOutput":1158},"src/edge-ws-connection.ts":{"bytesInOutput":8124},"src/errors.ts":{"bytesInOutput":232},"src/utils.ts":{"bytesInOutput":244},"src/edge-http-client.ts":{"bytesInOutput":11201},"src/http-client.ts":{"bytesInOutput":1673}},"bytes":36743},"dist/lib/browser/testing/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":9536},"dist/lib/browser/testing/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-IKP53CBQ.mjs","kind":"import-statement"},{"path":"@dxos/node-std/http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"isomorphic-ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true}],"exports":["DEFAULT_PORT","createTestEdgeWsServer","createTestServer","responseHandler"],"entryPoint":"src/testing/index.ts","inputs":{"src/testing/test-server.ts":{"bytesInOutput":1151},"src/testing/index.ts":{"bytesInOutput":0},"src/testing/test-utils.ts":{"bytesInOutput":3678}},"bytes":5103},"dist/lib/browser/chunk-IKP53CBQ.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":17477},"dist/lib/browser/chunk-IKP53CBQ.mjs":{"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf","kind":"import-statement","external":true},{"path":"@dxos/protocols/buf/dxos/edge/messenger_pb","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["CLOUDFLARE_MESSAGE_MAX_BYTES","CLOUDFLARE_RPC_MAX_BYTES","Protocol","WebSocketMuxer","getTypename","protocol","toUint8Array"],"inputs":{"src/edge-ws-muxer.ts":{"bytesInOutput":6257},"src/defs.ts":{"bytesInOutput":298},"src/protocol.ts":{"bytesInOutput":2888}},"bytes":9733}}}
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../src/testing/test-server.ts", "../../../../src/testing/test-utils.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport http from 'node:http';\n\nimport { log } from '@dxos/log';\n\nexport type TestServer = {\n url: string;\n close: () => void;\n};\n\nexport type ResponseHandler = (req: http.IncomingMessage, res: http.ServerResponse) => void;\n\nexport const createTestServer = (responseHandler: ResponseHandler) => {\n const server = http.createServer(responseHandler);\n\n return new Promise<TestServer>((resolve) => {\n server.listen(0, () => {\n const address = server.address();\n const port = typeof address === 'object' && address ? address.port : 0;\n resolve({\n url: `http://localhost:${port}`,\n close: () => server.close(),\n });\n });\n });\n};\n\nexport const responseHandler = (cb: (attempt: number) => false | object): ResponseHandler => {\n let attempt = 0;\n return (req, res) => {\n const data = cb(++attempt) ?? {};\n if (data === false) {\n log('simulating failure', { attempt });\n res.statusCode = 500;\n res.statusMessage = 'Simulating failure';\n res.end('');\n } else {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ success: true, data }));\n }\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'isomorphic-ws';\n\nimport { Trigger } from '@dxos/async';\nimport { log } from '@dxos/log';\nimport { EdgeWebsocketProtocol } from '@dxos/protocols';\nimport { buf } from '@dxos/protocols/buf';\nimport { type Message, MessageSchema, TextMessageSchema } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nimport { protocol } from '../defs';\nimport { WebSocketMuxer } from '../edge-ws-muxer';\nimport { toUint8Array } from '../protocol';\n\nexport const DEFAULT_PORT = 8080;\n\ntype TestEdgeWsServerParams = {\n admitConnection?: Trigger;\n payloadDecoder?: (payload: Uint8Array) => any;\n messageHandler?: (payload: any) => Promise<Uint8Array | undefined>;\n};\n\nexport const createTestEdgeWsServer = async (port = DEFAULT_PORT, params?: TestEdgeWsServerParams) => {\n const wsServer = new WebSocket.Server({\n port,\n verifyClient: createConnectionDelayHandler(params),\n handleProtocols: () => EdgeWebsocketProtocol.V1,\n });\n\n let connection: { ws: WebSocket; muxer: WebSocketMuxer } | undefined;\n\n const messageSink: any[] = [];\n const messageSourceLog: any[] = [];\n const closeTrigger = new Trigger();\n const sendResponseMessage = createResponseSender(() => connection!.muxer);\n\n wsServer.on('connection', (ws) => {\n const muxer = new WebSocketMuxer(ws);\n connection = { ws, muxer };\n ws.on('error', (err) => log.catch(err));\n ws.on('message', async (data) => {\n if (String(data) === '__ping__') {\n ws.send('__pong__');\n return;\n }\n const message = muxer.receiveData(await toUint8Array(data));\n if (!message) {\n return;\n }\n const { request, requestPayload } = await decodePayload(message, params);\n messageSourceLog.push(request.source);\n if (params?.messageHandler) {\n const responsePayload = await params.messageHandler(requestPayload);\n if (responsePayload && connection) {\n sendResponseMessage(request, responsePayload);\n }\n }\n log('message', { payload: requestPayload });\n messageSink.push(requestPayload);\n });\n\n ws.on('close', () => {\n connection = undefined;\n closeTrigger.wake();\n });\n });\n\n return {\n server: wsServer,\n messageSink,\n messageSourceLog,\n endpoint: `ws://127.0.0.1:${port}`,\n cleanup: () => wsServer.close(),\n currentConnection: () => connection,\n sendResponseMessage,\n sendMessage: (msg: Message) => {\n return connection!.muxer.send(msg);\n },\n closeConnection: () => {\n closeTrigger.reset();\n connection!.ws.close(1011);\n return closeTrigger.wait();\n },\n };\n};\n\nconst createConnectionDelayHandler = (params: TestEdgeWsServerParams | undefined) => {\n return (_: any, callback: (admit: boolean) => void) => {\n if (params?.admitConnection) {\n log('delaying edge connection admission');\n void params.admitConnection.wait().then(() => {\n callback(true);\n log('edge connection admitted');\n });\n } else {\n callback(true);\n }\n };\n};\n\nconst createResponseSender = (connection: () => WebSocketMuxer) => {\n return (request: Message, responsePayload: Uint8Array) => {\n const recipient = request.source!;\n void connection().send(\n buf.create(MessageSchema, {\n source: {\n identityKey: recipient.identityKey,\n peerKey: recipient.peerKey,\n },\n serviceId: request.serviceId!,\n payload: { value: responsePayload },\n }),\n );\n };\n};\n\nconst decodePayload = async (request: Message, params: TestEdgeWsServerParams | undefined) => {\n const requestPayload = params?.payloadDecoder\n ? params.payloadDecoder(request.payload!.value!)\n : protocol.getPayload(request, TextMessageSchema);\n return { request, requestPayload };\n};\n"],
5
- "mappings": ";;;;;;;AAIA,OAAOA,UAAU;AAEjB,SAASC,WAAW;;AASb,IAAMC,mBAAmB,CAACC,qBAAAA;AAC/B,QAAMC,SAASJ,KAAKK,aAAaF,gBAAAA;AAEjC,SAAO,IAAIG,QAAoB,CAACC,YAAAA;AAC9BH,WAAOI,OAAO,GAAG,MAAA;AACf,YAAMC,UAAUL,OAAOK,QAAO;AAC9B,YAAMC,OAAO,OAAOD,YAAY,YAAYA,UAAUA,QAAQC,OAAO;AACrEH,cAAQ;QACNI,KAAK,oBAAoBD,IAAAA;QACzBE,OAAO,MAAMR,OAAOQ,MAAK;MAC3B,CAAA;IACF,CAAA;EACF,CAAA;AACF;AAEO,IAAMT,kBAAkB,CAACU,OAAAA;AAC9B,MAAIC,UAAU;AACd,SAAO,CAACC,KAAKC,QAAAA;AACX,UAAMC,OAAOJ,GAAG,EAAEC,OAAAA,KAAY,CAAC;AAC/B,QAAIG,SAAS,OAAO;AAClBhB,UAAI,sBAAsB;QAAEa;MAAQ,GAAA;;;;;;AACpCE,UAAIE,aAAa;AACjBF,UAAIG,gBAAgB;AACpBH,UAAII,IAAI,EAAA;IACV,OAAO;AACLJ,UAAIK,UAAU,KAAK;QAAE,gBAAgB;MAAmB,CAAA;AACxDL,UAAII,IAAIE,KAAKC,UAAU;QAAEC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BAC3B7D,OAAO6D,eAAehC,QAAQO,QAASwB,KAAK,IAC5CE,SAASC,WAAWlC,SAASmC,iBAAAA;AACjC,SAAO;IAAEnC;IAASC;EAAe;AACnC;",
6
- "names": ["http", "log", "createTestServer", "responseHandler", "server", "createServer", "Promise", "resolve", "listen", "address", "port", "url", "close", "cb", "attempt", "req", "res", "data", "statusCode", "statusMessage", "end", "writeHead", "JSON", "stringify", "success", "WebSocket", "Trigger", "log", "EdgeWebsocketProtocol", "buf", "MessageSchema", "TextMessageSchema", "DEFAULT_PORT", "createTestEdgeWsServer", "port", "params", "wsServer", "WebSocket", "Server", "verifyClient", "createConnectionDelayHandler", "handleProtocols", "EdgeWebsocketProtocol", "V1", "connection", "messageSink", "messageSourceLog", "closeTrigger", "Trigger", "sendResponseMessage", "createResponseSender", "muxer", "on", "ws", "WebSocketMuxer", "err", "log", "catch", "data", "String", "send", "message", "receiveData", "toUint8Array", "request", "requestPayload", "decodePayload", "push", "source", "messageHandler", "responsePayload", "payload", "undefined", "wake", "server", "endpoint", "cleanup", "close", "currentConnection", "sendMessage", "msg", "closeConnection", "reset", "wait", "_", "callback", "admitConnection", "then", "recipient", "buf", "create", "MessageSchema", "identityKey", "peerKey", "serviceId", "value", "payloadDecoder", "protocol", "getPayload", "TextMessageSchema"]
7
- }