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