@bcts/envelope 1.0.0-alpha.12 → 1.0.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/index.cjs +2412 -619
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +898 -313
  4. package/dist/index.d.cts.map +1 -1
  5. package/dist/index.d.mts +898 -313
  6. package/dist/index.d.mts.map +1 -1
  7. package/dist/index.iife.js +2414 -623
  8. package/dist/index.iife.js.map +1 -1
  9. package/dist/index.mjs +2275 -614
  10. package/dist/index.mjs.map +1 -1
  11. package/package.json +10 -8
  12. package/src/base/assertions.ts +3 -0
  13. package/src/base/digest.ts +28 -156
  14. package/src/base/elide.ts +9 -0
  15. package/src/base/envelope-decodable.ts +179 -1
  16. package/src/base/envelope-encodable.ts +5 -1
  17. package/src/base/envelope.ts +160 -21
  18. package/src/base/error.ts +15 -2
  19. package/src/base/index.ts +9 -0
  20. package/src/base/leaf.ts +57 -0
  21. package/src/base/queries.ts +93 -0
  22. package/src/base/ur.ts +45 -0
  23. package/src/base/walk.ts +73 -0
  24. package/src/extension/attachment.ts +65 -0
  25. package/src/extension/compress.ts +2 -3
  26. package/src/extension/encrypt.ts +56 -105
  27. package/src/extension/event.ts +261 -0
  28. package/src/extension/expression.ts +556 -93
  29. package/src/extension/index.ts +89 -12
  30. package/src/extension/proof.ts +5 -2
  31. package/src/extension/recipient.ts +294 -339
  32. package/src/extension/request.ts +298 -0
  33. package/src/extension/response.ts +411 -0
  34. package/src/extension/salt.ts +90 -0
  35. package/src/extension/secret.ts +159 -0
  36. package/src/extension/signature.ts +253 -322
  37. package/src/extension/sskr.ts +240 -0
  38. package/src/extension/types.ts +2 -4
  39. package/src/format/envelope-summary.ts +167 -0
  40. package/src/format/format-context.ts +202 -0
  41. package/src/format/index.ts +50 -2
  42. package/src/format/mermaid.ts +331 -0
  43. package/src/format/notation.ts +478 -0
  44. package/src/format/tree.ts +36 -3
  45. package/src/index.ts +11 -1
  46. package/src/seal.ts +98 -0
package/dist/index.cjs CHANGED
@@ -25,60 +25,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  }) : target, mod));
26
26
 
27
27
  //#endregion
28
- let _bcts_crypto = require("@bcts/crypto");
28
+ let _bcts_components = require("@bcts/components");
29
29
  let _bcts_dcbor = require("@bcts/dcbor");
30
30
  let _bcts_known_values = require("@bcts/known-values");
31
- let _bcts_components = require("@bcts/components");
32
31
  let pako = require("pako");
33
32
  pako = __toESM(pako);
33
+ let _bcts_crypto = require("@bcts/crypto");
34
34
  let _bcts_rand = require("@bcts/rand");
35
+ let _bcts_uniform_resources = require("@bcts/uniform-resources");
36
+ let _bcts_tags = require("@bcts/tags");
35
37
 
36
38
  //#region src/base/digest.ts
