@dxos/edge-client 0.8.3 → 0.8.4-main.2e9d522

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 (49) hide show
  1. package/dist/lib/browser/{chunk-VHS3XEIX.mjs → chunk-LMP5TVOP.mjs} +8 -8
  2. package/dist/lib/browser/edge-ws-muxer.mjs +1 -1
  3. package/dist/lib/browser/index.mjs +216 -148
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +61 -16
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node-esm/{chunk-HGQUUFIJ.mjs → chunk-X7J46ISZ.mjs} +8 -8
  9. package/dist/lib/node-esm/edge-ws-muxer.mjs +1 -1
  10. package/dist/lib/node-esm/index.mjs +216 -148
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing/index.mjs +61 -16
  14. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  15. package/dist/types/src/edge-http-client.d.ts +33 -30
  16. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  17. package/dist/types/src/edge-http-client.test.d.ts +2 -0
  18. package/dist/types/src/edge-http-client.test.d.ts.map +1 -0
  19. package/dist/types/src/edge-ws-connection.d.ts +1 -0
  20. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  21. package/dist/types/src/http-client.d.ts +22 -0
  22. package/dist/types/src/http-client.d.ts.map +1 -0
  23. package/dist/types/src/http-client.test.d.ts +2 -0
  24. package/dist/types/src/http-client.test.d.ts.map +1 -0
  25. package/dist/types/src/testing/index.d.ts +1 -0
  26. package/dist/types/src/testing/index.d.ts.map +1 -1
  27. package/dist/types/src/testing/test-server.d.ts +9 -0
  28. package/dist/types/src/testing/test-server.d.ts.map +1 -0
  29. package/dist/types/tsconfig.tsbuildinfo +1 -1
  30. package/package.json +18 -14
  31. package/src/edge-http-client.test.ts +22 -0
  32. package/src/edge-http-client.ts +191 -134
  33. package/src/edge-ws-connection.ts +10 -2
  34. package/src/http-client.test.ts +54 -0
  35. package/src/http-client.ts +67 -0
  36. package/src/testing/index.ts +1 -0
  37. package/src/testing/test-server.ts +45 -0
  38. package/src/testing/test-utils.ts +1 -1
  39. package/dist/lib/node/chunk-XNHBUTNB.cjs +0 -317
  40. package/dist/lib/node/chunk-XNHBUTNB.cjs.map +0 -7
  41. package/dist/lib/node/edge-ws-muxer.cjs +0 -33
  42. package/dist/lib/node/edge-ws-muxer.cjs.map +0 -7
  43. package/dist/lib/node/index.cjs +0 -1060
  44. package/dist/lib/node/index.cjs.map +0 -7
  45. package/dist/lib/node/meta.json +0 -1
  46. package/dist/lib/node/testing/index.cjs +0 -169
  47. package/dist/lib/node/testing/index.cjs.map +0 -7
  48. /package/dist/lib/browser/{chunk-VHS3XEIX.mjs.map → chunk-LMP5TVOP.mjs.map} +0 -0
  49. /package/dist/lib/node-esm/{chunk-HGQUUFIJ.mjs.map → chunk-X7J46ISZ.mjs.map} +0 -0
