@covia/covia-sdk 1.1.0 → 1.3.0

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.
package/dist/index.mjs CHANGED
@@ -1,21 +1,32 @@
1
1
  import { Resolver } from 'did-resolver';
2
2
  import { getResolver } from 'web-did-resolver';
3
3
 
4
+ var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+
4
8
  // src/types.ts
5
- var RunStatus = /* @__PURE__ */ ((RunStatus3) => {
6
- RunStatus3["COMPLETE"] = "COMPLETE";
7
- RunStatus3["FAILED"] = "FAILED";
8
- RunStatus3["PENDING"] = "PENDING";
9
- RunStatus3["STARTED"] = "STARTED";
10
- RunStatus3["CANCELLED"] = "CANCELLED";
11
- RunStatus3["TIMEOUT"] = "TIMEOUT";
12
- RunStatus3["REJECTED"] = "REJECTED";
13
- RunStatus3["INPUT_REQUIRED"] = "INPUT_REQUIRED";
14
- RunStatus3["AUTH_REQUIRED"] = "AUTH_REQUIRED";
15
- RunStatus3["PAUSED"] = "PAUSED";
16
- return RunStatus3;
9
+ var RunStatus = /* @__PURE__ */ ((RunStatus2) => {
10
+ RunStatus2["COMPLETE"] = "COMPLETE";
11
+ RunStatus2["FAILED"] = "FAILED";
12
+ RunStatus2["PENDING"] = "PENDING";
13
+ RunStatus2["STARTED"] = "STARTED";
14
+ RunStatus2["CANCELLED"] = "CANCELLED";
15
+ RunStatus2["TIMEOUT"] = "TIMEOUT";
16
+ RunStatus2["REJECTED"] = "REJECTED";
17
+ RunStatus2["INPUT_REQUIRED"] = "INPUT_REQUIRED";
18
+ RunStatus2["AUTH_REQUIRED"] = "AUTH_REQUIRED";
19
+ RunStatus2["PAUSED"] = "PAUSED";
20
+ return RunStatus2;
17
21
  })(RunStatus || {});
18
22
  var JobStatus = RunStatus;
23
+ var AgentStatus = /* @__PURE__ */ ((AgentStatus2) => {
24
+ AgentStatus2["SLEEPING"] = "SLEEPING";
25
+ AgentStatus2["RUNNING"] = "RUNNING";
26
+ AgentStatus2["SUSPENDED"] = "SUSPENDED";
27
+ AgentStatus2["TERMINATED"] = "TERMINATED";
28
+ return AgentStatus2;
29
+ })(AgentStatus || {});
19
30
  var CoviaError = class extends Error {
20
31
  constructor(message, code = null) {
21
32
  super(message);
@@ -78,6 +89,996 @@ var JobNotFoundError = class extends NotFoundError {
78
89
  }
79
90
  };
80
91
 
92
+ // node_modules/@noble/ed25519/index.js
93
+ var ed25519_CURVE = {
94
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
95
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
96
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
97
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
98
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
99
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
100
+ };
101
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;
102
+ var h = 8n;
103
+ var L = 32;
104
+ var L2 = 64;
105
+ var err = (m = "") => {
106
+ throw new Error(m);
107
+ };
108
+ var isBig = (n) => typeof n === "bigint";
109
+ var isStr = (s) => typeof s === "string";
110
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
111
+ var abytes = (a, l) => !isBytes(a) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a;
112
+ var u8n = (len) => new Uint8Array(len);
113
+ var u8fr = (buf) => Uint8Array.from(buf);
114
+ var padh = (n, pad) => n.toString(16).padStart(pad, "0");
115
+ var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
116
+ var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
117
+ var _ch = (ch) => {
118
+ if (ch >= C._0 && ch <= C._9)
119
+ return ch - C._0;
120
+ if (ch >= C.A && ch <= C.F)
121
+ return ch - (C.A - 10);
122
+ if (ch >= C.a && ch <= C.f)
123
+ return ch - (C.a - 10);
124
+ return;
125
+ };
126
+ var hexToBytes = (hex) => {
127
+ const e = "hex invalid";
128
+ if (!isStr(hex))
129
+ return err(e);
130
+ const hl = hex.length;
131
+ const al = hl / 2;
132
+ if (hl % 2)
133
+ return err(e);
134
+ const array = u8n(al);
135
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
136
+ const n1 = _ch(hex.charCodeAt(hi));
137
+ const n2 = _ch(hex.charCodeAt(hi + 1));
138
+ if (n1 === void 0 || n2 === void 0)
139
+ return err(e);
140
+ array[ai] = n1 * 16 + n2;
141
+ }
142
+ return array;
143
+ };
144
+ var toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
145
+ var cr = () => globalThis?.crypto;
146
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined");
147
+ var concatBytes = (...arrs) => {
148
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
149
+ let pad = 0;
150
+ arrs.forEach((a) => {
151
+ r.set(a, pad);
152
+ pad += a.length;
153
+ });
154
+ return r;
155
+ };
156
+ var randomBytes = (len = L) => {
157
+ const c = cr();
158
+ return c.getRandomValues(u8n(len));
159
+ };
160
+ var big = BigInt;
161
+ var arange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
162
+ var M = (a, b = P) => {
163
+ const r = a % b;
164
+ return r >= 0n ? r : b + r;
165
+ };
166
+ var modN = (a) => M(a, N);
167
+ var invert = (num, md) => {
168
+ if (num === 0n || md <= 0n)
169
+ err("no inverse n=" + num + " mod=" + md);
170
+ let a = M(num, md), b = md, x = 0n, u = 1n;
171
+ while (a !== 0n) {
172
+ const q = b / a, r = b % a;
173
+ const m = x - u * q;
174
+ b = a, a = r, x = u, u = m;
175
+ }
176
+ return b === 1n ? M(x, md) : err("no inverse");
177
+ };
178
+ var callHash = (name) => {
179
+ const fn = etc[name];
180
+ if (typeof fn !== "function")
181
+ err("hashes." + name + " not set");
182
+ return fn;
183
+ };
184
+ var apoint = (p) => p instanceof Point ? p : err("Point expected");
185
+ var B256 = 2n ** 256n;
186
+ var _Point = class _Point {
187
+ constructor(ex, ey, ez, et) {
188
+ __publicField(this, "ex");
189
+ __publicField(this, "ey");
190
+ __publicField(this, "ez");
191
+ __publicField(this, "et");
192
+ const max = B256;
193
+ this.ex = arange(ex, 0n, max);
194
+ this.ey = arange(ey, 0n, max);
195
+ this.ez = arange(ez, 1n, max);
196
+ this.et = arange(et, 0n, max);
197
+ Object.freeze(this);
198
+ }
199
+ static fromAffine(p) {
200
+ return new _Point(p.x, p.y, 1n, M(p.x * p.y));
201
+ }
202
+ /** RFC8032 5.1.3: Uint8Array to Point. */
203
+ static fromBytes(hex, zip215 = false) {
204
+ const d = _d;
205
+ const normed = u8fr(abytes(hex, L));
206
+ const lastByte = hex[31];
207
+ normed[31] = lastByte & -129;
208
+ const y = bytesToNumLE(normed);
209
+ const max = zip215 ? B256 : P;
210
+ arange(y, 0n, max);
211
+ const y2 = M(y * y);
212
+ const u = M(y2 - 1n);
213
+ const v = M(d * y2 + 1n);
214
+ let { isValid, value: x } = uvRatio(u, v);
215
+ if (!isValid)
216
+ err("bad point: y not sqrt");
217
+ const isXOdd = (x & 1n) === 1n;
218
+ const isLastByteOdd = (lastByte & 128) !== 0;
219
+ if (!zip215 && x === 0n && isLastByteOdd)
220
+ err("bad point: x==0, isLastByteOdd");
221
+ if (isLastByteOdd !== isXOdd)
222
+ x = M(-x);
223
+ return new _Point(x, y, 1n, M(x * y));
224
+ }
225
+ /** Checks if the point is valid and on-curve. */
226
+ assertValidity() {
227
+ const a = _a;
228
+ const d = _d;
229
+ const p = this;
230
+ if (p.is0())
231
+ throw new Error("bad point: ZERO");
232
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
233
+ const X2 = M(X * X);
234
+ const Y2 = M(Y * Y);
235
+ const Z2 = M(Z * Z);
236
+ const Z4 = M(Z2 * Z2);
237
+ const aX2 = M(X2 * a);
238
+ const left = M(Z2 * M(aX2 + Y2));
239
+ const right = M(Z4 + M(d * M(X2 * Y2)));
240
+ if (left !== right)
241
+ throw new Error("bad point: equation left != right (1)");
242
+ const XY = M(X * Y);
243
+ const ZT = M(Z * T);
244
+ if (XY !== ZT)
245
+ throw new Error("bad point: equation left != right (2)");
246
+ return this;
247
+ }
248
+ /** Equality check: compare points P&Q. */
249
+ equals(other) {
250
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
251
+ const { ex: X2, ey: Y2, ez: Z2 } = apoint(other);
252
+ const X1Z2 = M(X1 * Z2);
253
+ const X2Z1 = M(X2 * Z1);
254
+ const Y1Z2 = M(Y1 * Z2);
255
+ const Y2Z1 = M(Y2 * Z1);
256
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
257
+ }
258
+ is0() {
259
+ return this.equals(I);
260
+ }
261
+ /** Flip point over y coordinate. */
262
+ negate() {
263
+ return new _Point(M(-this.ex), this.ey, this.ez, M(-this.et));
264
+ }
265
+ /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
266
+ double() {
267
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
268
+ const a = _a;
269
+ const A = M(X1 * X1);
270
+ const B = M(Y1 * Y1);
271
+ const C2 = M(2n * M(Z1 * Z1));
272
+ const D = M(a * A);
273
+ const x1y1 = X1 + Y1;
274
+ const E = M(M(x1y1 * x1y1) - A - B);
275
+ const G2 = D + B;
276
+ const F = G2 - C2;
277
+ const H = D - B;
278
+ const X3 = M(E * F);
279
+ const Y3 = M(G2 * H);
280
+ const T3 = M(E * H);
281
+ const Z3 = M(F * G2);
282
+ return new _Point(X3, Y3, Z3, T3);
283
+ }
284
+ /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
285
+ add(other) {
286
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
287
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other);
288
+ const a = _a;
289
+ const d = _d;
290
+ const A = M(X1 * X2);
291
+ const B = M(Y1 * Y2);
292
+ const C2 = M(T1 * d * T2);
293
+ const D = M(Z1 * Z2);
294
+ const E = M((X1 + Y1) * (X2 + Y2) - A - B);
295
+ const F = M(D - C2);
296
+ const G2 = M(D + C2);
297
+ const H = M(B - a * A);
298
+ const X3 = M(E * F);
299
+ const Y3 = M(G2 * H);
300
+ const T3 = M(E * H);
301
+ const Z3 = M(F * G2);
302
+ return new _Point(X3, Y3, Z3, T3);
303
+ }
304
+ /**
305
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
306
+ * Uses {@link wNAF} for base point.
307
+ * Uses fake point to mitigate side-channel leakage.
308
+ * @param n scalar by which point is multiplied
309
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
310
+ */
311
+ multiply(n, safe = true) {
312
+ if (!safe && (n === 0n || this.is0()))
313
+ return I;
314
+ arange(n, 1n, N);
315
+ if (n === 1n)
316
+ return this;
317
+ if (this.equals(G))
318
+ return wNAF(n).p;
319
+ let p = I;
320
+ let f = G;
321
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
322
+ if (n & 1n)
323
+ p = p.add(d);
324
+ else if (safe)
325
+ f = f.add(d);
326
+ }
327
+ return p;
328
+ }
329
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
330
+ toAffine() {
331
+ const { ex: x, ey: y, ez: z } = this;
332
+ if (this.equals(I))
333
+ return { x: 0n, y: 1n };
334
+ const iz = invert(z, P);
335
+ if (M(z * iz) !== 1n)
336
+ err("invalid inverse");
337
+ return { x: M(x * iz), y: M(y * iz) };
338
+ }
339
+ toBytes() {
340
+ const { x, y } = this.assertValidity().toAffine();
341
+ const b = numTo32bLE(y);
342
+ b[31] |= x & 1n ? 128 : 0;
343
+ return b;
344
+ }
345
+ toHex() {
346
+ return bytesToHex(this.toBytes());
347
+ }
348
+ // encode to hex string
349
+ clearCofactor() {
350
+ return this.multiply(big(h), false);
351
+ }
352
+ isSmallOrder() {
353
+ return this.clearCofactor().is0();
354
+ }
355
+ isTorsionFree() {
356
+ let p = this.multiply(N / 2n, false).double();
357
+ if (N % 2n)
358
+ p = p.add(this);
359
+ return p.is0();
360
+ }
361
+ static fromHex(hex, zip215) {
362
+ return _Point.fromBytes(toU8(hex), zip215);
363
+ }
364
+ get x() {
365
+ return this.toAffine().x;
366
+ }
367
+ get y() {
368
+ return this.toAffine().y;
369
+ }
370
+ toRawBytes() {
371
+ return this.toBytes();
372
+ }
373
+ };
374
+ __publicField(_Point, "BASE");
375
+ __publicField(_Point, "ZERO");
376
+ var Point = _Point;
377
+ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
378
+ var I = new Point(0n, 1n, 1n, 0n);
379
+ Point.BASE = G;
380
+ Point.ZERO = I;
381
+ var numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();
382
+ var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
383
+ var pow2 = (x, power) => {
384
+ let r = x;
385
+ while (power-- > 0n) {
386
+ r *= r;
387
+ r %= P;
388
+ }
389
+ return r;
390
+ };
391
+ var pow_2_252_3 = (x) => {
392
+ const x2 = x * x % P;
393
+ const b2 = x2 * x % P;
394
+ const b4 = pow2(b2, 2n) * b2 % P;
395
+ const b5 = pow2(b4, 1n) * x % P;
396
+ const b10 = pow2(b5, 5n) * b5 % P;
397
+ const b20 = pow2(b10, 10n) * b10 % P;
398
+ const b40 = pow2(b20, 20n) * b20 % P;
399
+ const b80 = pow2(b40, 40n) * b40 % P;
400
+ const b160 = pow2(b80, 80n) * b80 % P;
401
+ const b240 = pow2(b160, 80n) * b80 % P;
402
+ const b250 = pow2(b240, 10n) * b10 % P;
403
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
404
+ return { pow_p_5_8, b2 };
405
+ };
406
+ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
407
+ var uvRatio = (u, v) => {
408
+ const v3 = M(v * v * v);
409
+ const v7 = M(v3 * v3 * v);
410
+ const pow = pow_2_252_3(u * v7).pow_p_5_8;
411
+ let x = M(u * v3 * pow);
412
+ const vx2 = M(v * x * x);
413
+ const root1 = x;
414
+ const root2 = M(x * RM1);
415
+ const useRoot1 = vx2 === u;
416
+ const useRoot2 = vx2 === M(-u);
417
+ const noRoot = vx2 === M(-u * RM1);
418
+ if (useRoot1)
419
+ x = root1;
420
+ if (useRoot2 || noRoot)
421
+ x = root2;
422
+ if ((M(x) & 1n) === 1n)
423
+ x = M(-x);
424
+ return { isValid: useRoot1 || useRoot2, value: x };
425
+ };
426
+ var modL_LE = (hash) => modN(bytesToNumLE(hash));
427
+ var sha512a = (...m) => etc.sha512Async(...m);
428
+ var sha512s = (...m) => callHash("sha512Sync")(...m);
429
+ var hash2extK = (hashed) => {
430
+ const head = hashed.slice(0, L);
431
+ head[0] &= 248;
432
+ head[31] &= 127;
433
+ head[31] |= 64;
434
+ const prefix = hashed.slice(L, L2);
435
+ const scalar = modL_LE(head);
436
+ const point = G.multiply(scalar);
437
+ const pointBytes = point.toBytes();
438
+ return { head, prefix, scalar, point, pointBytes };
439
+ };
440
+ var getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, L)).then(hash2extK);
441
+ var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, L)));
442
+ var getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
443
+ var hashFinishS = (res) => res.finish(sha512s(res.hashable));
444
+ var _sign = (e, rBytes, msg) => {
445
+ const { pointBytes: P2, scalar: s } = e;
446
+ const r = modL_LE(rBytes);
447
+ const R = G.multiply(r).toBytes();
448
+ const hashable = concatBytes(R, P2, msg);
449
+ const finish = (hashed) => {
450
+ const S = modN(r + modL_LE(hashed) * s);
451
+ return abytes(concatBytes(R, numTo32bLE(S)), L2);
452
+ };
453
+ return { hashable, finish };
454
+ };
455
+ var sign = (msg, privKey) => {
456
+ const m = toU8(msg);
457
+ const e = getExtendedPublicKey(privKey);
458
+ const rBytes = sha512s(e.prefix, m);
459
+ return hashFinishS(_sign(e, rBytes, m));
460
+ };
461
+ var etc = {
462
+ sha512Async: async (...messages) => {
463
+ const s = subtle();
464
+ const m = concatBytes(...messages);
465
+ return u8n(await s.digest("SHA-512", m.buffer));
466
+ },
467
+ sha512Sync: void 0,
468
+ bytesToHex,
469
+ hexToBytes,
470
+ concatBytes,
471
+ mod: M,
472
+ invert,
473
+ randomBytes
474
+ };
475
+ var utils = {
476
+ getExtendedPublicKeyAsync,
477
+ getExtendedPublicKey,
478
+ randomPrivateKey: () => randomBytes(L),
479
+ precompute: (w = 8, p = G) => {
480
+ p.multiply(3n);
481
+ return p;
482
+ }
483
+ // no-op
484
+ };
485
+ var W = 8;
486
+ var scalarBits = 256;
487
+ var pwindows = Math.ceil(scalarBits / W) + 1;
488
+ var pwindowSize = 2 ** (W - 1);
489
+ var precompute = () => {
490
+ const points = [];
491
+ let p = G;
492
+ let b = p;
493
+ for (let w = 0; w < pwindows; w++) {
494
+ b = p;
495
+ points.push(b);
496
+ for (let i = 1; i < pwindowSize; i++) {
497
+ b = b.add(p);
498
+ points.push(b);
499
+ }
500
+ p = b.double();
501
+ }
502
+ return points;
503
+ };
504
+ var Gpows = void 0;
505
+ var ctneg = (cnd, p) => {
506
+ const n = p.negate();
507
+ return cnd ? n : p;
508
+ };
509
+ var wNAF = (n) => {
510
+ const comp = Gpows || (Gpows = precompute());
511
+ let p = I;
512
+ let f = G;
513
+ const pow_2_w = 2 ** W;
514
+ const maxNum = pow_2_w;
515
+ const mask = big(pow_2_w - 1);
516
+ const shiftBy = big(W);
517
+ for (let w = 0; w < pwindows; w++) {
518
+ let wbits = Number(n & mask);
519
+ n >>= shiftBy;
520
+ if (wbits > pwindowSize) {
521
+ wbits -= maxNum;
522
+ n += 1n;
523
+ }
524
+ const off = w * pwindowSize;
525
+ const offF = off;
526
+ const offP = off + Math.abs(wbits) - 1;
527
+ const isEven = w % 2 !== 0;
528
+ const isNeg = wbits < 0;
529
+ if (wbits === 0) {
530
+ f = f.add(ctneg(isEven, comp[offF]));
531
+ } else {
532
+ p = p.add(ctneg(isNeg, comp[offP]));
533
+ }
534
+ }
535
+ return { p, f };
536
+ };
537
+
538
+ // node_modules/@noble/hashes/esm/utils.js
539
+ function isBytes2(a) {
540
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
541
+ }
542
+ function abytes2(b, ...lengths) {
543
+ if (!isBytes2(b))
544
+ throw new Error("Uint8Array expected");
545
+ if (lengths.length > 0 && !lengths.includes(b.length))
546
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
547
+ }
548
+ function aexists(instance, checkFinished = true) {
549
+ if (instance.destroyed)
550
+ throw new Error("Hash instance has been destroyed");
551
+ if (checkFinished && instance.finished)
552
+ throw new Error("Hash#digest() has already been called");
553
+ }
554
+ function aoutput(out, instance) {
555
+ abytes2(out);
556
+ const min = instance.outputLen;
557
+ if (out.length < min) {
558
+ throw new Error("digestInto() expects output buffer of length at least " + min);
559
+ }
560
+ }
561
+ function clean(...arrays) {
562
+ for (let i = 0; i < arrays.length; i++) {
563
+ arrays[i].fill(0);
564
+ }
565
+ }
566
+ function createView(arr) {
567
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
568
+ }
569
+ function utf8ToBytes(str) {
570
+ if (typeof str !== "string")
571
+ throw new Error("string expected");
572
+ return new Uint8Array(new TextEncoder().encode(str));
573
+ }
574
+ function toBytes(data) {
575
+ if (typeof data === "string")
576
+ data = utf8ToBytes(data);
577
+ abytes2(data);
578
+ return data;
579
+ }
580
+ var Hash = class {
581
+ };
582
+ function createHasher(hashCons) {
583
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
584
+ const tmp = hashCons();
585
+ hashC.outputLen = tmp.outputLen;
586
+ hashC.blockLen = tmp.blockLen;
587
+ hashC.create = () => hashCons();
588
+ return hashC;
589
+ }
590
+
591
+ // node_modules/@noble/hashes/esm/_md.js
592
+ function setBigUint64(view, byteOffset, value, isLE) {
593
+ if (typeof view.setBigUint64 === "function")
594
+ return view.setBigUint64(byteOffset, value, isLE);
595
+ const _32n2 = BigInt(32);
596
+ const _u32_max = BigInt(4294967295);
597
+ const wh = Number(value >> _32n2 & _u32_max);
598
+ const wl = Number(value & _u32_max);
599
+ const h2 = isLE ? 4 : 0;
600
+ const l = isLE ? 0 : 4;
601
+ view.setUint32(byteOffset + h2, wh, isLE);
602
+ view.setUint32(byteOffset + l, wl, isLE);
603
+ }
604
+ var HashMD = class extends Hash {
605
+ constructor(blockLen, outputLen, padOffset, isLE) {
606
+ super();
607
+ this.finished = false;
608
+ this.length = 0;
609
+ this.pos = 0;
610
+ this.destroyed = false;
611
+ this.blockLen = blockLen;
612
+ this.outputLen = outputLen;
613
+ this.padOffset = padOffset;
614
+ this.isLE = isLE;
615
+ this.buffer = new Uint8Array(blockLen);
616
+ this.view = createView(this.buffer);
617
+ }
618
+ update(data) {
619
+ aexists(this);
620
+ data = toBytes(data);
621
+ abytes2(data);
622
+ const { view, buffer, blockLen } = this;
623
+ const len = data.length;
624
+ for (let pos = 0; pos < len; ) {
625
+ const take = Math.min(blockLen - this.pos, len - pos);
626
+ if (take === blockLen) {
627
+ const dataView = createView(data);
628
+ for (; blockLen <= len - pos; pos += blockLen)
629
+ this.process(dataView, pos);
630
+ continue;
631
+ }
632
+ buffer.set(data.subarray(pos, pos + take), this.pos);
633
+ this.pos += take;
634
+ pos += take;
635
+ if (this.pos === blockLen) {
636
+ this.process(view, 0);
637
+ this.pos = 0;
638
+ }
639
+ }
640
+ this.length += data.length;
641
+ this.roundClean();
642
+ return this;
643
+ }
644
+ digestInto(out) {
645
+ aexists(this);
646
+ aoutput(out, this);
647
+ this.finished = true;
648
+ const { buffer, view, blockLen, isLE } = this;
649
+ let { pos } = this;
650
+ buffer[pos++] = 128;
651
+ clean(this.buffer.subarray(pos));
652
+ if (this.padOffset > blockLen - pos) {
653
+ this.process(view, 0);
654
+ pos = 0;
655
+ }
656
+ for (let i = pos; i < blockLen; i++)
657
+ buffer[i] = 0;
658
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
659
+ this.process(view, 0);
660
+ const oview = createView(out);
661
+ const len = this.outputLen;
662
+ if (len % 4)
663
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
664
+ const outLen = len / 4;
665
+ const state = this.get();
666
+ if (outLen > state.length)
667
+ throw new Error("_sha2: outputLen bigger than state");
668
+ for (let i = 0; i < outLen; i++)
669
+ oview.setUint32(4 * i, state[i], isLE);
670
+ }
671
+ digest() {
672
+ const { buffer, outputLen } = this;
673
+ this.digestInto(buffer);
674
+ const res = buffer.slice(0, outputLen);
675
+ this.destroy();
676
+ return res;
677
+ }
678
+ _cloneInto(to) {
679
+ to || (to = new this.constructor());
680
+ to.set(...this.get());
681
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
682
+ to.destroyed = destroyed;
683
+ to.finished = finished;
684
+ to.length = length;
685
+ to.pos = pos;
686
+ if (length % blockLen)
687
+ to.buffer.set(buffer);
688
+ return to;
689
+ }
690
+ clone() {
691
+ return this._cloneInto();
692
+ }
693
+ };
694
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
695
+ 1779033703,
696
+ 4089235720,
697
+ 3144134277,
698
+ 2227873595,
699
+ 1013904242,
700
+ 4271175723,
701
+ 2773480762,
702
+ 1595750129,
703
+ 1359893119,
704
+ 2917565137,
705
+ 2600822924,
706
+ 725511199,
707
+ 528734635,
708
+ 4215389547,
709
+ 1541459225,
710
+ 327033209
711
+ ]);
712
+
713
+ // node_modules/@noble/hashes/esm/_u64.js
714
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
715
+ var _32n = /* @__PURE__ */ BigInt(32);
716
+ function fromBig(n, le = false) {
717
+ if (le)
718
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
719
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
720
+ }
721
+ function split(lst, le = false) {
722
+ const len = lst.length;
723
+ let Ah = new Uint32Array(len);
724
+ let Al = new Uint32Array(len);
725
+ for (let i = 0; i < len; i++) {
726
+ const { h: h2, l } = fromBig(lst[i], le);
727
+ [Ah[i], Al[i]] = [h2, l];
728
+ }
729
+ return [Ah, Al];
730
+ }
731
+ var shrSH = (h2, _l, s) => h2 >>> s;
732
+ var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
733
+ var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
734
+ var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
735
+ var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
736
+ var rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
737
+ function add(Ah, Al, Bh, Bl) {
738
+ const l = (Al >>> 0) + (Bl >>> 0);
739
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
740
+ }
741
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
742
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
743
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
744
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
745
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
746
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
747
+
748
+ // node_modules/@noble/hashes/esm/sha2.js
749
+ var K512 = /* @__PURE__ */ (() => split([
750
+ "0x428a2f98d728ae22",
751
+ "0x7137449123ef65cd",
752
+ "0xb5c0fbcfec4d3b2f",
753
+ "0xe9b5dba58189dbbc",
754
+ "0x3956c25bf348b538",
755
+ "0x59f111f1b605d019",
756
+ "0x923f82a4af194f9b",
757
+ "0xab1c5ed5da6d8118",
758
+ "0xd807aa98a3030242",
759
+ "0x12835b0145706fbe",
760
+ "0x243185be4ee4b28c",
761
+ "0x550c7dc3d5ffb4e2",
762
+ "0x72be5d74f27b896f",
763
+ "0x80deb1fe3b1696b1",
764
+ "0x9bdc06a725c71235",
765
+ "0xc19bf174cf692694",
766
+ "0xe49b69c19ef14ad2",
767
+ "0xefbe4786384f25e3",
768
+ "0x0fc19dc68b8cd5b5",
769
+ "0x240ca1cc77ac9c65",
770
+ "0x2de92c6f592b0275",
771
+ "0x4a7484aa6ea6e483",
772
+ "0x5cb0a9dcbd41fbd4",
773
+ "0x76f988da831153b5",
774
+ "0x983e5152ee66dfab",
775
+ "0xa831c66d2db43210",
776
+ "0xb00327c898fb213f",
777
+ "0xbf597fc7beef0ee4",
778
+ "0xc6e00bf33da88fc2",
779
+ "0xd5a79147930aa725",
780
+ "0x06ca6351e003826f",
781
+ "0x142929670a0e6e70",
782
+ "0x27b70a8546d22ffc",
783
+ "0x2e1b21385c26c926",
784
+ "0x4d2c6dfc5ac42aed",
785
+ "0x53380d139d95b3df",
786
+ "0x650a73548baf63de",
787
+ "0x766a0abb3c77b2a8",
788
+ "0x81c2c92e47edaee6",
789
+ "0x92722c851482353b",
790
+ "0xa2bfe8a14cf10364",
791
+ "0xa81a664bbc423001",
792
+ "0xc24b8b70d0f89791",
793
+ "0xc76c51a30654be30",
794
+ "0xd192e819d6ef5218",
795
+ "0xd69906245565a910",
796
+ "0xf40e35855771202a",
797
+ "0x106aa07032bbd1b8",
798
+ "0x19a4c116b8d2d0c8",
799
+ "0x1e376c085141ab53",
800
+ "0x2748774cdf8eeb99",
801
+ "0x34b0bcb5e19b48a8",
802
+ "0x391c0cb3c5c95a63",
803
+ "0x4ed8aa4ae3418acb",
804
+ "0x5b9cca4f7763e373",
805
+ "0x682e6ff3d6b2b8a3",
806
+ "0x748f82ee5defb2fc",
807
+ "0x78a5636f43172f60",
808
+ "0x84c87814a1f0ab72",
809
+ "0x8cc702081a6439ec",
810
+ "0x90befffa23631e28",
811
+ "0xa4506cebde82bde9",
812
+ "0xbef9a3f7b2c67915",
813
+ "0xc67178f2e372532b",
814
+ "0xca273eceea26619c",
815
+ "0xd186b8c721c0c207",
816
+ "0xeada7dd6cde0eb1e",
817
+ "0xf57d4f7fee6ed178",
818
+ "0x06f067aa72176fba",
819
+ "0x0a637dc5a2c898a6",
820
+ "0x113f9804bef90dae",
821
+ "0x1b710b35131c471b",
822
+ "0x28db77f523047d84",
823
+ "0x32caab7b40c72493",
824
+ "0x3c9ebe0a15c9bebc",
825
+ "0x431d67c49c100d4c",
826
+ "0x4cc5d4becb3e42b6",
827
+ "0x597f299cfc657e2a",
828
+ "0x5fcb6fab3ad6faec",
829
+ "0x6c44198c4a475817"
830
+ ].map((n) => BigInt(n))))();
831
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
832
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
833
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
834
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
835
+ var SHA512 = class extends HashMD {
836
+ constructor(outputLen = 64) {
837
+ super(128, outputLen, 16, false);
838
+ this.Ah = SHA512_IV[0] | 0;
839
+ this.Al = SHA512_IV[1] | 0;
840
+ this.Bh = SHA512_IV[2] | 0;
841
+ this.Bl = SHA512_IV[3] | 0;
842
+ this.Ch = SHA512_IV[4] | 0;
843
+ this.Cl = SHA512_IV[5] | 0;
844
+ this.Dh = SHA512_IV[6] | 0;
845
+ this.Dl = SHA512_IV[7] | 0;
846
+ this.Eh = SHA512_IV[8] | 0;
847
+ this.El = SHA512_IV[9] | 0;
848
+ this.Fh = SHA512_IV[10] | 0;
849
+ this.Fl = SHA512_IV[11] | 0;
850
+ this.Gh = SHA512_IV[12] | 0;
851
+ this.Gl = SHA512_IV[13] | 0;
852
+ this.Hh = SHA512_IV[14] | 0;
853
+ this.Hl = SHA512_IV[15] | 0;
854
+ }
855
+ // prettier-ignore
856
+ get() {
857
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
858
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
859
+ }
860
+ // prettier-ignore
861
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
862
+ this.Ah = Ah | 0;
863
+ this.Al = Al | 0;
864
+ this.Bh = Bh | 0;
865
+ this.Bl = Bl | 0;
866
+ this.Ch = Ch | 0;
867
+ this.Cl = Cl | 0;
868
+ this.Dh = Dh | 0;
869
+ this.Dl = Dl | 0;
870
+ this.Eh = Eh | 0;
871
+ this.El = El | 0;
872
+ this.Fh = Fh | 0;
873
+ this.Fl = Fl | 0;
874
+ this.Gh = Gh | 0;
875
+ this.Gl = Gl | 0;
876
+ this.Hh = Hh | 0;
877
+ this.Hl = Hl | 0;
878
+ }
879
+ process(view, offset) {
880
+ for (let i = 0; i < 16; i++, offset += 4) {
881
+ SHA512_W_H[i] = view.getUint32(offset);
882
+ SHA512_W_L[i] = view.getUint32(offset += 4);
883
+ }
884
+ for (let i = 16; i < 80; i++) {
885
+ const W15h = SHA512_W_H[i - 15] | 0;
886
+ const W15l = SHA512_W_L[i - 15] | 0;
887
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
888
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
889
+ const W2h = SHA512_W_H[i - 2] | 0;
890
+ const W2l = SHA512_W_L[i - 2] | 0;
891
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
892
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
893
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
894
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
895
+ SHA512_W_H[i] = SUMh | 0;
896
+ SHA512_W_L[i] = SUMl | 0;
897
+ }
898
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
899
+ for (let i = 0; i < 80; i++) {
900
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
901
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
902
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
903
+ const CHIl = El & Fl ^ ~El & Gl;
904
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
905
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
906
+ const T1l = T1ll | 0;
907
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
908
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
909
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
910
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
911
+ Hh = Gh | 0;
912
+ Hl = Gl | 0;
913
+ Gh = Fh | 0;
914
+ Gl = Fl | 0;
915
+ Fh = Eh | 0;
916
+ Fl = El | 0;
917
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
918
+ Dh = Ch | 0;
919
+ Dl = Cl | 0;
920
+ Ch = Bh | 0;
921
+ Cl = Bl | 0;
922
+ Bh = Ah | 0;
923
+ Bl = Al | 0;
924
+ const All = add3L(T1l, sigma0l, MAJl);
925
+ Ah = add3H(All, T1h, sigma0h, MAJh);
926
+ Al = All | 0;
927
+ }
928
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
929
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
930
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
931
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
932
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
933
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
934
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
935
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
936
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
937
+ }
938
+ roundClean() {
939
+ clean(SHA512_W_H, SHA512_W_L);
940
+ }
941
+ destroy() {
942
+ clean(this.buffer);
943
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
944
+ }
945
+ };
946
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
947
+
948
+ // node_modules/@noble/hashes/esm/sha512.js
949
+ var sha5122 = sha512;
950
+
951
+ // src/crypto/keys.ts
952
+ etc.sha512Sync = (...m) => {
953
+ const h2 = sha5122.create();
954
+ for (const msg of m) h2.update(msg);
955
+ return h2.digest();
956
+ };
957
+ function generateKeyPair() {
958
+ const privateKey = utils.randomPrivateKey();
959
+ const publicKey = getPublicKey(privateKey);
960
+ return { privateKey, publicKey };
961
+ }
962
+ function getPublicKey2(privateKey) {
963
+ return getPublicKey(privateKey);
964
+ }
965
+ function privateKeyToHex(key) {
966
+ return Array.from(key).map((b) => b.toString(16).padStart(2, "0")).join("");
967
+ }
968
+ function hexToPrivateKey(hex) {
969
+ const bytes = new Uint8Array(hex.length / 2);
970
+ for (let i = 0; i < bytes.length; i++) {
971
+ bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
972
+ }
973
+ return bytes;
974
+ }
975
+
976
+ // src/crypto/base58.ts
977
+ var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
978
+ var BASE = 58;
979
+ var ALPHABET_MAP = /* @__PURE__ */ new Map();
980
+ for (let i = 0; i < ALPHABET.length; i++) {
981
+ ALPHABET_MAP.set(ALPHABET[i], i);
982
+ }
983
+ function encode(bytes) {
984
+ if (bytes.length === 0) return "";
985
+ let zeros = 0;
986
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
987
+ const digits = [];
988
+ for (let i = zeros; i < bytes.length; i++) {
989
+ let carry = bytes[i];
990
+ for (let j = 0; j < digits.length; j++) {
991
+ carry += digits[j] << 8;
992
+ digits[j] = carry % BASE;
993
+ carry = carry / BASE | 0;
994
+ }
995
+ while (carry > 0) {
996
+ digits.push(carry % BASE);
997
+ carry = carry / BASE | 0;
998
+ }
999
+ }
1000
+ let result = ALPHABET[0].repeat(zeros);
1001
+ for (let i = digits.length - 1; i >= 0; i--) {
1002
+ result += ALPHABET[digits[i]];
1003
+ }
1004
+ return result;
1005
+ }
1006
+ function decode(str) {
1007
+ if (str.length === 0) return new Uint8Array(0);
1008
+ let zeros = 0;
1009
+ while (zeros < str.length && str[zeros] === ALPHABET[0]) zeros++;
1010
+ const bytes = [];
1011
+ for (let i = zeros; i < str.length; i++) {
1012
+ const val = ALPHABET_MAP.get(str[i]);
1013
+ if (val === void 0) throw new Error(`Invalid base58 character: ${str[i]}`);
1014
+ let carry = val;
1015
+ for (let j = 0; j < bytes.length; j++) {
1016
+ carry += bytes[j] * BASE;
1017
+ bytes[j] = carry & 255;
1018
+ carry >>= 8;
1019
+ }
1020
+ while (carry > 0) {
1021
+ bytes.push(carry & 255);
1022
+ carry >>= 8;
1023
+ }
1024
+ }
1025
+ const result = new Uint8Array(zeros + bytes.length);
1026
+ for (let i = 0; i < zeros; i++) result[i] = 0;
1027
+ for (let i = 0; i < bytes.length; i++) result[zeros + i] = bytes[bytes.length - 1 - i];
1028
+ return result;
1029
+ }
1030
+
1031
+ // src/crypto/multikey.ts
1032
+ var ED25519_PREFIX = new Uint8Array([237, 1]);
1033
+ function encodePublicKey(publicKey) {
1034
+ const prefixed = new Uint8Array(2 + publicKey.length);
1035
+ prefixed.set(ED25519_PREFIX, 0);
1036
+ prefixed.set(publicKey, 2);
1037
+ return "z" + encode(prefixed);
1038
+ }
1039
+ function decodePublicKey(multikey) {
1040
+ if (!multikey.startsWith("z")) {
1041
+ throw new Error('Multikey must start with "z"');
1042
+ }
1043
+ const decoded = decode(multikey.slice(1));
1044
+ if (decoded[0] !== 237 || decoded[1] !== 1) {
1045
+ throw new Error("Invalid Ed25519 multikey prefix");
1046
+ }
1047
+ return decoded.slice(2);
1048
+ }
1049
+ function didFromPublicKey(publicKey) {
1050
+ return `did:key:${encodePublicKey(publicKey)}`;
1051
+ }
1052
+
1053
+ // src/crypto/jwt.ts
1054
+ var encoder = new TextEncoder();
1055
+ function base64UrlEncode(data) {
1056
+ let binary = "";
1057
+ for (let i = 0; i < data.length; i++) {
1058
+ binary += String.fromCharCode(data[i]);
1059
+ }
1060
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1061
+ }
1062
+ function createEdDSAJWT(privateKey, lifetimeSeconds = 300) {
1063
+ const publicKey = getPublicKey2(privateKey);
1064
+ const multikey = encodePublicKey(publicKey);
1065
+ const did = `did:key:${multikey}`;
1066
+ const nowSecs = Math.floor(Date.now() / 1e3);
1067
+ const header = JSON.stringify({ alg: "EdDSA", typ: "JWT", kid: multikey });
1068
+ const payload = JSON.stringify({
1069
+ sub: did,
1070
+ iss: did,
1071
+ iat: nowSecs,
1072
+ exp: nowSecs + lifetimeSeconds
1073
+ });
1074
+ const headerB64 = base64UrlEncode(encoder.encode(header));
1075
+ const payloadB64 = base64UrlEncode(encoder.encode(payload));
1076
+ const signingInput = `${headerB64}.${payloadB64}`;
1077
+ const signature = sign(encoder.encode(signingInput), privateKey);
1078
+ const signatureB64 = base64UrlEncode(signature);
1079
+ return `${signingInput}.${signatureB64}`;
1080
+ }
1081
+
81
1082
  // src/Credentials.ts
