@dxos/edge-client 0.8.4-main.ead640a → 0.8.4-main.ef1bc66f44

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