@dxos/edge-client 0.8.3 → 0.8.4-main.1da679c

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 (59) hide show
  1. package/dist/lib/browser/{chunk-VHS3XEIX.mjs → chunk-IKP53CBQ.mjs} +51 -18
  2. package/dist/lib/browser/{chunk-VHS3XEIX.mjs.map → chunk-IKP53CBQ.mjs.map} +3 -3
  3. package/dist/lib/browser/edge-ws-muxer.mjs +1 -1
  4. package/dist/lib/browser/index.mjs +566 -350
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/browser/testing/index.mjs +61 -16
  8. package/dist/lib/browser/testing/index.mjs.map +4 -4
  9. package/dist/lib/node-esm/{chunk-HGQUUFIJ.mjs → chunk-DR5YNW5K.mjs} +51 -18
  10. package/dist/lib/node-esm/{chunk-HGQUUFIJ.mjs.map → chunk-DR5YNW5K.mjs.map} +3 -3
  11. package/dist/lib/node-esm/edge-ws-muxer.mjs +1 -1
  12. package/dist/lib/node-esm/index.mjs +566 -350
  13. package/dist/lib/node-esm/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/lib/node-esm/testing/index.mjs +61 -16
  16. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  17. package/dist/types/src/edge-client.d.ts +15 -15
  18. package/dist/types/src/edge-client.d.ts.map +1 -1
  19. package/dist/types/src/edge-http-client.d.ts +52 -30
  20. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  21. package/dist/types/src/edge-http-client.test.d.ts +2 -0
  22. package/dist/types/src/edge-http-client.test.d.ts.map +1 -0
  23. package/dist/types/src/edge-ws-connection.d.ts +1 -0
  24. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  25. package/dist/types/src/edge-ws-muxer.d.ts.map +1 -1
  26. package/dist/types/src/http-client.d.ts +22 -0
  27. package/dist/types/src/http-client.d.ts.map +1 -0
  28. package/dist/types/src/http-client.test.d.ts +2 -0
  29. package/dist/types/src/http-client.test.d.ts.map +1 -0
  30. package/dist/types/src/index.d.ts +4 -3
  31. package/dist/types/src/index.d.ts.map +1 -1
  32. package/dist/types/src/testing/index.d.ts +1 -0
  33. package/dist/types/src/testing/index.d.ts.map +1 -1
  34. package/dist/types/src/testing/test-server.d.ts +9 -0
  35. package/dist/types/src/testing/test-server.d.ts.map +1 -0
  36. package/dist/types/src/testing/test-utils.d.ts.map +1 -1
  37. package/dist/types/tsconfig.tsbuildinfo +1 -1
  38. package/package.json +21 -14
  39. package/src/edge-client.ts +40 -40
  40. package/src/edge-http-client.test.ts +22 -0
  41. package/src/edge-http-client.ts +330 -140
  42. package/src/edge-ws-connection.ts +11 -3
  43. package/src/edge-ws-muxer.ts +1 -1
  44. package/src/http-client.test.ts +55 -0
  45. package/src/http-client.ts +67 -0
  46. package/src/index.ts +4 -3
  47. package/src/testing/index.ts +1 -0
  48. package/src/testing/test-server.ts +45 -0
  49. package/src/testing/test-utils.ts +2 -2
  50. package/src/websocket.test.ts +1 -1
  51. package/dist/lib/node/chunk-XNHBUTNB.cjs +0 -317
  52. package/dist/lib/node/chunk-XNHBUTNB.cjs.map +0 -7
  53. package/dist/lib/node/edge-ws-muxer.cjs +0 -33
  54. package/dist/lib/node/edge-ws-muxer.cjs.map +0 -7
  55. package/dist/lib/node/index.cjs +0 -1060
  56. package/dist/lib/node/index.cjs.map +0 -7
  57. package/dist/lib/node/meta.json +0 -1
  58. package/dist/lib/node/testing/index.cjs +0 -169
  59. package/dist/lib/node/testing/index.cjs.map +0 -7
@@ -6,24 +6,135 @@ import {
6
6
  getTypename,
7
7
  protocol,
8
8
  toUint8Array
9
- } from "./chunk-VHS3XEIX.mjs";
9
+ } from "./chunk-IKP53CBQ.mjs";
10
10
 
11
- // packages/core/mesh/edge-client/src/index.ts
11
+ // src/index.ts
12
12
  export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
13
13
 
14
- // packages/core/mesh/edge-client/src/edge-client.ts
15
- import { Trigger, scheduleMicroTask, TriggerState, PersistentLifecycle, Event } from "@dxos/async";
14
+ // src/auth.ts
15
+ import { createCredential, signPresentation } from "@dxos/credentials";
16
+ import { invariant } from "@dxos/invariant";
17
+ import { Keyring } from "@dxos/keyring";
18
+ import { PublicKey } from "@dxos/keys";
19
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/auth.ts";
20
+ var createDeviceEdgeIdentity = async (signer, key) => {
21
+ return {
22
+ identityKey: key.toHex(),
23
+ peerKey: key.toHex(),
24
+ presentCredentials: async ({ challenge }) => {
25
+ return signPresentation({
26
+ presentation: {
27
+ credentials: [
28
+ // Verifier requires at least one credential in the presentation to establish the subject.
29
+ await createCredential({
30
+ assertion: {
31
+ "@type": "dxos.halo.credentials.Auth"
32
+ },
33
+ issuer: key,
34
+ subject: key,
35
+ signer
36
+ })
37
+ ]
38
+ },
39
+ signer,
40
+ signerKey: key,
41
+ nonce: challenge
42
+ });
43
+ }
44
+ };
45
+ };
46
+ var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
47
+ const credentialsToSign = credentials.length > 0 ? credentials : [
48
+ await createCredential({
49
+ assertion: {
50
+ "@type": "dxos.halo.credentials.Auth"
51
+ },
52
+ issuer: identityKey,
53
+ subject: identityKey,
54
+ signer,
55
+ chain,
56
+ signingKey: peerKey
57
+ })
58
+ ];
59
+ return {
60
+ identityKey: identityKey.toHex(),
61
+ peerKey: peerKey.toHex(),
62
+ presentCredentials: async ({ challenge }) => {
63
+ invariant(chain, void 0, {
64
+ F: __dxlog_file,
65
+ L: 75,
66
+ S: void 0,
67
+ A: [
68
+ "chain",
69
+ ""
70
+ ]
71
+ });
72
+ return signPresentation({
73
+ presentation: {
74
+ credentials: credentialsToSign
75
+ },
76
+ signer,
77
+ nonce: challenge,
78
+ signerKey: peerKey,
79
+ chain
80
+ });
81
+ }
82
+ };
83
+ };
84
+ var createEphemeralEdgeIdentity = async () => {
85
+ const keyring = new Keyring();
86
+ const key = await keyring.createKey();
87
+ return createDeviceEdgeIdentity(keyring, key);
88
+ };
89
+ var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
90
+ const deviceAdmission = await createCredential({
91
+ assertion: {
92
+ "@type": "dxos.halo.credentials.AuthorizedDevice",
93
+ deviceKey,
94
+ identityKey
95
+ },
96
+ issuer: identityKey,
97
+ subject: deviceKey,
98
+ signer
99
+ });
100
+ return createChainEdgeIdentity(signer, identityKey, deviceKey, {
101
+ credential: deviceAdmission
102
+ }, [
103
+ await createCredential({
104
+ assertion: {
105
+ "@type": "dxos.halo.credentials.Auth"
106
+ },
107
+ issuer: identityKey,
108
+ subject: identityKey,
109
+ signer
110
+ })
111
+ ]);
112
+ };
113
+ var createStubEdgeIdentity = () => {
114
+ const identityKey = PublicKey.random();
115
+ const deviceKey = PublicKey.random();
116
+ return {
117
+ identityKey: identityKey.toHex(),
118
+ peerKey: deviceKey.toHex(),
119
+ presentCredentials: async () => {
120
+ throw new Error("Stub identity does not support authentication.");
121
+ }
122
+ };
123
+ };
124
+
125
+ // src/edge-client.ts
126
+ import { Event, PersistentLifecycle, Trigger, TriggerState, scheduleMicroTask } from "@dxos/async";
16
127
  import { Resource as Resource2 } from "@dxos/context";