@@ -1,1060 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var node_exports = {};
31
- __export(node_exports, {
32
- CLOUDFLARE_MESSAGE_MAX_BYTES: () => import_chunk_XNHBUTNB.CLOUDFLARE_MESSAGE_MAX_BYTES,
33
- CLOUDFLARE_RPC_MAX_BYTES: () => import_chunk_XNHBUTNB.CLOUDFLARE_RPC_MAX_BYTES,
34
- EdgeClient: () => EdgeClient,
35
- EdgeConnectionClosedError: () => EdgeConnectionClosedError,
36
- EdgeHttpClient: () => EdgeHttpClient,
37
- EdgeIdentityChangedError: () => EdgeIdentityChangedError,
38
- Protocol: () => import_chunk_XNHBUTNB.Protocol,
39
- WebSocketMuxer: () => import_chunk_XNHBUTNB.WebSocketMuxer,
40
- createChainEdgeIdentity: () => createChainEdgeIdentity,
41
- createDeviceEdgeIdentity: () => createDeviceEdgeIdentity,
42
- createEphemeralEdgeIdentity: () => createEphemeralEdgeIdentity,
43
- createStubEdgeIdentity: () => createStubEdgeIdentity,
44
- createTestHaloEdgeIdentity: () => createTestHaloEdgeIdentity,
45
- getTypename: () => import_chunk_XNHBUTNB.getTypename,
46
- handleAuthChallenge: () => handleAuthChallenge,
47
- protocol: () => import_chunk_XNHBUTNB.protocol,
48
- toUint8Array: () => import_chunk_XNHBUTNB.toUint8Array
49
- });
50
- module.exports = __toCommonJS(node_exports);
51
- var import_chunk_XNHBUTNB = require("./chunk-XNHBUTNB.cjs");
52
- __reExport(node_exports, require("@dxos/protocols/buf/dxos/edge/messenger_pb"), module.exports);
53
- var import_async = require("@dxos/async");
54
- var import_context = require("@dxos/context");
55
- var import_log = require("@dxos/log");
56
- var import_services = require("@dxos/protocols/proto/dxos/client/services");
57
- var import_invariant = require("@dxos/invariant");
58
- var import_proto = require("@dxos/protocols/proto");
59
- var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
60
- var import_async2 = require("@dxos/async");
61
- var import_context2 = require("@dxos/context");
62
- var import_invariant2 = require("@dxos/invariant");
63
- var import_log2 = require("@dxos/log");
64
- var import_protocols = require("@dxos/protocols");
65
- var import_buf = require("@dxos/protocols/buf");
66
- var import_messenger_pb = require("@dxos/protocols/buf/dxos/edge/messenger_pb");
67
- var import_credentials = require("@dxos/credentials");
68
- var import_invariant3 = require("@dxos/invariant");
69
- var import_keyring = require("@dxos/keyring");
70
- var import_keys = require("@dxos/keys");
71
- var import_async3 = require("@dxos/async");
72
- var import_context3 = require("@dxos/context");
73
- var import_log3 = require("@dxos/log");
74
- var import_protocols2 = require("@dxos/protocols");
75
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
76
- var handleAuthChallenge = async (failedResponse, identity) => {
77
- (0, import_invariant.invariant)(failedResponse.status === 401, void 0, {
78
- F: __dxlog_file,
79
- L: 21,
80
- S: void 0,
81
- A: [
82
- "failedResponse.status === 401",
83
- ""
84
- ]
85
- });
86
- const headerValue = failedResponse.headers.get("Www-Authenticate");
87
- (0, import_invariant.invariant)(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, {
88
- F: __dxlog_file,
89
- L: 24,
90
- S: void 0,
91
- A: [
92
- "headerValue?.startsWith('VerifiablePresentation challenge=')",
93
- ""
94
- ]
95
- });
96
- const challenge = headerValue?.slice("VerifiablePresentation challenge=".length);
97
- (0, import_invariant.invariant)(challenge, void 0, {
98
- F: __dxlog_file,
99
- L: 27,
100
- S: void 0,
101
- A: [
102
- "challenge",
103
- ""
104
- ]
105
- });
106
- const presentation = await identity.presentCredentials({
107
- challenge: Buffer.from(challenge, "base64")
108
- });
109
- return import_proto.schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
110
- };
111
- function _ts_decorate(decorators, target, key, desc) {
112
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
113
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
114
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
115
- return c > 3 && r && Object.defineProperty(target, key, r), r;
116
- }
117
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
118
- var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
119
- var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
120
- var EdgeWsConnection = class extends import_context2.Resource {
121
- constructor(_identity, _connectionInfo, _callbacks) {
122
- super(), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks;
123
- }
124
- get info() {
125
- return {
126
- open: this.isOpen,
127
- identity: this._identity.identityKey,
128
- device: this._identity.peerKey
129
- };
130
- }
131
- send(message) {
132
- (0, import_invariant2.invariant)(this._ws, void 0, {
133
- F: __dxlog_file2,
134
- L: 52,
135
- S: this,
136
- A: [
137
- "this._ws",
138
- ""
139
- ]
140
- });
141
- (0, import_invariant2.invariant)(this._wsMuxer, void 0, {
142
- F: __dxlog_file2,
143
- L: 53,
144
- S: this,
145
- A: [
146
- "this._wsMuxer",
147
- ""
148
- ]
149
- });
150
- (0, import_log2.log)("sending...", {
151
- peerKey: this._identity.peerKey,
152
- payload: import_chunk_XNHBUTNB.protocol.getPayloadType(message)
153
- }, {
154
- F: __dxlog_file2,
155
- L: 54,
156
- S: this,
157
- C: (f, a) => f(...a)
158
- });
159
- if (this._ws?.protocol.includes(import_protocols.EdgeWebsocketProtocol.V0)) {
160
- const binary = import_buf.buf.toBinary(import_messenger_pb.MessageSchema, message);
161
- if (binary.length > import_chunk_XNHBUTNB.CLOUDFLARE_MESSAGE_MAX_BYTES) {
162
- import_log2.log.error("Message dropped because it was too large (>1MB).", {
163
- byteLength: binary.byteLength,
164
- serviceId: message.serviceId,
165
- payload: import_chunk_XNHBUTNB.protocol.getPayloadType(message)
166
- }, {
167
- F: __dxlog_file2,
168
- L: 58,
169
- S: this,
170
- C: (f, a) => f(...a)
171
- });
172
- return;
173
- }
174
- this._ws.send(binary);
175
- } else {
176
- this._wsMuxer.send(message).catch((e) => import_log2.log.catch(e, void 0, {
177
- F: __dxlog_file2,
178
- L: 67,
179
- S: this,
180
- C: (f, a) => f(...a)
181
- }));
182
- }
183
- }
184
- async _open() {
185
- const baseProtocols = [
186
- ...Object.values(import_protocols.EdgeWebsocketProtocol)
187
- ];
188
- this._ws = new import_isomorphic_ws.default(this._connectionInfo.url.toString(), this._connectionInfo.protocolHeader ? [
189
- ...baseProtocols,
190
- this._connectionInfo.protocolHeader
191
- ] : [
192
- ...baseProtocols
193
- ]);
194
- const muxer = new import_chunk_XNHBUTNB.WebSocketMuxer(this._ws);
195
- this._wsMuxer = muxer;
196
- this._ws.onopen = () => {
197
- if (this.isOpen) {
198
- (0, import_log2.log)("connected", void 0, {
199
- F: __dxlog_file2,
200
- L: 84,
201
- S: this,
202
- C: (f, a) => f(...a)
203
- });
204
- this._callbacks.onConnected();
205
- this._scheduleHeartbeats();
206
- } else {
207
- import_log2.log.verbose("connected after becoming inactive", {
208
- currentIdentity: this._identity
209
- }, {
210
- F: __dxlog_file2,
211
- L: 88,
212
- S: this,
213
- C: (f, a) => f(...a)
214
- });
215
- }
216
- };
217
- this._ws.onclose = (event) => {
218
- if (this.isOpen) {
219
- import_log2.log.warn("disconnected while being open", {
220
- code: event.code,
221
- reason: event.reason
222
- }, {
223
- F: __dxlog_file2,
224
- L: 93,
225
- S: this,
226
- C: (f, a) => f(...a)
227
- });
228
- this._callbacks.onRestartRequired();
229
- muxer.destroy();
230
- }
231
- };
232
- this._ws.onerror = (event) => {
233
- if (this.isOpen) {
234
- import_log2.log.warn("edge connection socket error", {
235
- error: event.error,
236
- info: event.message
237
- }, {
238
- F: __dxlog_file2,
239
- L: 100,
240
- S: this,
241
- C: (f, a) => f(...a)
242
- });
243
- this._callbacks.onRestartRequired();
244
- } else {
245
- import_log2.log.verbose("error ignored on closed connection", {
246
- error: event.error
247
- }, {
248
- F: __dxlog_file2,
249
- L: 103,
250
- S: this,
251
- C: (f, a) => f(...a)
252
- });
253
- }
254
- };
255
- this._ws.onmessage = async (event) => {
256
- if (!this.isOpen) {
257
- import_log2.log.verbose("message ignored on closed connection", {
258
- event: event.type
259
- }, {
260
- F: __dxlog_file2,
261
- L: 111,
262
- S: this,
263
- C: (f, a) => f(...a)
264
- });
265
- return;
266
- }
267
- if (event.data === "__pong__") {
268
- this._rescheduleHeartbeatTimeout();
269
- return;
270
- }
271
- const bytes = await (0, import_chunk_XNHBUTNB.toUint8Array)(event.data);
272
- if (!this.isOpen) {
273
- return;
274
- }
275
- const message = this._ws?.protocol?.includes(import_protocols.EdgeWebsocketProtocol.V0) ? import_buf.buf.fromBinary(import_messenger_pb.MessageSchema, bytes) : muxer.receiveData(bytes);
276
- if (message) {
277
- (0, import_log2.log)("received", {
278
- from: message.source,
279
- payload: import_chunk_XNHBUTNB.protocol.getPayloadType(message)
280
- }, {
281
- F: __dxlog_file2,
282
- L: 128,
283
- S: this,
284
- C: (f, a) => f(...a)
285
- });
286
- this._callbacks.onMessage(message);
287
- }
288
- };
289
- }
290
- async _close() {
291
- void this._inactivityTimeoutCtx?.dispose().catch(() => {
292
- });
293
- try {
294
- this._ws?.close();
295
- this._ws = void 0;
296
- this._wsMuxer?.destroy();
297
- this._wsMuxer = void 0;
298
- } catch (err) {
299
- if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
300
- return;
301
- }
302
- import_log2.log.warn("Error closing websocket", {
303
- err
304
- }, {
305
- F: __dxlog_file2,
306
- L: 146,
307
- S: this,
308
- C: (f, a) => f(...a)
309
- });
310
- }
311
- }
312
- _scheduleHeartbeats() {
313
- (0, import_invariant2.invariant)(this._ws, void 0, {
314
- F: __dxlog_file2,
315
- L: 151,
316
- S: this,
317
- A: [
318
- "this._ws",
319
- ""
320
- ]
321
- });
322
- (0, import_async2.scheduleTaskInterval)(this._ctx, async () => {
323
- this._ws?.send("__ping__");
324
- }, SIGNAL_KEEPALIVE_INTERVAL);
325
- this._ws.send("__ping__");
326
- this._rescheduleHeartbeatTimeout();
327
- }
328
- _rescheduleHeartbeatTimeout() {
329
- if (!this.isOpen) {
330
- return;
331
- }
332
- void this._inactivityTimeoutCtx?.dispose();
333
- this._inactivityTimeoutCtx = new import_context2.Context(void 0, {
334
- F: __dxlog_file2,
335
- L: 170
336
- });
337
- (0, import_async2.scheduleTask)(this._inactivityTimeoutCtx, () => {
338
- if (this.isOpen) {
339
- import_log2.log.warn("restart due to inactivity timeout", void 0, {
340
- F: __dxlog_file2,
341
- L: 175,
342
- S: this,
343
- C: (f, a) => f(...a)
344
- });
345
- this._callbacks.onRestartRequired();
346
- }
347
- }, SIGNAL_KEEPALIVE_TIMEOUT);
348
- }
349
- };
350
- _ts_decorate([
351
- import_log2.logInfo
352
- ], EdgeWsConnection.prototype, "info", null);
353
- var EdgeConnectionClosedError = class extends Error {
354
- constructor() {
355
- super("Edge connection closed.");
356
- }
357
- };
358
- var EdgeIdentityChangedError = class extends Error {
359
- constructor() {
360
- super("Edge identity changed.");
361
- }
362
- };
363
- var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
364
- const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
365
- const url = new URL(baseUrl);
366
- url.protocol = protocol2 + (isSecure ? "s" : "");
367
- return url.toString();
368
- };
369
- function _ts_decorate2(decorators, target, key, desc) {
370
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
371
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
372
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
373
- return c > 3 && r && Object.defineProperty(target, key, r), r;
374
- }
375
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
376
- var DEFAULT_TIMEOUT = 1e4;
377
- var EdgeClient = class extends import_context.Resource {
378
- constructor(_identity, _config) {
379
- super(), this._identity = _identity, this._config = _config, this.statusChanged = new import_async.Event(), this._persistentLifecycle = new import_async.PersistentLifecycle({
380
- start: async () => this._connect(),
381
- stop: async (state) => this._disconnect(state)
382
- }), this._messageListeners = /* @__PURE__ */ new Set(), this._reconnectListeners = /* @__PURE__ */ new Set(), this._currentConnection = void 0, this._ready = new import_async.Trigger(), this._isActive = (connection) => connection === this._currentConnection;
383
- this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
384
- this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
385
- }
386
- get info() {
387
- return {
388
- open: this.isOpen,
389
- status: this.status,
390
- identity: this._identity.identityKey,
391
- device: this._identity.peerKey
392
- };
393
- }
394
- get status() {
395
- return Boolean(this._currentConnection) && this._ready.state === import_async.TriggerState.RESOLVED ? import_services.EdgeStatus.CONNECTED : import_services.EdgeStatus.NOT_CONNECTED;
396
- }
397
- get identityKey() {
398
- return this._identity.identityKey;
399
- }
400
- get peerKey() {
401
- return this._identity.peerKey;
402
- }
403
- setIdentity(identity) {
404
- if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {
405
- (0, import_log.log)("Edge identity changed", {
406
- identity,
407
- oldIdentity: this._identity
408
- }, {
409
- F: __dxlog_file3,
410
- L: 99,
411
- S: this,
412
- C: (f, a) => f(...a)
413
- });
414
- this._identity = identity;
415
- this._closeCurrentConnection(new EdgeIdentityChangedError());
416
- void this._persistentLifecycle.scheduleRestart();
417
- }
418
- }
419
- onMessage(listener) {
420
- this._messageListeners.add(listener);
421
- return () => this._messageListeners.delete(listener);
422
- }
423
- onReconnected(listener) {
424
- this._reconnectListeners.add(listener);
425
- if (this._ready.state === import_async.TriggerState.RESOLVED) {
426
- (0, import_async.scheduleMicroTask)(this._ctx, () => {
427
- if (this._reconnectListeners.has(listener)) {
428
- try {
429
- listener();
430
- } catch (error) {
431
- import_log.log.catch(error, void 0, {
432
- F: __dxlog_file3,
433
- L: 121,
434
- S: this,
435
- C: (f, a) => f(...a)
436
- });
437
- }
438
- }
439
- });
440
- }
441
- return () => this._reconnectListeners.delete(listener);
442
- }
443
- /**
444
- * Open connection to messaging service.
445
- */
446
- async _open() {
447
- (0, import_log.log)("opening...", {
448
- info: this.info
449
- }, {
450
- F: __dxlog_file3,
451
- L: 133,
452
- S: this,
453
- C: (f, a) => f(...a)
454
- });
455
- this._persistentLifecycle.open().catch((err) => {
456
- import_log.log.warn("Error while opening connection", {
457
- err
458
- }, {
459
- F: __dxlog_file3,
460
- L: 135,
461
- S: this,
462
- C: (f, a) => f(...a)
463
- });
464
- });
465
- }
466
- /**
467
- * Close connection and free resources.
468
- */
469
- async _close() {
470
- (0, import_log.log)("closing...", {
471
- peerKey: this._identity.peerKey
472
- }, {
473
- F: __dxlog_file3,
474
- L: 143,
475
- S: this,
476
- C: (f, a) => f(...a)
477
- });
478
- this._closeCurrentConnection();
479
- await this._persistentLifecycle.close();
480
- }
481
- async _connect() {
482
- if (this._ctx.disposed) {
483
- return void 0;
484
- }
485
- const identity = this._identity;
486
- const path = `/ws/${identity.identityKey}/${identity.peerKey}`;
487
- const protocolHeader = this._config.disableAuth ? void 0 : await this._createAuthHeader(path);
488
- if (this._identity !== identity) {
489
- (0, import_log.log)("identity changed during auth header request", void 0, {
490
- F: __dxlog_file3,
491
- L: 157,
492
- S: this,
493
- C: (f, a) => f(...a)
494
- });
495
- return void 0;
496
- }
497
- const restartRequired = new import_async.Trigger();
498
- const url = new URL(path, this._baseWsUrl);
499
- (0, import_log.log)("Opening websocket", {
500
- url: url.toString(),
501
- protocolHeader
502
- }, {
503
- F: __dxlog_file3,
504
- L: 163,
505
- S: this,
506
- C: (f, a) => f(...a)
507
- });
508
- const connection = new EdgeWsConnection(identity, {
509
- url,
510
- protocolHeader
511
- }, {
512
- onConnected: () => {
513
- if (this._isActive(connection)) {
514
- this._ready.wake();
515
- this._notifyReconnected();
516
- } else {
517
- import_log.log.verbose("connected callback ignored, because connection is not active", void 0, {
518
- F: __dxlog_file3,
519
- L: 173,
520
- S: this,
521
- C: (f, a) => f(...a)
522
- });
523
- }
524
- },
525
- onRestartRequired: () => {
526
- if (this._isActive(connection)) {
527
- this._closeCurrentConnection();
528
- void this._persistentLifecycle.scheduleRestart();
529
- } else {
530
- import_log.log.verbose("restart requested by inactive connection", void 0, {
531
- F: __dxlog_file3,
532
- L: 181,
533
- S: this,
534
- C: (f, a) => f(...a)
535
- });
536
- }
537
- restartRequired.wake();
538
- },
539
- onMessage: (message) => {
540
- if (this._isActive(connection)) {
541
- this._notifyMessageReceived(message);
542
- } else {
543
- import_log.log.verbose("ignored a message on inactive connection", {
544
- from: message.source,
545
- type: message.payload?.typeUrl
546
- }, {
547
- F: __dxlog_file3,
548
- L: 189,
549
- S: this,
550
- C: (f, a) => f(...a)
551
- });
552
- }
553
- }
554
- });
555
- this._currentConnection = connection;
556
- await connection.open();
557
- await Promise.race([
558
- this._ready.wait({
559
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
560
- }),
561
- restartRequired
562
- ]);
563
- return connection;
564
- }
565
- async _disconnect(state) {
566
- await state.close();
567
- this.statusChanged.emit(this.status);
568
- }
569
- _closeCurrentConnection(error = new EdgeConnectionClosedError()) {
570
- this._currentConnection = void 0;
571
- this._ready.throw(error);
572
- this._ready.reset();
573
- this.statusChanged.emit(this.status);
574
- }
575
- _notifyReconnected() {
576
- this.statusChanged.emit(this.status);
577
- for (const listener of this._reconnectListeners) {
578
- try {
579
- listener();
580
- } catch (err) {
581
- import_log.log.error("ws reconnect listener failed", {
582
- err
583
- }, {
584
- F: __dxlog_file3,
585
- L: 225,
586
- S: this,
587
- C: (f, a) => f(...a)
588
- });
589
- }
590
- }
591
- }
592
- _notifyMessageReceived(message) {
593
- for (const listener of this._messageListeners) {
594
- try {
595
- listener(message);
596
- } catch (err) {
597
- import_log.log.error("ws incoming message processing failed", {
598
- err,
599
- payload: import_chunk_XNHBUTNB.protocol.getPayloadType(message)
600
- }, {
601
- F: __dxlog_file3,
602
- L: 235,
603
- S: this,
604
- C: (f, a) => f(...a)
605
- });
606
- }
607
- }
608
- }
609
- /**
610
- * Send message.
611
- * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
612
- */
613
- async send(message) {
614
- if (this._ready.state !== import_async.TriggerState.RESOLVED) {
615
- (0, import_log.log)("waiting for websocket to become ready", void 0, {
616
- F: __dxlog_file3,
617
- L: 246,
618
- S: this,
619
- C: (f, a) => f(...a)
620
- });
621
- await this._ready.wait({
622
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
623
- });
624
- }
625
- if (!this._currentConnection) {
626
- throw new EdgeConnectionClosedError();
627
- }
628
- if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
629
- throw new EdgeIdentityChangedError();
630
- }
631
- this._currentConnection.send(message);
632
- }
633
- async _createAuthHeader(path) {
634
- const httpUrl = new URL(path, this._baseHttpUrl);
635
- httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), "http");
636
- const response = await fetch(httpUrl, {
637
- method: "GET"
638
- });
639
- if (response.status === 401) {
640
- return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));
641
- } else {
642
- import_log.log.warn("no auth challenge from edge", {
643
- status: response.status,
644
- statusText: response.statusText
645
- }, {
646
- F: __dxlog_file3,
647
- L: 271,
648
- S: this,
649
- C: (f, a) => f(...a)
650
- });
651
- return void 0;
652
- }
653
- }
654
- };
655
- _ts_decorate2([
656
- import_log.logInfo
657
- ], EdgeClient.prototype, "info", null);
658
- var encodePresentationWsAuthHeader = (encodedPresentation) => {
659
- const encodedToken = Buffer.from(encodedPresentation).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
660
- return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
661
- };
662
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/auth.ts";
663
- var createDeviceEdgeIdentity = async (signer, key) => {
664
- return {
665
- identityKey: key.toHex(),
666
- peerKey: key.toHex(),
667
- presentCredentials: async ({ challenge }) => {
668
- return (0, import_credentials.signPresentation)({
669
- presentation: {
670
- credentials: [
671
- // Verifier requires at least one credential in the presentation to establish the subject.
672
- await (0, import_credentials.createCredential)({
673
- assertion: {
674
- "@type": "dxos.halo.credentials.Auth"
675
- },
676
- issuer: key,
677
- subject: key,
678
- signer
679
- })
680
- ]
681
- },
682
- signer,
683
- signerKey: key,
684
- nonce: challenge
685
- });
686
- }
687
- };
688
- };
689
- var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
690
- const credentialsToSign = credentials.length > 0 ? credentials : [
691
- await (0, import_credentials.createCredential)({
692
- assertion: {
693
- "@type": "dxos.halo.credentials.Auth"
694
- },
695
- issuer: identityKey,
696
- subject: identityKey,
697
- signer,
698
- chain,
699
- signingKey: peerKey
700
- })
701
- ];
702
- return {
703
- identityKey: identityKey.toHex(),
704
- peerKey: peerKey.toHex(),
705
- presentCredentials: async ({ challenge }) => {
706
- (0, import_invariant3.invariant)(chain, void 0, {
707
- F: __dxlog_file4,
708
- L: 75,
709
- S: void 0,
710
- A: [
711
- "chain",
712
- ""
713
- ]
714
- });
715
- return (0, import_credentials.signPresentation)({
716
- presentation: {
717
- credentials: credentialsToSign
718
- },
719
- signer,
720
- nonce: challenge,
721
- signerKey: peerKey,
722
- chain
723
- });
724
- }
725
- };
726
- };
727
- var createEphemeralEdgeIdentity = async () => {
728
- const keyring = new import_keyring.Keyring();
729
- const key = await keyring.createKey();
730
- return createDeviceEdgeIdentity(keyring, key);
731
- };
732
- var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
733
- const deviceAdmission = await (0, import_credentials.createCredential)({
734
- assertion: {
735
- "@type": "dxos.halo.credentials.AuthorizedDevice",
736
- deviceKey,
737
- identityKey
738
- },
739
- issuer: identityKey,
740
- subject: deviceKey,
741
- signer
742
- });
743
- return createChainEdgeIdentity(signer, identityKey, deviceKey, {
744
- credential: deviceAdmission
745
- }, [
746
- await (0, import_credentials.createCredential)({
747
- assertion: {
748
- "@type": "dxos.halo.credentials.Auth"
749
- },
750
- issuer: identityKey,
751
- subject: identityKey,
752
- signer
753
- })
754
- ]);
755
- };
756
- var createStubEdgeIdentity = () => {
757
- const identityKey = import_keys.PublicKey.random();
758
- const deviceKey = import_keys.PublicKey.random();
759
- return {
760
- identityKey: identityKey.toHex(),
761
- peerKey: deviceKey.toHex(),
762
- presentCredentials: async () => {
763
- throw new Error("Stub identity does not support authentication.");
764
- }
765
- };
766
- };
767
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
768
- var DEFAULT_RETRY_TIMEOUT = 1500;
769
- var DEFAULT_RETRY_JITTER = 500;
770
- var DEFAULT_MAX_RETRIES_COUNT = 3;
771
- var EdgeHttpClient = class {
772
- constructor(baseUrl) {
773
- this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
774
- (0, import_log3.log)("created", {
775
- url: this._baseUrl
776
- }, {
777
- F: __dxlog_file5,
778
- L: 53,
779
- S: this,
780
- C: (f, a) => f(...a)
781
- });
782
- }
783
- get baseUrl() {
784
- return this._baseUrl;
785
- }
786
- setIdentity(identity) {
787
- if (this._edgeIdentity?.identityKey !== identity.identityKey || this._edgeIdentity?.peerKey !== identity.peerKey) {
788
- this._edgeIdentity = identity;
789
- this._authHeader = void 0;
790
- }
791
- }
792
- createAgent(body, args) {
793
- return this._call("/agents/create", {
794
- ...args,
795
- method: "POST",
796
- body
797
- });
798
- }
799
- getAgentStatus(request, args) {
800
- return this._call(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, {
801
- ...args,
802
- method: "GET"
803
- });
804
- }
805
- getCredentialsForNotarization(spaceId, args) {
806
- return this._call(`/spaces/${spaceId}/notarization`, {
807
- ...args,
808
- method: "GET"
809
- });
810
- }
811
- async notarizeCredentials(spaceId, body, args) {
812
- await this._call(`/spaces/${spaceId}/notarization`, {
813
- ...args,
814
- body,
815
- method: "POST"
816
- });
817
- }
818
- async joinSpaceByInvitation(spaceId, body, args) {
819
- return this._call(`/spaces/${spaceId}/join`, {
820
- ...args,
821
- body,
822
- method: "POST"
823
- });
824
- }
825
- async recoverIdentity(body, args) {
826
- return this._call("/identity/recover", {
827
- ...args,
828
- body,
829
- method: "POST"
830
- });
831
- }
832
- async executeWorkflow(spaceId, graphId, input, args) {
833
- return this._call(`/workflows/${spaceId}/${graphId}`, {
834
- ...args,
835
- body: input,
836
- method: "POST"
837
- });
838
- }
839
- async uploadFunction(pathParts, body, args) {
840
- const path = [
841
- "functions",
842
- ...pathParts.functionId ? [
843
- pathParts.functionId
844
- ] : []
845
- ].join("/");
846
- return this._call(path, {
847
- ...args,
848
- body,
849
- method: "PUT"
850
- });
851
- }
852
- async initiateOAuthFlow(body, args) {
853
- return this._call("/oauth/initiate", {
854
- ...args,
855
- body,
856
- method: "POST"
857
- });
858
- }
859
- async queryQueue(subspaceTag, spaceId, query, args) {
860
- const { queueId } = query;
861
- const queryParams = new URLSearchParams();
862
- if (query.after != null) {
863
- queryParams.set("after", query.after);
864
- }
865
- if (query.before != null) {
866
- queryParams.set("before", query.before);
867
- }
868
- if (query.limit != null) {
869
- queryParams.set("limit", query.limit.toString());
870
- }
871
- if (query.reverse != null) {
872
- queryParams.set("reverse", query.reverse.toString());
873
- }
874
- if (query.objectIds != null) {
875
- queryParams.set("objectIds", query.objectIds.join(","));
876
- }
877
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query?${queryParams.toString()}`, {
878
- ...args,
879
- method: "GET"
880
- });
881
- }
882
- async insertIntoQueue(subspaceTag, spaceId, queueId, objects, args) {
883
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {
884
- ...args,
885
- body: {
886
- objects
887
- },
888
- method: "POST"
889
- });
890
- }
891
- async deleteFromQueue(subspaceTag, spaceId, queueId, objectIds, args) {
892
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {
893
- ...args,
894
- query: {
895
- ids: objectIds.join(",")
896
- },
897
- method: "DELETE"
898
- });
899
- }
900
- async createSpace(body, args) {
901
- return this._call("/spaces/create", {
902
- ...args,
903
- body,
904
- method: "POST"
905
- });
906
- }
907
- async _call(path, args) {
908
- const requestContext = args.context ?? new import_context3.Context(void 0, {
909
- F: __dxlog_file5,
910
- L: 192
911
- });
912
- const shouldRetry = createRetryHandler(args);
913
- let url = `${this._baseUrl}${path.startsWith("/") ? path.slice(1) : path}`;
914
- if (args.query) {
915
- const queryParams = new URLSearchParams();
916
- for (const [key, value] of Object.entries(args.query)) {
917
- queryParams.set(key, value.toString());
918
- }
919
- url += `?${queryParams.toString()}`;
920
- }
921
- (0, import_log3.log)("call", {
922
- method: args.method,
923
- path,
924
- request: args.body
925
- }, {
926
- F: __dxlog_file5,
927
- L: 204,
928
- S: this,
929
- C: (f, a) => f(...a)
930
- });
931
- let handledAuth = false;
932
- let authHeader = this._authHeader;
933
- while (true) {
934
- let processingError;
935
- let retryAfterHeaderValue = Number.NaN;
936
- try {
937
- const request = createRequest(args, authHeader);
938
- const response = await fetch(url, request);
939
- retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
940
- if (response.ok) {
941
- const body = await response.json();
942
- if (body.success) {
943
- return body.data;
944
- }
945
- (0, import_log3.log)("unsuccessful edge response", {
946
- path,
947
- body
948
- }, {
949
- F: __dxlog_file5,
950
- L: 223,
951
- S: this,
952
- C: (f, a) => f(...a)
953
- });
954
- if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
955
- processingError = new import_protocols2.EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
956
- } else {
957
- processingError = import_protocols2.EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
958
- }
959
- } else if (response.status === 401 && !handledAuth) {
960
- authHeader = await this._handleUnauthorized(response);
961
- handledAuth = true;
962
- continue;
963
- } else {
964
- processingError = import_protocols2.EdgeCallFailedError.fromHttpFailure(response);
965
- }
966
- } catch (error) {
967
- processingError = import_protocols2.EdgeCallFailedError.fromProcessingFailureCause(error);
968
- }
969
- if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
970
- (0, import_log3.log)("retrying edge request", {
971
- path,
972
- processingError
973
- }, {
974
- F: __dxlog_file5,
975
- L: 242,
976
- S: this,
977
- C: (f, a) => f(...a)
978
- });
979
- } else {
980
- throw processingError;
981
- }
982
- }
983
- }
984
- async _handleUnauthorized(response) {
985
- if (!this._edgeIdentity) {
986
- import_log3.log.warn("edge unauthorized response received before identity was set", void 0, {
987
- F: __dxlog_file5,
988
- L: 251,
989
- S: this,
990
- C: (f, a) => f(...a)
991
- });
992
- throw import_protocols2.EdgeCallFailedError.fromHttpFailure(response);
993
- }
994
- const challenge = await handleAuthChallenge(response, this._edgeIdentity);
995
- this._authHeader = encodeAuthHeader(challenge);
996
- (0, import_log3.log)("auth header updated", void 0, {
997
- F: __dxlog_file5,
998
- L: 256,
999
- S: this,
1000
- C: (f, a) => f(...a)
1001
- });
1002
- return this._authHeader;
1003
- }
1004
- };
1005
- var createRetryHandler = (args) => {
1006
- if (!args.retry || args.retry.count < 1) {
1007
- return async () => false;
1008
- }
1009
- let retries = 0;
1010
- const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
1011
- const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
1012
- const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
1013
- return async (ctx, retryAfter) => {
1014
- if (++retries > maxRetries || ctx.disposed) {
1015
- return false;
1016
- }
1017
- if (retryAfter) {
1018
- await (0, import_async3.sleep)(retryAfter);
1019
- } else {
1020
- const timeout = baseTimeout + Math.random() * jitter;
1021
- await (0, import_async3.sleep)(timeout);
1022
- }
1023
- return true;
1024
- };
1025
- };
1026
- var createRequest = (args, authHeader) => {
1027
- return {
1028
- method: args.method,
1029
- body: args.body && JSON.stringify(args.body),
1030
- headers: authHeader ? {
1031
- Authorization: authHeader
1032
- } : void 0
1033
- };
1034
- };
1035
- var encodeAuthHeader = (challenge) => {
1036
- const encodedChallenge = Buffer.from(challenge).toString("base64");
1037
- return `VerifiablePresentation pb;base64,${encodedChallenge}`;
1038
- };
1039
- // Annotate the CommonJS export names for ESM import in node:
1040
- 0 && (module.exports = {
1041
- CLOUDFLARE_MESSAGE_MAX_BYTES,
1042
- CLOUDFLARE_RPC_MAX_BYTES,
1043
- EdgeClient,
1044
- EdgeConnectionClosedError,
1045
- EdgeHttpClient,
1046
- EdgeIdentityChangedError,
1047
- Protocol,
1048
- WebSocketMuxer,
1049
- createChainEdgeIdentity,
1050
- createDeviceEdgeIdentity,
1051
- createEphemeralEdgeIdentity,
1052
- createStubEdgeIdentity,
1053
- createTestHaloEdgeIdentity,
1054
- getTypename,
1055
- handleAuthChallenge,
1056
- protocol,
1057
- toUint8Array,
1058
- ...require("@dxos/protocols/buf/dxos/edge/messenger_pb")
1059
- });
1060
- //# sourceMappingURL=index.cjs.map