37
- var Digest = class Digest {
38
- #data;
39
- constructor(data) {
40
- if (data.length !== 32) throw new Error(`Digest must be exactly 32 bytes, got ${data.length} bytes`);
41
- this.#data = data;
42
- }
43
- data() {
44
- return this.#data;
45
- }
46
- static fromImage(image) {
47
- return new Digest((0, _bcts_crypto.sha256)(image));
48
- }
49
- static fromDigests(digests) {
50
- const totalLength = digests.length * 32;
51
- const combined = new Uint8Array(totalLength);
52
- let offset = 0;
53
- for (const digest of digests) {
54
- combined.set(digest.data(), offset);
55
- offset += 32;
56
- }
57
- return Digest.fromImage(combined);
58
- }
59
- hex() {
60
- return Array.from(this.#data).map((b) => b.toString(16).padStart(2, "0")).join("");
61
- }
62
- short() {
63
- return this.hex().substring(0, 7);
64
- }
65
- static fromHex(hex) {
66
- if (hex.length !== 64) throw new Error(`Hex string must be exactly 64 characters, got ${hex.length}`);
67
- const data = new Uint8Array(32);
68
- for (let i = 0; i < 32; i++) data[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
69
- return new Digest(data);
70
- }
71
- equals(other) {
72
- if (this.#data.length !== other.#data.length) return false;
73
- for (let i = 0; i < this.#data.length; i++) if (this.#data[i] !== other.#data[i]) return false;
74
- return true;
75
- }
76
- toString() {
77
- return this.short();
78
- }
79
- clone() {
80
- return new Digest(new Uint8Array(this.#data));
81
- }
39
+ _bcts_components.Digest.prototype.short = function() {
40
+ return this.hex().slice(0, 7);
82
41
  };
83
42
 
84
43
  //#endregion
@@ -113,6 +72,7 @@ let ErrorCode = /* @__PURE__ */ function(ErrorCode$1) {
113
72
  ErrorCode$1["SSKR"] = "SSKR";
114
73
  ErrorCode$1["INVALID_TYPE"] = "INVALID_TYPE";
115
74
  ErrorCode$1["AMBIGUOUS_TYPE"] = "AMBIGUOUS_TYPE";
75
+ ErrorCode$1["SUBJECT_NOT_UNIT"] = "SUBJECT_NOT_UNIT";
116
76
  ErrorCode$1["UNEXPECTED_RESPONSE_ID"] = "UNEXPECTED_RESPONSE_ID";
117
77
  ErrorCode$1["INVALID_RESPONSE"] = "INVALID_RESPONSE";
118
78
  ErrorCode$1["CBOR"] = "CBOR";
@@ -159,8 +119,8 @@ var EnvelopeError = class EnvelopeError extends Error {
159
119
  static invalidAssertion() {
160
120
  return new EnvelopeError(ErrorCode.INVALID_ASSERTION, "assertion must be a map with exactly one element");
161
121
  }
162
- static invalidAttachment() {
163
- return new EnvelopeError(ErrorCode.INVALID_ATTACHMENT, "invalid attachment");
122
+ static invalidAttachment(message) {
123
+ return new EnvelopeError(ErrorCode.INVALID_ATTACHMENT, message !== void 0 ? `invalid attachment: ${message}` : "invalid attachment");
164
124
  }
165
125
  static nonexistentAttachment() {
166
126
  return new EnvelopeError(ErrorCode.NONEXISTENT_ATTACHMENT, "nonexistent attachment");
@@ -216,6 +176,9 @@ var EnvelopeError = class EnvelopeError extends Error {
216
176
  static ambiguousType() {
217
177
  return new EnvelopeError(ErrorCode.AMBIGUOUS_TYPE, "ambiguous type");
218
178
  }
179
+ static subjectNotUnit() {
180
+ return new EnvelopeError(ErrorCode.SUBJECT_NOT_UNIT, "subject is not the unit value");
181
+ }
219
182
  static unexpectedResponseId() {
220
183
  return new EnvelopeError(ErrorCode.UNEXPECTED_RESPONSE_ID, "unexpected response ID");
221
184
  }
@@ -245,7 +208,7 @@ var Assertion = class Assertion {
245
208
  constructor(predicate, object) {
246
209
  this.#predicate = predicate instanceof Envelope ? predicate : Envelope.new(predicate);
247
210
  this.#object = object instanceof Envelope ? object : Envelope.new(object);
248
- this.#digest = Digest.fromDigests([this.#predicate.digest(), this.#object.digest()]);
211
+ this.#digest = _bcts_components.Digest.fromDigests([this.#predicate.digest(), this.#object.digest()]);
249
212
  }
250
213
  predicate() {
251
214
  return this.#predicate;
@@ -348,45 +311,33 @@ function registerCompressExtension() {
348
311
  return this.case().type === "compressed";
349
312
  };
350
313
  }
351
- registerCompressExtension();
352
314
 
353
315
  //#endregion
354
316
  //#region src/extension/encrypt.ts
355
- function createSecureRng$1() {
356
- return new _bcts_rand.SecureRandomNumberGenerator();
317
+ /**
318
+ * Encrypts plaintext with a symmetric key using the given digest as AAD.
319
+ * This is an envelope-specific helper function that returns an envelope EncryptedMessage.
320
+ */
321
+ function encryptWithDigest(key, plaintext, digest) {
322
+ const nonce = (0, _bcts_rand.rngRandomData)(new _bcts_rand.SecureRandomNumberGenerator(), _bcts_crypto.SYMMETRIC_NONCE_SIZE);
323
+ const aad = digest.data();
324
+ const [ciphertext, authTag] = (0, _bcts_crypto.aeadChaCha20Poly1305EncryptWithAad)(plaintext, key.data(), nonce, aad);
325
+ return new EncryptedMessage(ciphertext, nonce, authTag, digest);
357
326
  }
358
- var SymmetricKey = class SymmetricKey {
359
- #key;
360
- constructor(key) {
361
- if (key.length !== _bcts_crypto.SYMMETRIC_KEY_SIZE) throw new Error(`Symmetric key must be ${_bcts_crypto.SYMMETRIC_KEY_SIZE} bytes`);
362
- this.#key = key;
363
- }
364
- static generate() {
365
- return new SymmetricKey((0, _bcts_rand.rngRandomData)(createSecureRng$1(), _bcts_crypto.SYMMETRIC_KEY_SIZE));
366
- }
367
- static from(key) {
368
- return new SymmetricKey(key);
369
- }
370
- data() {
371
- return this.#key;
372
- }
373
- encrypt(plaintext, digest) {
374
- const nonce = (0, _bcts_rand.rngRandomData)(createSecureRng$1(), _bcts_crypto.SYMMETRIC_NONCE_SIZE);
375
- const aad = digest.data();
376
- const [ciphertext, authTag] = (0, _bcts_crypto.aeadChaCha20Poly1305EncryptWithAad)(plaintext, this.#key, nonce, aad);
377
- return new EncryptedMessage(ciphertext, nonce, authTag, digest);
378
- }
379
- decrypt(message) {
380
- const digest = message.aadDigest();
381
- if (digest === void 0) throw EnvelopeError.general("Missing digest in encrypted message");
382
- const aad = digest.data();
383
- try {
384
- return (0, _bcts_crypto.aeadChaCha20Poly1305DecryptWithAad)(message.ciphertext(), this.#key, message.nonce(), aad, message.authTag());
385
- } catch (_error) {
386
- throw EnvelopeError.general("Decryption failed: invalid key or corrupted data");
387
- }
327
+ /**
328
+ * Decrypts an envelope EncryptedMessage with a symmetric key.
329
+ * This is an envelope-specific helper function.
330
+ */
331
+ function decryptWithDigest(key, message) {
332
+ const digest = message.aadDigest();
333
+ if (digest === void 0) throw EnvelopeError.general("Missing digest in encrypted message");
334
+ const aad = digest.data();
335
+ try {
336
+ return (0, _bcts_crypto.aeadChaCha20Poly1305DecryptWithAad)(message.ciphertext(), key.data(), message.nonce(), aad, message.authTag());
337
+ } catch (_error) {
338
+ throw EnvelopeError.general("Decryption failed: invalid key or corrupted data");
388
339
  }
389
- };
340
+ }
390
341
  var EncryptedMessage = class {
391
342
  #ciphertext;
392
343
  #nonce;
@@ -424,18 +375,14 @@ function registerEncryptExtension() {
424
375
  if (c.type === "elided") throw EnvelopeError.general("Cannot encrypt elided envelope");
425
376
  if (c.type === "node") {
426
377
  if (c.subject.isEncrypted()) throw EnvelopeError.general("Subject is already encrypted");
427
- const encodedCbor$1 = (0, _bcts_dcbor.cborData)(c.subject.taggedCbor());
428
- const subjectDigest = c.subject.digest();
429
- const encryptedMessage$1 = key.encrypt(encodedCbor$1, subjectDigest);
378
+ const encryptedMessage$1 = encryptWithDigest(key, (0, _bcts_dcbor.cborData)(c.subject.taggedCbor()), c.subject.digest());
430
379
  const encryptedSubject = Envelope.fromCase({
431
380
  type: "encrypted",
432
381
  message: encryptedMessage$1
433
382
  });
434
383
  return Envelope.newWithAssertions(encryptedSubject, c.assertions);
435
384
  }
436
- const encodedCbor = (0, _bcts_dcbor.cborData)(this.taggedCbor());
437
- const digest = this.digest();
438
- const encryptedMessage = key.encrypt(encodedCbor, digest);
385
+ const encryptedMessage = encryptWithDigest(key, (0, _bcts_dcbor.cborData)(this.taggedCbor()), this.digest());
439
386
  return Envelope.fromCase({
440
387
  type: "encrypted",
441
388
  message: encryptedMessage
@@ -447,7 +394,7 @@ function registerEncryptExtension() {
447
394
  const message = subjectCase.message;
448
395
  const subjectDigest = message.aadDigest();
449
396
  if (subjectDigest === void 0) throw EnvelopeError.general("Missing digest in encrypted message");
450
- const cbor$1 = (0, _bcts_dcbor.decodeCbor)(key.decrypt(message));
397
+ const cbor$1 = (0, _bcts_dcbor.decodeCbor)(decryptWithDigest(key, message));
451
398
  const resultSubject = Envelope.fromTaggedCbor(cbor$1);
452
399
  if (!resultSubject.digest().equals(subjectDigest)) throw EnvelopeError.general("Invalid digest after decryption");
453
400
  const c = this.case();
@@ -468,7 +415,6 @@ function registerEncryptExtension() {
468
415
  return this.case().type === "encrypted";
469
416
  };
470
417
  }
471
- registerEncryptExtension();
472
418
 
473
419
  //#endregion
474
420
  //#region src/base/envelope.ts
@@ -486,6 +432,7 @@ var Envelope = class Envelope {
486
432
  }
487
433
  static new(subject) {
488
434
  if (subject instanceof Envelope) return subject;
435
+ if (subject instanceof _bcts_known_values.KnownValue) return Envelope.newWithKnownValue(subject);
489
436
  return Envelope.newLeaf(subject);
490
437
  }
491
438
  static newOrNull(subject) {
@@ -519,7 +466,7 @@ var Envelope = class Envelope {
519
466
  type: "node",
520
467
  subject,
521
468
  assertions: sortedAssertions,
522
- digest: Digest.fromDigests(digests)
469
+ digest: _bcts_components.Digest.fromDigests(digests)
523
470
  });
524
471
  }
525
472
  static newWithAssertions(subject, assertions) {
@@ -537,7 +484,7 @@ var Envelope = class Envelope {
537
484
  return new Envelope({
538
485
  type: "knownValue",
539
486
  value: knownValue,
540
- digest: Digest.fromImage(knownValue.toCborData())
487
+ digest: _bcts_components.Digest.fromImage(knownValue.toCborData())
541
488
  });
542
489
  }
543
490
  static newWithEncrypted(encryptedMessage) {
@@ -564,14 +511,14 @@ var Envelope = class Envelope {
564
511
  return new Envelope({
565
512
  type: "leaf",
566
513
  cbor: cbor$1,
567
- digest: Digest.fromImage(cborBytes)
514
+ digest: _bcts_components.Digest.fromImage(cborBytes)
568
515
  });
569
516
  }
570
517
  static newWrapped(envelope) {
571
518
  return new Envelope({
572
519
  type: "wrapped",
573
520
  envelope,
574
- digest: Digest.fromDigests([envelope.digest()])
521
+ digest: _bcts_components.Digest.fromDigests([envelope.digest()])
575
522
  });
576
523
  }
577
524
  digest() {
@@ -633,7 +580,7 @@ var Envelope = class Envelope {
633
580
  case "wrapped": return c.envelope.taggedCbor();
634
581
  case "assertion": return c.assertion.toCbor();
635
582
  case "elided": return Envelope.valueToCbor(c.digest.data());
636
- case "knownValue": throw new Error("Known value encoding not yet implemented");
583
+ case "knownValue": return c.value.untaggedCbor();
637
584
  case "encrypted": {
638
585
  const message = c.message;
639
586
  const digest = message.aadDigest();
@@ -678,7 +625,7 @@ var Envelope = class Envelope {
678
625
  if (compressedData === void 0) throw EnvelopeError.cbor("compressed data must be byte string");
679
626
  const digestBytes = arr.length === 2 ? (0, _bcts_dcbor.asByteString)(arr.get(1)) : void 0;
680
627
  if (arr.length === 2 && digestBytes === void 0) throw EnvelopeError.cbor("digest must be byte string");
681
- const compressed = new Compressed(compressedData, digestBytes !== void 0 ? new Digest(digestBytes) : void 0);
628
+ const compressed = new Compressed(compressedData, digestBytes !== void 0 ? _bcts_components.Digest.fromData(digestBytes) : void 0);
682
629
  return Envelope.fromCase({
683
630
  type: "compressed",
684
631
  value: compressed
@@ -693,7 +640,7 @@ var Envelope = class Envelope {
693
640
  if (ciphertext === void 0 || nonce === void 0 || authTag === void 0) throw EnvelopeError.cbor("ciphertext, nonce, and auth must be byte strings");
694
641
  const digestBytes = arr.length === 4 ? (0, _bcts_dcbor.asByteString)(arr.get(3)) : void 0;
695
642
  if (arr.length === 4 && digestBytes === void 0) throw EnvelopeError.cbor("aad digest must be byte string");
696
- const message = new EncryptedMessage(ciphertext, nonce, authTag, digestBytes !== void 0 ? new Digest(digestBytes) : void 0);
643
+ const message = new EncryptedMessage(ciphertext, nonce, authTag, digestBytes !== void 0 ? _bcts_components.Digest.fromData(digestBytes) : void 0);
697
644
  return Envelope.fromCase({
698
645
  type: "encrypted",
699
646
  message
@@ -705,7 +652,7 @@ var Envelope = class Envelope {
705
652
  const bytes = (0, _bcts_dcbor.asByteString)(cbor$1);
706
653
  if (bytes !== void 0) {
707
654
  if (bytes.length !== 32) throw EnvelopeError.cbor("elided digest must be 32 bytes");
708
- return Envelope.newElided(new Digest(bytes));
655
+ return Envelope.newElided(_bcts_components.Digest.fromData(bytes));
709
656
  }
710
657
  const array = (0, _bcts_dcbor.asCborArray)(cbor$1);
711
658
  if (array !== void 0) {
@@ -902,6 +849,54 @@ Envelope.prototype.extractBytes = function() {
902
849
  Envelope.prototype.extractNull = function() {
903
850
  return extractNull(this);
904
851
  };
852
+ function extractSubject(envelope, decoder) {
853
+ const cbor$1 = envelope.subject().tryLeaf();
854
+ try {
855
+ return decoder(cbor$1);
856
+ } catch (error) {
857
+ throw EnvelopeError.cbor("failed to decode subject", error instanceof Error ? error : void 0);
858
+ }
859
+ }
860
+ Envelope.prototype.extractSubject = function(decoder) {
861
+ return extractSubject(this, decoder);
862
+ };
863
+ function tryObjectForPredicate(envelope, predicate, decoder) {
864
+ return extractSubject(envelope.objectForPredicate(predicate), decoder);
865
+ }
866
+ Envelope.prototype.tryObjectForPredicate = function(predicate, decoder) {
867
+ return tryObjectForPredicate(this, predicate, decoder);
868
+ };
869
+ function tryOptionalObjectForPredicate(envelope, predicate, decoder) {
870
+ const obj = envelope.optionalObjectForPredicate(predicate);
871
+ if (obj === void 0) return;
872
+ return extractSubject(obj, decoder);
873
+ }
874
+ Envelope.prototype.tryOptionalObjectForPredicate = function(predicate, decoder) {
875
+ return tryOptionalObjectForPredicate(this, predicate, decoder);
876
+ };
877
+ function extractObjectForPredicateWithDefault(envelope, predicate, decoder, defaultValue) {
878
+ return tryOptionalObjectForPredicate(envelope, predicate, decoder) ?? defaultValue;
879
+ }
880
+ Envelope.prototype.extractObjectForPredicateWithDefault = function(predicate, decoder, defaultValue) {
881
+ return extractObjectForPredicateWithDefault(this, predicate, decoder, defaultValue);
882
+ };
883
+ function extractObjectsForPredicate(envelope, predicate, decoder) {
884
+ return envelope.objectsForPredicate(predicate).map((obj) => extractSubject(obj, decoder));
885
+ }
886
+ Envelope.prototype.extractObjectsForPredicate = function(predicate, decoder) {
887
+ return extractObjectsForPredicate(this, predicate, decoder);
888
+ };
889
+ function tryObjectsForPredicate(envelope, predicate, decoder) {
890
+ try {
891
+ return extractObjectsForPredicate(envelope, predicate, decoder);
892
+ } catch (error) {
893
+ if (error instanceof EnvelopeError && error.code === ErrorCode.NONEXISTENT_PREDICATE) return [];
894
+ throw error;
895
+ }
896
+ }
897
+ Envelope.prototype.tryObjectsForPredicate = function(predicate, decoder) {
898
+ return tryObjectsForPredicate(this, predicate, decoder);
899
+ };
905
900
 
906
901
  //#endregion
907
902
  //#region src/base/elide.ts
@@ -942,6 +937,9 @@ function elideSetWithAction(envelope, target, isRevealing, action) {
942
937
  Envelope.prototype.elideRemovingSetWithAction = function(target, action) {
943
938
  return elideSetWithAction(this, target, false, action);
944
939
  };
940
+ Envelope.prototype.elideSetWithAction = function(target, action) {
941
+ return elideSetWithAction(this, target, true, action);
942
+ };
945
943
  Envelope.prototype.elideRemovingSet = function(target) {
946
944
  return elideSetWithAction(this, target, false, elideAction());
947
945
  };
@@ -1148,6 +1146,39 @@ function walkTree(envelope, level, incomingEdge, state, visit) {
1148
1146
  }
1149
1147
  return currentState;
1150
1148
  }
1149
+ Envelope.prototype.digests = function(levelLimit) {
1150
+ const result = /* @__PURE__ */ new Set();
1151
+ const visitor = (envelope, level, _incomingEdge, _state) => {
1152
+ if (level < levelLimit) {
1153
+ result.add(envelope.digest());
1154
+ result.add(envelope.subject().digest());
1155
+ }
1156
+ return [void 0, false];
1157
+ };
1158
+ this.walk(false, void 0, visitor);
1159
+ return result;
1160
+ };
1161
+ Envelope.prototype.deepDigests = function() {
1162
+ return this.digests(Number.MAX_SAFE_INTEGER);
1163
+ };
1164
+ Envelope.prototype.shallowDigests = function() {
1165
+ return this.digests(2);
1166
+ };
1167
+ Envelope.prototype.object = function() {
1168
+ return this.tryObject();
1169
+ };
1170
+ Envelope.prototype.predicate = function() {
1171
+ return this.tryPredicate();
1172
+ };
1173
+ Envelope.prototype.toCbor = function() {
1174
+ return this.taggedCbor();
1175
+ };
1176
+ Envelope.prototype.expectLeaf = function() {
1177
+ return this.tryLeaf();
1178
+ };
1179
+ Envelope.prototype.checkTypeValue = function(type) {
1180
+ this.checkType(type);
1181
+ };
1151
1182
 
1152
1183
  //#endregion
1153
1184
  //#region src/base/assertions.ts
@@ -1287,6 +1318,30 @@ Envelope.prototype.asLeaf = function() {
1287
1318
  const c = this.case();
1288
1319
  if (c.type === "leaf") return c.cbor;
1289
1320
  };
1321
+ Envelope.unit = function() {
1322
+ return Envelope.new(_bcts_known_values.UNIT);
1323
+ };
1324
+ Envelope.prototype.asKnownValue = function() {
1325
+ const c = this.case();
1326
+ if (c.type === "knownValue") return c.value;
1327
+ };
1328
+ Envelope.prototype.tryKnownValue = function() {
1329
+ const kv = this.asKnownValue();
1330
+ if (kv === void 0) throw EnvelopeError.notKnownValue();
1331
+ return kv;
1332
+ };
1333
+ Envelope.prototype.isKnownValue = function() {
1334
+ return this.case().type === "knownValue";
1335
+ };
1336
+ Envelope.prototype.isSubjectUnit = function() {
1337
+ const kv = this.subject().asKnownValue();
1338
+ if (kv === void 0) return false;
1339
+ return kv.equals(_bcts_known_values.UNIT);
1340
+ };
1341
+ Envelope.prototype.checkSubjectUnit = function() {
1342
+ if (this.isSubjectUnit()) return this;
1343
+ throw EnvelopeError.subjectNotUnit();
1344
+ };
1290
1345
 
1291
1346
  //#endregion
1292
1347
  //#region src/base/queries.ts
@@ -1402,6 +1457,38 @@ Envelope.prototype.elementsCount = function() {
1402
1457
  }
1403
1458
  return count;
1404
1459
  };
1460
+ Envelope.prototype.isSubjectEncrypted = function() {
1461
+ const c = this.case();
1462
+ if (c.type === "encrypted") return true;
1463
+ if (c.type === "node") return c.subject.isSubjectEncrypted();
1464
+ return false;
1465
+ };
1466
+ Envelope.prototype.isSubjectCompressed = function() {
1467
+ const c = this.case();
1468
+ if (c.type === "compressed") return true;
1469
+ if (c.type === "node") return c.subject.isSubjectCompressed();
1470
+ return false;
1471
+ };
1472
+ Envelope.prototype.isSubjectElided = function() {
1473
+ const c = this.case();
1474
+ if (c.type === "elided") return true;
1475
+ if (c.type === "node") return c.subject.isSubjectElided();
1476
+ return false;
1477
+ };
1478
+ Envelope.prototype.setPosition = function(position) {
1479
+ const positionAssertions = this.assertionsWithPredicate(_bcts_known_values.POSITION);
1480
+ if (positionAssertions.length > 1) throw EnvelopeError.invalidFormat();
1481
+ return (positionAssertions.length === 1 ? this.removeAssertion(positionAssertions[0]) : this).addAssertion(_bcts_known_values.POSITION, position);
1482
+ };
1483
+ Envelope.prototype.position = function() {
1484
+ return this.objectForPredicate(_bcts_known_values.POSITION).extractNumber();
1485
+ };
1486
+ Envelope.prototype.removePosition = function() {
1487
+ const positionAssertions = this.assertionsWithPredicate(_bcts_known_values.POSITION);
1488
+ if (positionAssertions.length > 1) throw EnvelopeError.invalidFormat();
1489
+ if (positionAssertions.length === 1) return this.removeAssertion(positionAssertions[0]);
1490
+ return this;
1491
+ };
1405
1492
 
1406
1493
  //#endregion
1407
1494
  //#region src/base/wrap.ts
@@ -1417,15 +1504,35 @@ Envelope.prototype.unwrap = function() {
1417
1504
  return this.tryUnwrap();
1418
1505
  };
1419
1506
 
1507
+ //#endregion
1508
+ //#region src/base/ur.ts
1509
+ Envelope.prototype.urString = function() {
1510
+ return _bcts_uniform_resources.UR.new("envelope", this.untaggedCbor()).string();
1511
+ };
1512
+ Envelope.prototype.ur = function() {
1513
+ return _bcts_uniform_resources.UR.new("envelope", this.untaggedCbor());
1514
+ };
1515
+ Envelope.prototype.taggedCborData = function() {
1516
+ return this.cborBytes();
1517
+ };
1518
+ Envelope.fromUrString = function(urString) {
1519
+ const ur = _bcts_uniform_resources.UR.fromURString(urString);
1520
+ return Envelope.fromUR(ur);
1521
+ };
1522
+ Envelope.fromURString = Envelope.fromUrString;
1523
+ Envelope.fromUR = function(ur) {
1524
+ ur.checkType("envelope");
1525
+ return Envelope.fromUntaggedCbor(ur.cbor());
1526
+ };
1527
+
1420
1528
  //#endregion
1421
1529
  //#region src/extension/types.ts
1422
- const IS_A = "isA";
1423
1530
  if (Envelope?.prototype) {
1424
1531
  Envelope.prototype.addType = function(object) {
1425
- return this.addAssertion(IS_A, object);
1532
+ return this.addAssertion(_bcts_known_values.IS_A, object);
1426
1533
  };
1427
1534
  Envelope.prototype.types = function() {
1428
- return this.objectsForPredicate(IS_A);
1535
+ return this.objectsForPredicate(_bcts_known_values.IS_A);
1429
1536
  };
1430
1537
  Envelope.prototype.getType = function() {
1431
1538
  const t = this.types();
@@ -1470,6 +1577,7 @@ if (Envelope?.prototype) {
1470
1577
  const saltBytes = generateRandomBytes(count);
1471
1578
  return this.addAssertion(SALT, saltBytes);
1472
1579
  };
1580
+ Envelope.prototype.addSaltWithLen = Envelope.prototype.addSaltWithLength;
1473
1581
  Envelope.prototype.addSaltBytes = function(saltBytes) {
1474
1582
  if (saltBytes.length < MIN_SALT_SIZE) throw EnvelopeError.general(`Salt must be at least ${MIN_SALT_SIZE} bytes, got ${saltBytes.length}`);
1475
1583
  return this.addAssertion(SALT, saltBytes);
@@ -1481,6 +1589,32 @@ if (Envelope?.prototype) {
1481
1589
  const saltBytes = generateRandomBytes((0, _bcts_rand.rngNextInClosedRangeI32)(rng, min, max), rng);
1482
1590
  return this.addAssertion(SALT, saltBytes);
1483
1591
  };
1592
+ Envelope.prototype.addAssertionSalted = function(predicate, object, salted) {
1593
+ const assertion = Envelope.newAssertion(predicate, object);
1594
+ if (!salted) return this.addAssertionEnvelope(assertion);
1595
+ const saltedAssertion = assertion.addSalt();
1596
+ const c = this.case();
1597
+ if (c.type === "node") return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);
1598
+ return Envelope.newWithUncheckedAssertions(this, [saltedAssertion]);
1599
+ };
1600
+ Envelope.prototype.addAssertionEnvelopeSalted = function(assertionEnvelope, salted) {
1601
+ if (!salted) return this.addAssertionEnvelope(assertionEnvelope);
1602
+ const saltedAssertion = assertionEnvelope.addSalt();
1603
+ const c = this.case();
1604
+ if (c.type === "node") return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);
1605
+ return Envelope.newWithUncheckedAssertions(this, [saltedAssertion]);
1606
+ };
1607
+ Envelope.prototype.addOptionalAssertionEnvelopeSalted = function(assertionEnvelope, salted) {
1608
+ if (assertionEnvelope === void 0) return this;
1609
+ if (!salted) return this.addOptionalAssertionEnvelope(assertionEnvelope);
1610
+ const saltedAssertion = assertionEnvelope.addSalt();
1611
+ const c = this.case();
1612
+ if (c.type === "node") {
1613
+ if (c.assertions.some((a) => a.digest().equals(saltedAssertion.digest()))) return this;
1614
+ return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);
1615
+ }
1616
+ return Envelope.newWithUncheckedAssertions(this.subject(), [saltedAssertion]);
1617
+ };
1484
1618
  }
1485
1619
 
1486
1620
  //#endregion
@@ -1513,123 +1647,21 @@ const VERIFIED_BY = "verifiedBy";
1513
1647
  */
1514
1648
  const NOTE = "note";
1515
1649
  /**
1516
- * Represents a cryptographic signature.
1517
- */
1518
- var Signature = class Signature {
1519
- #data;
1520
- constructor(data) {
1521
- this.#data = data;
1522
- }
1523
- /**
1524
- * Returns the raw signature bytes.
1525
- */
1526
- data() {
1527
- return this.#data;
1528
- }
1529
- /**
1530
- * Returns the hex-encoded signature.
1531
- */
1532
- hex() {
1533
- return Array.from(this.#data).map((b) => b.toString(16).padStart(2, "0")).join("");
1534
- }
1535
- /**
1536
- * Creates a Signature from hex string.
1537
- */
1538
- static fromHex(hex) {
1539
- const bytes = new Uint8Array(hex.length / 2);
1540
- for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
1541
- return new Signature(bytes);
1542
- }
1543
- };
1544
- /**
1545
- * ECDSA signing key using secp256k1 curve.
1546
- * Uses @bcts/crypto functions.
1547
- */
1548
- var SigningPrivateKey = class SigningPrivateKey {
1549
- #privateKey;
1550
- constructor(privateKey) {
1551
- if (privateKey.length !== _bcts_crypto.ECDSA_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${_bcts_crypto.ECDSA_PRIVATE_KEY_SIZE} bytes`);
1552
- this.#privateKey = privateKey;
1553
- }
1554
- /**
1555
- * Generates a new random private key.
1556
- */
1557
- static generate() {
1558
- return new SigningPrivateKey((0, _bcts_rand.rngRandomData)(new _bcts_rand.SecureRandomNumberGenerator(), _bcts_crypto.ECDSA_PRIVATE_KEY_SIZE));
1559
- }
1560
- /**
1561
- * Creates a private key from hex string.
1562
- */
1563
- static fromHex(hex) {
1564
- const bytes = new Uint8Array(hex.length / 2);
1565
- for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
1566
- return new SigningPrivateKey(bytes);
1567
- }
1568
- /**
1569
- * Returns the corresponding public key.
1570
- */
1571
- publicKey() {
1572
- return new SigningPublicKey((0, _bcts_crypto.ecdsaPublicKeyFromPrivateKey)(this.#privateKey));
1573
- }
1574
- /**
1575
- * Signs data and returns a Signature.
1576
- */
1577
- sign(data) {
1578
- return new Signature((0, _bcts_crypto.ecdsaSign)(this.#privateKey, data));
1579
- }
1580
- /**
1581
- * Returns the raw private key bytes.
1582
- */
1583
- data() {
1584
- return this.#privateKey;
1585
- }
1586
- };
1587
- /**
1588
- * ECDSA public key for signature verification using secp256k1 curve.
1589
- * Uses @bcts/crypto functions.
1650
+ * Metadata that can be attached to a signature.
1590
1651
  */
1591
- var SigningPublicKey = class SigningPublicKey {
1592
- #publicKey;
1593
- constructor(publicKey) {
1594
- if (publicKey.length !== _bcts_crypto.ECDSA_PUBLIC_KEY_SIZE && publicKey.length !== _bcts_crypto.ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${_bcts_crypto.ECDSA_PUBLIC_KEY_SIZE} bytes (compressed) or ${_bcts_crypto.ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE} bytes (uncompressed)`);
1595
- this.#publicKey = publicKey;
1596
- }
1597
- /**
1598
- * Creates a public key from hex string.
1599
- */
1600
- static fromHex(hex) {
1601
- const bytes = new Uint8Array(hex.length / 2);
1602
- for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
1603
- return new SigningPublicKey(bytes);
1604
- }
1605
- /**
1606
- * Verifies a signature against the provided data.
1607
- */
1608
- verify(data, signature) {
1609
- try {
1610
- return (0, _bcts_crypto.ecdsaVerify)(this.#publicKey, signature.data(), data);
1611
- } catch {
1612
- return false;
1613
- }
1614
- }
1652
+ var SignatureMetadata = class SignatureMetadata {
1653
+ #assertions = [];
1615
1654
  /**
1616
- * Returns the raw public key bytes.
1655
+ * Creates a new SignatureMetadata instance.
1656
+ * Use the static `new()` method for fluent API style.
1617
1657
  */
1618
- data() {
1619
- return this.#publicKey;
1620
- }
1658
+ constructor() {}
1621
1659
  /**
1622
- * Returns the hex-encoded public key.
1660
+ * Creates a new empty SignatureMetadata.
1623
1661
  */
1624
- hex() {
1625
- return Array.from(this.#publicKey).map((b) => b.toString(16).padStart(2, "0")).join("");
1662
+ static new() {
1663
+ return new SignatureMetadata();
1626
1664
  }
1627
- };
1628
- /**
1629
- * Metadata that can be attached to a signature.
1630
- */
1631
- var SignatureMetadata = class SignatureMetadata {
1632
- #assertions = [];
1633
1665
  /**
1634
1666
  * Adds an assertion to the metadata.
1635
1667
  */
@@ -1640,114 +1672,110 @@ var SignatureMetadata = class SignatureMetadata {
1640
1672
  return metadata;
1641
1673
  }
1642
1674
  /**
1643
- * Returns all assertions in the metadata.
1675
+ * Returns all assertions in this metadata.
1644
1676
  */
1645
1677
  assertions() {
1646
1678
  return this.#assertions;
1647
1679
  }
1648
- /**
1649
- * Returns true if this metadata has any assertions.
1650
- */
1651
- hasAssertions() {
1652
- return this.#assertions.length > 0;
1680
+ };
1681
+ Envelope.prototype.addSignatureWithMetadata = function(signer, metadata) {
1682
+ const digest = this.subject().digest();
1683
+ const signature = signer.sign(digest.data());
1684
+ let signatureEnvelope = Envelope.new(signature);
1685
+ if ("publicKey" in signer && typeof signer.publicKey === "function") {
1686
+ const verifier = signer.publicKey();
1687
+ signatureEnvelope = signatureEnvelope.addAssertion(VERIFIED_BY, verifier);
1688
+ }
1689
+ if (metadata !== void 0) for (const [predicate, object] of metadata.assertions()) signatureEnvelope = signatureEnvelope.addAssertion(predicate, object);
1690
+ return this.addAssertion(SIGNED, signatureEnvelope);
1691
+ };
1692
+ Envelope.prototype.addSignature = function(signer) {
1693
+ return this.addSignatureWithMetadata(signer, void 0);
1694
+ };
1695
+ Envelope.prototype.addSignatureOpt = function(signer, _options, metadata) {
1696
+ return this.addSignatureWithMetadata(signer, metadata);
1697
+ };
1698
+ Envelope.prototype.addSignatures = function(signers) {
1699
+ return signers.reduce((envelope, signer) => envelope.addSignature(signer), this);
1700
+ };
1701
+ Envelope.prototype.addSignaturesWithMetadata = function(signersWithMetadata) {
1702
+ return signersWithMetadata.reduce((envelope, { signer, metadata }) => envelope.addSignatureWithMetadata(signer, metadata), this);
1703
+ };
1704
+ Envelope.prototype.hasSignatureFrom = function(verifier) {
1705
+ const signedAssertions = this.assertionsWithPredicate(SIGNED);
1706
+ for (const assertion of signedAssertions) try {
1707
+ const signatureCbor = assertion.tryObject().subject().tryLeaf();
1708
+ const signature = _bcts_components.Signature.fromTaggedCbor(signatureCbor);
1709
+ const digest = this.subject().digest();
1710
+ if (verifier.verify(signature, digest.data())) return true;
1711
+ } catch {
1712
+ continue;
1653
1713
  }
1714
+ return false;
1654
1715
  };
1655
- if (Envelope?.prototype) {
1656
- Envelope.prototype.addSignature = function(signer) {
1657
- return this.addSignatureWithMetadata(signer, void 0);
1658
- };
1659
- Envelope.prototype.addSignatureWithMetadata = function(signer, metadata) {
1716
+ Envelope.prototype.hasSignaturesFrom = function(verifiers) {
1717
+ return verifiers.every((verifier) => this.hasSignatureFrom(verifier));
1718
+ };
1719
+ Envelope.prototype.hasSignaturesFromThreshold = function(verifiers, threshold) {
1720
+ let count = 0;
1721
+ for (const verifier of verifiers) if (this.hasSignatureFrom(verifier)) {
1722
+ count++;
1723
+ if (count >= threshold) return true;
1724
+ }
1725
+ return false;
1726
+ };
1727
+ Envelope.prototype.sign = function(signer) {
1728
+ return this.wrap().addSignature(signer);
1729
+ };
1730
+ Envelope.prototype.signWithMetadata = function(signer, metadata) {
1731
+ return this.wrap().addSignatureWithMetadata(signer, metadata);
1732
+ };
1733
+ Envelope.prototype.verify = function(verifier) {
1734
+ if (!this.hasSignatureFrom(verifier)) throw EnvelopeError.general("Signature verification failed");
1735
+ return this.unwrap();
1736
+ };
1737
+ Envelope.prototype.verifyReturningMetadata = function(verifier) {
1738
+ const signedAssertions = this.assertionsWithPredicate(SIGNED);
1739
+ for (const assertion of signedAssertions) try {
1740
+ const signatureEnvelope = assertion.tryObject();
1741
+ const signatureCbor = signatureEnvelope.subject().tryLeaf();
1742
+ const signature = _bcts_components.Signature.fromTaggedCbor(signatureCbor);
1660
1743
  const digest = this.subject().digest();
1661
- const signature = signer.sign(digest.data());
1662
- let signatureEnvelope = Envelope.new(signature.data());
1663
- if (metadata?.hasAssertions() === true) {
1664
- for (const [predicate, object] of metadata.assertions()) signatureEnvelope = signatureEnvelope.addAssertion(predicate, object);
1665
- signatureEnvelope = signatureEnvelope.wrap();
1666
- const outerSignature = signer.sign(signatureEnvelope.digest().data());
1667
- signatureEnvelope = signatureEnvelope.addAssertion(SIGNED, outerSignature.data());
1668
- }
1669
- return this.addAssertion(SIGNED, signatureEnvelope);
1670
- };
1671
- Envelope.prototype.addSignatures = function(signers) {
1672
- return signers.reduce((envelope, signer) => envelope.addSignature(signer), this);
1673
- };
1674
- Envelope.prototype.hasSignatureFrom = function(verifier) {
1675
- const subjectDigest = this.subject().digest();
1676
- const signatures = this.signatures();
1677
- for (const sigEnvelope of signatures) {
1678
- const c = sigEnvelope.case();
1679
- if (c.type === "leaf") try {
1680
- const sigData = sigEnvelope.asByteString();
1681
- if (sigData !== void 0) {
1682
- const signature = new Signature(sigData);
1683
- if (verifier.verify(subjectDigest.data(), signature)) return true;
1684
- }
1685
- } catch {
1686
- continue;
1687
- }
1688
- else if (c.type === "node") {
1689
- const outerSigs = sigEnvelope.assertions().filter((a) => {
1690
- const aC = a.case();
1691
- if (aC.type === "assertion") {
1692
- const pred = aC.assertion.predicate();
1693
- try {
1694
- return pred.asText() === SIGNED;
1695
- } catch {
1696
- return false;
1697
- }
1698
- }
1699
- return false;
1700
- });
1701
- for (const outerSig of outerSigs) {
1702
- const outerSigCase = outerSig.case();
1703
- if (outerSigCase.type === "assertion") {
1704
- const outerSigObj = outerSigCase.assertion.object();
1705
- try {
1706
- const outerSigData = outerSigObj.asByteString();
1707
- if (outerSigData !== void 0) {
1708
- const outerSignature = new Signature(outerSigData);
1709
- const nodeSubject = c.subject;
1710
- const nodeSubjectCase = nodeSubject.case();
1711
- if (nodeSubjectCase.type === "wrapped" && verifier.verify(nodeSubject.digest().data(), outerSignature)) {
1712
- const innerSigData = nodeSubjectCase.envelope.subject().asByteString();
1713
- if (innerSigData !== void 0) {
1714
- const innerSignature = new Signature(innerSigData);
1715
- if (verifier.verify(subjectDigest.data(), innerSignature)) return true;
1716
- }
1717
- }
1718
- }
1719
- } catch {
1720
- continue;
1721
- }
1722
- }
1723
- }
1724
- }
1744
+ if (verifier.verify(signature, digest.data())) {
1745
+ const metadata = new SignatureMetadata();
1746
+ for (const metaAssertion of signatureEnvelope.assertions()) try {
1747
+ const pred = metaAssertion.tryPredicate();
1748
+ const obj = metaAssertion.tryObject();
1749
+ const predValue = pred.tryLeaf();
1750
+ const objValue = obj.tryLeaf();
1751
+ if (predValue !== VERIFIED_BY) metadata.withAssertion(predValue, objValue);
1752
+ } catch {}
1753
+ return {
1754
+ envelope: this.unwrap(),
1755
+ metadata
1756
+ };
1725
1757
  }
1726
- return false;
1727
- };
1728
- Envelope.prototype.verifySignatureFrom = function(verifier) {
1729
- if (this.hasSignatureFrom(verifier)) return this;
1730
- throw EnvelopeError.general("No valid signature found from the given verifier");
1731
- };
1732
- Envelope.prototype.signatures = function() {
1733
- return this.assertions().filter((a) => {
1734
- const c = a.case();
1735
- if (c.type === "assertion") {
1736
- const pred = c.assertion.predicate();
1737
- try {
1738
- return pred.asText() === SIGNED;
1739
- } catch {
1740
- return false;
1741
- }
1742
- }
1743
- return false;
1744
- }).map((a) => {
1745
- const c = a.case();
1746
- if (c.type === "assertion") return c.assertion.object();
1747
- throw EnvelopeError.general("Invalid signature assertion");
1748
- });
1749
- };
1750
- }
1758
+ } catch {
1759
+ continue;
1760
+ }
1761
+ throw EnvelopeError.general("Signature verification failed");
1762
+ };
1763
+ Envelope.prototype.signatures = function() {
1764
+ return this.assertionsWithPredicate(SIGNED).map((assertion) => assertion.tryObject());
1765
+ };
1766
+ Envelope.prototype.verifySignatureFrom = function(verifier) {
1767
+ if (!this.hasSignatureFrom(verifier)) throw EnvelopeError.general("Signature verification failed");
1768
+ return this;
1769
+ };
1770
+ Envelope.prototype.verifySignaturesFrom = function(verifiers) {
1771
+ if (!this.hasSignaturesFrom(verifiers)) throw EnvelopeError.general("Signature verification failed");
1772
+ return this;
1773
+ };
1774
+ Envelope.prototype.verifySignaturesFromThreshold = function(verifiers, threshold) {
1775
+ const t = threshold ?? verifiers.length;
1776
+ if (!this.hasSignaturesFromThreshold(verifiers, t)) throw EnvelopeError.general("Signature verification failed - threshold not met");
1777
+ return this;
1778
+ };
1751
1779
 
1752
1780
  //#endregion
1753
1781
  //#region src/extension/attachment.ts
@@ -1931,188 +1959,268 @@ if (Envelope?.prototype) {
1931
1959
  }
1932
1960
  });
1933
1961
  };
1962
+ /**
1963
+ * Validates that this envelope is a valid attachment.
1964
+ *
1965
+ * An attachment is valid if:
1966
+ * 1. The envelope is an assertion with 'attachment' as predicate
1967
+ * 2. The object contains a wrapped payload with vendor assertion
1968
+ * 3. Reconstructing the attachment yields an equivalent envelope
1969
+ *
1970
+ * @throws EnvelopeError if the envelope is not a valid attachment
1971
+ */
1972
+ Envelope.prototype.validateAttachment = function() {
1973
+ const c = this.case();
1974
+ if (c.type !== "assertion") throw EnvelopeError.invalidAttachment("Envelope is not an assertion");
1975
+ if (c.assertion.predicate().asText() !== ATTACHMENT) throw EnvelopeError.invalidAttachment("Assertion predicate is not 'attachment'");
1976
+ const payload = this.attachmentPayload();
1977
+ const vendor = this.attachmentVendor();
1978
+ const conformsTo = this.attachmentConformsTo();
1979
+ const reconstructed = Envelope.newAttachment(payload, vendor, conformsTo);
1980
+ if (!this.digest().equals(reconstructed.digest())) throw EnvelopeError.invalidAttachment("Attachment structure is invalid");
1981
+ };
1982
+ /**
1983
+ * Finds a single attachment matching the given vendor and conformsTo.
1984
+ *
1985
+ * Unlike `attachmentsWithVendorAndConformsTo` which returns an array,
1986
+ * this method requires exactly one attachment to match.
1987
+ *
1988
+ * @param vendor - Optional vendor identifier to match
1989
+ * @param conformsTo - Optional conformsTo URI to match
1990
+ * @returns The matching attachment envelope
1991
+ * @throws EnvelopeError if not exactly one attachment matches
1992
+ */
1993
+ Envelope.prototype.attachmentWithVendorAndConformsTo = function(vendor, conformsTo) {
1994
+ const matches = this.attachmentsWithVendorAndConformsTo(vendor, conformsTo);
1995
+ if (matches.length === 0) throw EnvelopeError.general("No matching attachment found");
1996
+ if (matches.length > 1) throw EnvelopeError.general(`Expected exactly one attachment, found ${matches.length}`);
1997
+ return matches[0];
1998
+ };
1934
1999
  }
1935
2000
 
1936
2001
  //#endregion
1937
2002
  //#region src/extension/recipient.ts
1938
- const HAS_RECIPIENT = "hasRecipient";
1939
- var PublicKeyBase = class PublicKeyBase {
1940
- #publicKey;
1941
- constructor(publicKey) {
1942
- if (publicKey.length !== _bcts_crypto.X25519_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${_bcts_crypto.X25519_PUBLIC_KEY_SIZE} bytes`);
1943
- this.#publicKey = publicKey;
2003
+ /**
2004
+ * Public key encryption extension for Gordian Envelope.
2005
+ *
2006
+ * This module implements public key encryption for Gordian Envelope, allowing
2007
+ * encrypted content to be selectively shared with one or more recipients. Each
2008
+ * recipient needs their own public/private key pair, and only recipients with
2009
+ * the corresponding private key can decrypt the envelope's content.
2010
+ *
2011
+ * The recipient extension builds on the basic envelope encryption capabilities
2012
+ * by adding:
2013
+ *
2014
+ * - **Multiple Recipients** - A single envelope can be encrypted to multiple
2015
+ * recipients
2016
+ * - **Content Key Distribution** - Uses public key cryptography to securely
2017
+ * distribute the symmetric key that encrypts the actual content
2018
+ * - **Privacy** - Recipients can decrypt the envelope independently without
2019
+ * revealing their identity or access to other recipients
2020
+ *
2021
+ * ## How It Works
2022
+ *
2023
+ * The envelope's subject is encrypted using a random symmetric key (the
2024
+ * "content key"), and then this content key is encrypted to each recipient's
2025
+ * public key using a `SealedMessage`. Each encrypted content key is attached
2026
+ * to the envelope with a `hasRecipient` assertion.
2027
+ *
2028
+ * When recipients want to decrypt the envelope, they use their private key to
2029
+ * decrypt the content key from the appropriate `SealedMessage`, and then use
2030
+ * that content key to decrypt the envelope's subject.
2031
+ *
2032
+ * Ported from bc-envelope-rust/src/extension/recipient.rs
2033
+ */
2034
+ /**
2035
+ * Predicate constant for recipient assertions.
2036
+ * This is the known value 'hasRecipient' used to identify recipient assertions.
2037
+ */
2038
+ const HAS_RECIPIENT = _bcts_known_values.HAS_RECIPIENT;
2039
+ /**
2040
+ * SealedMessage wrapping the sealed content key for a recipient.
2041
+ * This is the proper implementation from @bcts/components that supports
2042
+ * both X25519 and MLKEM encryption schemes.
2043
+ */
2044
+ var SealedMessage = class SealedMessage {
2045
+ #inner;
2046
+ constructor(sealedMessage) {
2047
+ this.#inner = sealedMessage;
1944
2048
  }
1945
- data() {
1946
- return this.#publicKey;
1947
- }
1948
- hex() {
1949
- return Array.from(this.#publicKey).map((b) => b.toString(16).padStart(2, "0")).join("");
1950
- }
1951
- static fromHex(hex) {
1952
- if (hex.length !== 64) throw new Error("Hex string must be 64 characters (32 bytes)");
1953
- const bytes = new Uint8Array(32);
1954
- for (let i = 0; i < 32; i++) bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
1955
- return new PublicKeyBase(bytes);
1956
- }
1957
- };
1958
- var PrivateKeyBase = class PrivateKeyBase {
1959
- #privateKey;
1960
- #publicKey;
1961
- constructor(privateKey, publicKey) {
1962
- this.#privateKey = privateKey;
1963
- this.#publicKey = new PublicKeyBase(publicKey);
1964
- }
1965
- static generate() {
1966
- const privateKey = (0, _bcts_crypto.x25519NewPrivateKeyUsing)(new _bcts_rand.SecureRandomNumberGenerator());
1967
- return new PrivateKeyBase(privateKey, (0, _bcts_crypto.x25519PublicKeyFromPrivateKey)(privateKey));
1968
- }
1969
- static fromBytes(privateKey, publicKey) {
1970
- if (privateKey.length !== _bcts_crypto.X25519_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${_bcts_crypto.X25519_PRIVATE_KEY_SIZE} bytes`);
1971
- if (publicKey.length !== _bcts_crypto.X25519_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${_bcts_crypto.X25519_PUBLIC_KEY_SIZE} bytes`);
1972
- return new PrivateKeyBase(privateKey, publicKey);
1973
- }
1974
- static fromHex(privateHex, publicHex) {
1975
- const privateBytes = new Uint8Array(32);
1976
- const publicBytes = new Uint8Array(32);
1977
- for (let i = 0; i < 32; i++) {
1978
- privateBytes[i] = parseInt(privateHex.substr(i * 2, 2), 16);
1979
- publicBytes[i] = parseInt(publicHex.substr(i * 2, 2), 16);
1980
- }
1981
- return new PrivateKeyBase(privateBytes, publicBytes);
2049
+ /**
2050
+ * Creates a sealed message by encrypting a symmetric key to a recipient.
2051
+ * Uses the Encrypter interface which supports both X25519 and MLKEM.
2052
+ *
2053
+ * @param contentKey - The symmetric key to encrypt
2054
+ * @param recipient - The recipient's public key (implements Encrypter)
2055
+ * @param testNonce - Optional nonce for deterministic testing
2056
+ * @returns A sealed message containing the encrypted content key
2057
+ */
2058
+ static seal(contentKey, recipient, testNonce) {
2059
+ const encapsulationPublicKey = recipient.encapsulationPublicKey();
2060
+ return new SealedMessage(_bcts_components.SealedMessage.newOpt(contentKey.data(), encapsulationPublicKey, new Uint8Array(0), testNonce));
2061
+ }
2062
+ /**
2063
+ * Decrypts this sealed message using recipient's private key.
2064
+ *
2065
+ * @param recipient - The recipient's private key (implements Decrypter)
2066
+ * @returns The decrypted content key data
2067
+ */
2068
+ decrypt(recipient) {
2069
+ const encapsulationPrivateKey = recipient.encapsulationPrivateKey();
2070
+ return this.#inner.decrypt(encapsulationPrivateKey);
1982
2071
  }
1983
- publicKeys() {
1984
- return this.#publicKey;
2072
+ /**
2073
+ * Returns the underlying SealedMessage from components.
2074
+ */
2075
+ inner() {
2076
+ return this.#inner;
1985
2077
  }
2078
+ /**
2079
+ * Returns the CBOR-encoded data of this sealed message.
2080
+ */
1986
2081
  data() {
1987
- return this.#privateKey;
1988
- }
1989
- hex() {
1990
- return Array.from(this.#privateKey).map((b) => b.toString(16).padStart(2, "0")).join("");
2082
+ return this.#inner.taggedCborData();
1991
2083
  }
1992
- unseal(sealedMessage) {
1993
- try {
1994
- const decrypted = sealedMessage.decrypt(this.#privateKey, this.#publicKey.data());
1995
- return SymmetricKey.from(decrypted);
1996
- } catch (_error) {
1997
- throw EnvelopeError.general("Failed to unseal message: not a recipient");
1998
- }
1999
- }
2000
- };
2001
- var SealedMessage = class SealedMessage {
2002
- #data;
2003
- constructor(data) {
2004
- this.#data = data;
2005
- }
2006
- static seal(contentKey, recipientPublicKey) {
2007
- const rng = new _bcts_rand.SecureRandomNumberGenerator();
2008
- const ephemeralPrivate = (0, _bcts_crypto.x25519NewPrivateKeyUsing)(rng);
2009
- const ephemeralPublic = (0, _bcts_crypto.x25519PublicKeyFromPrivateKey)(ephemeralPrivate);
2010
- const encryptionKey = (0, _bcts_crypto.hkdfHmacSha256)((0, _bcts_crypto.x25519SharedKey)(ephemeralPrivate, recipientPublicKey.data()), new TextEncoder().encode("sealed_message"), 32);
2011
- const nonce = (0, _bcts_rand.rngRandomData)(rng, _bcts_crypto.SYMMETRIC_NONCE_SIZE);
2012
- const [ciphertext, authTag] = (0, _bcts_crypto.aeadChaCha20Poly1305EncryptWithAad)(contentKey.data(), encryptionKey, nonce, new Uint8Array(0));
2013
- const totalLength = ephemeralPublic.length + nonce.length + ciphertext.length + authTag.length;
2014
- const sealed = new Uint8Array(totalLength);
2015
- let offset = 0;
2016
- sealed.set(ephemeralPublic, offset);
2017
- offset += ephemeralPublic.length;
2018
- sealed.set(nonce, offset);
2019
- offset += nonce.length;
2020
- sealed.set(ciphertext, offset);
2021
- offset += ciphertext.length;
2022
- sealed.set(authTag, offset);
2023
- return new SealedMessage(sealed);
2024
- }
2025
- decrypt(recipientPrivate, _recipientPublic) {
2026
- const minLength = _bcts_crypto.X25519_PUBLIC_KEY_SIZE + _bcts_crypto.SYMMETRIC_NONCE_SIZE + _bcts_crypto.SYMMETRIC_AUTH_SIZE;
2027
- if (this.#data.length < minLength) throw new Error("Sealed message too short");
2028
- let offset = 0;
2029
- const ephemeralPublic = this.#data.slice(offset, offset + _bcts_crypto.X25519_PUBLIC_KEY_SIZE);
2030
- offset += _bcts_crypto.X25519_PUBLIC_KEY_SIZE;
2031
- const nonce = this.#data.slice(offset, offset + _bcts_crypto.SYMMETRIC_NONCE_SIZE);
2032
- offset += _bcts_crypto.SYMMETRIC_NONCE_SIZE;
2033
- const ciphertextAndTag = this.#data.slice(offset);
2034
- const ciphertext = ciphertextAndTag.slice(0, -_bcts_crypto.SYMMETRIC_AUTH_SIZE);
2035
- const authTag = ciphertextAndTag.slice(-_bcts_crypto.SYMMETRIC_AUTH_SIZE);
2036
- return (0, _bcts_crypto.aeadChaCha20Poly1305DecryptWithAad)(ciphertext, (0, _bcts_crypto.hkdfHmacSha256)((0, _bcts_crypto.x25519SharedKey)(recipientPrivate, ephemeralPublic), new TextEncoder().encode("sealed_message"), 32), nonce, new Uint8Array(0), authTag);
2037
- }
2038
- data() {
2039
- return this.#data;
2040
- }
2041
- hex() {
2042
- return Array.from(this.#data).map((b) => b.toString(16).padStart(2, "0")).join("");
2043
- }
2044
- static fromHex(hex) {
2045
- const bytes = new Uint8Array(hex.length / 2);
2046
- for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
2047
- return new SealedMessage(bytes);
2084
+ /**
2085
+ * Creates a SealedMessage from CBOR-encoded data.
2086
+ */
2087
+ static fromData(data) {
2088
+ return new SealedMessage(_bcts_components.SealedMessage.fromTaggedCborData(data));
2048
2089
  }
2049
2090
  };
2050
2091
  if (Envelope?.prototype) {
2051
- Envelope.prototype.encryptSubjectToRecipient = function(recipientPublicKey) {
2052
- const contentKey = SymmetricKey.generate();
2053
- return this.encryptSubject(contentKey).addRecipient(recipientPublicKey, contentKey);
2092
+ /**
2093
+ * Adds a recipient assertion to this envelope.
2094
+ *
2095
+ * This method adds a `hasRecipient` assertion containing a `SealedMessage`
2096
+ * that holds the content key encrypted to the recipient's public key.
2097
+ *
2098
+ * @param recipient - The recipient's public key (implements Encrypter)
2099
+ * @param contentKey - The symmetric key used to encrypt the envelope's subject
2100
+ * @param testNonce - Optional nonce for deterministic testing
2101
+ * @returns A new envelope with the recipient assertion added
2102
+ */
2103
+ Envelope.prototype.addRecipient = function(recipient, contentKey, testNonce) {
2104
+ const sealedMessage = SealedMessage.seal(contentKey, recipient, testNonce);
2105
+ return this.addAssertion(HAS_RECIPIENT, sealedMessage.inner());
2106
+ };
2107
+ /**
2108
+ * Encrypts the envelope's subject and adds a recipient assertion.
2109
+ *
2110
+ * This is a convenience method that:
2111
+ * 1. Generates a random content key
2112
+ * 2. Encrypts the subject with the content key
2113
+ * 3. Adds a recipient assertion with the sealed content key
2114
+ *
2115
+ * @param recipient - The recipient's public key (implements Encrypter)
2116
+ * @returns A new envelope with encrypted subject and recipient assertion
2117
+ */
2118
+ Envelope.prototype.encryptSubjectToRecipient = function(recipient) {
2119
+ if (!(0, _bcts_components.isEncrypter)(recipient)) throw EnvelopeError.general("Recipient must implement Encrypter interface. Use PublicKeys or EncapsulationPublicKey from @bcts/components.");
2120
+ const contentKey = _bcts_components.SymmetricKey.new();
2121
+ return this.encryptSubject(contentKey).addRecipient(recipient, contentKey);
2054
2122
  };
2123
+ /**
2124
+ * Encrypts the envelope's subject and adds recipient assertions for multiple recipients.
2125
+ *
2126
+ * @param recipients - Array of recipient public keys (each implements Encrypter)
2127
+ * @returns A new envelope with encrypted subject and recipient assertions
2128
+ */
2055
2129
  Envelope.prototype.encryptSubjectToRecipients = function(recipients) {
2056
2130
  if (recipients.length === 0) throw EnvelopeError.general("Must provide at least one recipient");
2057
- const contentKey = SymmetricKey.generate();
2131
+ const contentKey = _bcts_components.SymmetricKey.new();
2058
2132
  let result = this.encryptSubject(contentKey);
2059
- for (const recipient of recipients) result = result.addRecipient(recipient, contentKey);
2133
+ for (const recipient of recipients) {
2134
+ if (!(0, _bcts_components.isEncrypter)(recipient)) throw EnvelopeError.general("All recipients must implement Encrypter interface. Use PublicKeys or EncapsulationPublicKey from @bcts/components.");
2135
+ result = result.addRecipient(recipient, contentKey);
2136
+ }
2060
2137
  return result;
2061
2138
  };
2062
- Envelope.prototype.addRecipient = function(recipientPublicKey, contentKey) {
2063
- const sealedMessage = SealedMessage.seal(contentKey, recipientPublicKey);
2064
- return this.addAssertion(HAS_RECIPIENT, sealedMessage.data());
2065
- };
2066
- Envelope.prototype.decryptSubjectToRecipient = function(recipientPrivateKey) {
2067
- if (this.subject().case().type !== "encrypted") throw EnvelopeError.general("Subject is not encrypted");
2068
- const recipientAssertions = this.assertions().filter((assertion) => {
2139
+ /**
2140
+ * Returns all SealedMessages from the envelope's `hasRecipient` assertions.
2141
+ *
2142
+ * @returns Array of SealedMessage objects
2143
+ */
2144
+ Envelope.prototype.recipients = function() {
2145
+ return this.assertions().filter((assertion) => {
2069
2146
  try {
2070
2147
  const predicate = assertion.subject().asPredicate();
2071
2148
  if (predicate === void 0) return false;
2072
- return predicate.asText() === HAS_RECIPIENT;
2149
+ const knownValue = predicate.asKnownValue();
2150
+ if (knownValue !== void 0) return knownValue.equals(HAS_RECIPIENT);
2151
+ return predicate.asText() === "hasRecipient";
2073
2152
  } catch {
2074
2153
  return false;
2075
2154
  }
2155
+ }).map((assertion) => {
2156
+ const assertionCase = assertion.case();
2157
+ if (assertionCase.type !== "assertion") throw EnvelopeError.general("Invalid recipient assertion structure");
2158
+ const obj = assertionCase.assertion.object();
2159
+ try {
2160
+ const leafCbor = obj.asLeaf();
2161
+ if (leafCbor !== void 0) {
2162
+ const cborData$6 = leafCbor.toData();
2163
+ return new SealedMessage(_bcts_components.SealedMessage.fromTaggedCborData(cborData$6));
2164
+ }
2165
+ const cborData$5 = obj.taggedCborData();
2166
+ return new SealedMessage(_bcts_components.SealedMessage.fromTaggedCborData(cborData$5));
2167
+ } catch {
2168
+ try {
2169
+ const sealedData = obj.asByteString();
2170
+ if (sealedData !== void 0) return SealedMessage.fromData(sealedData);
2171
+ } catch {}
2172
+ throw EnvelopeError.general("Invalid recipient sealed message format");
2173
+ }
2076
2174
  });
2077
- if (recipientAssertions.length === 0) throw EnvelopeError.general("No recipients found");
2078
- let contentKey = null;
2079
- for (const assertion of recipientAssertions) try {
2080
- const obj = assertion.subject().asObject();
2081
- if (obj === void 0) continue;
2082
- const sealedData = obj.asByteString();
2083
- if (sealedData === void 0) continue;
2084
- const sealedMessage = new SealedMessage(sealedData);
2085
- contentKey = recipientPrivateKey.unseal(sealedMessage);
2175
+ };
2176
+ /**
2177
+ * Decrypts the envelope's subject using the recipient's private key.
2178
+ *
2179
+ * This method:
2180
+ * 1. Finds all `hasRecipient` assertions
2181
+ * 2. Tries to decrypt each sealed message until one succeeds
2182
+ * 3. Uses the recovered content key to decrypt the subject
2183
+ *
2184
+ * @param recipient - The recipient's private key (implements Decrypter)
2185
+ * @returns A new envelope with decrypted subject
2186
+ */
2187
+ Envelope.prototype.decryptSubjectToRecipient = function(recipient) {
2188
+ if (this.subject().case().type !== "encrypted") throw EnvelopeError.general("Subject is not encrypted");
2189
+ const sealedMessages = this.recipients();
2190
+ if (sealedMessages.length === 0) throw EnvelopeError.general("No recipients found");
2191
+ let contentKeyData = null;
2192
+ for (const sealedMessage of sealedMessages) try {
2193
+ contentKeyData = sealedMessage.decrypt(recipient);
2086
2194
  break;
2087
2195
  } catch {
2088
2196
  continue;
2089
2197
  }
2090
- if (contentKey === null) throw EnvelopeError.general("Not a valid recipient");
2198
+ if (contentKeyData === null) throw EnvelopeError.general("Not a valid recipient");
2199
+ const contentKey = _bcts_components.SymmetricKey.from(contentKeyData);
2091
2200
  return this.decryptSubject(contentKey);
2092
2201
  };
2093
- Envelope.prototype.decryptToRecipient = function(recipientPrivateKey) {
2094
- return this.decryptSubjectToRecipient(recipientPrivateKey).unwrap();
2202
+ /**
2203
+ * Decrypts an envelope that was encrypted to a recipient and unwraps it.
2204
+ *
2205
+ * This is a convenience method that:
2206
+ * 1. Decrypts the subject using the recipient's private key
2207
+ * 2. Unwraps the resulting envelope
2208
+ *
2209
+ * @param recipient - The recipient's private key (implements Decrypter)
2210
+ * @returns The unwrapped, decrypted envelope
2211
+ */
2212
+ Envelope.prototype.decryptToRecipient = function(recipient) {
2213
+ return this.decryptSubjectToRecipient(recipient).unwrap();
2095
2214
  };
2215
+ /**
2216
+ * Wraps and encrypts an envelope to multiple recipients.
2217
+ *
2218
+ * @param recipients - Array of recipient public keys (each implements Encrypter)
2219
+ * @returns A wrapped and encrypted envelope
2220
+ */
2096
2221
  Envelope.prototype.encryptToRecipients = function(recipients) {
2097
2222
  return this.wrap().encryptSubjectToRecipients(recipients);
2098
2223
  };
2099
- Envelope.prototype.recipients = function() {
2100
- return this.assertions().filter((assertion) => {
2101
- try {
2102
- const predicate = assertion.subject().asPredicate();
2103
- if (predicate === void 0) return false;
2104
- return predicate.asText() === HAS_RECIPIENT;
2105
- } catch {
2106
- return false;
2107
- }
2108
- }).map((assertion) => {
2109
- const obj = assertion.subject().asObject();
2110
- if (obj === void 0) throw EnvelopeError.general("Invalid recipient assertion");
2111
- const sealedData = obj.asByteString();
2112
- if (sealedData === void 0) throw EnvelopeError.general("Invalid recipient data");
2113
- return new SealedMessage(sealedData);
2114
- });
2115
- };
2116
2224
  }
2117
2225
 
2118
2226
  //#endregion
@@ -2144,72 +2252,306 @@ const PARAMETER_IDS = {
2144
2252
  RHS: 3
2145
2253
  };
2146
2254
  var Function = class Function {
2147
- #id;
2148
- constructor(id) {
2149
- this.#id = id;
2255
+ #variant;
2256
+ #value;
2257
+ #name;
2258
+ constructor(variant, value, name) {
2259
+ this.#variant = variant;
2260
+ this.#value = value;
2261
+ this.#name = name;
2262
+ }
2263
+ static newKnown(value, name) {
2264
+ return new Function("known", value, name);
2265
+ }
2266
+ static newNamed(name) {
2267
+ return new Function("named", 0, name);
2268
+ }
2269
+ static fromNumeric(id) {
2270
+ return Function.newKnown(id);
2271
+ }
2272
+ static fromString(name) {
2273
+ return Function.newNamed(name);
2274
+ }
2275
+ isKnown() {
2276
+ return this.#variant === "known";
2277
+ }
2278
+ isNamed() {
2279
+ return this.#variant === "named";
2280
+ }
2281
+ value() {
2282
+ return this.#variant === "known" ? this.#value : void 0;
2150
2283
  }
2151
2284
  id() {
2152
- return this.#id;
2285
+ if (this.#variant === "known") return this.#value;
2286
+ if (this.#name === void 0) throw new Error("Invalid named function: missing name");
2287
+ return this.#name;
2288
+ }
2289
+ name() {
2290
+ if (this.#variant === "known") return this.#name ?? this.#value.toString();
2291
+ else return `"${this.#name}"`;
2292
+ }
2293
+ namedName() {
2294
+ return this.#variant === "named" ? this.#name : void 0;
2295
+ }
2296
+ assignedName() {
2297
+ return this.#variant === "known" ? this.#name : void 0;
2153
2298
  }
2154
2299
  isNumeric() {
2155
- return typeof this.#id === "number";
2300
+ return this.#variant === "known";
2156
2301
  }
2157
2302
  isString() {
2158
- return typeof this.#id === "string";
2303
+ return this.#variant === "named";
2159
2304
  }
2160
2305
  envelope() {
2161
- const functionStr = typeof this.#id === "number" ? `«${this.#id}»` : `«"${this.#id}"»`;
2306
+ const functionStr = this.#variant === "known" ? `«${this.#value}»` : `«"${this.#name}"»`;
2162
2307
  return Envelope.new(functionStr);
2163
2308
  }
2309
+ intoEnvelope() {
2310
+ return this.envelope();
2311
+ }
2164
2312
  withParameter(param, value) {
2165
2313
  return new Expression(this).withParameter(param, value);
2166
2314
  }
2167
- static fromNumeric(id) {
2168
- return new Function(id);
2169
- }
2170
- static fromString(name) {
2171
- return new Function(name);
2315
+ equals(other) {
2316
+ if (this.#variant !== other.#variant) return false;
2317
+ if (this.#variant === "known") return this.#value === other.#value;
2318
+ else return this.#name === other.#name;
2319
+ }
2320
+ hashCode() {
2321
+ if (this.#variant === "known") return this.#value;
2322
+ else {
2323
+ let hash = 0;
2324
+ for (let i = 0; i < (this.#name?.length ?? 0); i++) hash = hash * 31 + (this.#name?.charCodeAt(i) ?? 0) | 0;
2325
+ return hash;
2326
+ }
2172
2327
  }
2173
2328
  toString() {
2174
- return typeof this.#id === "number" ? `«${this.#id}»` : `«"${this.#id}"»`;
2329
+ return this.#variant === "known" ? `«${this.#value}»` : `«"${this.#name}"»`;
2330
+ }
2331
+ };
2332
+ var FunctionsStore = class {
2333
+ #dict = /* @__PURE__ */ new Map();
2334
+ constructor(functions = []) {
2335
+ for (const func of functions) this.insert(func);
2336
+ }
2337
+ insert(func) {
2338
+ if (func.isKnown()) {
2339
+ const value = func.value();
2340
+ if (value !== void 0) this.#dict.set(value, func);
2341
+ } else {
2342
+ const name = func.namedName();
2343
+ if (name !== void 0) this.#dict.set(name, func);
2344
+ }
2345
+ }
2346
+ assignedName(func) {
2347
+ let key;
2348
+ if (func.isKnown()) key = func.value();
2349
+ else key = func.namedName();
2350
+ if (key === void 0) return void 0;
2351
+ return this.#dict.get(key)?.assignedName();
2352
+ }
2353
+ name(func) {
2354
+ return this.assignedName(func) ?? func.name();
2355
+ }
2356
+ static nameForFunction(func, store) {
2357
+ if (store !== void 0) {
2358
+ const assigned = store.assignedName(func);
2359
+ if (assigned !== void 0 && assigned !== "") return assigned;
2360
+ }
2361
+ return func.name();
2175
2362
  }
2176
2363
  };
2177
2364
  var Parameter = class Parameter {
2178
- #id;
2365
+ #variant;
2179
2366
  #value;
2180
- constructor(id, value) {
2181
- this.#id = id;
2367
+ #name;
2368
+ #paramValue;
2369
+ constructor(variant, value, name, paramValue) {
2370
+ this.#variant = variant;
2182
2371
  this.#value = value;
2372
+ this.#name = name;
2373
+ this.#paramValue = paramValue;
2183
2374
  }
2184
- id() {
2185
- return this.#id;
2375
+ static newKnown(value, name) {
2376
+ return new Parameter("known", value, name);
2377
+ }
2378
+ static newNamed(name) {
2379
+ return new Parameter("named", 0, name);
2380
+ }
2381
+ static withValue(id, value) {
2382
+ if (typeof id === "number") return new Parameter("known", id, void 0, value);
2383
+ else return new Parameter("named", 0, id, value);
2384
+ }
2385
+ isKnown() {
2386
+ return this.#variant === "known";
2387
+ }
2388
+ isNamed() {
2389
+ return this.#variant === "named";
2186
2390
  }
2187
2391
  value() {
2188
- return this.#value;
2392
+ return this.#variant === "known" ? this.#value : void 0;
2393
+ }
2394
+ id() {
2395
+ if (this.#variant === "known") return this.#value;
2396
+ if (this.#name === void 0) throw new Error("Invalid named parameter: missing name");
2397
+ return this.#name;
2398
+ }
2399
+ name() {
2400
+ if (this.#variant === "known") return this.#name ?? this.#value.toString();
2401
+ else return `"${this.#name}"`;
2402
+ }
2403
+ namedName() {
2404
+ return this.#variant === "named" ? this.#name : void 0;
2405
+ }
2406
+ assignedName() {
2407
+ return this.#variant === "known" ? this.#name : void 0;
2408
+ }
2409
+ paramValue() {
2410
+ return this.#paramValue;
2189
2411
  }
2190
2412
  isNumeric() {
2191
- return typeof this.#id === "number";
2413
+ return this.#variant === "known";
2192
2414
  }
2193
2415
  isString() {
2194
- return typeof this.#id === "string";
2416
+ return this.#variant === "named";
2195
2417
  }
2196
2418
  envelope() {
2197
- const paramStr = typeof this.#id === "number" ? `❰${this.#id}❱` : `❰"${this.#id}"❱`;
2198
- return Envelope.newAssertion(paramStr, this.#value);
2419
+ const paramStr = this.#variant === "known" ? `❰${this.#value}❱` : `❰"${this.#name}"❱`;
2420
+ if (this.#paramValue !== void 0) return Envelope.newAssertion(paramStr, this.#paramValue);
2421
+ return Envelope.new(paramStr);
2422
+ }
2423
+ intoEnvelope() {
2424
+ return this.envelope();
2425
+ }
2426
+ equals(other) {
2427
+ if (this.#variant !== other.#variant) return false;
2428
+ if (this.#variant === "known") return this.#value === other.#value;
2429
+ else return this.#name === other.#name;
2430
+ }
2431
+ hashCode() {
2432
+ if (this.#variant === "known") return this.#value;
2433
+ else {
2434
+ let hash = 0;
2435
+ for (let i = 0; i < (this.#name?.length ?? 0); i++) hash = hash * 31 + (this.#name?.charCodeAt(i) ?? 0) | 0;
2436
+ return hash;
2437
+ }
2438
+ }
2439
+ toString() {
2440
+ const idStr = this.#variant === "known" ? `❰${this.#value}❱` : `❰"${this.#name}"❱`;
2441
+ if (this.#paramValue !== void 0) return `${idStr}: ${this.#paramValue.asText()}`;
2442
+ return idStr;
2199
2443
  }
2200
2444
  static blank(value) {
2201
- return new Parameter(PARAMETER_IDS.BLANK, Envelope.new(value));
2445
+ return Parameter.withValue(PARAMETER_IDS.BLANK, Envelope.new(value));
2202
2446
  }
2203
2447
  static lhs(value) {
2204
- return new Parameter(PARAMETER_IDS.LHS, Envelope.new(value));
2448
+ return Parameter.withValue(PARAMETER_IDS.LHS, Envelope.new(value));
2205
2449
  }
2206
2450
  static rhs(value) {
2207
- return new Parameter(PARAMETER_IDS.RHS, Envelope.new(value));
2451
+ return Parameter.withValue(PARAMETER_IDS.RHS, Envelope.new(value));
2208
2452
  }
2209
- toString() {
2210
- return `${typeof this.#id === "number" ? `❰${this.#id}❱` : `❰"${this.#id}"❱`}: ${this.#value.asText()}`;
2453
+ };
2454
+ var ParametersStore = class {
2455
+ #dict = /* @__PURE__ */ new Map();
2456
+ constructor(parameters = []) {
2457
+ for (const param of parameters) this.insert(param);
2458
+ }
2459
+ insert(param) {
2460
+ if (param.isKnown()) {
2461
+ const value = param.value();
2462
+ if (value !== void 0) this.#dict.set(value, param);
2463
+ } else {
2464
+ const name = param.namedName();
2465
+ if (name !== void 0) this.#dict.set(name, param);
2466
+ }
2467
+ }
2468
+ assignedName(param) {
2469
+ let key;
2470
+ if (param.isKnown()) key = param.value();
2471
+ else key = param.namedName();
2472
+ if (key === void 0) return void 0;
2473
+ return this.#dict.get(key)?.assignedName();
2474
+ }
2475
+ name(param) {
2476
+ return this.assignedName(param) ?? param.name();
2477
+ }
2478
+ static nameForParameter(param, store) {
2479
+ if (store !== void 0) {
2480
+ const assigned = store.assignedName(param);
2481
+ if (assigned !== void 0 && assigned !== "") return assigned;
2482
+ }
2483
+ return param.name();
2211
2484
  }
2212
2485
  };
2486
+ const ADD = Function.newKnown(FUNCTION_IDS.ADD, "add");
2487
+ const SUB = Function.newKnown(FUNCTION_IDS.SUB, "sub");
2488
+ const MUL = Function.newKnown(FUNCTION_IDS.MUL, "mul");
2489
+ const DIV = Function.newKnown(FUNCTION_IDS.DIV, "div");
2490
+ const NEG = Function.newKnown(FUNCTION_IDS.NEG, "neg");
2491
+ const LT = Function.newKnown(FUNCTION_IDS.LT, "lt");
2492
+ const LE = Function.newKnown(FUNCTION_IDS.LE, "le");
2493
+ const GT = Function.newKnown(FUNCTION_IDS.GT, "gt");
2494
+ const GE = Function.newKnown(FUNCTION_IDS.GE, "ge");
2495
+ const EQ = Function.newKnown(FUNCTION_IDS.EQ, "eq");
2496
+ const NE = Function.newKnown(FUNCTION_IDS.NE, "ne");
2497
+ const AND = Function.newKnown(FUNCTION_IDS.AND, "and");
2498
+ const OR = Function.newKnown(FUNCTION_IDS.OR, "or");
2499
+ const XOR = Function.newKnown(FUNCTION_IDS.XOR, "xor");
2500
+ const NOT = Function.newKnown(FUNCTION_IDS.NOT, "not");
2501
+ const ADD_VALUE = FUNCTION_IDS.ADD;
2502
+ const SUB_VALUE = FUNCTION_IDS.SUB;
2503
+ const MUL_VALUE = FUNCTION_IDS.MUL;
2504
+ const DIV_VALUE = FUNCTION_IDS.DIV;
2505
+ const NEG_VALUE = FUNCTION_IDS.NEG;
2506
+ const LT_VALUE = FUNCTION_IDS.LT;
2507
+ const LE_VALUE = FUNCTION_IDS.LE;
2508
+ const GT_VALUE = FUNCTION_IDS.GT;
2509
+ const GE_VALUE = FUNCTION_IDS.GE;
2510
+ const EQ_VALUE = FUNCTION_IDS.EQ;
2511
+ const NE_VALUE = FUNCTION_IDS.NE;
2512
+ const AND_VALUE = FUNCTION_IDS.AND;
2513
+ const OR_VALUE = FUNCTION_IDS.OR;
2514
+ const XOR_VALUE = FUNCTION_IDS.XOR;
2515
+ const NOT_VALUE = FUNCTION_IDS.NOT;
2516
+ const BLANK = Parameter.newKnown(PARAMETER_IDS.BLANK, "_");
2517
+ const LHS = Parameter.newKnown(PARAMETER_IDS.LHS, "lhs");
2518
+ const RHS = Parameter.newKnown(PARAMETER_IDS.RHS, "rhs");
2519
+ const BLANK_VALUE = PARAMETER_IDS.BLANK;
2520
+ const LHS_VALUE = PARAMETER_IDS.LHS;
2521
+ const RHS_VALUE = PARAMETER_IDS.RHS;
2522
+ var LazyStore = class {
2523
+ #store;
2524
+ #initializer;
2525
+ constructor(initializer) {
2526
+ this.#initializer = initializer;
2527
+ }
2528
+ get() {
2529
+ this.#store ??= this.#initializer();
2530
+ return this.#store;
2531
+ }
2532
+ };
2533
+ const GLOBAL_FUNCTIONS = new LazyStore(() => new FunctionsStore([
2534
+ ADD,
2535
+ SUB,
2536
+ MUL,
2537
+ DIV,
2538
+ NEG,
2539
+ LT,
2540
+ LE,
2541
+ GT,
2542
+ GE,
2543
+ EQ,
2544
+ NE,
2545
+ AND,
2546
+ OR,
2547
+ XOR,
2548
+ NOT
2549
+ ]));
2550
+ const GLOBAL_PARAMETERS = new LazyStore(() => new ParametersStore([
2551
+ BLANK,
2552
+ LHS,
2553
+ RHS
2554
+ ]));
2213
2555
  var Expression = class Expression {
2214
2556
  #function;
2215
2557
  #parameters = /* @__PURE__ */ new Map();
@@ -2225,7 +2567,7 @@ var Expression = class Expression {
2225
2567
  }
2226
2568
  withParameter(param, value) {
2227
2569
  const key = typeof param === "number" ? param.toString() : param;
2228
- this.#parameters.set(key, new Parameter(param, Envelope.new(value)));
2570
+ this.#parameters.set(key, Parameter.withValue(param, Envelope.new(value)));
2229
2571
  this.#envelope = null;
2230
2572
  return this;
2231
2573
  }
@@ -2235,7 +2577,7 @@ var Expression = class Expression {
2235
2577
  }
2236
2578
  getParameter(param) {
2237
2579
  const key = typeof param === "number" ? param.toString() : param;
2238
- return this.#parameters.get(key)?.value();
2580
+ return this.#parameters.get(key)?.paramValue();
2239
2581
  }
2240
2582
  hasParameter(param) {
2241
2583
  const key = typeof param === "number" ? param.toString() : param;
@@ -2245,29 +2587,33 @@ var Expression = class Expression {
2245
2587
  if (this.#envelope !== null) return this.#envelope;
2246
2588
  let env = this.#function.envelope();
2247
2589
  for (const param of this.#parameters.values()) {
2248
- const assertion = param.envelope().assertions()[0];
2249
- if (assertion !== void 0) {
2250
- const predicate = assertion.subject().asPredicate();
2251
- const object = assertion.subject().asObject();
2252
- if (predicate !== void 0 && object !== void 0) env = env.addAssertion(predicate.asText(), object);
2590
+ const paramCase = param.envelope().case();
2591
+ if (paramCase.type === "assertion") {
2592
+ const predicate = paramCase.assertion.predicate();
2593
+ const object = paramCase.assertion.object();
2594
+ const predText = predicate.asText();
2595
+ if (predText !== void 0) env = env.addAssertion(predText, object);
2253
2596
  }
2254
2597
  }
2255
2598
  this.#envelope = env;
2256
2599
  return env;
2257
2600
  }
2601
+ intoEnvelope() {
2602
+ return this.envelope();
2603
+ }
2258
2604
  static fromEnvelope(envelope) {
2259
2605
  const subjectText = envelope.subject().asText();
2260
2606
  if (subjectText === void 0) throw EnvelopeError.general("Not a valid function envelope");
2261
- let funcId;
2607
+ let func;
2262
2608
  if (subjectText.startsWith("«") && subjectText.endsWith("»")) {
2263
2609
  const inner = subjectText.slice(1, -1);
2264
- if (inner.startsWith("\"") && inner.endsWith("\"")) funcId = inner.slice(1, -1);
2265
- else funcId = parseInt(inner, 10);
2610
+ if (inner.startsWith("\"") && inner.endsWith("\"")) func = Function.newNamed(inner.slice(1, -1));
2611
+ else func = Function.newKnown(parseInt(inner, 10));
2266
2612
  } else throw EnvelopeError.general("Not a valid function envelope");
2267
- const expr = new Expression(new Function(funcId));
2613
+ const expr = new Expression(func);
2268
2614
  for (const assertion of envelope.assertions()) try {
2269
2615
  const pred = assertion.subject().asPredicate();
2270
- const obj = assertion.subject().asObject();
2616
+ const obj = assertion.asObject();
2271
2617
  if (pred !== void 0 && obj !== void 0) {
2272
2618
  const predText = pred.asText();
2273
2619
  if (predText !== void 0 && predText.startsWith("❰") && predText.endsWith("❱")) {
@@ -2289,37 +2635,49 @@ var Expression = class Expression {
2289
2635
  }
2290
2636
  };
2291
2637
  function add(lhs, rhs) {
2292
- return Function.fromNumeric(FUNCTION_IDS.ADD).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2638
+ return new Expression(ADD).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2293
2639
  }
2294
2640
  function sub(lhs, rhs) {
2295
- return Function.fromNumeric(FUNCTION_IDS.SUB).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2641
+ return new Expression(SUB).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2296
2642
  }
2297
2643
  function mul(lhs, rhs) {
2298
- return Function.fromNumeric(FUNCTION_IDS.MUL).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2644
+ return new Expression(MUL).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2299
2645
  }
2300
2646
  function div(lhs, rhs) {
2301
- return Function.fromNumeric(FUNCTION_IDS.DIV).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2647
+ return new Expression(DIV).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2302
2648
  }
2303
2649
  function neg(value) {
2304
- return Function.fromNumeric(FUNCTION_IDS.NEG).withParameter(PARAMETER_IDS.BLANK, value);
2650
+ return new Expression(NEG).withParameter(PARAMETER_IDS.BLANK, value);
2305
2651
  }
2306
2652
  function lt(lhs, rhs) {
2307
- return Function.fromNumeric(FUNCTION_IDS.LT).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2653
+ return new Expression(LT).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2654
+ }
2655
+ function le(lhs, rhs) {
2656
+ return new Expression(LE).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2308
2657
  }
2309
2658
  function gt(lhs, rhs) {
2310
- return Function.fromNumeric(FUNCTION_IDS.GT).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2659
+ return new Expression(GT).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2660
+ }
2661
+ function ge(lhs, rhs) {
2662
+ return new Expression(GE).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2311
2663
  }
2312
2664
  function eq(lhs, rhs) {
2313
- return Function.fromNumeric(FUNCTION_IDS.EQ).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2665
+ return new Expression(EQ).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2666
+ }
2667
+ function ne(lhs, rhs) {
2668
+ return new Expression(NE).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2314
2669
  }
2315
2670
  function and(lhs, rhs) {
2316
- return Function.fromNumeric(FUNCTION_IDS.AND).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2671
+ return new Expression(AND).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2317
2672
  }
2318
2673
  function or(lhs, rhs) {
2319
- return Function.fromNumeric(FUNCTION_IDS.OR).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2674
+ return new Expression(OR).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2675
+ }
2676
+ function xor(lhs, rhs) {
2677
+ return new Expression(XOR).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2320
2678
  }
2321
2679
  function not(value) {
2322
- return Function.fromNumeric(FUNCTION_IDS.NOT).withParameter(PARAMETER_IDS.BLANK, value);
2680
+ return new Expression(NOT).withParameter(PARAMETER_IDS.BLANK, value);
2323
2681
  }
2324
2682
 
2325
2683
  //#endregion
@@ -2351,7 +2709,7 @@ function revealSetOfSet(envelope, target) {
2351
2709
  function revealSets(envelope, target, current, result) {
2352
2710
  const newCurrent = new Set(current);
2353
2711
  newCurrent.add(envelope.digest());
2354
- if (containsDigest(target, envelope.digest())) for (const digest of newCurrent) result.add(digest);
2712
+ if (containsDigest$1(target, envelope.digest())) for (const digest of newCurrent) result.add(digest);
2355
2713
  const envelopeCase = envelope.case();
2356
2714
  if (envelopeCase.type === "node") {
2357
2715
  revealSets(envelopeCase.subject, target, newCurrent, result);
@@ -2370,7 +2728,7 @@ function containsAll(envelope, target) {
2370
2728
  return targetCopy.size === 0;
2371
2729
  }
2372
2730
  function removeAllFound(envelope, target) {
2373
- if (containsDigest(target, envelope.digest())) removeDigest(target, envelope.digest());
2731
+ if (containsDigest$1(target, envelope.digest())) removeDigest(target, envelope.digest());
2374
2732
  if (target.size === 0) return;
2375
2733
  const envelopeCase = envelope.case();
2376
2734
  if (envelopeCase.type === "node") {
@@ -2387,7 +2745,7 @@ function removeAllFound(envelope, target) {
2387
2745
  if (target.size > 0) removeAllFound(object, target);
2388
2746
  }
2389
2747
  }
2390
- function containsDigest(set, digest) {
2748
+ function containsDigest$1(set, digest) {
2391
2749
  const hexToFind = digest.hex();
2392
2750
  for (const d of set) if (d.hex() === hexToFind) return true;
2393
2751
  return false;
@@ -2400,121 +2758,780 @@ function removeDigest(set, digest) {
2400
2758
  }
2401
2759
  }
2402
2760
  function isSubset(subset, superset) {
2403
- for (const digest of subset) if (!containsDigest(superset, digest)) return false;
2761
+ for (const digest of subset) if (!containsDigest$1(superset, digest)) return false;
2404
2762
  return true;
2405
2763
  }
2764
+ function registerProofExtension() {}
2406
2765
 
2407
2766
  //#endregion
2408
- //#region src/format/hex.ts
2409
- Envelope.prototype.hex = function() {
2410
- const bytes = this.cborBytes();
2411
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2767
+ //#region src/extension/secret.ts
2768
+ Envelope.prototype.lockSubject = function(method, secret) {
2769
+ const contentKey = _bcts_components.SymmetricKey.new();
2770
+ const componentsKey = _bcts_components.SymmetricKey.fromData(contentKey.data());
2771
+ const encryptedKey = _bcts_components.EncryptedKey.lock(method, secret, componentsKey);
2772
+ return this.encryptSubject(contentKey).addAssertion(_bcts_known_values.HAS_SECRET, encryptedKey);
2412
2773
  };
2413
- Envelope.prototype.cborBytes = function() {
2414
- return (0, _bcts_dcbor.cborData)(this.taggedCbor());
2774
+ Envelope.prototype.unlockSubject = function(secret) {
2775
+ const assertions = this.assertionsWithPredicate(_bcts_known_values.HAS_SECRET);
2776
+ for (const assertion of assertions) {
2777
+ const obj = assertion.asObject();
2778
+ if (obj === void 0) continue;
2779
+ if (obj.isObscured()) continue;
2780
+ try {
2781
+ const componentsKey = obj.extractSubject((cbor$1) => _bcts_components.EncryptedKey.fromTaggedCbor(cbor$1)).unlock(secret);
2782
+ const contentKey = _bcts_components.SymmetricKey.from(componentsKey.data());
2783
+ return this.decryptSubject(contentKey);
2784
+ } catch {
2785
+ continue;
2786
+ }
2787
+ }
2788
+ throw EnvelopeError.unknownSecret();
2789
+ };
2790
+ Envelope.prototype.isLockedWithPassword = function() {
2791
+ const assertions = this.assertionsWithPredicate(_bcts_known_values.HAS_SECRET);
2792
+ for (const assertion of assertions) {
2793
+ const obj = assertion.asObject();
2794
+ if (obj === void 0) continue;
2795
+ try {
2796
+ if (obj.extractSubject((cbor$1) => _bcts_components.EncryptedKey.fromTaggedCbor(cbor$1)).isPasswordBased()) return true;
2797
+ } catch {
2798
+ continue;
2799
+ }
2800
+ }
2801
+ return false;
2802
+ };
2803
+ Envelope.prototype.isLockedWithSshAgent = function() {
2804
+ const assertions = this.assertionsWithPredicate(_bcts_known_values.HAS_SECRET);
2805
+ for (const assertion of assertions) {
2806
+ const obj = assertion.asObject();
2807
+ if (obj === void 0) continue;
2808
+ try {
2809
+ if (obj.extractSubject((cbor$1) => _bcts_components.EncryptedKey.fromTaggedCbor(cbor$1)).isSshAgent()) return true;
2810
+ } catch {
2811
+ continue;
2812
+ }
2813
+ }
2814
+ return false;
2415
2815
  };
2816
+ Envelope.prototype.addSecret = function(method, secret, contentKey) {
2817
+ const componentsKey = _bcts_components.SymmetricKey.fromData(contentKey.data());
2818
+ const encryptedKey = _bcts_components.EncryptedKey.lock(method, secret, componentsKey);
2819
+ return this.addAssertion(_bcts_known_values.HAS_SECRET, encryptedKey);
2820
+ };
2821
+ Envelope.prototype.lock = function(method, secret) {
2822
+ return this.wrap().lockSubject(method, secret);
2823
+ };
2824
+ Envelope.prototype.unlock = function(secret) {
2825
+ return this.unlockSubject(secret).tryUnwrap();
2826
+ };
2827
+ const registerSecretExtension = () => {};
2416
2828
 
2417
2829
  //#endregion
2418
- //#region src/format/diagnostic.ts
2419
- function cborToDiagnostic(cbor$1, indent = 0) {
2420
- if (typeof cbor$1 === "object" && cbor$1 !== null && "tag" in cbor$1 && "value" in cbor$1) {
2421
- const tagged = cbor$1;
2422
- return `${tagged.tag}(${cborToDiagnostic(tagged.value, indent)})`;
2423
- }
2424
- if (Array.isArray(cbor$1)) {
2425
- if (cbor$1.length === 0) return "[]";
2426
- return `[${cbor$1.map((item) => cborToDiagnostic(item, indent + 2)).join(", ")}]`;
2830
+ //#region src/extension/sskr.ts
2831
+ const addSskrShare = (envelope, share) => {
2832
+ return envelope.addAssertion(_bcts_known_values.SSKR_SHARE, share);
2833
+ };
2834
+ Envelope.prototype.sskrSplit = function(spec, contentKey) {
2835
+ const shareGroups = (0, _bcts_components.sskrGenerateShares)(spec, _bcts_components.SSKRSecret.new(contentKey.data()));
2836
+ const result = [];
2837
+ for (const group of shareGroups) {
2838
+ const groupResult = [];
2839
+ for (const share of group) {
2840
+ const shareEnvelope = addSskrShare(this, share);
2841
+ groupResult.push(shareEnvelope);
2842
+ }
2843
+ result.push(groupResult);
2427
2844
  }
2428
- if (cbor$1 instanceof Map) {
2429
- if (cbor$1.size === 0) return "{}";
2430
- const entries = [];
2431
- for (const [key, value] of cbor$1) {
2432
- const keyStr = cborToDiagnostic(key, indent + 2);
2433
- const valueStr = cborToDiagnostic(value, indent + 2);
2434
- entries.push(`${keyStr}: ${valueStr}`);
2845
+ return result;
2846
+ };
2847
+ Envelope.prototype.sskrSplitFlattened = function(spec, contentKey) {
2848
+ return this.sskrSplit(spec, contentKey).flat();
2849
+ };
2850
+ Envelope.prototype.sskrSplitUsing = function(spec, contentKey, rng) {
2851
+ const shareGroups = (0, _bcts_components.sskrGenerateUsing)(spec, _bcts_components.SSKRSecret.new(contentKey.data()), rng);
2852
+ const result = [];
2853
+ for (const group of shareGroups) {
2854
+ const groupResult = [];
2855
+ for (const shareData of group) {
2856
+ const share = _bcts_components.SSKRShareCbor.fromData(shareData);
2857
+ const shareEnvelope = addSskrShare(this, share);
2858
+ groupResult.push(shareEnvelope);
2435
2859
  }
2436
- return `{${entries.join(", ")}}`;
2860
+ result.push(groupResult);
2437
2861
  }
2438
- if (cbor$1 instanceof Uint8Array) return `h'${Array.from(cbor$1).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
2439
- if (typeof cbor$1 === "string") return JSON.stringify(cbor$1);
2440
- if (typeof cbor$1 === "object" && cbor$1 !== null && "type" in cbor$1) {
2441
- const typed = cbor$1;
2442
- switch (typed.type) {
2443
- case 0: return String(typed.value);
2444
- case 1: return String(-1 - Number(typed.value));
2445
- case 7: {
2446
- const simpleValue = typed.value;
2447
- if (simpleValue !== null && typeof simpleValue === "object" && "type" in simpleValue) {
2448
- const floatValue = simpleValue;
2449
- if (floatValue.type === "Float") return String(floatValue.value);
2450
- }
2451
- if (simpleValue === 20) return "false";
2452
- if (simpleValue === 21) return "true";
2453
- if (simpleValue === 22) return "null";
2454
- if (simpleValue === 23) return "undefined";
2455
- return `simple(${String(simpleValue)})`;
2862
+ return result;
2863
+ };
2864
+ const extractSskrSharesGrouped = (envelopes) => {
2865
+ const result = /* @__PURE__ */ new Map();
2866
+ for (const envelope of envelopes) {
2867
+ const assertions = envelope.assertionsWithPredicate(_bcts_known_values.SSKR_SHARE);
2868
+ for (const assertion of assertions) {
2869
+ const obj = assertion.asObject();
2870
+ if (obj === void 0) continue;
2871
+ if (obj.isObscured()) continue;
2872
+ try {
2873
+ const share = obj.extractSubject((cbor$1) => _bcts_components.SSKRShareCbor.fromTaggedCbor(cbor$1));
2874
+ const identifier = share.identifier();
2875
+ const existing = result.get(identifier);
2876
+ if (existing !== void 0) existing.push(share);
2877
+ else result.set(identifier, [share]);
2878
+ } catch {
2879
+ continue;
2456
2880
  }
2457
2881
  }
2458
2882
  }
2459
- if (typeof cbor$1 === "boolean") return String(cbor$1);
2460
- if (typeof cbor$1 === "number") return String(cbor$1);
2461
- if (typeof cbor$1 === "bigint") return String(cbor$1);
2462
- if (cbor$1 === null) return "null";
2463
- if (cbor$1 === void 0) return "undefined";
2464
- try {
2465
- return JSON.stringify(cbor$1);
2883
+ return result;
2884
+ };
2885
+ Envelope.sskrJoin = function(envelopes) {
2886
+ if (envelopes.length === 0) throw EnvelopeError.invalidShares();
2887
+ const groupedShares = extractSskrSharesGrouped(envelopes);
2888
+ for (const shares of groupedShares.values()) try {
2889
+ const secret = (0, _bcts_components.sskrCombineShares)(shares);
2890
+ const contentKey = _bcts_components.SymmetricKey.from(secret.getData());
2891
+ return envelopes[0].decryptSubject(contentKey).subject();
2466
2892
  } catch {
2467
- return String(cbor$1);
2893
+ continue;
2468
2894
  }
2469
- }
2470
- Envelope.prototype.diagnostic = function() {
2471
- return cborToDiagnostic(this.taggedCbor());
2895
+ throw EnvelopeError.invalidShares();
2472
2896
  };
2897
+ const registerSskrExtension = () => {};
2473
2898
 
2474
2899
  //#endregion
2475
- //#region src/format/tree.ts
2476
- Envelope.prototype.shortId = function(format = "short") {
2477
- const digest = this.digest();
2478
- if (format === "full") return digest.hex();
2479
- return digest.short();
2480
- };
2481
- Envelope.prototype.summary = function(maxLength = 40) {
2482
- switch (this.case().type) {
2483
- case "node": return "NODE";
2484
- case "leaf": {
2485
- try {
2486
- const text = this.asText();
2487
- if (text !== void 0) {
2488
- const truncated = text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
2489
- return JSON.stringify(truncated);
2490
- }
2491
- } catch {}
2492
- try {
2493
- const num = this.extractNumber();
2494
- return String(num);
2495
- } catch {}
2496
- try {
2497
- const bool = this.extractBoolean();
2498
- return String(bool);
2499
- } catch {}
2500
- if (this.isNull()) return "null";
2501
- const bytes = this.asByteString();
2502
- if (bytes !== void 0 && bytes.length <= 16) return `h'${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
2503
- return "LEAF";
2504
- }
2505
- case "wrapped": return "WRAPPED";
2506
- case "assertion": return "ASSERTION";
2507
- case "elided": return "ELIDED";
2508
- case "encrypted": return "ENCRYPTED";
2509
- case "compressed": return "COMPRESSED";
2510
- case "knownValue": return "KNOWN_VALUE";
2511
- default: return "UNKNOWN";
2512
- }
2513
- };
2514
- Envelope.prototype.treeFormat = function(options = {}) {
2515
- const hideNodes = options.hideNodes ?? false;
2516
- const highlightDigests = options.highlightDigests ?? /* @__PURE__ */ new Set();
2517
- const digestDisplay = options.digestDisplay ?? "short";
2900
+ //#region src/extension/request.ts
2901
+ /**
2902
+ * Request type for distributed function calls.
2903
+ *
2904
+ * Ported from bc-envelope-rust/src/extension/expressions/request.rs
2905
+ *
2906
+ * A Request represents a message requesting execution of a function with
2907
+ * parameters. Requests are part of the expression system that enables
2908
+ * distributed function calls and communication between systems.
2909
+ *
2910
+ * Each request:
2911
+ * - Contains a body (an Expression) that represents the function to be executed
2912
+ * - Has a unique identifier (ARID) for tracking and correlation
2913
+ * - May include optional metadata like a note and timestamp
2914
+ *
2915
+ * Requests are designed to be paired with Response objects that contain the
2916
+ * results of executing the requested function.
2917
+ *
2918
+ * When serialized to an envelope, requests are tagged with REQUEST tag.
2919
+ */
2920
+ /**
2921
+ * A Request represents a message requesting execution of a function with parameters.
2922
+ *
2923
+ * @example
2924
+ * ```typescript
2925
+ * import { Request, ARID } from '@bcts/envelope';
2926
+ *
2927
+ * // Create a random request ID
2928
+ * const requestId = ARID.new();
2929
+ *
2930
+ * // Create a request to execute a function with parameters
2931
+ * const request = Request.new("getBalance", requestId)
2932
+ * .withParameter("account", "alice")
2933
+ * .withParameter("currency", "USD")
2934
+ * .withNote("Monthly balance check");
2935
+ *
2936
+ * // Convert to an envelope
2937
+ * const envelope = request.toEnvelope();
2938
+ * ```
2939
+ */
2940
+ var Request = class Request {
2941
+ #body;
2942
+ #id;
2943
+ #note;
2944
+ #date;
2945
+ constructor(body, id, note = "", date) {
2946
+ this.#body = body;
2947
+ this.#id = id;
2948
+ this.#note = note;
2949
+ this.#date = date;
2950
+ }
2951
+ /**
2952
+ * Creates a new request with the specified expression body and ID.
2953
+ */
2954
+ static newWithBody(body, id) {
2955
+ return new Request(body, id);
2956
+ }
2957
+ /**
2958
+ * Creates a new request with a function and ID.
2959
+ *
2960
+ * This is a convenience method that creates an expression from the
2961
+ * function and then creates a request with that expression.
2962
+ */
2963
+ static new(func, id) {
2964
+ const f = typeof func === "string" ? Function.newNamed(func) : typeof func === "number" ? Function.newKnown(func) : func;
2965
+ return Request.newWithBody(new Expression(f), id);
2966
+ }
2967
+ /**
2968
+ * Returns a human-readable summary of the request.
2969
+ */
2970
+ summary() {
2971
+ return `id: ${this.#id.shortDescription()}, body: ${this.#body.envelope().formatFlat()}`;
2972
+ }
2973
+ withParameter(param, value) {
2974
+ this.#body.withParameter(param, value);
2975
+ return this;
2976
+ }
2977
+ withNote(note) {
2978
+ this.#note = note;
2979
+ return this;
2980
+ }
2981
+ withDate(date) {
2982
+ this.#date = date;
2983
+ return this;
2984
+ }
2985
+ body() {
2986
+ return this.#body;
2987
+ }
2988
+ id() {
2989
+ return this.#id;
2990
+ }
2991
+ note() {
2992
+ return this.#note;
2993
+ }
2994
+ date() {
2995
+ return this.#date;
2996
+ }
2997
+ function() {
2998
+ return this.#body.function();
2999
+ }
3000
+ expressionEnvelope() {
3001
+ return this.#body.envelope();
3002
+ }
3003
+ /**
3004
+ * Converts the request to an envelope.
3005
+ *
3006
+ * The envelope's subject is the request's ID tagged with TAG_REQUEST,
3007
+ * and assertions include the request's body, note (if not empty), and date (if present).
3008
+ */
3009
+ toEnvelope() {
3010
+ const taggedArid = (0, _bcts_dcbor.toTaggedValue)(_bcts_tags.REQUEST, this.#id.untaggedCbor());
3011
+ let envelope = Envelope.newLeaf(taggedArid).addAssertion(_bcts_known_values.BODY, this.#body.envelope());
3012
+ if (this.#note !== "") envelope = envelope.addAssertion(_bcts_known_values.NOTE, this.#note);
3013
+ if (this.#date !== void 0) envelope = envelope.addAssertion(_bcts_known_values.DATE, this.#date.toISOString());
3014
+ return envelope;
3015
+ }
3016
+ /**
3017
+ * Converts this request into an envelope (EnvelopeEncodable implementation).
3018
+ */
3019
+ intoEnvelope() {
3020
+ return this.toEnvelope();
3021
+ }
3022
+ /**
3023
+ * Creates a request from an envelope.
3024
+ */
3025
+ static fromEnvelope(envelope, expectedFunction) {
3026
+ const bodyEnvelope = envelope.objectForPredicate(_bcts_known_values.BODY);
3027
+ if (bodyEnvelope === void 0) throw EnvelopeError.general("Request envelope missing body");
3028
+ const body = Expression.fromEnvelope(bodyEnvelope);
3029
+ if (expectedFunction !== void 0 && !body.function().equals(expectedFunction)) throw EnvelopeError.general("Request function mismatch");
3030
+ const leaf = envelope.subject().asLeaf();
3031
+ if (leaf === void 0) throw EnvelopeError.general("Request envelope has invalid subject");
3032
+ const aridBytes = leaf.expectTag(_bcts_tags.REQUEST).toByteString();
3033
+ const id = _bcts_components.ARID.fromData(aridBytes);
3034
+ let note = "";
3035
+ try {
3036
+ const noteObj = envelope.objectForPredicate(_bcts_known_values.NOTE);
3037
+ if (noteObj !== void 0) note = noteObj.asText() ?? "";
3038
+ } catch {}
3039
+ let date;
3040
+ try {
3041
+ const dateObj = envelope.objectForPredicate(_bcts_known_values.DATE);
3042
+ if (dateObj !== void 0) {
3043
+ const dateStr = dateObj.asText();
3044
+ if (dateStr !== void 0) date = new Date(dateStr);
3045
+ }
3046
+ } catch {}
3047
+ return new Request(body, id, note, date);
3048
+ }
3049
+ /**
3050
+ * Returns a string representation of the request.
3051
+ */
3052
+ toString() {
3053
+ return `Request(${this.summary()})`;
3054
+ }
3055
+ /**
3056
+ * Checks equality with another request.
3057
+ */
3058
+ equals(other) {
3059
+ return this.#id.equals(other.#id) && this.#note === other.#note && this.#date?.getTime() === other.#date?.getTime();
3060
+ }
3061
+ };
3062
+
3063
+ //#endregion
3064
+ //#region src/extension/response.ts
3065
+ /**
3066
+ * Response type for distributed function calls.
3067
+ *
3068
+ * Ported from bc-envelope-rust/src/extension/expressions/response.rs
3069
+ *
3070
+ * A Response represents a reply to a Request containing either a
3071
+ * successful result or an error.
3072
+ *
3073
+ * Responses are part of the expression system that enables distributed
3074
+ * function calls. Each response contains:
3075
+ * - A reference to the original request's ID (ARID) for correlation
3076
+ * - Either a successful result or an error message
3077
+ *
3078
+ * When serialized to an envelope, responses are tagged with RESPONSE tag.
3079
+ */
3080
+ /**
3081
+ * A Response represents a reply to a Request containing either a
3082
+ * successful result or an error.
3083
+ *
3084
+ * @example
3085
+ * ```typescript
3086
+ * import { Response, ARID } from '@bcts/envelope';
3087
+ *
3088
+ * // Create a request ID (normally this would come from the original request)
3089
+ * const requestId = ARID.new();
3090
+ *
3091
+ * // Create a successful response
3092
+ * const successResponse = Response.newSuccess(requestId)
3093
+ * .withResult("Transaction completed");
3094
+ *
3095
+ * // Create an error response
3096
+ * const errorResponse = Response.newFailure(requestId)
3097
+ * .withError("Insufficient funds");
3098
+ *
3099
+ * // Convert to envelopes
3100
+ * const successEnvelope = successResponse.toEnvelope();
3101
+ * const errorEnvelope = errorResponse.toEnvelope();
3102
+ * ```
3103
+ */
3104
+ var Response = class Response {
3105
+ #result;
3106
+ constructor(result) {
3107
+ this.#result = result;
3108
+ }
3109
+ /**
3110
+ * Creates a new successful response with the specified request ID.
3111
+ *
3112
+ * By default, the result will be the 'OK' known value. Use `withResult`
3113
+ * to set a specific result value.
3114
+ */
3115
+ static newSuccess(id) {
3116
+ return new Response({
3117
+ ok: true,
3118
+ id,
3119
+ result: Response.ok()
3120
+ });
3121
+ }
3122
+ /**
3123
+ * Creates a new failure response with the specified request ID.
3124
+ *
3125
+ * By default, the error will be the 'Unknown' known value. Use
3126
+ * `withError` to set a specific error message.
3127
+ */
3128
+ static newFailure(id) {
3129
+ return new Response({
3130
+ ok: false,
3131
+ id,
3132
+ error: Response.unknown()
3133
+ });
3134
+ }
3135
+ /**
3136
+ * Creates a new early failure response without a request ID.
3137
+ *
3138
+ * An early failure occurs when the error happens before the request
3139
+ * has been fully processed, so the request ID is not known.
3140
+ */
3141
+ static newEarlyFailure() {
3142
+ return new Response({
3143
+ ok: false,
3144
+ id: void 0,
3145
+ error: Response.unknown()
3146
+ });
3147
+ }
3148
+ /**
3149
+ * Creates an envelope containing the 'Unknown' known value.
3150
+ */
3151
+ static unknown() {
3152
+ return Envelope.new(_bcts_known_values.UNKNOWN_VALUE);
3153
+ }
3154
+ /**
3155
+ * Creates an envelope containing the 'OK' known value.
3156
+ */
3157
+ static ok() {
3158
+ return Envelope.new(_bcts_known_values.OK_VALUE);
3159
+ }
3160
+ /**
3161
+ * Returns a human-readable summary of the response.
3162
+ */
3163
+ summary() {
3164
+ if (this.#result.ok) return `id: ${this.#result.id.shortDescription()}, result: ${this.#result.result.formatFlat()}`;
3165
+ else return `id: ${this.#result.id !== void 0 ? this.#result.id.shortDescription() : "'Unknown'"}, error: ${this.#result.error.formatFlat()}`;
3166
+ }
3167
+ withResult(result) {
3168
+ if (!this.#result.ok) throw new Error("Cannot set result on a failed response");
3169
+ this.#result = {
3170
+ ok: true,
3171
+ id: this.#result.id,
3172
+ result: Envelope.new(result)
3173
+ };
3174
+ return this;
3175
+ }
3176
+ withOptionalResult(result) {
3177
+ if (result !== void 0) return this.withResult(result);
3178
+ return this.withResult(null);
3179
+ }
3180
+ withError(error) {
3181
+ if (this.#result.ok) throw new Error("Cannot set error on a successful response");
3182
+ this.#result = {
3183
+ ok: false,
3184
+ id: this.#result.id,
3185
+ error: Envelope.new(error)
3186
+ };
3187
+ return this;
3188
+ }
3189
+ withOptionalError(error) {
3190
+ if (error !== void 0) return this.withError(error);
3191
+ return this;
3192
+ }
3193
+ isOk() {
3194
+ return this.#result.ok;
3195
+ }
3196
+ isErr() {
3197
+ return !this.#result.ok;
3198
+ }
3199
+ id() {
3200
+ return this.#result.id;
3201
+ }
3202
+ expectId() {
3203
+ const id = this.id();
3204
+ if (id === void 0) throw new Error("Expected an ID");
3205
+ return id;
3206
+ }
3207
+ result() {
3208
+ if (!this.#result.ok) throw EnvelopeError.general("Cannot get result from failed response");
3209
+ return this.#result.result;
3210
+ }
3211
+ error() {
3212
+ if (this.#result.ok) throw EnvelopeError.general("Cannot get error from successful response");
3213
+ return this.#result.error;
3214
+ }
3215
+ /**
3216
+ * Extracts a typed result value from a successful response.
3217
+ */
3218
+ extractResult(decoder) {
3219
+ return this.result().extractSubject(decoder);
3220
+ }
3221
+ /**
3222
+ * Extracts a typed error value from a failure response.
3223
+ */
3224
+ extractError(decoder) {
3225
+ return this.error().extractSubject(decoder);
3226
+ }
3227
+ /**
3228
+ * Converts the response to an envelope.
3229
+ *
3230
+ * Successful responses have the request ID as the subject and a 'result'
3231
+ * assertion. Failure responses have the request ID (or 'Unknown' if not known)
3232
+ * as the subject and an 'error' assertion.
3233
+ */
3234
+ toEnvelope() {
3235
+ if (this.#result.ok) {
3236
+ const taggedArid = (0, _bcts_dcbor.toTaggedValue)(_bcts_tags.RESPONSE, this.#result.id.untaggedCbor());
3237
+ return Envelope.newLeaf(taggedArid).addAssertion(_bcts_known_values.RESULT, this.#result.result);
3238
+ } else {
3239
+ let subject;
3240
+ if (this.#result.id !== void 0) {
3241
+ const taggedArid = (0, _bcts_dcbor.toTaggedValue)(_bcts_tags.RESPONSE, this.#result.id.untaggedCbor());
3242
+ subject = Envelope.newLeaf(taggedArid);
3243
+ } else {
3244
+ const taggedUnknown = (0, _bcts_dcbor.toTaggedValue)(_bcts_tags.RESPONSE, _bcts_known_values.UNKNOWN_VALUE.untaggedCbor());
3245
+ subject = Envelope.newLeaf(taggedUnknown);
3246
+ }
3247
+ return subject.addAssertion(_bcts_known_values.ERROR, this.#result.error);
3248
+ }
3249
+ }
3250
+ /**
3251
+ * Converts this response into an envelope (EnvelopeEncodable implementation).
3252
+ */
3253
+ intoEnvelope() {
3254
+ return this.toEnvelope();
3255
+ }
3256
+ /**
3257
+ * Creates a response from an envelope.
3258
+ */
3259
+ static fromEnvelope(envelope) {
3260
+ let hasResult = false;
3261
+ let hasError = false;
3262
+ try {
3263
+ hasResult = envelope.objectForPredicate(_bcts_known_values.RESULT) !== void 0;
3264
+ } catch {}
3265
+ try {
3266
+ hasError = envelope.objectForPredicate(_bcts_known_values.ERROR) !== void 0;
3267
+ } catch {}
3268
+ if (hasResult === hasError) throw EnvelopeError.invalidResponse();
3269
+ const leaf = envelope.subject().asLeaf();
3270
+ if (leaf === void 0) throw EnvelopeError.general("Response envelope has invalid subject");
3271
+ const content = leaf.expectTag(_bcts_tags.RESPONSE);
3272
+ let id;
3273
+ const bytes = content.asByteString();
3274
+ if (bytes !== void 0) id = _bcts_components.ARID.fromData(bytes);
3275
+ if (hasResult) {
3276
+ const resultEnvelope = envelope.objectForPredicate(_bcts_known_values.RESULT);
3277
+ if (id === void 0) throw EnvelopeError.general("Successful response must have an ID");
3278
+ return new Response({
3279
+ ok: true,
3280
+ id,
3281
+ result: resultEnvelope ?? Response.ok()
3282
+ });
3283
+ } else {
3284
+ const errorEnvelope = envelope.objectForPredicate(_bcts_known_values.ERROR);
3285
+ return new Response({
3286
+ ok: false,
3287
+ id,
3288
+ error: errorEnvelope ?? Response.unknown()
3289
+ });
3290
+ }
3291
+ }
3292
+ /**
3293
+ * Returns a string representation of the response.
3294
+ */
3295
+ toString() {
3296
+ return `Response(${this.summary()})`;
3297
+ }
3298
+ /**
3299
+ * Checks equality with another response.
3300
+ */
3301
+ equals(other) {
3302
+ if (this.#result.ok !== other.#result.ok) return false;
3303
+ if (this.#result.ok && other.#result.ok) return this.#result.id.equals(other.#result.id);
3304
+ if (!this.#result.ok && !other.#result.ok) {
3305
+ if (this.#result.id === void 0 && other.#result.id === void 0) return true;
3306
+ if (this.#result.id !== void 0 && other.#result.id !== void 0) return this.#result.id.equals(other.#result.id);
3307
+ return false;
3308
+ }
3309
+ return false;
3310
+ }
3311
+ };
3312
+
3313
+ //#endregion
3314
+ //#region src/extension/event.ts
3315
+ /**
3316
+ * Event type for notifications and messages.
3317
+ *
3318
+ * Ported from bc-envelope-rust/src/extension/expressions/event.rs
3319
+ *
3320
+ * An Event represents a notification or message that doesn't expect a
3321
+ * response.
3322
+ *
3323
+ * Unlike Request and Response which form a pair, an Event is a
3324
+ * standalone message that can be used for broadcasting information, logging,
3325
+ * or publishing notifications. Events are used when the sender does not expect
3326
+ * or require a response from the recipients.
3327
+ *
3328
+ * Each event contains:
3329
+ * - Content of a generic type that holds the event payload
3330
+ * - A unique identifier (ARID) for tracking and correlation
3331
+ * - Optional metadata like a note and timestamp
3332
+ *
3333
+ * When serialized to an envelope, events are tagged with EVENT tag.
3334
+ */
3335
+ /**
3336
+ * An Event represents a notification or message that doesn't expect a response.
3337
+ *
3338
+ * @example
3339
+ * ```typescript
3340
+ * import { Event, ARID } from '@bcts/envelope';
3341
+ *
3342
+ * // Create a status update event
3343
+ * const eventId = ARID.new();
3344
+ * const timestamp = new Date("2024-08-15T13:45:30Z");
3345
+ *
3346
+ * const statusEvent = Event.new("System online", eventId)
3347
+ * .withNote("Regular status update")
3348
+ * .withDate(timestamp);
3349
+ *
3350
+ * // Convert to an envelope for transmission
3351
+ * const envelope = statusEvent.toEnvelope();
3352
+ * ```
3353
+ *
3354
+ * @typeParam T - The type of content this event carries
3355
+ */
3356
+ var Event = class Event {
3357
+ #content;
3358
+ #id;
3359
+ #note;
3360
+ #date;
3361
+ constructor(content, id, note = "", date) {
3362
+ this.#content = content;
3363
+ this.#id = id;
3364
+ this.#note = note;
3365
+ this.#date = date;
3366
+ }
3367
+ /**
3368
+ * Creates a new event with the specified content and ID.
3369
+ */
3370
+ static new(content, id) {
3371
+ return new Event(content, id);
3372
+ }
3373
+ /**
3374
+ * Returns a human-readable summary of the event.
3375
+ */
3376
+ summary() {
3377
+ const contentEnvelope = Envelope.new(this.#content);
3378
+ return `id: ${this.#id.shortDescription()}, content: ${contentEnvelope.formatFlat()}`;
3379
+ }
3380
+ withNote(note) {
3381
+ this.#note = note;
3382
+ return this;
3383
+ }
3384
+ withDate(date) {
3385
+ this.#date = date;
3386
+ return this;
3387
+ }
3388
+ content() {
3389
+ return this.#content;
3390
+ }
3391
+ id() {
3392
+ return this.#id;
3393
+ }
3394
+ note() {
3395
+ return this.#note;
3396
+ }
3397
+ date() {
3398
+ return this.#date;
3399
+ }
3400
+ /**
3401
+ * Converts the event to an envelope.
3402
+ *
3403
+ * The envelope's subject is the event's ID tagged with TAG_EVENT,
3404
+ * and assertions include the event's content, note (if not empty), and date
3405
+ * (if present).
3406
+ */
3407
+ toEnvelope() {
3408
+ const taggedArid = (0, _bcts_dcbor.toTaggedValue)(_bcts_tags.EVENT, this.#id.untaggedCbor());
3409
+ const contentEnvelope = Envelope.new(this.#content);
3410
+ let envelope = Envelope.newLeaf(taggedArid).addAssertion(_bcts_known_values.CONTENT, contentEnvelope);
3411
+ if (this.#note !== "") envelope = envelope.addAssertion(_bcts_known_values.NOTE, this.#note);
3412
+ if (this.#date !== void 0) envelope = envelope.addAssertion(_bcts_known_values.DATE, this.#date.toISOString());
3413
+ return envelope;
3414
+ }
3415
+ /**
3416
+ * Converts this event into an envelope (EnvelopeEncodable implementation).
3417
+ */
3418
+ intoEnvelope() {
3419
+ return this.toEnvelope();
3420
+ }
3421
+ /**
3422
+ * Creates an event from an envelope.
3423
+ *
3424
+ * @typeParam T - The type to extract the content as
3425
+ */
3426
+ static fromEnvelope(envelope, contentExtractor) {
3427
+ const contentEnvelope = envelope.objectForPredicate(_bcts_known_values.CONTENT);
3428
+ if (contentEnvelope === void 0) throw EnvelopeError.general("Event envelope missing content");
3429
+ const content = contentExtractor(contentEnvelope);
3430
+ const leaf = envelope.subject().asLeaf();
3431
+ if (leaf === void 0) throw EnvelopeError.general("Event envelope has invalid subject");
3432
+ const aridBytes = leaf.expectTag(_bcts_tags.EVENT).toByteString();
3433
+ const id = _bcts_components.ARID.fromData(aridBytes);
3434
+ let note = "";
3435
+ try {
3436
+ const noteObj = envelope.objectForPredicate(_bcts_known_values.NOTE);
3437
+ if (noteObj !== void 0) note = noteObj.asText() ?? "";
3438
+ } catch {}
3439
+ let date;
3440
+ try {
3441
+ const dateObj = envelope.objectForPredicate(_bcts_known_values.DATE);
3442
+ if (dateObj !== void 0) {
3443
+ const dateStr = dateObj.asText();
3444
+ if (dateStr !== void 0) date = new Date(dateStr);
3445
+ }
3446
+ } catch {}
3447
+ return new Event(content, id, note, date);
3448
+ }
3449
+ /**
3450
+ * Creates a string event from an envelope.
3451
+ */
3452
+ static stringFromEnvelope(envelope) {
3453
+ return Event.fromEnvelope(envelope, (env) => env.asText() ?? "");
3454
+ }
3455
+ /**
3456
+ * Returns a string representation of the event.
3457
+ */
3458
+ toString() {
3459
+ return `Event(${this.summary()})`;
3460
+ }
3461
+ /**
3462
+ * Checks equality with another event.
3463
+ */
3464
+ equals(other) {
3465
+ return this.#id.equals(other.#id) && this.#note === other.#note && this.#date?.getTime() === other.#date?.getTime();
3466
+ }
3467
+ };
3468
+
3469
+ //#endregion
3470
+ //#region src/format/tree.ts
3471
+ /**
3472
+ * Specifies the format for displaying envelope digests in tree output.
3473
+ *
3474
+ * Ported from bc-envelope-rust/src/format/tree/format/digest.rs
3475
+ */
3476
+ let DigestDisplayFormat = /* @__PURE__ */ function(DigestDisplayFormat$1) {
3477
+ /**
3478
+ * Short format: first 7 hex characters of the digest.
3479
+ * This is the default format.
3480
+ */
3481
+ DigestDisplayFormat$1["Short"] = "short";
3482
+ /**
3483
+ * Full format: complete 64 hex character digest.
3484
+ */
3485
+ DigestDisplayFormat$1["Full"] = "full";
3486
+ /**
3487
+ * UR format: digest encoded as a UR string.
3488
+ */
3489
+ DigestDisplayFormat$1["UR"] = "ur";
3490
+ return DigestDisplayFormat$1;
3491
+ }({});
3492
+ Envelope.prototype.shortId = function(format = "short") {
3493
+ const digest = this.digest();
3494
+ if (format === "full") return digest.hex();
3495
+ if (format === "ur") return digest.urString();
3496
+ return digest.short();
3497
+ };
3498
+ Envelope.prototype.summary = function(maxLength = 40) {
3499
+ switch (this.case().type) {
3500
+ case "node": return "NODE";
3501
+ case "leaf": {
3502
+ try {
3503
+ const text = this.asText();
3504
+ if (text !== void 0) {
3505
+ const truncated = text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
3506
+ return JSON.stringify(truncated);
3507
+ }
3508
+ } catch {}
3509
+ try {
3510
+ const num = this.extractNumber();
3511
+ return String(num);
3512
+ } catch {}
3513
+ try {
3514
+ const bool = this.extractBoolean();
3515
+ return String(bool);
3516
+ } catch {}
3517
+ if (this.isNull()) return "null";
3518
+ const bytes = this.asByteString();
3519
+ if (bytes !== void 0 && bytes.length <= 16) return `h'${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
3520
+ return "LEAF";
3521
+ }
3522
+ case "wrapped": return "WRAPPED";
3523
+ case "assertion": return "ASSERTION";
3524
+ case "elided": return "ELIDED";
3525
+ case "encrypted": return "ENCRYPTED";
3526
+ case "compressed": return "COMPRESSED";
3527
+ case "knownValue": return "KNOWN_VALUE";
3528
+ default: return "UNKNOWN";
3529
+ }
3530
+ };
3531
+ Envelope.prototype.treeFormat = function(options = {}) {
3532
+ const hideNodes = options.hideNodes ?? false;
3533
+ const highlightDigests = options.highlightDigests ?? /* @__PURE__ */ new Set();
3534
+ const digestDisplay = options.digestDisplay ?? "short";
2518
3535
  const elements = [];
2519
3536
  this.walk(hideNodes, void 0, (envelope, level, incomingEdge, _state) => {
2520
3537
  const digestStr = envelope.digest().short();
@@ -2540,6 +3557,650 @@ Envelope.prototype.treeFormat = function(options = {}) {
2540
3557
  }).join("\n");
2541
3558
  };
2542
3559
 
3560
+ //#endregion
3561
+ //#region src/format/format-context.ts
3562
+ const formatContextNone = () => ({ type: "none" });
3563
+ const formatContextGlobal = () => ({ type: "global" });
3564
+ const formatContextCustom = (context) => ({
3565
+ type: "custom",
3566
+ context
3567
+ });
3568
+ var FormatContext = class FormatContext {
3569
+ #tags;
3570
+ #knownValues;
3571
+ constructor(tags, knownValues) {
3572
+ this.#tags = tags ?? new _bcts_dcbor.TagsStore();
3573
+ this.#knownValues = knownValues ?? new _bcts_known_values.KnownValuesStore();
3574
+ }
3575
+ tags() {
3576
+ return this.#tags;
3577
+ }
3578
+ knownValues() {
3579
+ return this.#knownValues;
3580
+ }
3581
+ assignedNameForTag(tag) {
3582
+ return this.#tags.assignedNameForTag(tag);
3583
+ }
3584
+ nameForTag(tag) {
3585
+ return this.#tags.nameForTag(tag);
3586
+ }
3587
+ tagForValue(value) {
3588
+ return this.#tags.tagForValue(value);
3589
+ }
3590
+ tagForName(name) {
3591
+ return this.#tags.tagForName(name);
3592
+ }
3593
+ nameForValue(value) {
3594
+ return this.#tags.nameForValue(value);
3595
+ }
3596
+ summarizer(tag) {
3597
+ return this.#tags.summarizer(tag);
3598
+ }
3599
+ registerTag(value, name) {
3600
+ this.#tags.insert({
3601
+ value: BigInt(value),
3602
+ name
3603
+ });
3604
+ }
3605
+ clone() {
3606
+ return new FormatContext(this.#tags, this.#knownValues);
3607
+ }
3608
+ };
3609
+ let _globalFormatContextInstance;
3610
+ let isInitialized = false;
3611
+ const getGlobalFormatContext = () => {
3612
+ if (!isInitialized) {
3613
+ (0, _bcts_dcbor.registerTags)();
3614
+ _globalFormatContextInstance = new FormatContext((0, _bcts_dcbor.getGlobalTagsStore)(), _bcts_known_values.KNOWN_VALUES.get());
3615
+ isInitialized = true;
3616
+ setupKnownValueSummarizer(_globalFormatContextInstance);
3617
+ }
3618
+ return _globalFormatContextInstance;
3619
+ };
3620
+ const withFormatContext = (action) => {
3621
+ return action(getGlobalFormatContext());
3622
+ };
3623
+ const withFormatContextMut = (action) => {
3624
+ return action(getGlobalFormatContext());
3625
+ };
3626
+ const setupKnownValueSummarizer = (context) => {
3627
+ const knownValues = context.knownValues();
3628
+ const tags = context.tags();
3629
+ const summarizer = (cbor$1, _flat) => {
3630
+ try {
3631
+ const kv = _bcts_known_values.KnownValue.fromUntaggedCbor(cbor$1);
3632
+ return {
3633
+ ok: true,
3634
+ value: `'${knownValues.name(kv)}'`
3635
+ };
3636
+ } catch {
3637
+ return {
3638
+ ok: true,
3639
+ value: "'<unknown>'"
3640
+ };
3641
+ }
3642
+ };
3643
+ tags.setSummarizer(BigInt(_bcts_known_values.TAG_KNOWN_VALUE), summarizer);
3644
+ };
3645
+ const registerTagsIn = (context) => {
3646
+ (0, _bcts_dcbor.registerTags)();
3647
+ setupKnownValueSummarizer(context);
3648
+ };
3649
+ const registerTags = () => {
3650
+ withFormatContextMut((context) => {
3651
+ registerTagsIn(context);
3652
+ });
3653
+ };
3654
+ const globalFormatContext = getGlobalFormatContext;
3655
+ const GLOBAL_FORMAT_CONTEXT = { get: getGlobalFormatContext };
3656
+
3657
+ //#endregion
3658
+ //#region src/format/envelope-summary.ts
3659
+ const flankedBy = (s, prefix, suffix) => {
3660
+ return `${prefix}${s}${suffix}`;
3661
+ };
3662
+ const cborEnvelopeSummary = (cbor$1, maxLength, context) => {
3663
+ if ((0, _bcts_dcbor.isUnsigned)(cbor$1)) return String(cbor$1);
3664
+ if ((0, _bcts_dcbor.isNegative)(cbor$1)) {
3665
+ const n = cbor$1;
3666
+ return String(-1n - n);
3667
+ }
3668
+ if ((0, _bcts_dcbor.isBytes)(cbor$1)) return `Bytes(${cbor$1.length})`;
3669
+ if ((0, _bcts_dcbor.isText)(cbor$1)) {
3670
+ let text = (0, _bcts_dcbor.asText)(cbor$1) ?? "";
3671
+ if (text.length > maxLength) text = `${text.substring(0, maxLength)}…`;
3672
+ text = text.replace(/\n/g, "\\n");
3673
+ return flankedBy(text, "\"", "\"");
3674
+ }
3675
+ if ((0, _bcts_dcbor.isSimple)(cbor$1)) {
3676
+ const value = cbor$1;
3677
+ if (value === true) return "true";
3678
+ if (value === false) return "false";
3679
+ if (value === null) return "null";
3680
+ if (value === void 0) return "undefined";
3681
+ if (typeof value === "number") {
3682
+ if (Number.isNaN(value)) return "NaN";
3683
+ if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
3684
+ return String(value);
3685
+ }
3686
+ return (0, _bcts_dcbor.diagnosticOpt)(cbor$1, { summarize: true });
3687
+ }
3688
+ if ((0, _bcts_dcbor.isArray)(cbor$1) || (0, _bcts_dcbor.isMap)(cbor$1) || (0, _bcts_dcbor.isTagged)(cbor$1)) {
3689
+ const opts = { summarize: true };
3690
+ if (context.type === "custom") return (0, _bcts_dcbor.diagnosticOpt)(cbor$1, {
3691
+ ...opts,
3692
+ tags: context.context.tags()
3693
+ });
3694
+ else if (context.type === "global") {
3695
+ const ctx = getGlobalFormatContext();
3696
+ return (0, _bcts_dcbor.diagnosticOpt)(cbor$1, {
3697
+ ...opts,
3698
+ tags: ctx.tags()
3699
+ });
3700
+ } else return (0, _bcts_dcbor.diagnosticOpt)(cbor$1, opts);
3701
+ }
3702
+ return String(cbor$1);
3703
+ };
3704
+ Envelope.prototype.summaryWithContext = function(maxLength, context) {
3705
+ const c = this.case();
3706
+ switch (c.type) {
3707
+ case "node": return "NODE";
3708
+ case "leaf": return cborEnvelopeSummary(c.cbor, maxLength, {
3709
+ type: "custom",
3710
+ context
3711
+ });
3712
+ case "wrapped": return "WRAPPED";
3713
+ case "assertion": return "ASSERTION";
3714
+ case "elided": return "ELIDED";
3715
+ case "knownValue": return flankedBy(context.knownValues().name(c.value), "'", "'");
3716
+ case "encrypted": return "ENCRYPTED";
3717
+ case "compressed": return "COMPRESSED";
3718
+ default: return "UNKNOWN";
3719
+ }
3720
+ };
3721
+
3722
+ //#endregion
3723
+ //#region src/format/notation.ts
3724
+ const defaultFormatOpts = () => ({
3725
+ flat: false,
3726
+ context: formatContextGlobal()
3727
+ });
3728
+ const flatFormatOpts = () => ({
3729
+ flat: true,
3730
+ context: formatContextGlobal()
3731
+ });
3732
+ const formatBegin = (value) => ({
3733
+ type: "begin",
3734
+ value
3735
+ });
3736
+ const formatEnd = (value) => ({
3737
+ type: "end",
3738
+ value
3739
+ });
3740
+ const formatItem = (value) => ({
3741
+ type: "item",
3742
+ value
3743
+ });
3744
+ const formatSeparator = () => ({ type: "separator" });
3745
+ const formatList = (items) => ({
3746
+ type: "list",
3747
+ items
3748
+ });
3749
+ const flatten = (item) => {
3750
+ if (item.type === "list") return item.items.flatMap(flatten);
3751
+ return [item];
3752
+ };
3753
+ const nicen = (items) => {
3754
+ const input = [...items];
3755
+ const result = [];
3756
+ while (input.length > 0) {
3757
+ const current = input.shift();
3758
+ if (input.length === 0) {
3759
+ result.push(current);
3760
+ break;
3761
+ }
3762
+ if (current.type === "end" && input[0]?.type === "begin") {
3763
+ const endString = current.value;
3764
+ const beginString = input[0].value;
3765
+ result.push(formatEnd(`${endString} ${beginString}`));
3766
+ result.push(formatBegin(""));
3767
+ input.shift();
3768
+ } else result.push(current);
3769
+ }
3770
+ return result;
3771
+ };
3772
+ const indent = (level) => " ".repeat(level * 4);
3773
+ const addSpaceAtEndIfNeeded = (s) => {
3774
+ if (s.length === 0) return " ";
3775
+ if (s.endsWith(" ")) return s;
3776
+ return `${s} `;
3777
+ };
3778
+ const formatFlat = (item) => {
3779
+ let line = "";
3780
+ const items = flatten(item);
3781
+ for (const i of items) switch (i.type) {
3782
+ case "begin":
3783
+ if (!line.endsWith(" ")) line += " ";
3784
+ line += `${i.value} `;
3785
+ break;
3786
+ case "end":
3787
+ if (!line.endsWith(" ")) line += " ";
3788
+ line += `${i.value} `;
3789
+ break;
3790
+ case "item":
3791
+ line += i.value;
3792
+ break;
3793
+ case "separator":
3794
+ line = `${line.trimEnd()}, `;
3795
+ break;
3796
+ case "list":
3797
+ for (const subItem of i.items) line += formatFlat(subItem);
3798
+ break;
3799
+ }
3800
+ return line;
3801
+ };
3802
+ const formatHierarchical = (item) => {
3803
+ const lines = [];
3804
+ let level = 0;
3805
+ let currentLine = "";
3806
+ const items = nicen(flatten(item));
3807
+ for (const i of items) switch (i.type) {
3808
+ case "begin": {
3809
+ const delimiter = i.value;
3810
+ if (delimiter.length > 0) {
3811
+ const c = currentLine.length === 0 ? delimiter : `${addSpaceAtEndIfNeeded(currentLine)}${delimiter}`;
3812
+ lines.push(`${indent(level)}${c}\n`);
3813
+ }
3814
+ level += 1;
3815
+ currentLine = "";
3816
+ break;
3817
+ }
3818
+ case "end": {
3819
+ const delimiter = i.value;
3820
+ if (currentLine.length > 0) {
3821
+ lines.push(`${indent(level)}${currentLine}\n`);
3822
+ currentLine = "";
3823
+ }
3824
+ level -= 1;
3825
+ lines.push(`${indent(level)}${delimiter}\n`);
3826
+ break;
3827
+ }
3828
+ case "item":
3829
+ currentLine += i.value;
3830
+ break;
3831
+ case "separator":
3832
+ if (currentLine.length > 0) {
3833
+ lines.push(`${indent(level)}${currentLine}\n`);
3834
+ currentLine = "";
3835
+ }
3836
+ break;
3837
+ case "list":
3838
+ lines.push("<list>");
3839
+ break;
3840
+ }
3841
+ if (currentLine.length > 0) lines.push(currentLine);
3842
+ return lines.join("");
3843
+ };
3844
+ const formatFormatItem = (item, opts) => {
3845
+ if (opts.flat) return formatFlat(item);
3846
+ return formatHierarchical(item);
3847
+ };
3848
+ const formatCbor = (cbor$1, opts) => {
3849
+ if ((0, _bcts_dcbor.isTagged)(cbor$1)) {
3850
+ const tag = (0, _bcts_dcbor.tagValue)(cbor$1);
3851
+ if (tag === 200n || tag === 200) try {
3852
+ return formatEnvelope(Envelope.fromTaggedCbor(cbor$1), opts);
3853
+ } catch {
3854
+ return formatItem("<error>");
3855
+ }
3856
+ }
3857
+ return formatItem(cborEnvelopeSummary(cbor$1, Number.MAX_SAFE_INTEGER, opts.context));
3858
+ };
3859
+ const formatAssertion = (assertion, opts) => {
3860
+ return formatList([
3861
+ formatEnvelope(assertion.predicate(), opts),
3862
+ formatItem(": "),
3863
+ formatEnvelope(assertion.object(), opts)
3864
+ ]);
3865
+ };
3866
+ const formatEnvelope = (envelope, opts) => {
3867
+ const c = envelope.case();
3868
+ switch (c.type) {
3869
+ case "leaf": return formatCbor(c.cbor, opts);
3870
+ case "wrapped": return formatList([
3871
+ formatBegin("{"),
3872
+ formatEnvelope(c.envelope, opts),
3873
+ formatEnd("}")
3874
+ ]);
3875
+ case "assertion": return formatAssertion(c.assertion, opts);
3876
+ case "knownValue": {
3877
+ let name;
3878
+ if (opts.context.type === "custom") name = opts.context.context.knownValues().assignedName(c.value) ?? c.value.name();
3879
+ else if (opts.context.type === "global") name = getGlobalFormatContext().knownValues().assignedName(c.value) ?? c.value.name();
3880
+ else name = c.value.name();
3881
+ return formatItem(`'${name}'`);
3882
+ }
3883
+ case "encrypted": return formatItem("ENCRYPTED");
3884
+ case "compressed": return formatItem("COMPRESSED");
3885
+ case "elided": return formatItem("ELIDED");
3886
+ case "node": {
3887
+ const items = [];
3888
+ const subjectItem = formatEnvelope(c.subject, opts);
3889
+ let elidedCount = 0;
3890
+ let encryptedCount = 0;
3891
+ let compressedCount = 0;
3892
+ const typeAssertionItems = [];
3893
+ const assertionItems = [];
3894
+ for (const assertion of c.assertions) switch (assertion.case().type) {
3895
+ case "elided":
3896
+ elidedCount += 1;
3897
+ break;
3898
+ case "encrypted":
3899
+ encryptedCount += 1;
3900
+ break;
3901
+ case "compressed":
3902
+ compressedCount += 1;
3903
+ break;
3904
+ case "node":
3905
+ case "leaf":
3906
+ case "wrapped":
3907
+ case "assertion":
3908
+ case "knownValue": {
3909
+ const item = [formatEnvelope(assertion, opts)];
3910
+ let isTypeAssertion = false;
3911
+ if (assertion.asPredicate()?.subject().asKnownValue()?.equals(_bcts_known_values.IS_A) === true) isTypeAssertion = true;
3912
+ if (isTypeAssertion) typeAssertionItems.push(item);
3913
+ else assertionItems.push(item);
3914
+ break;
3915
+ }
3916
+ }
3917
+ typeAssertionItems.sort((a, b) => compareFormatItems(a[0], b[0]));
3918
+ assertionItems.sort((a, b) => compareFormatItems(a[0], b[0]));
3919
+ const allAssertionItems = [...typeAssertionItems, ...assertionItems];
3920
+ if (compressedCount > 1) allAssertionItems.push([formatItem(`COMPRESSED (${compressedCount})`)]);
3921
+ else if (compressedCount > 0) allAssertionItems.push([formatItem("COMPRESSED")]);
3922
+ if (elidedCount > 1) allAssertionItems.push([formatItem(`ELIDED (${elidedCount})`)]);
3923
+ else if (elidedCount > 0) allAssertionItems.push([formatItem("ELIDED")]);
3924
+ if (encryptedCount > 1) allAssertionItems.push([formatItem(`ENCRYPTED (${encryptedCount})`)]);
3925
+ else if (encryptedCount > 0) allAssertionItems.push([formatItem("ENCRYPTED")]);
3926
+ const joinedAssertionItems = [];
3927
+ for (let i = 0; i < allAssertionItems.length; i++) {
3928
+ if (i > 0) joinedAssertionItems.push(formatSeparator());
3929
+ joinedAssertionItems.push(...allAssertionItems[i]);
3930
+ }
3931
+ const needsBraces = c.subject.isSubjectAssertion();
3932
+ if (needsBraces) items.push(formatBegin("{"));
3933
+ items.push(subjectItem);
3934
+ if (needsBraces) items.push(formatEnd("}"));
3935
+ items.push(formatBegin("["));
3936
+ items.push(...joinedAssertionItems);
3937
+ items.push(formatEnd("]"));
3938
+ return formatList(items);
3939
+ }
3940
+ }
3941
+ };
3942
+ const compareFormatItems = (a, b) => {
3943
+ const getIndex = (item) => {
3944
+ switch (item.type) {
3945
+ case "begin": return 1;
3946
+ case "end": return 2;
3947
+ case "item": return 3;
3948
+ case "separator": return 4;
3949
+ case "list": return 5;
3950
+ }
3951
+ };
3952
+ const aIndex = getIndex(a);
3953
+ const bIndex = getIndex(b);
3954
+ if (aIndex !== bIndex) return aIndex - bIndex;
3955
+ if (a.type === "item" && b.type === "item") return a.value.localeCompare(b.value);
3956
+ if (a.type === "begin" && b.type === "begin") return a.value.localeCompare(b.value);
3957
+ if (a.type === "end" && b.type === "end") return a.value.localeCompare(b.value);
3958
+ return 0;
3959
+ };
3960
+ Envelope.prototype.formatOpt = function(opts) {
3961
+ return formatFormatItem(formatEnvelope(this, opts), opts).trim();
3962
+ };
3963
+ Envelope.prototype.format = function() {
3964
+ return this.formatOpt(defaultFormatOpts());
3965
+ };
3966
+ Envelope.prototype.formatFlat = function() {
3967
+ return this.formatOpt(flatFormatOpts());
3968
+ };
3969
+
3970
+ //#endregion
3971
+ //#region src/format/mermaid.ts
3972
+ let MermaidOrientation = /* @__PURE__ */ function(MermaidOrientation$1) {
3973
+ MermaidOrientation$1["LeftToRight"] = "LR";
3974
+ MermaidOrientation$1["TopToBottom"] = "TB";
3975
+ MermaidOrientation$1["RightToLeft"] = "RL";
3976
+ MermaidOrientation$1["BottomToTop"] = "BT";
3977
+ return MermaidOrientation$1;
3978
+ }({});
3979
+ let MermaidTheme = /* @__PURE__ */ function(MermaidTheme$1) {
3980
+ MermaidTheme$1["Default"] = "default";
3981
+ MermaidTheme$1["Neutral"] = "neutral";
3982
+ MermaidTheme$1["Dark"] = "dark";
3983
+ MermaidTheme$1["Forest"] = "forest";
3984
+ MermaidTheme$1["Base"] = "base";
3985
+ return MermaidTheme$1;
3986
+ }({});
3987
+ const defaultMermaidOpts = () => ({
3988
+ hideNodes: false,
3989
+ monochrome: false,
3990
+ theme: MermaidTheme.Default,
3991
+ orientation: MermaidOrientation.LeftToRight,
3992
+ highlightingTarget: /* @__PURE__ */ new Set()
3993
+ });
3994
+ Envelope.prototype.mermaidFormat = function() {
3995
+ return this.mermaidFormatOpt(defaultMermaidOpts());
3996
+ };
3997
+ Envelope.prototype.mermaidFormatOpt = function(opts) {
3998
+ const hideNodes = opts.hideNodes ?? false;
3999
+ const monochrome = opts.monochrome ?? false;
4000
+ const theme = opts.theme ?? MermaidTheme.Default;
4001
+ const orientation = opts.orientation ?? MermaidOrientation.LeftToRight;
4002
+ const highlightingTarget = opts.highlightingTarget ?? /* @__PURE__ */ new Set();
4003
+ const elements = [];
4004
+ let nextId = 0;
4005
+ const parentStack = [];
4006
+ this.walk(hideNodes, void 0, (envelope, level, incomingEdge, _state) => {
4007
+ const id = nextId++;
4008
+ let parent;
4009
+ while (parentStack.length > 0 && parentStack[parentStack.length - 1].level >= level) parentStack.pop();
4010
+ if (parentStack.length > 0) parent = parentStack[parentStack.length - 1];
4011
+ const isHighlighted = containsDigest(highlightingTarget, envelope.digest());
4012
+ const elem = {
4013
+ id,
4014
+ level,
4015
+ envelope,
4016
+ incomingEdge,
4017
+ showId: !hideNodes,
4018
+ isHighlighted,
4019
+ parent
4020
+ };
4021
+ elements.push(elem);
4022
+ parentStack.push(elem);
4023
+ return [void 0, false];
4024
+ });
4025
+ const formattedIds = /* @__PURE__ */ new Set();
4026
+ const lines = [`%%{ init: { 'theme': '${theme}', 'flowchart': { 'curve': 'basis' } } }%%`, `graph ${orientation}`];
4027
+ const nodeStyles = [];
4028
+ const linkStyles = [];
4029
+ let linkIndex = 0;
4030
+ for (const element of elements) {
4031
+ const indent$1 = " ".repeat(element.level);
4032
+ let content;
4033
+ if (element.parent !== void 0) {
4034
+ const thisLinkStyles = [];
4035
+ if (!monochrome) {
4036
+ const strokeColor = linkStrokeColor(element.incomingEdge);
4037
+ if (strokeColor !== void 0) thisLinkStyles.push(`stroke:${strokeColor}`);
4038
+ }
4039
+ if (element.isHighlighted && element.parent.isHighlighted) thisLinkStyles.push("stroke-width:4px");
4040
+ else thisLinkStyles.push("stroke-width:2px");
4041
+ if (thisLinkStyles.length > 0) linkStyles.push(`linkStyle ${linkIndex} ${thisLinkStyles.join(",")}`);
4042
+ linkIndex++;
4043
+ content = formatEdge(element, formattedIds);
4044
+ } else content = formatNode(element, formattedIds);
4045
+ const thisNodeStyles = [];
4046
+ if (!monochrome) {
4047
+ const strokeColor = nodeColor(element.envelope);
4048
+ thisNodeStyles.push(`stroke:${strokeColor}`);
4049
+ }
4050
+ if (element.isHighlighted) thisNodeStyles.push("stroke-width:6px");
4051
+ else thisNodeStyles.push("stroke-width:4px");
4052
+ if (thisNodeStyles.length > 0) nodeStyles.push(`style ${element.id} ${thisNodeStyles.join(",")}`);
4053
+ lines.push(`${indent$1}${content}`);
4054
+ }
4055
+ for (const style of nodeStyles) lines.push(style);
4056
+ for (const style of linkStyles) lines.push(style);
4057
+ return lines.join("\n");
4058
+ };
4059
+ const containsDigest = (set, digest) => {
4060
+ for (const d of set) if (d.equals(digest)) return true;
4061
+ return false;
4062
+ };
4063
+ const formatNode = (element, formattedIds) => {
4064
+ if (!formattedIds.has(element.id)) {
4065
+ formattedIds.add(element.id);
4066
+ const lines = [];
4067
+ const summary = withFormatContext((ctx) => {
4068
+ return element.envelope.summaryWithContext(20, ctx).replace(/"/g, "&quot;");
4069
+ });
4070
+ lines.push(summary);
4071
+ if (element.showId) {
4072
+ const id = element.envelope.digest().short();
4073
+ lines.push(id);
4074
+ }
4075
+ const content = lines.join("<br>");
4076
+ const [frameL, frameR] = mermaidFrame(element.envelope);
4077
+ return `${element.id}${frameL}"${content}"${frameR}`;
4078
+ } else return `${element.id}`;
4079
+ };
4080
+ const formatEdge = (element, formattedIds) => {
4081
+ const parent = element.parent;
4082
+ const label = edgeLabel(element.incomingEdge);
4083
+ const arrow = label !== void 0 ? `-- ${label} -->` : "-->";
4084
+ return `${formatNode(parent, formattedIds)} ${arrow} ${formatNode(element, formattedIds)}`;
4085
+ };
4086
+ const mermaidFrame = (envelope) => {
4087
+ switch (envelope.case().type) {
4088
+ case "node": return ["((", "))"];
4089
+ case "leaf": return ["[", "]"];
4090
+ case "wrapped": return ["[/", "\\]"];
4091
+ case "assertion": return ["([", "])"];
4092
+ case "elided": return ["{{", "}}"];
4093
+ case "knownValue": return ["[/", "/]"];
4094
+ case "encrypted": return [">", "]"];
4095
+ case "compressed": return ["[[", "]]"];
4096
+ default: return ["[", "]"];
4097
+ }
4098
+ };
4099
+ const nodeColor = (envelope) => {
4100
+ switch (envelope.case().type) {
4101
+ case "node": return "red";
4102
+ case "leaf": return "teal";
4103
+ case "wrapped": return "blue";
4104
+ case "assertion": return "green";
4105
+ case "elided": return "gray";
4106
+ case "knownValue": return "goldenrod";
4107
+ case "encrypted": return "coral";
4108
+ case "compressed": return "purple";
4109
+ default: return "gray";
4110
+ }
4111
+ };
4112
+ const linkStrokeColor = (edgeType) => {
4113
+ switch (edgeType) {
4114
+ case EdgeType.Subject: return "red";
4115
+ case EdgeType.Content: return "blue";
4116
+ case EdgeType.Predicate: return "cyan";
4117
+ case EdgeType.Object: return "magenta";
4118
+ case EdgeType.None:
4119
+ case EdgeType.Assertion: return;
4120
+ }
4121
+ };
4122
+ const registerMermaidExtension = () => {};
4123
+
4124
+ //#endregion
4125
+ //#region src/format/hex.ts
4126
+ Envelope.prototype.hex = function() {
4127
+ const bytes = this.cborBytes();
4128
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
4129
+ };
4130
+ Envelope.prototype.cborBytes = function() {
4131
+ return (0, _bcts_dcbor.cborData)(this.taggedCbor());
4132
+ };
4133
+
4134
+ //#endregion
4135
+ //#region src/format/diagnostic.ts
4136
+ function cborToDiagnostic(cbor$1, indent$1 = 0) {
4137
+ if (typeof cbor$1 === "object" && cbor$1 !== null && "tag" in cbor$1 && "value" in cbor$1) {
4138
+ const tagged = cbor$1;
4139
+ return `${tagged.tag}(${cborToDiagnostic(tagged.value, indent$1)})`;
4140
+ }
4141
+ if (Array.isArray(cbor$1)) {
4142
+ if (cbor$1.length === 0) return "[]";
4143
+ return `[${cbor$1.map((item) => cborToDiagnostic(item, indent$1 + 2)).join(", ")}]`;
4144
+ }
4145
+ if (cbor$1 instanceof Map) {
4146
+ if (cbor$1.size === 0) return "{}";
4147
+ const entries = [];
4148
+ for (const [key, value] of cbor$1) {
4149
+ const keyStr = cborToDiagnostic(key, indent$1 + 2);
4150
+ const valueStr = cborToDiagnostic(value, indent$1 + 2);
4151
+ entries.push(`${keyStr}: ${valueStr}`);
4152
+ }
4153
+ return `{${entries.join(", ")}}`;
4154
+ }
4155
+ if (cbor$1 instanceof Uint8Array) return `h'${Array.from(cbor$1).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
4156
+ if (typeof cbor$1 === "string") return JSON.stringify(cbor$1);
4157
+ if (typeof cbor$1 === "object" && cbor$1 !== null && "type" in cbor$1) {
4158
+ const typed = cbor$1;
4159
+ switch (typed.type) {
4160
+ case 0: return String(typed.value);
4161
+ case 1: return String(-1 - Number(typed.value));
4162
+ case 7: {
4163
+ const simpleValue = typed.value;
4164
+ if (simpleValue !== null && typeof simpleValue === "object" && "type" in simpleValue) {
4165
+ const floatValue = simpleValue;
4166
+ if (floatValue.type === "Float") return String(floatValue.value);
4167
+ }
4168
+ if (simpleValue === 20) return "false";
4169
+ if (simpleValue === 21) return "true";
4170
+ if (simpleValue === 22) return "null";
4171
+ if (simpleValue === 23) return "undefined";
4172
+ return `simple(${String(simpleValue)})`;
4173
+ }
4174
+ }
4175
+ }
4176
+ if (typeof cbor$1 === "boolean") return String(cbor$1);
4177
+ if (typeof cbor$1 === "number") return String(cbor$1);
4178
+ if (typeof cbor$1 === "bigint") return String(cbor$1);
4179
+ if (cbor$1 === null) return "null";
4180
+ if (cbor$1 === void 0) return "undefined";
4181
+ try {
4182
+ return JSON.stringify(cbor$1);
4183
+ } catch {
4184
+ return String(cbor$1);
4185
+ }
4186
+ }
4187
+ Envelope.prototype.diagnostic = function() {
4188
+ return cborToDiagnostic(this.taggedCbor());
4189
+ };
4190
+
4191
+ //#endregion
4192
+ //#region src/seal.ts
4193
+ Envelope.prototype.encryptToRecipient = function(recipient) {
4194
+ return this.wrap().encryptSubjectToRecipient(recipient);
4195
+ };
4196
+ Envelope.prototype.seal = function(sender, recipient) {
4197
+ return this.addSignature(sender).encryptToRecipient(recipient);
4198
+ };
4199
+ Envelope.prototype.unseal = function(senderPublicKey, recipient) {
4200
+ return this.decryptToRecipient(recipient).verifySignatureFrom(senderPublicKey);
4201
+ };
4202
+ const registerSealExtension = () => {};
4203
+
2543
4204
  //#endregion
2544
4205
  //#region src/utils/string.ts
2545
4206
  /**
@@ -2576,16 +4237,38 @@ registerCompressExtension();
2576
4237
  const VERSION = "0.37.0";
2577
4238
 
2578
4239
  //#endregion
4240
+ exports.ADD = ADD;
4241
+ exports.ADD_VALUE = ADD_VALUE;
4242
+ exports.AND = AND;
4243
+ exports.AND_VALUE = AND_VALUE;
2579
4244
  exports.ATTACHMENT = ATTACHMENT;
2580
4245
  exports.Assertion = Assertion;
2581
4246
  exports.Attachments = Attachments;
4247
+ exports.BLANK = BLANK;
4248
+ exports.BLANK_VALUE = BLANK_VALUE;
2582
4249
  exports.CBOR_TAG_FUNCTION = CBOR_TAG_FUNCTION;
2583
4250
  exports.CBOR_TAG_PARAMETER = CBOR_TAG_PARAMETER;
2584
4251
  exports.CBOR_TAG_PLACEHOLDER = CBOR_TAG_PLACEHOLDER;
2585
4252
  exports.CBOR_TAG_REPLACEMENT = CBOR_TAG_REPLACEMENT;
2586
4253
  exports.CONFORMS_TO = CONFORMS_TO;
4254
+ Object.defineProperty(exports, 'ComponentsSealedMessage', {
4255
+ enumerable: true,
4256
+ get: function () {
4257
+ return _bcts_components.SealedMessage;
4258
+ }
4259
+ });
2587
4260
  exports.Compressed = Compressed;
2588
- exports.Digest = Digest;
4261
+ exports.DIV = DIV;
4262
+ exports.DIV_VALUE = DIV_VALUE;
4263
+ Object.defineProperty(exports, 'Digest', {
4264
+ enumerable: true,
4265
+ get: function () {
4266
+ return _bcts_components.Digest;
4267
+ }
4268
+ });
4269
+ exports.DigestDisplayFormat = DigestDisplayFormat;
4270
+ exports.EQ = EQ;
4271
+ exports.EQ_VALUE = EQ_VALUE;
2589
4272
  exports.EdgeType = EdgeType;
2590
4273
  exports.EncryptedMessage = EncryptedMessage;
2591
4274
  exports.Envelope = Envelope;
@@ -2595,35 +4278,112 @@ exports.EnvelopeCBORTaggedEncodable = EnvelopeCBORTaggedEncodable;
2595
4278
  exports.EnvelopeDecoder = EnvelopeDecoder;
2596
4279
  exports.EnvelopeError = EnvelopeError;
2597
4280
  exports.ErrorCode = ErrorCode;
4281
+ exports.Event = Event;
2598
4282
  exports.Expression = Expression;
2599
4283
  exports.FUNCTION_IDS = FUNCTION_IDS;
4284
+ exports.FormatContext = FormatContext;
2600
4285
  exports.Function = Function;
4286
+ exports.FunctionsStore = FunctionsStore;
4287
+ exports.GE = GE;
4288
+ exports.GE_VALUE = GE_VALUE;
4289
+ exports.GLOBAL_FORMAT_CONTEXT = GLOBAL_FORMAT_CONTEXT;
4290
+ exports.GLOBAL_FUNCTIONS = GLOBAL_FUNCTIONS;
4291
+ exports.GLOBAL_PARAMETERS = GLOBAL_PARAMETERS;
4292
+ exports.GT = GT;
4293
+ exports.GT_VALUE = GT_VALUE;
2601
4294
  exports.HAS_RECIPIENT = HAS_RECIPIENT;
2602
- exports.IS_A = IS_A;
4295
+ Object.defineProperty(exports, 'IS_A', {
4296
+ enumerable: true,
4297
+ get: function () {
4298
+ return _bcts_known_values.IS_A;
4299
+ }
4300
+ });
4301
+ exports.LE = LE;
4302
+ exports.LE_VALUE = LE_VALUE;
4303
+ exports.LHS = LHS;
4304
+ exports.LHS_VALUE = LHS_VALUE;
4305
+ exports.LT = LT;
4306
+ exports.LT_VALUE = LT_VALUE;
4307
+ exports.LazyStore = LazyStore;
4308
+ exports.MUL = MUL;
4309
+ exports.MUL_VALUE = MUL_VALUE;
4310
+ exports.MermaidOrientation = MermaidOrientation;
4311
+ exports.MermaidTheme = MermaidTheme;
4312
+ exports.NE = NE;
4313
+ exports.NEG = NEG;
4314
+ exports.NEG_VALUE = NEG_VALUE;
4315
+ exports.NE_VALUE = NE_VALUE;
4316
+ exports.NOT = NOT;
2603
4317
  exports.NOTE = NOTE;
4318
+ exports.NOT_VALUE = NOT_VALUE;
4319
+ exports.OR = OR;
4320
+ exports.OR_VALUE = OR_VALUE;
2604
4321
  exports.ObscureType = ObscureType;
2605
4322
  exports.PARAMETER_IDS = PARAMETER_IDS;
2606
4323
  exports.Parameter = Parameter;
2607
- exports.PrivateKeyBase = PrivateKeyBase;
2608
- exports.PublicKeyBase = PublicKeyBase;
4324
+ exports.ParametersStore = ParametersStore;
4325
+ Object.defineProperty(exports, 'PrivateKeyBase', {
4326
+ enumerable: true,
4327
+ get: function () {
4328
+ return _bcts_components.PrivateKeys;
4329
+ }
4330
+ });
4331
+ Object.defineProperty(exports, 'PublicKeyBase', {
4332
+ enumerable: true,
4333
+ get: function () {
4334
+ return _bcts_components.EncapsulationPublicKey;
4335
+ }
4336
+ });
4337
+ exports.RHS = RHS;
4338
+ exports.RHS_VALUE = RHS_VALUE;
4339
+ exports.Request = Request;
4340
+ exports.Response = Response;
2609
4341
  exports.SALT = SALT;
2610
4342
  exports.SIGNED = SIGNED;
4343
+ exports.SUB = SUB;
4344
+ exports.SUB_VALUE = SUB_VALUE;
2611
4345
  exports.SealedMessage = SealedMessage;
2612
- exports.Signature = Signature;
4346
+ Object.defineProperty(exports, 'Signature', {
4347
+ enumerable: true,
4348
+ get: function () {
4349
+ return _bcts_components.Signature;
4350
+ }
4351
+ });
2613
4352
  exports.SignatureMetadata = SignatureMetadata;
2614
- exports.SigningPrivateKey = SigningPrivateKey;
2615
- exports.SigningPublicKey = SigningPublicKey;
2616
- exports.SymmetricKey = SymmetricKey;
4353
+ Object.defineProperty(exports, 'SigningPrivateKey', {
4354
+ enumerable: true,
4355
+ get: function () {
4356
+ return _bcts_components.SigningPrivateKey;
4357
+ }
4358
+ });
4359
+ Object.defineProperty(exports, 'SigningPublicKey', {
4360
+ enumerable: true,
4361
+ get: function () {
4362
+ return _bcts_components.SigningPublicKey;
4363
+ }
4364
+ });
4365
+ Object.defineProperty(exports, 'SymmetricKey', {
4366
+ enumerable: true,
4367
+ get: function () {
4368
+ return _bcts_components.SymmetricKey;
4369
+ }
4370
+ });
2617
4371
  exports.VENDOR = VENDOR;
2618
4372
  exports.VERIFIED_BY = VERIFIED_BY;
2619
4373
  exports.VERSION = VERSION;
4374
+ exports.XOR = XOR;
4375
+ exports.XOR_VALUE = XOR_VALUE;
2620
4376
  exports.add = add;
2621
4377
  exports.and = and;
4378
+ exports.cborEnvelopeSummary = cborEnvelopeSummary;
4379
+ exports.defaultFormatOpts = defaultFormatOpts;
4380
+ exports.defaultMermaidOpts = defaultMermaidOpts;
2622
4381
  exports.div = div;
2623
4382
  exports.edgeLabel = edgeLabel;
2624
4383
  exports.elideAction = elideAction;
2625
4384
  exports.envelopeFromBytes = envelopeFromBytes;
2626
4385
  exports.envelopeFromCbor = envelopeFromCbor;
4386
+ exports.envelopeSummary = cborEnvelopeSummary;
2627
4387
  exports.envelopeToBytes = envelopeToBytes;
2628
4388
  exports.envelopeToCbor = envelopeToCbor;
2629
4389
  exports.eq = eq;
@@ -2631,16 +4391,49 @@ exports.extractBoolean = extractBoolean;
2631
4391
  exports.extractBytes = extractBytes;
2632
4392
  exports.extractNull = extractNull;
2633
4393
  exports.extractNumber = extractNumber;
4394
+ exports.extractObjectForPredicateWithDefault = extractObjectForPredicateWithDefault;
4395
+ exports.extractObjectsForPredicate = extractObjectsForPredicate;
2634
4396
  exports.extractString = extractString;
4397
+ exports.extractSubject = extractSubject;
2635
4398
  exports.flanked = flanked;
4399
+ exports.flatFormatOpts = flatFormatOpts;
4400
+ exports.formatAssertion = formatAssertion;
4401
+ exports.formatBegin = formatBegin;
4402
+ exports.formatCbor = formatCbor;
4403
+ exports.formatContextCustom = formatContextCustom;
4404
+ exports.formatContextGlobal = formatContextGlobal;
4405
+ exports.formatContextNone = formatContextNone;
4406
+ exports.formatEnd = formatEnd;
4407
+ exports.formatEnvelope = formatEnvelope;
4408
+ exports.formatItem = formatItem;
4409
+ exports.formatList = formatList;
4410
+ exports.formatSeparator = formatSeparator;
4411
+ exports.ge = ge;
4412
+ exports.getGlobalFormatContext = getGlobalFormatContext;
4413
+ exports.globalFormatContext = globalFormatContext;
2636
4414
  exports.gt = gt;
2637
4415
  exports.isEnvelopeEncodable = isEnvelopeEncodable;
4416
+ exports.le = le;
2638
4417
  exports.lt = lt;
2639
4418
  exports.mul = mul;
4419
+ exports.ne = ne;
2640
4420
  exports.neg = neg;
2641
4421
  exports.not = not;
2642
4422
  exports.or = or;
2643
4423
  exports.registerCompressExtension = registerCompressExtension;
2644
4424
  exports.registerEncryptExtension = registerEncryptExtension;
4425
+ exports.registerMermaidExtension = registerMermaidExtension;
4426
+ exports.registerProofExtension = registerProofExtension;
4427
+ exports.registerSealExtension = registerSealExtension;
4428
+ exports.registerSecretExtension = registerSecretExtension;
4429
+ exports.registerSskrExtension = registerSskrExtension;
4430
+ exports.registerTags = registerTags;
4431
+ exports.registerTagsIn = registerTagsIn;
2645
4432
  exports.sub = sub;
4433
+ exports.tryObjectForPredicate = tryObjectForPredicate;
4434
+ exports.tryObjectsForPredicate = tryObjectsForPredicate;
4435
+ exports.tryOptionalObjectForPredicate = tryOptionalObjectForPredicate;
4436
+ exports.withFormatContext = withFormatContext;
4437
+ exports.withFormatContextMut = withFormatContextMut;
4438
+ exports.xor = xor;
2646
4439
  //# sourceMappingURL=index.cjs.map