17
128
  import { log as log2, logInfo as logInfo2 } from "@dxos/log";
18
129
  import { EdgeStatus } from "@dxos/protocols/proto/dxos/client/services";
19
130
 
20
- // packages/core/mesh/edge-client/src/edge-identity.ts
21
- import { invariant } from "@dxos/invariant";
131
+ // src/edge-identity.ts
132
+ import { invariant as invariant2 } from "@dxos/invariant";
22
133
  import { schema } from "@dxos/protocols/proto";
23
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
134
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
24
135
  var handleAuthChallenge = async (failedResponse, identity) => {
25
- invariant(failedResponse.status === 401, void 0, {
26
- F: __dxlog_file,
136
+ invariant2(failedResponse.status === 401, void 0, {
137
+ F: __dxlog_file2,
27
138
  L: 21,
28
139
  S: void 0,
29
140
  A: [
@@ -32,8 +143,8 @@ var handleAuthChallenge = async (failedResponse, identity) => {
32
143
  ]
33
144
  });
34
145
  const headerValue = failedResponse.headers.get("Www-Authenticate");
35
- invariant(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, {
36
- F: __dxlog_file,
146
+ invariant2(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, {
147
+ F: __dxlog_file2,
37
148
  L: 24,
38
149
  S: void 0,
39
150
  A: [
@@ -42,8 +153,8 @@ var handleAuthChallenge = async (failedResponse, identity) => {
42
153
  ]
43
154
  });
44
155
  const challenge = headerValue?.slice("VerifiablePresentation challenge=".length);
45
- invariant(challenge, void 0, {
46
- F: __dxlog_file,
156
+ invariant2(challenge, void 0, {
157
+ F: __dxlog_file2,
47
158
  L: 27,
48
159
  S: void 0,
49
160
  A: [
@@ -57,28 +168,38 @@ var handleAuthChallenge = async (failedResponse, identity) => {
57
168
  return schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
58
169
  };
59
170
 
60
- // packages/core/mesh/edge-client/src/edge-ws-connection.ts
171
+ // src/edge-ws-connection.ts
61
172
  import WebSocket from "isomorphic-ws";
62
173
  import { scheduleTask, scheduleTaskInterval } from "@dxos/async";
63
174
  import { Context, Resource } from "@dxos/context";
64
- import { invariant as invariant2 } from "@dxos/invariant";
175
+ import { invariant as invariant3 } from "@dxos/invariant";
65
176
  import { log, logInfo } from "@dxos/log";
66
177
  import { EdgeWebsocketProtocol } from "@dxos/protocols";
67
178
  import { buf } from "@dxos/protocols/buf";
68
179
  import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
180
+ function _define_property(obj, key, value) {
181
+ if (key in obj) {
182
+ Object.defineProperty(obj, key, {
183
+ value,
184
+ enumerable: true,
185
+ configurable: true,
186
+ writable: true
187
+ });
188
+ } else {
189
+ obj[key] = value;
190
+ }
191
+ return obj;
192
+ }
69
193
  function _ts_decorate(decorators, target, key, desc) {
70
194
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
71
195
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
72
196
  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;
73
197
  return c > 3 && r && Object.defineProperty(target, key, r), r;
74
198
  }
75
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
199
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
76
200
  var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
77
201
  var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
78
202
  var EdgeWsConnection = class extends Resource {
79
- constructor(_identity, _connectionInfo, _callbacks) {
80
- super(), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks;
81
- }
82
203
  get info() {
83
204
  return {
84
205
  open: this.isOpen,
@@ -87,18 +208,18 @@ var EdgeWsConnection = class extends Resource {
87
208
  };
88
209
  }
89
210
  send(message) {
90
- invariant2(this._ws, void 0, {
91
- F: __dxlog_file2,
92
- L: 52,
211
+ invariant3(this._ws, void 0, {
212
+ F: __dxlog_file3,
213
+ L: 53,
93
214
  S: this,
94
215
  A: [
95
216
  "this._ws",
96
217
  ""
97
218
  ]
98
219
  });
99
- invariant2(this._wsMuxer, void 0, {
100
- F: __dxlog_file2,
101
- L: 53,
220
+ invariant3(this._wsMuxer, void 0, {
221
+ F: __dxlog_file3,
222
+ L: 54,
102
223
  S: this,
103
224
  A: [
104
225
  "this._wsMuxer",
@@ -109,8 +230,8 @@ var EdgeWsConnection = class extends Resource {
109
230
  peerKey: this._identity.peerKey,
110
231
  payload: protocol.getPayloadType(message)
111
232
  }, {
112
- F: __dxlog_file2,
113
- L: 54,
233
+ F: __dxlog_file3,
234
+ L: 55,
114
235
  S: this,
115
236
  C: (f, a) => f(...a)
116
237
  });
@@ -122,8 +243,8 @@ var EdgeWsConnection = class extends Resource {
122
243
  serviceId: message.serviceId,
123
244
  payload: protocol.getPayloadType(message)
124
245
  }, {
125
- F: __dxlog_file2,
126
- L: 58,
246
+ F: __dxlog_file3,
247
+ L: 59,
127
248
  S: this,
128
249
  C: (f, a) => f(...a)
129
250
  });
@@ -132,8 +253,8 @@ var EdgeWsConnection = class extends Resource {
132
253
  this._ws.send(binary);
133
254
  } else {
134
255
  this._wsMuxer.send(message).catch((e) => log.catch(e, void 0, {
135
- F: __dxlog_file2,
136
- L: 67,
256
+ F: __dxlog_file3,
257
+ L: 68,
137
258
  S: this,
138
259
  C: (f, a) => f(...a)
139
260
  }));
@@ -154,8 +275,8 @@ var EdgeWsConnection = class extends Resource {
154
275
  this._ws.onopen = () => {
155
276
  if (this.isOpen) {
156
277
  log("connected", void 0, {
157
- F: __dxlog_file2,
158
- L: 84,
278
+ F: __dxlog_file3,
279
+ L: 85,
159
280
  S: this,
160
281
  C: (f, a) => f(...a)
161
282
  });
@@ -165,8 +286,8 @@ var EdgeWsConnection = class extends Resource {
165
286
  log.verbose("connected after becoming inactive", {
166
287
  currentIdentity: this._identity
167
288
  }, {
168
- F: __dxlog_file2,
169
- L: 88,
289
+ F: __dxlog_file3,
290
+ L: 89,
170
291
  S: this,
171
292
  C: (f, a) => f(...a)
172
293
  });
@@ -178,8 +299,8 @@ var EdgeWsConnection = class extends Resource {
178
299
  code: event.code,
179
300
  reason: event.reason
180
301
  }, {
181
- F: __dxlog_file2,
182
- L: 93,
302
+ F: __dxlog_file3,
303
+ L: 94,
183
304
  S: this,
184
305
  C: (f, a) => f(...a)
185
306
  });
@@ -193,8 +314,8 @@ var EdgeWsConnection = class extends Resource {
193
314
  error: event.error,
194
315
  info: event.message
195
316
  }, {
196
- F: __dxlog_file2,
197
- L: 100,
317
+ F: __dxlog_file3,
318
+ L: 101,
198
319
  S: this,
199
320
  C: (f, a) => f(...a)
200
321
  });
@@ -203,8 +324,8 @@ var EdgeWsConnection = class extends Resource {
203
324
  log.verbose("error ignored on closed connection", {
204
325
  error: event.error
205
326
  }, {
206
- F: __dxlog_file2,
207
- L: 103,
327
+ F: __dxlog_file3,
328
+ L: 104,
208
329
  S: this,
209
330
  C: (f, a) => f(...a)
210
331
  });
@@ -215,13 +336,14 @@ var EdgeWsConnection = class extends Resource {
215
336
  log.verbose("message ignored on closed connection", {
216
337
  event: event.type
217
338
  }, {
218
- F: __dxlog_file2,
219
- L: 111,
339
+ F: __dxlog_file3,
340
+ L: 112,
220
341
  S: this,
221
342
  C: (f, a) => f(...a)
222
343
  });
223
344
  return;
224
345
  }
346
+ this._lastReceivedMessageTimestamp = Date.now();
225
347
  if (event.data === "__pong__") {
226
348
  this._rescheduleHeartbeatTimeout();
227
349
  return;
@@ -236,8 +358,8 @@ var EdgeWsConnection = class extends Resource {
236
358
  from: message.source,
237
359
  payload: protocol.getPayloadType(message)
238
360
  }, {
239
- F: __dxlog_file2,
240
- L: 128,
361
+ F: __dxlog_file3,
362
+ L: 130,
241
363
  S: this,
242
364
  C: (f, a) => f(...a)
243
365
  });
@@ -260,17 +382,17 @@ var EdgeWsConnection = class extends Resource {
260
382
  log.warn("Error closing websocket", {
261
383
  err
262
384
  }, {
263
- F: __dxlog_file2,
264
- L: 146,
385
+ F: __dxlog_file3,
386
+ L: 148,
265
387
  S: this,
266
388
  C: (f, a) => f(...a)
267
389
  });
268
390
  }
269
391
  }
270
392
  _scheduleHeartbeats() {
271
- invariant2(this._ws, void 0, {
272
- F: __dxlog_file2,
273
- L: 151,
393
+ invariant3(this._ws, void 0, {
394
+ F: __dxlog_file3,
395
+ L: 153,
274
396
  S: this,
275
397
  A: [
276
398
  "this._ws",
@@ -289,27 +411,36 @@ var EdgeWsConnection = class extends Resource {
289
411
  }
290
412
  void this._inactivityTimeoutCtx?.dispose();
291
413
  this._inactivityTimeoutCtx = new Context(void 0, {
292
- F: __dxlog_file2,
293
- L: 170
414
+ F: __dxlog_file3,
415
+ L: 172
294
416
  });
295
417
  scheduleTask(this._inactivityTimeoutCtx, () => {
296
418
  if (this.isOpen) {
297
- log.warn("restart due to inactivity timeout", void 0, {
298
- F: __dxlog_file2,
299
- L: 175,
300
- S: this,
301
- C: (f, a) => f(...a)
302
- });
303
- this._callbacks.onRestartRequired();
419
+ if (Date.now() - this._lastReceivedMessageTimestamp > SIGNAL_KEEPALIVE_TIMEOUT) {
420
+ log.warn("restart due to inactivity timeout", {
421
+ lastReceivedMessageTimestamp: this._lastReceivedMessageTimestamp
422
+ }, {
423
+ F: __dxlog_file3,
424
+ L: 178,
425
+ S: this,
426
+ C: (f, a) => f(...a)
427
+ });
428
+ this._callbacks.onRestartRequired();
429
+ } else {
430
+ this._rescheduleHeartbeatTimeout();
431
+ }
304
432
  }
305
433
  }, SIGNAL_KEEPALIVE_TIMEOUT);
306
434
  }
435
+ constructor(_identity, _connectionInfo, _callbacks) {
436
+ super(), _define_property(this, "_identity", void 0), _define_property(this, "_connectionInfo", void 0), _define_property(this, "_callbacks", void 0), _define_property(this, "_inactivityTimeoutCtx", void 0), _define_property(this, "_ws", void 0), _define_property(this, "_wsMuxer", void 0), _define_property(this, "_lastReceivedMessageTimestamp", void 0), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks, this._lastReceivedMessageTimestamp = Date.now();
437
+ }
307
438
  };
308
439
  _ts_decorate([
309
440
  logInfo
310
441
  ], EdgeWsConnection.prototype, "info", null);
311
442
 
312
- // packages/core/mesh/edge-client/src/errors.ts
443
+ // src/errors.ts
313
444
  var EdgeConnectionClosedError = class extends Error {
314
445
  constructor() {
315
446
  super("Edge connection closed.");
@@ -321,7 +452,7 @@ var EdgeIdentityChangedError = class extends Error {
321
452
  }
322
453
  };
323
454
 
324
- // packages/core/mesh/edge-client/src/utils.ts
455
+ // src/utils.ts
325
456
  var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
326
457
  const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
327
458
  const url = new URL(baseUrl);
@@ -329,24 +460,29 @@ var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
329
460
  return url.toString();
330
461
  };
331
462
 
332
- // packages/core/mesh/edge-client/src/edge-client.ts
463
+ // src/edge-client.ts
464
+ function _define_property2(obj, key, value) {
465
+ if (key in obj) {
466
+ Object.defineProperty(obj, key, {
467
+ value,
468
+ enumerable: true,
469
+ configurable: true,
470
+ writable: true
471
+ });
472
+ } else {
473
+ obj[key] = value;
474
+ }
475
+ return obj;
476
+ }
333
477
  function _ts_decorate2(decorators, target, key, desc) {
334
478
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
335
479
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
336
480
  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;
337
481
  return c > 3 && r && Object.defineProperty(target, key, r), r;
338
482
  }
339
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
483
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
340
484
  var DEFAULT_TIMEOUT = 1e4;
341
485
  var EdgeClient = class extends Resource2 {
342
- constructor(_identity, _config) {
343
- super(), this._identity = _identity, this._config = _config, this.statusChanged = new Event(), this._persistentLifecycle = new PersistentLifecycle({
344
- start: async () => this._connect(),
345
- stop: async (state) => this._disconnect(state)
346
- }), this._messageListeners = /* @__PURE__ */ new Set(), this._reconnectListeners = /* @__PURE__ */ new Set(), this._currentConnection = void 0, this._ready = new Trigger(), this._isActive = (connection) => connection === this._currentConnection;
347
- this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
348
- this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
349
- }
350
486
  get info() {
351
487
  return {
352
488
  open: this.isOpen,
@@ -370,7 +506,7 @@ var EdgeClient = class extends Resource2 {
370
506
  identity,
371
507
  oldIdentity: this._identity
372
508
  }, {
373
- F: __dxlog_file3,
509
+ F: __dxlog_file4,
374
510
  L: 99,
375
511
  S: this,
376
512
  C: (f, a) => f(...a)
@@ -380,6 +516,30 @@ var EdgeClient = class extends Resource2 {
380
516
  void this._persistentLifecycle.scheduleRestart();
381
517
  }
382
518
  }
519
+ /**
520
+ * Send message.
521
+ * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
522
+ */
523
+ async send(message) {
524
+ if (this._ready.state !== TriggerState.RESOLVED) {
525
+ log2("waiting for websocket", void 0, {
526
+ F: __dxlog_file4,
527
+ L: 112,
528
+ S: this,
529
+ C: (f, a) => f(...a)
530
+ });
531
+ await this._ready.wait({
532
+ timeout: this._config.timeout ?? DEFAULT_TIMEOUT
533
+ });
534
+ }
535
+ if (!this._currentConnection) {
536
+ throw new EdgeConnectionClosedError();
537
+ }
538
+ if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
539
+ throw new EdgeIdentityChangedError();
540
+ }
541
+ this._currentConnection.send(message);
542
+ }
383
543
  onMessage(listener) {
384
544
  this._messageListeners.add(listener);
385
545
  return () => this._messageListeners.delete(listener);
@@ -393,8 +553,8 @@ var EdgeClient = class extends Resource2 {
393
553
  listener();
394
554
  } catch (error) {
395
555
  log2.catch(error, void 0, {
396
- F: __dxlog_file3,
397
- L: 121,
556
+ F: __dxlog_file4,
557
+ L: 145,
398
558
  S: this,
399
559
  C: (f, a) => f(...a)
400
560
  });
@@ -411,8 +571,8 @@ var EdgeClient = class extends Resource2 {
411
571
  log2("opening...", {
412
572
  info: this.info
413
573
  }, {
414
- F: __dxlog_file3,
415
- L: 133,
574
+ F: __dxlog_file4,
575
+ L: 158,
416
576
  S: this,
417
577
  C: (f, a) => f(...a)
418
578
  });
@@ -420,8 +580,8 @@ var EdgeClient = class extends Resource2 {
420
580
  log2.warn("Error while opening connection", {
421
581
  err
422
582
  }, {
423
- F: __dxlog_file3,
424
- L: 135,
583
+ F: __dxlog_file4,
584
+ L: 160,
425
585
  S: this,
426
586
  C: (f, a) => f(...a)
427
587
  });
@@ -434,8 +594,8 @@ var EdgeClient = class extends Resource2 {
434
594
  log2("closing...", {
435
595
  peerKey: this._identity.peerKey
436
596
  }, {
437
- F: __dxlog_file3,
438
- L: 143,
597
+ F: __dxlog_file4,
598
+ L: 168,
439
599
  S: this,
440
600
  C: (f, a) => f(...a)
441
601
  });
@@ -451,8 +611,8 @@ var EdgeClient = class extends Resource2 {
451
611
  const protocolHeader = this._config.disableAuth ? void 0 : await this._createAuthHeader(path);
452
612
  if (this._identity !== identity) {
453
613
  log2("identity changed during auth header request", void 0, {
454
- F: __dxlog_file3,
455
- L: 157,
614
+ F: __dxlog_file4,
615
+ L: 182,
456
616
  S: this,
457
617
  C: (f, a) => f(...a)
458
618
  });
@@ -464,8 +624,8 @@ var EdgeClient = class extends Resource2 {
464
624
  url: url.toString(),
465
625
  protocolHeader
466
626
  }, {
467
- F: __dxlog_file3,
468
- L: 163,
627
+ F: __dxlog_file4,
628
+ L: 188,
469
629
  S: this,
470
630
  C: (f, a) => f(...a)
471
631
  });
@@ -479,8 +639,8 @@ var EdgeClient = class extends Resource2 {
479
639
  this._notifyReconnected();
480
640
  } else {
481
641
  log2.verbose("connected callback ignored, because connection is not active", void 0, {
482
- F: __dxlog_file3,
483
- L: 173,
642
+ F: __dxlog_file4,
643
+ L: 198,
484
644
  S: this,
485
645
  C: (f, a) => f(...a)
486
646
  });
@@ -492,8 +652,8 @@ var EdgeClient = class extends Resource2 {
492
652
  void this._persistentLifecycle.scheduleRestart();
493
653
  } else {
494
654
  log2.verbose("restart requested by inactive connection", void 0, {
495
- F: __dxlog_file3,
496
- L: 181,
655
+ F: __dxlog_file4,
656
+ L: 206,
497
657
  S: this,
498
658
  C: (f, a) => f(...a)
499
659
  });
@@ -508,8 +668,8 @@ var EdgeClient = class extends Resource2 {
508
668
  from: message.source,
509
669
  type: message.payload?.typeUrl
510
670
  }, {
511
- F: __dxlog_file3,
512
- L: 189,
671
+ F: __dxlog_file4,
672
+ L: 214,
513
673
  S: this,
514
674
  C: (f, a) => f(...a)
515
675
  });
@@ -545,8 +705,8 @@ var EdgeClient = class extends Resource2 {
545
705
  log2.error("ws reconnect listener failed", {
546
706
  err
547
707
  }, {
548
- F: __dxlog_file3,
549
- L: 225,
708
+ F: __dxlog_file4,
709
+ L: 249,
550
710
  S: this,
551
711
  C: (f, a) => f(...a)
552
712
  });
@@ -562,38 +722,14 @@ var EdgeClient = class extends Resource2 {
562
722
  err,
563
723
  payload: protocol.getPayloadType(message)
564
724
  }, {
565
- F: __dxlog_file3,
566
- L: 235,
725
+ F: __dxlog_file4,
726
+ L: 259,
567
727
  S: this,
568
728
  C: (f, a) => f(...a)
569
729
  });
570
730
  }
571
731
  }
572
732
  }
573
- /**
574
- * Send message.
575
- * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
576
- */
577
- async send(message) {
578
- if (this._ready.state !== TriggerState.RESOLVED) {
579
- log2("waiting for websocket to become ready", void 0, {
580
- F: __dxlog_file3,
581
- L: 246,
582
- S: this,
583
- C: (f, a) => f(...a)
584
- });
585
- await this._ready.wait({
586
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
587
- });
588
- }
589
- if (!this._currentConnection) {
590
- throw new EdgeConnectionClosedError();
591
- }
592
- if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
593
- throw new EdgeIdentityChangedError();
594
- }
595
- this._currentConnection.send(message);
596
- }
597
733
  async _createAuthHeader(path) {
598
734
  const httpUrl = new URL(path, this._baseHttpUrl);
599
735
  httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), "http");
@@ -607,7 +743,7 @@ var EdgeClient = class extends Resource2 {
607
743
  status: response.status,
608
744
  statusText: response.statusText
609
745
  }, {
610
- F: __dxlog_file3,
746
+ F: __dxlog_file4,
611
747
  L: 271,
612
748
  S: this,
613
749
  C: (f, a) => f(...a)
@@ -615,6 +751,14 @@ var EdgeClient = class extends Resource2 {
615
751
  return void 0;
616
752
  }
617
753
  }
754
+ constructor(_identity, _config) {
755
+ super(), _define_property2(this, "_identity", void 0), _define_property2(this, "_config", void 0), _define_property2(this, "statusChanged", void 0), _define_property2(this, "_persistentLifecycle", void 0), _define_property2(this, "_messageListeners", void 0), _define_property2(this, "_reconnectListeners", void 0), _define_property2(this, "_baseWsUrl", void 0), _define_property2(this, "_baseHttpUrl", void 0), _define_property2(this, "_currentConnection", void 0), _define_property2(this, "_ready", void 0), _define_property2(this, "_isActive", void 0), this._identity = _identity, this._config = _config, this.statusChanged = new Event(), this._persistentLifecycle = new PersistentLifecycle({
756
+ start: async () => this._connect(),
757
+ stop: async (state) => this._disconnect(state)
758
+ }), this._messageListeners = /* @__PURE__ */ new Set(), this._reconnectListeners = /* @__PURE__ */ new Set(), this._currentConnection = void 0, this._ready = new Trigger(), this._isActive = (connection) => connection === this._currentConnection;
759
+ this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
760
+ this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
761
+ }
618
762
  };
619
763
  _ts_decorate2([
620
764
  logInfo2
@@ -624,138 +768,86 @@ var encodePresentationWsAuthHeader = (encodedPresentation) => {
624
768
  return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
625
769
  };
626
770
 
627
- // packages/core/mesh/edge-client/src/auth.ts
628
- import { createCredential, signPresentation } from "@dxos/credentials";
629
- import { invariant as invariant3 } from "@dxos/invariant";
630
- import { Keyring } from "@dxos/keyring";
631
- import { PublicKey } from "@dxos/keys";
632
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/auth.ts";
633
- var createDeviceEdgeIdentity = async (signer, key) => {
634
- return {
635
- identityKey: key.toHex(),
636
- peerKey: key.toHex(),
637
- presentCredentials: async ({ challenge }) => {
638
- return signPresentation({
639
- presentation: {
640
- credentials: [
641
- // Verifier requires at least one credential in the presentation to establish the subject.
642
- await createCredential({
643
- assertion: {
644
- "@type": "dxos.halo.credentials.Auth"
645
- },
646
- issuer: key,
647
- subject: key,
648
- signer
649
- })
650
- ]
651
- },
652
- signer,
653
- signerKey: key,
654
- nonce: challenge
655
- });
656
- }
657
- };
658
- };
659
- var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
660
- const credentialsToSign = credentials.length > 0 ? credentials : [
661
- await createCredential({
662
- assertion: {
663
- "@type": "dxos.halo.credentials.Auth"
664
- },
665
- issuer: identityKey,
666
- subject: identityKey,
667
- signer,
668
- chain,
669
- signingKey: peerKey
670
- })
671
- ];
672
- return {
673
- identityKey: identityKey.toHex(),
674
- peerKey: peerKey.toHex(),
675
- presentCredentials: async ({ challenge }) => {
676
- invariant3(chain, void 0, {
677
- F: __dxlog_file4,
678
- L: 75,
679
- S: void 0,
680
- A: [
681
- "chain",
682
- ""
683
- ]
684
- });
685
- return signPresentation({
686
- presentation: {
687
- credentials: credentialsToSign
688
- },
689
- signer,
690
- nonce: challenge,
691
- signerKey: peerKey,
692
- chain
693
- });
694
- }
695
- };
771
+ // src/edge-http-client.ts
772
+ import { FetchHttpClient, HttpClient } from "@effect/platform";
773
+ import { Effect as Effect2, pipe } from "effect";
774
+ import { sleep } from "@dxos/async";
775
+ import { Context as Context3 } from "@dxos/context";
776
+ import { log as log4 } from "@dxos/log";
777
+ import { EdgeAuthChallengeError, EdgeCallFailedError } from "@dxos/protocols";
778
+ import { createUrl } from "@dxos/util";
779
+
780
+ // src/http-client.ts
781
+ import { Context as Context2, Duration, Effect, Layer, Schedule } from "effect";
782
+ import { log as log3 } from "@dxos/log";
783
+ function _define_property3(obj, key, value) {
784
+ if (key in obj) {
785
+ Object.defineProperty(obj, key, {
786
+ value,
787
+ enumerable: true,
788
+ configurable: true,
789
+ writable: true
790
+ });
791
+ } else {
792
+ obj[key] = value;
793
+ }
794
+ return obj;
795
+ }
796
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/http-client.ts";
797
+ var _Context_Tag;
798
+ var HttpConfig = class extends (_Context_Tag = Context2.Tag("HttpConfig")()) {
696
799
  };
697
- var createEphemeralEdgeIdentity = async () => {
698
- const keyring = new Keyring();
699
- const key = await keyring.createKey();
700
- return createDeviceEdgeIdentity(keyring, key);
800
+ _define_property3(HttpConfig, "default", Layer.succeed(HttpConfig, {
801
+ timeout: Duration.millis(1e3),
802
+ retryTimes: 3,
803
+ retryBaseDelay: Duration.millis(1e3)
804
+ }));
805
+ var withRetry = (effect, { timeout = Duration.millis(1e3), retryBaseDelay = Duration.millis(1e3), retryTimes = 3 } = {}) => {
806
+ return effect.pipe(Effect.flatMap((res) => (
807
+ // Treat 500 errors as retryable?
808
+ res.status === 500 ? Effect.fail(new Error(res.status.toString())) : res.json
809
+ )), Effect.timeout(timeout), Effect.retry({
810
+ schedule: Schedule.exponential(retryBaseDelay).pipe(Schedule.jittered),
811
+ times: retryTimes
812
+ }));
701
813
  };
702
- var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
703
- const deviceAdmission = await createCredential({
704
- assertion: {
705
- "@type": "dxos.halo.credentials.AuthorizedDevice",
706
- deviceKey,
707
- identityKey
708
- },
709
- issuer: identityKey,
710
- subject: deviceKey,
711
- signer
712
- });
713
- return createChainEdgeIdentity(signer, identityKey, deviceKey, {
714
- credential: deviceAdmission
715
- }, [
716
- await createCredential({
717
- assertion: {
718
- "@type": "dxos.halo.credentials.Auth"
719
- },
720
- issuer: identityKey,
721
- subject: identityKey,
722
- signer
723
- })
724
- ]);
725
- };
726
- var createStubEdgeIdentity = () => {
727
- const identityKey = PublicKey.random();
728
- const deviceKey = PublicKey.random();
729
- return {
730
- identityKey: identityKey.toHex(),
731
- peerKey: deviceKey.toHex(),
732
- presentCredentials: async () => {
733
- throw new Error("Stub identity does not support authentication.");
734
- }
735
- };
814
+ var withRetryConfig = (effect) => Effect.gen(function* () {
815
+ const config = yield* HttpConfig;
816
+ return yield* withRetry(effect, config);
817
+ });
818
+ var withLogging = (effect) => effect.pipe(Effect.tap((res) => log3.info("response", {
819
+ status: res.status
820
+ }, {
821
+ F: __dxlog_file5,
822
+ L: 58,
823
+ S: void 0,
824
+ C: (f, a) => f(...a)
825
+ })));
826
+ var encodeAuthHeader = (challenge) => {
827
+ const encodedChallenge = Buffer.from(challenge).toString("base64");
828
+ return `VerifiablePresentation pb;base64,${encodedChallenge}`;
736
829
  };
737
830
 
738
- // packages/core/mesh/edge-client/src/edge-http-client.ts
739
- import { sleep } from "@dxos/async";
740
- import { Context as Context2 } from "@dxos/context";
741
- import { log as log3 } from "@dxos/log";
742
- import { EdgeCallFailedError, EdgeAuthChallengeError } from "@dxos/protocols";
743
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
831
+ // src/edge-http-client.ts
832
+ function _define_property4(obj, key, value) {
833
+ if (key in obj) {
834
+ Object.defineProperty(obj, key, {
835
+ value,
836
+ enumerable: true,
837
+ configurable: true,
838
+ writable: true
839
+ });
840
+ } else {
841
+ obj[key] = value;
842
+ }
843
+ return obj;
844
+ }
845
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
744
846
  var DEFAULT_RETRY_TIMEOUT = 1500;
745
847
  var DEFAULT_RETRY_JITTER = 500;
746
848
  var DEFAULT_MAX_RETRIES_COUNT = 3;
849
+ var WARNING_BODY_SIZE = 10 * 1024 * 1024;
747
850
  var EdgeHttpClient = class {
748
- constructor(baseUrl) {
749
- this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
750
- log3("created", {
751
- url: this._baseUrl
752
- }, {
753
- F: __dxlog_file5,
754
- L: 53,
755
- S: this,
756
- C: (f, a) => f(...a)
757
- });
758
- }
759
851
  get baseUrl() {
760
852
  return this._baseUrl;
761
853
  }
@@ -765,190 +857,283 @@ var EdgeHttpClient = class {
765
857
  this._authHeader = void 0;
766
858
  }
767
859
  }
860
+ //
861
+ // Status
862
+ //
863
+ async getStatus(args) {
864
+ return this._call(new URL("/status", this.baseUrl), {
865
+ ...args,
866
+ method: "GET"
867
+ });
868
+ }
869
+ //
870
+ // Agents
871
+ //
768
872
  createAgent(body, args) {
769
- return this._call("/agents/create", {
873
+ return this._call(new URL("/agents/create", this.baseUrl), {
770
874
  ...args,
771
875
  method: "POST",
772
876
  body
773
877
  });
774
878
  }
775
879
  getAgentStatus(request, args) {
776
- return this._call(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, {
880
+ return this._call(new URL(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, this.baseUrl), {
777
881
  ...args,
778
882
  method: "GET"
779
883
  });
780
884
  }
885
+ //
886
+ // Credentials
887
+ //
781
888
  getCredentialsForNotarization(spaceId, args) {
782
- return this._call(`/spaces/${spaceId}/notarization`, {
889
+ return this._call(new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), {
783
890
  ...args,
784
891
  method: "GET"
785
892
  });
786
893
  }
787
894
  async notarizeCredentials(spaceId, body, args) {
788
- await this._call(`/spaces/${spaceId}/notarization`, {
895
+ await this._call(new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), {
896
+ ...args,
897
+ body,
898
+ method: "POST"
899
+ });
900
+ }
901
+ //
902
+ // Identity
903
+ //
904
+ async recoverIdentity(body, args) {
905
+ return this._call(new URL("/identity/recover", this.baseUrl), {
789
906
  ...args,
790
907
  body,
791
908
  method: "POST"
792
909
  });
793
910
  }
911
+ //
912
+ // Invitations
913
+ //
794
914
  async joinSpaceByInvitation(spaceId, body, args) {
795
- return this._call(`/spaces/${spaceId}/join`, {
915
+ return this._call(new URL(`/spaces/${spaceId}/join`, this.baseUrl), {
796
916
  ...args,
797
917
  body,
798
918
  method: "POST"
799
919
  });
800
920
  }
801
- async recoverIdentity(body, args) {
802
- return this._call("/identity/recover", {
921
+ //
922
+ // OAuth and credentials
923
+ //
924
+ async initiateOAuthFlow(body, args) {
925
+ return this._call(new URL("/oauth/initiate", this.baseUrl), {
803
926
  ...args,
804
927
  body,
805
928
  method: "POST"
806
929
  });
807
930
  }
808
- async executeWorkflow(spaceId, graphId, input, args) {
809
- return this._call(`/workflows/${spaceId}/${graphId}`, {
931
+ //
932
+ // Spaces
933
+ //
934
+ async createSpace(body, args) {
935
+ return this._call(new URL("/spaces/create", this.baseUrl), {
810
936
  ...args,
811
- body: input,
937
+ body,
938
+ method: "POST"
939
+ });
940
+ }
941
+ //
942
+ // Queues
943
+ //
944
+ async queryQueue(subspaceTag, spaceId, query, args) {
945
+ const { queueId } = query;
946
+ return this._call(createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query`, this.baseUrl), {
947
+ after: query.after,
948
+ before: query.before,
949
+ limit: query.limit,
950
+ reverse: query.reverse,
951
+ objectIds: query.objectIds?.join(",")
952
+ }), {
953
+ ...args,
954
+ method: "GET"
955
+ });
956
+ }
957
+ async insertIntoQueue(subspaceTag, spaceId, queueId, objects, args) {
958
+ return this._call(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {
959
+ ...args,
960
+ body: {
961
+ objects
962
+ },
812
963
  method: "POST"
813
964
  });
814
965
  }
966
+ async deleteFromQueue(subspaceTag, spaceId, queueId, objectIds, args) {
967
+ return this._call(createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {
968
+ ids: objectIds.join(",")
969
+ }), {
970
+ ...args,
971
+ method: "DELETE"
972
+ });
973
+ }
974
+ //
975
+ // Functions
976
+ //
815
977
  async uploadFunction(pathParts, body, args) {
978
+ const formData = new FormData();
979
+ formData.append("name", body.name ?? "");
980
+ formData.append("version", body.version);
981
+ formData.append("ownerPublicKey", body.ownerPublicKey);
982
+ formData.append("entryPoint", body.entryPoint);
983
+ for (const [filename, content] of Object.entries(body.assets)) {
984
+ formData.append("assets", new Blob([
985
+ content
986
+ ], {
987
+ type: getFileMimeType(filename)
988
+ }), filename);
989
+ }
816
990
  const path = [
817
991
  "functions",
818
992
  ...pathParts.functionId ? [
819
993
  pathParts.functionId
820
994
  ] : []
821
995
  ].join("/");
822
- return this._call(path, {
996
+ return this._call(new URL(path, this.baseUrl), {
823
997
  ...args,
824
- body,
825
- method: "PUT"
998
+ body: formData,
999
+ method: "PUT",
1000
+ json: false
826
1001
  });
827
1002
  }
828
- async initiateOAuthFlow(body, args) {
829
- return this._call("/oauth/initiate", {
1003
+ async listFunctions(args) {
1004
+ return this._call(new URL("/functions", this.baseUrl), {
830
1005
  ...args,
831
- body,
832
- method: "POST"
1006
+ method: "GET"
833
1007
  });
834
1008
  }
835
- async queryQueue(subspaceTag, spaceId, query, args) {
836
- const { queueId } = query;
837
- const queryParams = new URLSearchParams();
838
- if (query.after != null) {
839
- queryParams.set("after", query.after);
840
- }
841
- if (query.before != null) {
842
- queryParams.set("before", query.before);
1009
+ async invokeFunction(params, input, args) {
1010
+ const url = new URL(`/functions/${params.functionId}`, this.baseUrl);
1011
+ if (params.version) {
1012
+ url.searchParams.set("version", params.version);
843
1013
  }
844
- if (query.limit != null) {
845
- queryParams.set("limit", query.limit.toString());
1014
+ if (params.spaceId) {
1015
+ url.searchParams.set("spaceId", params.spaceId.toString());
846
1016
  }
847
- if (query.reverse != null) {
848
- queryParams.set("reverse", query.reverse.toString());
1017
+ if (params.cpuTimeLimit) {
1018
+ url.searchParams.set("cpuTimeLimit", params.cpuTimeLimit.toString());
849
1019
  }
850
- if (query.objectIds != null) {
851
- queryParams.set("objectIds", query.objectIds.join(","));
1020
+ if (params.subrequestsLimit) {
1021
+ url.searchParams.set("subrequestsLimit", params.subrequestsLimit.toString());
852
1022
  }
853
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query?${queryParams.toString()}`, {
1023
+ return this._call(url, {
854
1024
  ...args,
855
- method: "GET"
1025
+ body: input,
1026
+ method: "POST",
1027
+ rawResponse: true
856
1028
  });
857
1029
  }
858
- async insertIntoQueue(subspaceTag, spaceId, queueId, objects, args) {
859
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {
1030
+ //
1031
+ // Workflows
1032
+ //
1033
+ async executeWorkflow(spaceId, graphId, input, args) {
1034
+ return this._call(new URL(`/workflows/${spaceId}/${graphId}`, this.baseUrl), {
860
1035
  ...args,
861
- body: {
862
- objects
863
- },
1036
+ body: input,
864
1037
  method: "POST"
865
1038
  });
866
1039
  }
867
- async deleteFromQueue(subspaceTag, spaceId, queueId, objectIds, args) {
868
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {
1040
+ //
1041
+ // Triggers
1042
+ //
1043
+ async getCronTriggers(spaceId) {
1044
+ return this._call(new URL(`/test/functions/${spaceId}/triggers/crons`, this.baseUrl), {
1045
+ method: "GET"
1046
+ });
1047
+ }
1048
+ //
1049
+ // Import/Export space.
1050
+ //
1051
+ async importBundle(spaceId, body, args) {
1052
+ return this._call(new URL(`/spaces/${spaceId}/import`, this.baseUrl), {
869
1053
  ...args,
870
- query: {
871
- ids: objectIds.join(",")
872
- },
873
- method: "DELETE"
1054
+ body,
1055
+ method: "PUT"
874
1056
  });
875
1057
  }
876
- async createSpace(body, args) {
877
- return this._call("/spaces/create", {
1058
+ async exportBundle(spaceId, body, args) {
1059
+ return this._call(new URL(`/spaces/${spaceId}/export`, this.baseUrl), {
878
1060
  ...args,
879
1061
  body,
880
1062
  method: "POST"
881
1063
  });
882
1064
  }
883
- async _call(path, args) {
884
- const requestContext = args.context ?? new Context2(void 0, {
885
- F: __dxlog_file5,
886
- L: 192
887
- });
1065
+ //
1066
+ // Internal
1067
+ //
1068
+ async _fetch(url, args) {
1069
+ return pipe(HttpClient.get(url), withLogging, withRetryConfig, Effect2.provide(FetchHttpClient.layer), Effect2.provide(HttpConfig.default), Effect2.withSpan("EdgeHttpClient"), Effect2.runPromise);
1070
+ }
1071
+ // TODO(burdon): Refactor with effect (see edge-http-client.test.ts).
1072
+ async _call(url, args) {
888
1073
  const shouldRetry = createRetryHandler(args);
889
- let url = `${this._baseUrl}${path.startsWith("/") ? path.slice(1) : path}`;
890
- if (args.query) {
891
- const queryParams = new URLSearchParams();
892
- for (const [key, value] of Object.entries(args.query)) {
893
- queryParams.set(key, value.toString());
894
- }
895
- url += `?${queryParams.toString()}`;
896
- }
897
- log3("call", {
898
- method: args.method,
899
- path,
1074
+ const requestContext = args.context ?? new Context3(void 0, {
1075
+ F: __dxlog_file6,
1076
+ L: 389
1077
+ });
1078
+ log4("fetch", {
1079
+ url,
900
1080
  request: args.body
901
1081
  }, {
902
- F: __dxlog_file5,
903
- L: 204,
1082
+ F: __dxlog_file6,
1083
+ L: 390,
904
1084
  S: this,
905
1085
  C: (f, a) => f(...a)
906
1086
  });
907
1087
  let handledAuth = false;
908
- let authHeader = this._authHeader;
909
1088
  while (true) {
910
- let processingError;
1089
+ let processingError = void 0;
911
1090
  let retryAfterHeaderValue = Number.NaN;
912
1091
  try {
913
- const request = createRequest(args, authHeader);
1092
+ const request = createRequest(args, this._authHeader);
914
1093
  const response = await fetch(url, request);
915
1094
  retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
916
1095
  if (response.ok) {
917
1096
  const body = await response.json();
1097
+ if (args.rawResponse) {
1098
+ return body;
1099
+ }
1100
+ if (!("success" in body)) {
1101
+ return body;
1102
+ }
918
1103
  if (body.success) {
919
1104
  return body.data;
920
1105
  }
921
- log3("unsuccessful edge response", {
922
- path,
1106
+ log4.warn("unsuccessful edge response", {
1107
+ url,
923
1108
  body
924
1109
  }, {
925
- F: __dxlog_file5,
926
- L: 223,
1110
+ F: __dxlog_file6,
1111
+ L: 415,
927
1112
  S: this,
928
1113
  C: (f, a) => f(...a)
929
1114
  });
930
1115
  if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
931
1116
  processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
932
- } else {
1117
+ } else if (body.errorData) {
933
1118
  processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
934
1119
  }
935
1120
  } else if (response.status === 401 && !handledAuth) {
936
- authHeader = await this._handleUnauthorized(response);
1121
+ this._authHeader = await this._handleUnauthorized(response);
937
1122
  handledAuth = true;
938
1123
  continue;
939
1124
  } else {
940
- processingError = EdgeCallFailedError.fromHttpFailure(response);
1125
+ processingError = await EdgeCallFailedError.fromHttpFailure(response);
941
1126
  }
942
1127
  } catch (error) {
943
1128
  processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
944
1129
  }
945
- if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
946
- log3("retrying edge request", {
947
- path,
1130
+ if (processingError?.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
1131
+ log4("retrying edge request", {
1132
+ url,
948
1133
  processingError
949
1134
  }, {
950
- F: __dxlog_file5,
951
- L: 242,
1135
+ F: __dxlog_file6,
1136
+ L: 433,
952
1137
  S: this,
953
1138
  C: (f, a) => f(...a)
954
1139
  });
@@ -959,33 +1144,68 @@ var EdgeHttpClient = class {
959
1144
  }
960
1145
  async _handleUnauthorized(response) {
961
1146
  if (!this._edgeIdentity) {
962
- log3.warn("edge unauthorized response received before identity was set", void 0, {
963
- F: __dxlog_file5,
964
- L: 251,
1147
+ log4.warn("unauthorized response received before identity was set", void 0, {
1148
+ F: __dxlog_file6,
1149
+ L: 442,
965
1150
  S: this,
966
1151
  C: (f, a) => f(...a)
967
1152
  });
968
- throw EdgeCallFailedError.fromHttpFailure(response);
1153
+ throw await EdgeCallFailedError.fromHttpFailure(response);
969
1154
  }
970
1155
  const challenge = await handleAuthChallenge(response, this._edgeIdentity);
971
- this._authHeader = encodeAuthHeader(challenge);
972
- log3("auth header updated", void 0, {
973
- F: __dxlog_file5,
974
- L: 256,
1156
+ return encodeAuthHeader(challenge);
1157
+ }
1158
+ constructor(baseUrl) {
1159
+ _define_property4(this, "_baseUrl", void 0);
1160
+ _define_property4(this, "_edgeIdentity", void 0);
1161
+ _define_property4(this, "_authHeader", void 0);
1162
+ this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
1163
+ log4("created", {
1164
+ url: this._baseUrl
1165
+ }, {
1166
+ F: __dxlog_file6,
1167
+ L: 97,
975
1168
  S: this,
976
1169
  C: (f, a) => f(...a)
977
1170
  });
978
- return this._authHeader;
979
1171
  }
980
1172
  };
981
- var createRetryHandler = (args) => {
982
- if (!args.retry || args.retry.count < 1) {
1173
+ var createRequest = ({ method, body, json = true }, authHeader) => {
1174
+ let requestBody;
1175
+ const headers = {};
1176
+ if (json) {
1177
+ requestBody = body && JSON.stringify(body);
1178
+ headers["Content-Type"] = "application/json";
1179
+ } else {
1180
+ requestBody = body;
1181
+ }
1182
+ if (typeof requestBody === "string" && requestBody.length > WARNING_BODY_SIZE) {
1183
+ log4.warn("Request with large body", {
1184
+ bodySize: requestBody.length
1185
+ }, {
1186
+ F: __dxlog_file6,
1187
+ L: 466,
1188
+ S: void 0,
1189
+ C: (f, a) => f(...a)
1190
+ });
1191
+ }
1192
+ if (authHeader) {
1193
+ headers["Authorization"] = authHeader;
1194
+ }
1195
+ return {
1196
+ method,
1197
+ body: requestBody,
1198
+ headers
1199
+ };
1200
+ };
1201
+ var createRetryHandler = ({ retry }) => {
1202
+ if (!retry || retry.count < 1) {
983
1203
  return async () => false;
984
1204
  }
985
1205
  let retries = 0;
986
- const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
987
- const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
988
- const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
1206
+ const maxRetries = retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
1207
+ const baseTimeout = retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
1208
+ const jitter = retry.jitter ?? DEFAULT_RETRY_JITTER;
989
1209
  return async (ctx, retryAfter) => {
990
1210
  if (++retries > maxRetries || ctx.disposed) {
991
1211
  return false;
@@ -999,19 +1219,10 @@ var createRetryHandler = (args) => {
999
1219
  return true;
1000
1220
  };
1001
1221
  };
1002
- var createRequest = (args, authHeader) => {
1003
- return {
1004
- method: args.method,
1005
- body: args.body && JSON.stringify(args.body),
1006
- headers: authHeader ? {
1007
- Authorization: authHeader
1008
- } : void 0
1009
- };
1010
- };
1011
- var encodeAuthHeader = (challenge) => {
1012
- const encodedChallenge = Buffer.from(challenge).toString("base64");
1013
- return `VerifiablePresentation pb;base64,${encodedChallenge}`;
1014
- };
1222
+ var getFileMimeType = (filename) => [
1223
+ ".js",
1224
+ ".mjs"
1225
+ ].some((codeExtension) => filename.endsWith(codeExtension)) ? "application/javascript+module" : filename.endsWith(".wasm") ? "application/wasm" : "application/octet-stream";
1015
1226
  export {
1016
1227
  CLOUDFLARE_MESSAGE_MAX_BYTES,
1017
1228
  CLOUDFLARE_RPC_MAX_BYTES,
@@ -1019,6 +1230,7 @@ export {
1019
1230
  EdgeConnectionClosedError,
1020
1231
  EdgeHttpClient,
1021
1232
  EdgeIdentityChangedError,
1233
+ HttpConfig,
1022
1234
  Protocol,
1023
1235
  WebSocketMuxer,
1024
1236
  createChainEdgeIdentity,
@@ -1026,9 +1238,13 @@ export {
1026
1238
  createEphemeralEdgeIdentity,
1027
1239
  createStubEdgeIdentity,
1028
1240
  createTestHaloEdgeIdentity,
1241
+ encodeAuthHeader,
1029
1242
  getTypename,
1030
1243
  handleAuthChallenge,
1031
1244
  protocol,
1032
- toUint8Array
1245
+ toUint8Array,
1246
+ withLogging,
1247
+ withRetry,
1248
+ withRetryConfig
1033
1249
  };
1034
1250
  //# sourceMappingURL=index.mjs.map