82
1083
  var Auth = class {
83
1084
  };
@@ -94,24 +1095,38 @@ var BearerAuth = class extends Auth {
94
1095
  headers["Authorization"] = `Bearer ${this._token}`;
95
1096
  }
96
1097
  };
97
- var BasicAuth = class extends Auth {
98
- constructor(username, password) {
1098
+ var KeyPairAuth = class _KeyPairAuth extends Auth {
1099
+ /**
1100
+ * @param privateKey - 32-byte Ed25519 private key
1101
+ * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
1102
+ */
1103
+ constructor(privateKey, tokenLifetimeSeconds = 300) {
99
1104
  super();
100
- this._encoded = btoa(`${username}:${password}`);
1105
+ this._privateKey = privateKey;
1106
+ this._publicKey = getPublicKey2(privateKey);
1107
+ this._did = didFromPublicKey(this._publicKey);
1108
+ this._lifetime = tokenLifetimeSeconds;
101
1109
  }
102
1110
  apply(headers) {
103
- headers["Authorization"] = `Basic ${this._encoded}`;
1111
+ const jwt = createEdDSAJWT(this._privateKey, this._lifetime);
1112
+ headers["Authorization"] = `Bearer ${jwt}`;
104
1113
  }
105
- };
106
- var CoviaUserAuth = class extends Auth {
107
- constructor(userId) {
108
- super();
109
- this._userId = userId;
1114
+ /** The caller's DID derived from the public key. */
1115
+ getDID() {
1116
+ return this._did;
110
1117
  }
111
- apply(headers) {
112
- if (this._userId && this._userId !== "") {
113
- headers["X-Covia-User"] = this._userId;
114
- }
1118
+ /** The 32-byte Ed25519 public key. */
1119
+ getPublicKey() {
1120
+ return this._publicKey;
1121
+ }
1122
+ /** Generate a new random keypair and return a KeyPairAuth instance. */
1123
+ static generate(tokenLifetimeSeconds = 300) {
1124
+ const { privateKey } = generateKeyPair();
1125
+ return new _KeyPairAuth(privateKey, tokenLifetimeSeconds);
1126
+ }
1127
+ /** Create from a hex-encoded private key string. */
1128
+ static fromHex(privateKeyHex, tokenLifetimeSeconds = 300) {
1129
+ return new _KeyPairAuth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
115
1130
  }
116
1131
  };
117
1132
  var CredentialsHTTP = class {
@@ -319,92 +1334,44 @@ async function* parseSSEStream(response) {
319
1334
  }
320
1335
  }
321
1336
 
322
- // src/Asset.ts
323
- var cache = /* @__PURE__ */ new Map();
324
- var Asset = class {
325
- constructor(id, venue, metadata = {}) {
326
- this.id = id;
1337
+ // src/AgentManager.ts
1338
+ var AgentManager = class {
1339
+ constructor(venue) {
327
1340
  this.venue = venue;
328
- this.metadata = metadata;
329
1341
  }
330
- /**
331
- * Get asset metadata
332
- * @returns {Promise<AssetMetadata>}
333
- */
334
- async getMetadata() {
335
- if (cache.has(this.id)) {
336
- return Promise.resolve(cache.get(this.id));
337
- } else {
338
- const data = this.venue.getMetadata(this.id);
339
- if (data) {
340
- cache.set(this.id, data);
341
- }
342
- return data;
343
- }
1342
+ async create(input) {
1343
+ return this.venue.operations.run("v/ops/agent/create", input);
344
1344
  }
345
- /**
346
- * Read stream from asset
347
- * @param reader - ReadableStreamDefaultReader
348
- */
349
- async readStream(reader) {
350
- return this.readStream(reader);
1345
+ async request(agentId, input, wait) {
1346
+ return this.venue.operations.run("v/ops/agent/request", { agentId, input, wait });
351
1347
  }
352
- /**
353
- * Put content to asset
354
- * @param content - Content to upload
355
- * @returns {Promise<ReadableStream<Uint8Array> | null>}
356
- */
357
- putContent(content) {
358
- return this.venue.putContent(this.id, content);
1348
+ async message(agentId, message) {
1349
+ return this.venue.operations.run("v/ops/agent/message", { agentId, message });
359
1350
  }
360
- /**
361
- * Get asset content
362
- * @returns {Promise<ReadableStream<Uint8Array> | null>}
363
- */
364
- getContent() {
365
- return this.venue.getContent(this.id);
1351
+ async trigger(agentId) {
1352
+ return this.venue.operations.run("v/ops/agent/trigger", { agentId });
366
1353
  }
367
- /**
368
- * Get the URL for downloading asset content
369
- * @returns {string} The URL for downloading the asset content
370
- */
371
- getContentURL() {
372
- return `${this.venue.baseUrl}/api/v1/assets/${this.id}/content`;
1354
+ async query(agentId) {
1355
+ return this.venue.operations.run("v/ops/agent/info", { agentId });
373
1356
  }
374
- /**
375
- * Execute the operation
376
- * @param input - Operation input parameters
377
- * @returns {Promise<any>}
378
- */
379
- run(input) {
380
- return this.venue.run(this.id, input);
1357
+ async list(includeTerminated) {
1358
+ return this.venue.operations.run("v/ops/agent/list", { includeTerminated });
381
1359
  }
382
- /**
383
- * Execute the operation
384
- * @param input - Operation input parameters
385
- * @returns {Promise<any>}
386
- */
387
- invoke(input) {
388
- return this.venue.invoke(this.id, input);
1360
+ async delete(agentId, remove) {
1361
+ return this.venue.operations.run("v/ops/agent/delete", { agentId, remove });
389
1362
  }
390
- };
391
-
392
- // src/Operation.ts
393
- var Operation = class extends Asset {
394
- constructor(id, venue, metadata = {}) {
395
- super(id, venue, metadata);
1363
+ async suspend(agentId) {
1364
+ return this.venue.operations.run("v/ops/agent/suspend", { agentId });
396
1365
  }
397
- // Operation-specific methods can be added here
398
- // For now, it inherits all functionality from Asset
399
- };
400
-
401
- // src/DataAsset.ts
402
- var DataAsset = class extends Asset {
403
- constructor(id, venue, metadata = {}) {
404
- super(id, venue, metadata);
1366
+ async resume(agentId, autoWake) {
1367
+ return this.venue.operations.run("v/ops/agent/resume", { agentId, autoWake });
1368
+ }
1369
+ async update(input) {
1370
+ return this.venue.operations.run("v/ops/agent/update", input);
1371
+ }
1372
+ async cancelTask(agentId, taskId) {
1373
+ return this.venue.operations.run("v/ops/agent/cancel-task", { agentId, taskId });
405
1374
  }
406
- // DataAsset-specific methods can be added here
407
- // For now, it inherits all functionality from Asset
408
1375
  };
409
1376
 
410
1377
  // src/Job.ts
@@ -416,6 +1383,7 @@ var Job = class {
416
1383
  this.id = id;
417
1384
  this.venue = venue;
418
1385
  this.metadata = metadata;
1386
+ this._jobs = venue.jobs;
419
1387
  }
420
1388
  /**
421
1389
  * Whether the job has reached a terminal state
@@ -491,166 +1459,117 @@ var Job = class {
491
1459
  * @returns AsyncGenerator yielding SSEEvent objects
492
1460
  */
493
1461
  async *stream() {
494
- yield* this.venue.streamJobEvents(this.id);
1462
+ yield* this._jobs.stream(this.id);
495
1463
  }
496
1464
  /**
497
- * Cancels the execution of the job
498
- * @returns {Promise<number>}
1465
+ * Whether the job is paused (PAUSED, INPUT_REQUIRED, or AUTH_REQUIRED)
499
1466
  */
500
- async cancelJob() {
501
- return this.venue.cancelJob(this.id);
1467
+ get isPaused() {
1468
+ return this.metadata.status != null && isJobPaused(this.metadata.status);
502
1469
  }
503
1470
  /**
504
- * Delete the job
505
- * @returns {Promise<number>}
1471
+ * Whether the job requires user input
506
1472
  */
507
- async deleteJob() {
508
- return this.venue.deleteJob(this.id);
1473
+ get needsInput() {
1474
+ return this.metadata.status === "INPUT_REQUIRED" /* INPUT_REQUIRED */;
509
1475
  }
510
- };
511
-
512
- // src/Venue.ts
513
- var webResolver = getResolver();
514
- var resolver = new Resolver(webResolver);
515
- var cache2 = /* @__PURE__ */ new Map();
516
- var Venue = class _Venue {
517
- constructor(options = {}) {
518
- this.baseUrl = options.baseUrl || "";
519
- this.venueId = options.venueId || "";
520
- this.auth = options.auth || new NoAuth();
521
- this.metadata = {
522
- name: options.name || "default",
523
- description: options.description || ""
524
- };
1476
+ /**
1477
+ * Whether the job requires authentication
1478
+ */
1479
+ get needsAuth() {
1480
+ return this.metadata.status === "AUTH_REQUIRED" /* AUTH_REQUIRED */;
525
1481
  }
526
1482
  /**
527
- * Static method to connect to a venue
528
- * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
529
- * @param credentials - Optional credentials for venue authentication
530
- * @returns {Promise<Venue>} A new Venue instance configured appropriately
1483
+ * Send a message to the running job
1484
+ * @param message - Message payload
1485
+ * @returns {Promise<any>}
531
1486
  */
532
- static async connect(venueId, auth) {
533
- if (venueId instanceof _Venue) {
534
- return new _Venue({
535
- baseUrl: venueId.baseUrl,
536
- venueId: venueId.venueId,
537
- name: venueId.metadata.name,
538
- auth
539
- });
540
- }
541
- if (typeof venueId === "string") {
542
- let baseUrl;
543
- if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
544
- baseUrl = venueId;
545
- if (baseUrl.endsWith("/"))
546
- baseUrl = baseUrl.substring(0, baseUrl.length - 1);
547
- } else if (venueId.startsWith("did:web:")) {
548
- const didDoc = await resolver.resolve(venueId);
549
- if (!didDoc.didDocument) {
550
- throw new CoviaError("Invalid DID document");
551
- }
552
- const endpoint = didDoc.didDocument.service?.find((service) => service.type === "Covia.API.v1")?.serviceEndpoint;
553
- if (!endpoint) {
554
- throw new CoviaError("No endpoint found for DID");
555
- }
556
- baseUrl = endpoint.toString().replace(/\/api\/v1/, "");
557
- } else {
558
- baseUrl = `https://${venueId}`;
559
- }
560
- const data = await fetchWithError(baseUrl + "/api/v1/status");
561
- return new _Venue({
562
- baseUrl,
563
- venueId: data.did,
564
- name: data.name,
565
- auth
566
- });
567
- }
568
- throw new CoviaError("Invalid venue ID parameter. Must be a string (URL/DNS) or Venue instance.");
1487
+ async sendMessage(message) {
1488
+ return this._jobs.sendMessage(this.id, message);
569
1489
  }
570
1490
  /**
571
- * Register a new asset
572
- * @param assetData - Asset configuration
573
- * @returns {Promise<Asset>}
1491
+ * Pause the job
1492
+ * @returns {Promise<JobMetadata>} Updated job metadata
574
1493
  */
575
- async register(assetData) {
576
- return fetchWithError(`${this.baseUrl}/api/v1/assets/`, {
577
- method: "POST",
578
- headers: this._buildHeaders(),
579
- body: JSON.stringify(assetData)
580
- }).then((response) => {
581
- return this.getAsset(response);
582
- });
1494
+ async pause() {
1495
+ this.metadata = await this._jobs.pause(this.id);
1496
+ return this.metadata;
583
1497
  }
584
1498
  /**
585
- * Read stream from asset
586
- * @param reader - ReadableStreamDefaultReader
1499
+ * Resume the job
1500
+ * @returns {Promise<JobMetadata>} Updated job metadata
587
1501
  */
588
- async readStream(reader) {
589
- while (true) {
590
- const { done, value } = await reader.read();
591
- if (done) {
592
- break;
593
- }
594
- }
1502
+ async resume() {
1503
+ this.metadata = await this._jobs.resume(this.id);
1504
+ return this.metadata;
595
1505
  }
596
1506
  /**
597
- * Get asset by ID
598
- * @param assetId - Asset identifier
599
- * @returns {Promise<Asset>} Returns either an Operation or DataAsset based on the asset's metadata
1507
+ * Cancel the job
1508
+ * @returns {Promise<JobMetadata>} Updated job metadata
600
1509
  */
601
- async getAsset(assetId) {
602
- if (cache2.has(assetId)) {
603
- const cachedData = cache2.get(assetId);
604
- if (cachedData.metadata?.operation) {
605
- return new Operation(assetId, this, cachedData);
606
- } else {
607
- return new DataAsset(assetId, this, cachedData);
1510
+ async cancel() {
1511
+ this.metadata = await this._jobs.cancel(this.id);
1512
+ return this.metadata;
1513
+ }
1514
+ /**
1515
+ * Delete the job
1516
+ */
1517
+ async delete() {
1518
+ return this._jobs.delete(this.id);
1519
+ }
1520
+ };
1521
+
1522
+ // src/JobManager.ts
1523
+ var JobManager = class {
1524
+ constructor(venue) {
1525
+ this.venue = venue;
1526
+ }
1527
+ async list() {
1528
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/jobs`);
1529
+ }
1530
+ async get(jobId) {
1531
+ try {
1532
+ const data = await fetchWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}`);
1533
+ return new Job(jobId, this.venue, data);
1534
+ } catch (error) {
1535
+ if (error instanceof NotFoundError) {
1536
+ throw new JobNotFoundError(jobId);
608
1537
  }
1538
+ throw error;
609
1539
  }
1540
+ }
1541
+ async cancel(jobId) {
610
1542
  try {
611
- const data = await fetchWithError(`${this.baseUrl}/api/v1/assets/${assetId}`);
612
- cache2.set(assetId, data);
613
- if (data.metadata?.operation) {
614
- return new Operation(assetId, this, data);
615
- } else {
616
- return new DataAsset(assetId, this, data);
617
- }
1543
+ return await fetchWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}/cancel`, {
1544
+ method: "PUT",
1545
+ headers: this._buildHeaders()
1546
+ });
618
1547
  } catch (error) {
619
1548
  if (error instanceof NotFoundError) {
620
- throw new AssetNotFoundError(assetId);
1549
+ throw new JobNotFoundError(jobId);
621
1550
  }
622
1551
  throw error;
623
1552
  }
624
1553
  }
625
- /**
626
- * List assets with pagination support
627
- * @param options - Pagination options (offset, limit)
628
- * @returns {Promise<AssetList>} Paginated list of asset IDs with metadata
629
- */
630
- async listAssets(options = {}) {
631
- const params = new URLSearchParams();
632
- params.set("offset", String(options.offset ?? 0));
633
- if (options.limit !== void 0) {
634
- params.set("limit", String(options.limit));
1554
+ async delete(jobId) {
1555
+ try {
1556
+ await fetchStreamWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}/delete`, {
1557
+ method: "PUT",
1558
+ headers: this._buildHeaders()
1559
+ });
1560
+ } catch (error) {
1561
+ if (error instanceof NotFoundError) {
1562
+ throw new JobNotFoundError(jobId);
1563
+ }
1564
+ throw error;
635
1565
  }
636
- return fetchWithError(`${this.baseUrl}/api/v1/assets/?${params.toString()}`);
637
1566
  }
638
- /**
639
- * List all jobs
640
- * @returns {Promise<string[]>}
641
- */
642
- async listJobs() {
643
- return fetchWithError(`${this.baseUrl}/api/v1/jobs`);
644
- }
645
- /**
646
- * Get job by ID
647
- * @param jobId - Job identifier
648
- * @returns {Promise<Job>}
649
- */
650
- async getJob(jobId) {
1567
+ async pause(jobId) {
651
1568
  try {
652
- const data = await fetchWithError(`${this.baseUrl}/api/v1/jobs/${jobId}`);
653
- return new Job(jobId, this, data);
1569
+ return await fetchWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}/pause`, {
1570
+ method: "PUT",
1571
+ headers: this._buildHeaders()
1572
+ });
654
1573
  } catch (error) {
655
1574
  if (error instanceof NotFoundError) {
656
1575
  throw new JobNotFoundError(jobId);
@@ -658,15 +1577,12 @@ var Venue = class _Venue {
658
1577
  throw error;
659
1578
  }
660
1579
  }
661
- /**
662
- * Cancel job by ID
663
- * @param jobId - Job identifier
664
- * @returns {Promise<number>}
665
- */
666
- async cancelJob(jobId) {
1580
+ async resume(jobId) {
667
1581
  try {
668
- const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/jobs/${jobId}/cancel`, { method: "PUT" });
669
- return response.status;
1582
+ return await fetchWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}/resume`, {
1583
+ method: "PUT",
1584
+ headers: this._buildHeaders()
1585
+ });
670
1586
  } catch (error) {
671
1587
  if (error instanceof NotFoundError) {
672
1588
  throw new JobNotFoundError(jobId);
@@ -674,15 +1590,13 @@ var Venue = class _Venue {
674
1590
  throw error;
675
1591
  }
676
1592
  }
677
- /**
678
- * Delete job by ID
679
- * @param jobId - Job identifier
680
- * @returns {Promise<number>}
681
- */
682
- async deleteJob(jobId) {
1593
+ async sendMessage(jobId, message) {
683
1594
  try {
684
- const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/jobs/${jobId}/delete`, { method: "PUT" });
685
- return response.status;
1595
+ return await fetchWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}`, {
1596
+ method: "POST",
1597
+ headers: this._buildHeaders(),
1598
+ body: JSON.stringify(message)
1599
+ });
686
1600
  } catch (error) {
687
1601
  if (error instanceof NotFoundError) {
688
1602
  throw new JobNotFoundError(jobId);
@@ -690,56 +1604,167 @@ var Venue = class _Venue {
690
1604
  throw error;
691
1605
  }
692
1606
  }
1607
+ async *stream(jobId) {
1608
+ const response = await fetchStreamWithError(`${this.venue.baseUrl}/api/v1/jobs/${jobId}/sse`, {
1609
+ headers: { ...this._buildHeaders(), "Accept": "text/event-stream" }
1610
+ });
1611
+ yield* parseSSEStream(response);
1612
+ }
1613
+ _buildHeaders() {
1614
+ const headers = { "Content-Type": "application/json" };
1615
+ this.venue.auth.apply(headers);
1616
+ return headers;
1617
+ }
1618
+ };
1619
+
1620
+ // src/Asset.ts
1621
+ var cache = /* @__PURE__ */ new Map();
1622
+ var Asset = class {
1623
+ constructor(id, venue, metadata = {}) {
1624
+ this.id = id;
1625
+ this.venue = venue;
1626
+ this.metadata = metadata;
1627
+ this._assets = venue.assets;
1628
+ this._operations = venue.operations;
1629
+ }
693
1630
  /**
694
- * Get venue status
695
- * @returns {Promise<StatusData>}
1631
+ * Get asset metadata
1632
+ * @returns {Promise<AssetMetadata>}
696
1633
  */
697
- status() {
698
- return fetchWithError(`${this.baseUrl}/api/v1/status`);
1634
+ async getMetadata() {
1635
+ if (cache.has(this.id)) {
1636
+ return Promise.resolve(cache.get(this.id));
1637
+ } else {
1638
+ const data = this._assets.getMetadata(this.id);
1639
+ if (data) {
1640
+ cache.set(this.id, data);
1641
+ }
1642
+ return data;
1643
+ }
699
1644
  }
700
1645
  /**
701
- * List all named operations available on this venue
702
- * @returns {Promise<OperationInfo[]>}
1646
+ * Put content to asset
1647
+ * @param content - Content to upload
1648
+ * @returns {Promise<ContentHashResult>} The content hash returned by the server
703
1649
  */
704
- async listOperations() {
705
- return fetchWithError(`${this.baseUrl}/api/v1/operations`);
1650
+ putContent(content) {
1651
+ return this._assets.putContent(this.id, content);
706
1652
  }
707
1653
  /**
708
- * Get details of a named operation
709
- * @param name - Operation name (e.g., "test:echo")
710
- * @returns {Promise<OperationInfo>}
1654
+ * Get asset content
1655
+ * @returns {Promise<ReadableStream<Uint8Array> | null>}
711
1656
  */
712
- async getOperation(name) {
713
- return fetchWithError(`${this.baseUrl}/api/v1/operations/${name}`);
1657
+ getContent() {
1658
+ return this._assets.getContent(this.id);
714
1659
  }
715
1660
  /**
716
- * Get the full DID document for this venue
717
- * @returns {Promise<DIDDocument>}
1661
+ * Get the URL for downloading asset content
1662
+ * @returns {string} The URL for downloading the asset content
718
1663
  */
719
- async didDocument() {
720
- return fetchWithError(`${this.baseUrl}/.well-known/did.json`);
1664
+ getContentURL() {
1665
+ return `${this.venue.baseUrl}/api/v1/assets/${this.id}/content`;
721
1666
  }
722
1667
  /**
723
- * Get MCP (Model Context Protocol) discovery information
724
- * @returns {Promise<MCPDiscovery>}
1668
+ * Execute the operation
1669
+ * @param input - Operation input parameters
1670
+ * @returns {Promise<any>}
725
1671
  */
726
- async mcpDiscovery() {
727
- return fetchWithError(`${this.baseUrl}/.well-known/mcp`);
1672
+ run(input) {
1673
+ return this._operations.run(this.id, input);
728
1674
  }
729
1675
  /**
730
- * Get the A2A (Agent-to-Agent) agent card
731
- * @returns {Promise<AgentCard>}
1676
+ * Execute the operation
1677
+ * @param input - Operation input parameters
1678
+ * @returns {Promise<Job>}
1679
+ */
1680
+ invoke(input) {
1681
+ return this._operations.invoke(this.id, input);
1682
+ }
1683
+ };
1684
+
1685
+ // src/Operation.ts
1686
+ var Operation = class extends Asset {
1687
+ constructor(id, venue, metadata = {}) {
1688
+ super(id, venue, metadata);
1689
+ }
1690
+ // Operation-specific methods can be added here
1691
+ // For now, it inherits all functionality from Asset
1692
+ };
1693
+
1694
+ // src/DataAsset.ts
1695
+ var DataAsset = class extends Asset {
1696
+ constructor(id, venue, metadata = {}) {
1697
+ super(id, venue, metadata);
1698
+ }
1699
+ // DataAsset-specific methods can be added here
1700
+ // For now, it inherits all functionality from Asset
1701
+ };
1702
+
1703
+ // src/AssetManager.ts
1704
+ var cache2 = /* @__PURE__ */ new Map();
1705
+ var AssetManager = class {
1706
+ constructor(venue) {
1707
+ this.venue = venue;
1708
+ }
1709
+ /**
1710
+ * Get asset by ID
1711
+ * @param assetId - Asset identifier
1712
+ * @returns Returns either an Operation or DataAsset based on the asset's metadata
732
1713
  */
733
- async agentCard() {
734
- return fetchWithError(`${this.baseUrl}/.well-known/agent-card.json`);
1714
+ async get(assetId) {
1715
+ if (cache2.has(assetId)) {
1716
+ const cachedData = cache2.get(assetId);
1717
+ if (cachedData.metadata?.operation) {
1718
+ return new Operation(assetId, this.venue, cachedData);
1719
+ } else {
1720
+ return new DataAsset(assetId, this.venue, cachedData);
1721
+ }
1722
+ }
1723
+ try {
1724
+ const data = await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}`);
1725
+ cache2.set(assetId, data);
1726
+ if (data.metadata?.operation) {
1727
+ return new Operation(assetId, this.venue, data);
1728
+ } else {
1729
+ return new DataAsset(assetId, this.venue, data);
1730
+ }
1731
+ } catch (error) {
1732
+ if (error instanceof NotFoundError) {
1733
+ throw new AssetNotFoundError(assetId);
1734
+ }
1735
+ throw error;
1736
+ }
1737
+ }
1738
+ /**
1739
+ * List assets with pagination support
1740
+ * @param options - Pagination options (offset, limit)
1741
+ */
1742
+ async list(options = {}) {
1743
+ const params = new URLSearchParams();
1744
+ params.set("offset", String(options.offset ?? 0));
1745
+ if (options.limit !== void 0) {
1746
+ params.set("limit", String(options.limit));
1747
+ }
1748
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/assets?${params.toString()}`);
1749
+ }
1750
+ /**
1751
+ * Register a new asset
1752
+ * @param assetData - Asset configuration
1753
+ */
1754
+ async register(assetData) {
1755
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/assets`, {
1756
+ method: "POST",
1757
+ headers: this._buildHeaders(),
1758
+ body: JSON.stringify(assetData)
1759
+ }).then((response) => this.get(response));
735
1760
  }
736
1761
  /**
737
1762
  * Get asset metadata
738
- * @returns {Promise<AssetMetadata>}
1763
+ * @param assetId - Asset identifier
739
1764
  */
740
1765
  async getMetadata(assetId) {
741
1766
  try {
742
- return await fetchWithError(`${this.baseUrl}/api/v1/assets/${assetId}`);
1767
+ return await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}`);
743
1768
  } catch (error) {
744
1769
  if (error instanceof NotFoundError) {
745
1770
  throw new AssetNotFoundError(assetId);
@@ -749,17 +1774,17 @@ var Venue = class _Venue {
749
1774
  }
750
1775
  /**
751
1776
  * Put content to asset
1777
+ * @param assetId - Asset identifier
752
1778
  * @param content - Content to upload
753
- * @returns {Promise<ReadableStream<Uint8Array> | null>}
1779
+ * @returns The content hash returned by the server
754
1780
  */
755
1781
  async putContent(assetId, content) {
756
1782
  try {
757
- const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/assets/${assetId}/content`, {
1783
+ return await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}/content`, {
758
1784
  method: "PUT",
759
1785
  headers: this._buildHeaders(),
760
1786
  body: content
761
1787
  });
762
- return response.body;
763
1788
  } catch (error) {
764
1789
  if (error instanceof NotFoundError) {
765
1790
  throw new AssetNotFoundError(assetId);
@@ -769,11 +1794,11 @@ var Venue = class _Venue {
769
1794
  }
770
1795
  /**
771
1796
  * Get asset content
772
- * @returns {Promise<ReadableStream<Uint8Array> | null>}
1797
+ * @param assetId - Asset identifier
773
1798
  */
774
1799
  async getContent(assetId) {
775
1800
  try {
776
- const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/assets/${assetId}/content`);
1801
+ const response = await fetchStreamWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}/content`);
777
1802
  return response.body;
778
1803
  } catch (error) {
779
1804
  if (error instanceof NotFoundError) {
@@ -783,64 +1808,309 @@ var Venue = class _Venue {
783
1808
  }
784
1809
  }
785
1810
  /**
786
- * Execute the operation
787
- * @param input - Operation input parameters
788
- * @returns {Promise<any>}
789
- */
790
- async run(assetId, input) {
1811
+ * Clear the asset cache.
1812
+ */
1813
+ clearCache() {
1814
+ cache2.clear();
1815
+ }
1816
+ _buildHeaders() {
1817
+ const headers = { "Content-Type": "application/json" };
1818
+ this.venue.auth.apply(headers);
1819
+ return headers;
1820
+ }
1821
+ };
1822
+
1823
+ // src/OperationManager.ts
1824
+ var OperationManager = class {
1825
+ constructor(venue) {
1826
+ this.venue = venue;
1827
+ }
1828
+ /**
1829
+ * List all named operations available on this venue
1830
+ */
1831
+ async list() {
1832
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/operations`);
1833
+ }
1834
+ /**
1835
+ * Get details of a named operation
1836
+ * @param name - Operation name (e.g., "test:echo")
1837
+ */
1838
+ async get(name) {
1839
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/operations/${name}`);
1840
+ }
1841
+ /**
1842
+ * Execute an operation and wait for the result
1843
+ * @param assetId - Operation asset ID or named operation
1844
+ * @param input - Operation input parameters
1845
+ * @param options - Invoke options (e.g., ucans)
1846
+ */
1847
+ async run(assetId, input, options) {
1848
+ const job = await this.invoke(assetId, input, options);
1849
+ return job.result();
1850
+ }
1851
+ /**
1852
+ * Execute an operation and return a Job for tracking
1853
+ * @param assetId - Operation asset ID or named operation
1854
+ * @param input - Operation input parameters
1855
+ * @param options - Invoke options (e.g., ucans)
1856
+ */
1857
+ async invoke(assetId, input, options) {
791
1858
  const payload = {
792
1859
  operation: assetId,
793
1860
  input
794
1861
  };
795
- try {
796
- const response = await fetchWithError(`${this.baseUrl}/api/v1/invoke/`, {
797
- method: "POST",
798
- headers: this._buildHeaders(),
799
- body: JSON.stringify(payload)
800
- });
801
- return response?.output;
802
- } catch (error) {
803
- throw error;
1862
+ if (options?.ucans) {
1863
+ payload.ucans = options.ucans;
804
1864
  }
1865
+ const response = await fetchWithError(`${this.venue.baseUrl}/api/v1/invoke`, {
1866
+ method: "POST",
1867
+ headers: this._buildHeaders(),
1868
+ body: JSON.stringify(payload)
1869
+ });
1870
+ return new Job(response?.id, this.venue, response);
1871
+ }
1872
+ _buildHeaders() {
1873
+ const headers = { "Content-Type": "application/json" };
1874
+ this.venue.auth.apply(headers);
1875
+ return headers;
1876
+ }
1877
+ };
1878
+
1879
+ // src/WorkspaceManager.ts
1880
+ var WorkspaceManager = class {
1881
+ constructor(venue) {
1882
+ this.venue = venue;
1883
+ }
1884
+ async read(path, maxSize) {
1885
+ return this.venue.operations.run("v/ops/covia/read", { path, maxSize });
1886
+ }
1887
+ async write(path, value) {
1888
+ return this.venue.operations.run("v/ops/covia/write", { path, value });
1889
+ }
1890
+ async delete(path) {
1891
+ return this.venue.operations.run("v/ops/covia/delete", { path });
1892
+ }
1893
+ async append(path, value) {
1894
+ return this.venue.operations.run("v/ops/covia/append", { path, value });
1895
+ }
1896
+ async list(path, limit, offset) {
1897
+ return this.venue.operations.run("v/ops/covia/list", { path, limit, offset });
1898
+ }
1899
+ async slice(path, offset, limit) {
1900
+ return this.venue.operations.run("v/ops/covia/slice", { path, offset, limit });
1901
+ }
1902
+ };
1903
+
1904
+ // src/UCANManager.ts
1905
+ var UCANManager = class {
1906
+ constructor(venue) {
1907
+ this.venue = venue;
1908
+ }
1909
+ async issue(aud, att, exp) {
1910
+ return this.venue.operations.run("v/ops/ucan/issue", { aud, att, exp });
1911
+ }
1912
+ };
1913
+
1914
+ // src/SecretManager.ts
1915
+ var SecretManager = class {
1916
+ constructor(venue) {
1917
+ this.venue = venue;
1918
+ }
1919
+ async set(name, value) {
1920
+ return this.venue.operations.run("v/ops/secret/set", { name, value });
805
1921
  }
806
1922
  /**
807
- * Execute the operation
808
- * @param input - Operation input parameters
809
- * @returns {Promise<Job>}
810
- */
811
- async invoke(assetId, input) {
812
- const payload = {
813
- operation: assetId,
814
- input
1923
+ * Extract a secret value by name.
1924
+ * NOTE: This operation requires a UCAN capability grant. The backend
1925
+ * may reject requests that lack the appropriate capability proof.
1926
+ */
1927
+ async extract(name) {
1928
+ return this.venue.operations.run("v/ops/secret/extract", { name });
1929
+ }
1930
+ async list() {
1931
+ return this.venue.listSecrets();
1932
+ }
1933
+ async put(name, value) {
1934
+ return this.venue.putSecret(name, value);
1935
+ }
1936
+ async delete(name) {
1937
+ return this.venue.deleteSecret(name);
1938
+ }
1939
+ };
1940
+ var webResolver = getResolver();
1941
+ var resolver = new Resolver(webResolver);
1942
+ var Venue = class _Venue {
1943
+ get agents() {
1944
+ return this._agents ?? (this._agents = new AgentManager(this));
1945
+ }
1946
+ get jobs() {
1947
+ return this._jobs ?? (this._jobs = new JobManager(this));
1948
+ }
1949
+ get assets() {
1950
+ return this._assets ?? (this._assets = new AssetManager(this));
1951
+ }
1952
+ get operations() {
1953
+ return this._operations ?? (this._operations = new OperationManager(this));
1954
+ }
1955
+ get workspace() {
1956
+ return this._workspace ?? (this._workspace = new WorkspaceManager(this));
1957
+ }
1958
+ get ucan() {
1959
+ return this._ucan ?? (this._ucan = new UCANManager(this));
1960
+ }
1961
+ get secrets() {
1962
+ return this._secrets ?? (this._secrets = new SecretManager(this));
1963
+ }
1964
+ constructor(options = {}) {
1965
+ this.baseUrl = options.baseUrl || "";
1966
+ this.venueId = options.venueId || "";
1967
+ this.auth = options.auth || new NoAuth();
1968
+ this.metadata = {
1969
+ name: options.name || "default",
1970
+ description: options.description || ""
815
1971
  };
816
- try {
817
- const response = await fetchWithError(`${this.baseUrl}/api/v1/invoke/`, {
818
- method: "POST",
819
- headers: this._buildHeaders(),
820
- body: JSON.stringify(payload)
1972
+ }
1973
+ /**
1974
+ * Static method to connect to a venue
1975
+ * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
1976
+ * @param credentials - Optional credentials for venue authentication
1977
+ * @returns {Promise<Venue>} A new Venue instance configured appropriately
1978
+ */
1979
+ static async connect(venueId, auth) {
1980
+ if (venueId instanceof _Venue) {
1981
+ return new _Venue({
1982
+ baseUrl: venueId.baseUrl,
1983
+ venueId: venueId.venueId,
1984
+ name: venueId.metadata.name,
1985
+ auth
821
1986
  });
822
- return new Job(response?.id, this, response);
823
- } catch (error) {
824
- throw error;
825
1987
  }
1988
+ if (typeof venueId === "string") {
1989
+ let baseUrl;
1990
+ if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
1991
+ baseUrl = venueId;
1992
+ if (baseUrl.endsWith("/"))
1993
+ baseUrl = baseUrl.substring(0, baseUrl.length - 1);
1994
+ } else if (venueId.startsWith("did:web:")) {
1995
+ const didDoc = await resolver.resolve(venueId);
1996
+ if (!didDoc.didDocument) {
1997
+ throw new CoviaError("Invalid DID document");
1998
+ }
1999
+ const endpoint = didDoc.didDocument.service?.find((service) => service.type === "Covia.API.v1")?.serviceEndpoint;
2000
+ if (!endpoint) {
2001
+ throw new CoviaError("No endpoint found for DID");
2002
+ }
2003
+ baseUrl = endpoint.toString().replace(/\/api\/v1/, "");
2004
+ } else {
2005
+ baseUrl = `https://${venueId}`;
2006
+ }
2007
+ const data = await fetchWithError(baseUrl + "/api/v1/status");
2008
+ return new _Venue({
2009
+ baseUrl,
2010
+ venueId: data.did,
2011
+ name: data.name,
2012
+ auth
2013
+ });
2014
+ }
2015
+ throw new CoviaError("Invalid venue ID parameter. Must be a string (URL/DNS) or Venue instance.");
2016
+ }
2017
+ /**
2018
+ * Get asset by ID (convenience delegate to venue.assets.get)
2019
+ * @param assetId - Asset identifier
2020
+ * @returns {Promise<Asset>} Returns either an Operation or DataAsset based on the asset's metadata
2021
+ */
2022
+ async getAsset(assetId) {
2023
+ return this.assets.get(assetId);
2024
+ }
2025
+ /**
2026
+ * List assets with pagination support (convenience delegate to venue.assets.list)
2027
+ * @param options - Pagination options (offset, limit)
2028
+ * @returns {Promise<AssetList>} Paginated list of asset IDs with metadata
2029
+ */
2030
+ async listAssets(options = {}) {
2031
+ return this.assets.list(options);
2032
+ }
2033
+ /**
2034
+ * List all jobs
2035
+ * @returns {Promise<string[]>}
2036
+ */
2037
+ async listJobs() {
2038
+ return this.jobs.list();
826
2039
  }
827
2040
  /**
828
- * Stream server-sent events for a job.
2041
+ * Get job by ID
829
2042
  * @param jobId - Job identifier
830
- * @returns AsyncGenerator yielding SSEEvent objects
2043
+ * @returns {Promise<Job>}
831
2044
  */
832
- async *streamJobEvents(jobId) {
833
- const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/jobs/${jobId}/sse`, {
834
- headers: { ...this._buildHeaders(), "Accept": "text/event-stream" }
2045
+ async getJob(jobId) {
2046
+ return this.jobs.get(jobId);
2047
+ }
2048
+ /**
2049
+ * List secret names
2050
+ * @returns {Promise<string[]>}
2051
+ */
2052
+ async listSecrets() {
2053
+ const result = await fetchWithError(`${this.baseUrl}/api/v1/secrets`, {
2054
+ headers: this._buildHeaders()
2055
+ });
2056
+ return result.items;
2057
+ }
2058
+ /**
2059
+ * Store a secret value
2060
+ * @param name - Secret name
2061
+ * @param value - Secret value
2062
+ */
2063
+ async putSecret(name, value) {
2064
+ await fetchWithError(`${this.baseUrl}/api/v1/secrets/${encodeURIComponent(name)}`, {
2065
+ method: "PUT",
2066
+ headers: this._buildHeaders(),
2067
+ body: JSON.stringify({ value })
2068
+ });
2069
+ }
2070
+ /**
2071
+ * Delete a secret
2072
+ * @param name - Secret name
2073
+ */
2074
+ async deleteSecret(name) {
2075
+ await fetchStreamWithError(`${this.baseUrl}/api/v1/secrets/${encodeURIComponent(name)}`, {
2076
+ method: "DELETE",
2077
+ headers: this._buildHeaders()
835
2078
  });
836
- yield* parseSSEStream(response);
2079
+ }
2080
+ /**
2081
+ * Get venue status
2082
+ * @returns {Promise<StatusData>}
2083
+ */
2084
+ status() {
2085
+ return fetchWithError(`${this.baseUrl}/api/v1/status`);
2086
+ }
2087
+ /**
2088
+ * Get the full DID document for this venue
2089
+ * @returns {Promise<DIDDocument>}
2090
+ */
2091
+ async didDocument() {
2092
+ return fetchWithError(`${this.baseUrl}/.well-known/did.json`);
2093
+ }
2094
+ /**
2095
+ * Get MCP (Model Context Protocol) discovery information
2096
+ * @returns {Promise<MCPDiscovery>}
2097
+ */
2098
+ async mcpDiscovery() {
2099
+ return fetchWithError(`${this.baseUrl}/.well-known/mcp`);
2100
+ }
2101
+ /**
2102
+ * Get the A2A (Agent-to-Agent) agent card
2103
+ * @returns {Promise<AgentCard>}
2104
+ */
2105
+ async agentCard() {
2106
+ return fetchWithError(`${this.baseUrl}/.well-known/agent-card.json`);
837
2107
  }
838
2108
  /**
839
2109
  * Close the venue and release resources.
840
2110
  * Clears cached asset data for this venue.
841
2111
  */
842
2112
  close() {
843
- cache2.clear();
2113
+ this.assets.clearCache();
844
2114
  }
845
2115
  /**
846
2116
  * Disposable support — allows `using venue = await Grid.connect(...)` in TS 5.2+.
@@ -861,7 +2131,7 @@ var Grid = class {
861
2131
  /**
862
2132
  * Static method to connect to a venue
863
2133
  * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
864
- * @param auth - Optional authentication provider (BearerAuth, BasicAuth, etc.)
2134
+ * @param auth - Optional authentication provider (BearerAuth, KeyPairAuth, etc.)
865
2135
  * @returns {Promise<Venue>} A new Venue instance configured appropriately
866
2136
  */
867
2137
  static async connect(venueId, auth) {
@@ -872,5 +2142,13 @@ var Grid = class {
872
2142
  return Promise.resolve(connectedVenue);
873
2143
  }
874
2144
  };
2145
+ /*! Bundled license information:
2146
+
2147
+ @noble/ed25519/index.js:
2148
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
2149
+
2150
+ @noble/hashes/esm/utils.js:
2151
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2152
+ */
875
2153
 
876
- export { Asset, AssetNotFoundError, Auth, BasicAuth, BearerAuth, CoviaConnectionError, CoviaError, CoviaTimeoutError, CoviaUserAuth, CredentialsHTTP, DataAsset, Grid, GridError, Job, JobFailedError, JobNotFoundError, JobStatus, NoAuth, NotFoundError, Operation, RunStatus, Venue, createSSEEvent, fetchStreamWithError, fetchWithError, getAssetIdFromPath, getAssetIdFromVenueId, getParsedAssetId, isJobComplete, isJobFinished, isJobPaused, logger, parseSSEStream };
2154
+ export { AgentManager, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BearerAuth, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DataAsset, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, NoAuth, NotFoundError, Operation, OperationManager, RunStatus, SecretManager, UCANManager, Venue, WorkspaceManager, createSSEEvent, decodePublicKey, didFromPublicKey, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getParsedAssetId, hexToPrivateKey, isJobComplete, isJobFinished, isJobPaused, logger, parseSSEStream, privateKeyToHex };