@bcts/envelope 1.0.0-alpha.10

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 (44) hide show
  1. package/LICENSE +48 -0
  2. package/README.md +23 -0
  3. package/dist/index.cjs +2646 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +782 -0
  6. package/dist/index.d.cts.map +1 -0
  7. package/dist/index.d.mts +782 -0
  8. package/dist/index.d.mts.map +1 -0
  9. package/dist/index.iife.js +2644 -0
  10. package/dist/index.iife.js.map +1 -0
  11. package/dist/index.mjs +2552 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/package.json +84 -0
  14. package/src/base/assertion.ts +179 -0
  15. package/src/base/assertions.ts +153 -0
  16. package/src/base/cbor.ts +122 -0
  17. package/src/base/digest.ts +204 -0
  18. package/src/base/elide.ts +390 -0
  19. package/src/base/envelope-decodable.ts +186 -0
  20. package/src/base/envelope-encodable.ts +71 -0
  21. package/src/base/envelope.ts +988 -0
  22. package/src/base/error.ts +421 -0
  23. package/src/base/index.ts +56 -0
  24. package/src/base/leaf.ts +147 -0
  25. package/src/base/queries.ts +244 -0
  26. package/src/base/walk.ts +215 -0
  27. package/src/base/wrap.ts +26 -0
  28. package/src/extension/attachment.ts +280 -0
  29. package/src/extension/compress.ts +176 -0
  30. package/src/extension/encrypt.ts +297 -0
  31. package/src/extension/expression.ts +404 -0
  32. package/src/extension/index.ts +72 -0
  33. package/src/extension/proof.ts +227 -0
  34. package/src/extension/recipient.ts +440 -0
  35. package/src/extension/salt.ts +114 -0
  36. package/src/extension/signature.ts +398 -0
  37. package/src/extension/types.ts +92 -0
  38. package/src/format/diagnostic.ts +116 -0
  39. package/src/format/hex.ts +25 -0
  40. package/src/format/index.ts +13 -0
  41. package/src/format/tree.ts +168 -0
  42. package/src/index.ts +32 -0
  43. package/src/utils/index.ts +8 -0
  44. package/src/utils/string.ts +48 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2552 @@
1
+ import { ECDSA_PRIVATE_KEY_SIZE, ECDSA_PUBLIC_KEY_SIZE, ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, SYMMETRIC_AUTH_SIZE, SYMMETRIC_KEY_SIZE, SYMMETRIC_NONCE_SIZE, X25519_PRIVATE_KEY_SIZE, X25519_PUBLIC_KEY_SIZE, aeadChaCha20Poly1305DecryptWithAad, aeadChaCha20Poly1305EncryptWithAad, ecdsaPublicKeyFromPrivateKey, ecdsaSign, ecdsaVerify, hkdfHmacSha256, sha256, x25519NewPrivateKeyUsing, x25519PublicKeyFromPrivateKey, x25519SharedKey } from "@bcts/crypto";
2
+ import { CborMap, MajorType, TAG_ENCODED_CBOR, asArray, asByteString, asCborArray, asCborMap, asMap, asTaggedValue, asText, cbor, cborData, decodeCbor, isNaN, isNull, isNumber, tagsForValues, toTaggedValue, tryExpectedTaggedValue, tryIntoBool, tryIntoByteString, tryIntoText } from "@bcts/dcbor";
3
+ import { KnownValue } from "@bcts/known-values";
4
+ import { COMPRESSED, ENCRYPTED, ENVELOPE, LEAF } from "@bcts/components";
5
+ import * as pako from "pako";
6
+ import { SecureRandomNumberGenerator, rngNextInClosedRangeI32, rngRandomData } from "@bcts/rand";
7
+
8
+ //#region src/base/digest.ts
9
+ var Digest = class Digest {
10
+ #data;
11
+ constructor(data) {
12
+ if (data.length !== 32) throw new Error(`Digest must be exactly 32 bytes, got ${data.length} bytes`);
13
+ this.#data = data;
14
+ }
15
+ data() {
16
+ return this.#data;
17
+ }
18
+ static fromImage(image) {
19
+ return new Digest(sha256(image));
20
+ }
21
+ static fromDigests(digests) {
22
+ const totalLength = digests.length * 32;
23
+ const combined = new Uint8Array(totalLength);
24
+ let offset = 0;
25
+ for (const digest of digests) {
26
+ combined.set(digest.data(), offset);
27
+ offset += 32;
28
+ }
29
+ return Digest.fromImage(combined);
30
+ }
31
+ hex() {
32
+ return Array.from(this.#data).map((b) => b.toString(16).padStart(2, "0")).join("");
33
+ }
34
+ short() {
35
+ return this.hex().substring(0, 7);
36
+ }
37
+ static fromHex(hex) {
38
+ if (hex.length !== 64) throw new Error(`Hex string must be exactly 64 characters, got ${hex.length}`);
39
+ const data = new Uint8Array(32);
40
+ for (let i = 0; i < 32; i++) data[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
41
+ return new Digest(data);
42
+ }
43
+ equals(other) {
44
+ if (this.#data.length !== other.#data.length) return false;
45
+ for (let i = 0; i < this.#data.length; i++) if (this.#data[i] !== other.#data[i]) return false;
46
+ return true;
47
+ }
48
+ toString() {
49
+ return this.short();
50
+ }
51
+ clone() {
52
+ return new Digest(new Uint8Array(this.#data));
53
+ }
54
+ };
55
+
56
+ //#endregion
57
+ //#region src/base/error.ts
58
+ let ErrorCode = /* @__PURE__ */ function(ErrorCode$1) {
59
+ ErrorCode$1["ALREADY_ELIDED"] = "ALREADY_ELIDED";
60
+ ErrorCode$1["AMBIGUOUS_PREDICATE"] = "AMBIGUOUS_PREDICATE";
61
+ ErrorCode$1["INVALID_DIGEST"] = "INVALID_DIGEST";
62
+ ErrorCode$1["INVALID_FORMAT"] = "INVALID_FORMAT";
63
+ ErrorCode$1["MISSING_DIGEST"] = "MISSING_DIGEST";
64
+ ErrorCode$1["NONEXISTENT_PREDICATE"] = "NONEXISTENT_PREDICATE";
65
+ ErrorCode$1["NOT_WRAPPED"] = "NOT_WRAPPED";
66
+ ErrorCode$1["NOT_LEAF"] = "NOT_LEAF";
67
+ ErrorCode$1["NOT_ASSERTION"] = "NOT_ASSERTION";
68
+ ErrorCode$1["INVALID_ASSERTION"] = "INVALID_ASSERTION";
69
+ ErrorCode$1["INVALID_ATTACHMENT"] = "INVALID_ATTACHMENT";
70
+ ErrorCode$1["NONEXISTENT_ATTACHMENT"] = "NONEXISTENT_ATTACHMENT";
71
+ ErrorCode$1["AMBIGUOUS_ATTACHMENT"] = "AMBIGUOUS_ATTACHMENT";
72
+ ErrorCode$1["ALREADY_COMPRESSED"] = "ALREADY_COMPRESSED";
73
+ ErrorCode$1["NOT_COMPRESSED"] = "NOT_COMPRESSED";
74
+ ErrorCode$1["ALREADY_ENCRYPTED"] = "ALREADY_ENCRYPTED";
75
+ ErrorCode$1["NOT_ENCRYPTED"] = "NOT_ENCRYPTED";
76
+ ErrorCode$1["NOT_KNOWN_VALUE"] = "NOT_KNOWN_VALUE";
77
+ ErrorCode$1["UNKNOWN_RECIPIENT"] = "UNKNOWN_RECIPIENT";
78
+ ErrorCode$1["UNKNOWN_SECRET"] = "UNKNOWN_SECRET";
79
+ ErrorCode$1["UNVERIFIED_SIGNATURE"] = "UNVERIFIED_SIGNATURE";
80
+ ErrorCode$1["INVALID_OUTER_SIGNATURE_TYPE"] = "INVALID_OUTER_SIGNATURE_TYPE";
81
+ ErrorCode$1["INVALID_INNER_SIGNATURE_TYPE"] = "INVALID_INNER_SIGNATURE_TYPE";
82
+ ErrorCode$1["UNVERIFIED_INNER_SIGNATURE"] = "UNVERIFIED_INNER_SIGNATURE";
83
+ ErrorCode$1["INVALID_SIGNATURE_TYPE"] = "INVALID_SIGNATURE_TYPE";
84
+ ErrorCode$1["INVALID_SHARES"] = "INVALID_SHARES";
85
+ ErrorCode$1["SSKR"] = "SSKR";
86
+ ErrorCode$1["INVALID_TYPE"] = "INVALID_TYPE";
87
+ ErrorCode$1["AMBIGUOUS_TYPE"] = "AMBIGUOUS_TYPE";
88
+ ErrorCode$1["UNEXPECTED_RESPONSE_ID"] = "UNEXPECTED_RESPONSE_ID";
89
+ ErrorCode$1["INVALID_RESPONSE"] = "INVALID_RESPONSE";
90
+ ErrorCode$1["CBOR"] = "CBOR";
91
+ ErrorCode$1["COMPONENTS"] = "COMPONENTS";
92
+ ErrorCode$1["GENERAL"] = "GENERAL";
93
+ return ErrorCode$1;
94
+ }({});
95
+ var EnvelopeError = class EnvelopeError extends Error {
96
+ code;
97
+ constructor(code, message, cause) {
98
+ super(message);
99
+ this.name = "EnvelopeError";
100
+ this.code = code;
101
+ if (cause !== void 0) this.cause = cause;
102
+ if ("captureStackTrace" in Error) Error.captureStackTrace(this, EnvelopeError);
103
+ }
104
+ static alreadyElided() {
105
+ return new EnvelopeError(ErrorCode.ALREADY_ELIDED, "envelope was elided, so it cannot be compressed or encrypted");
106
+ }
107
+ static ambiguousPredicate() {
108
+ return new EnvelopeError(ErrorCode.AMBIGUOUS_PREDICATE, "more than one assertion matches the predicate");
109
+ }
110
+ static invalidDigest() {
111
+ return new EnvelopeError(ErrorCode.INVALID_DIGEST, "digest did not match");
112
+ }
113
+ static invalidFormat() {
114
+ return new EnvelopeError(ErrorCode.INVALID_FORMAT, "invalid format");
115
+ }
116
+ static missingDigest() {
117
+ return new EnvelopeError(ErrorCode.MISSING_DIGEST, "a digest was expected but not found");
118
+ }
119
+ static nonexistentPredicate() {
120
+ return new EnvelopeError(ErrorCode.NONEXISTENT_PREDICATE, "no assertion matches the predicate");
121
+ }
122
+ static notWrapped() {
123
+ return new EnvelopeError(ErrorCode.NOT_WRAPPED, "cannot unwrap an envelope that was not wrapped");
124
+ }
125
+ static notLeaf() {
126
+ return new EnvelopeError(ErrorCode.NOT_LEAF, "the envelope's subject is not a leaf");
127
+ }
128
+ static notAssertion() {
129
+ return new EnvelopeError(ErrorCode.NOT_ASSERTION, "the envelope's subject is not an assertion");
130
+ }
131
+ static invalidAssertion() {
132
+ return new EnvelopeError(ErrorCode.INVALID_ASSERTION, "assertion must be a map with exactly one element");
133
+ }
134
+ static invalidAttachment() {
135
+ return new EnvelopeError(ErrorCode.INVALID_ATTACHMENT, "invalid attachment");
136
+ }
137
+ static nonexistentAttachment() {
138
+ return new EnvelopeError(ErrorCode.NONEXISTENT_ATTACHMENT, "nonexistent attachment");
139
+ }
140
+ static ambiguousAttachment() {
141
+ return new EnvelopeError(ErrorCode.AMBIGUOUS_ATTACHMENT, "ambiguous attachment");
142
+ }
143
+ static alreadyCompressed() {
144
+ return new EnvelopeError(ErrorCode.ALREADY_COMPRESSED, "envelope was already compressed");
145
+ }
146
+ static notCompressed() {
147
+ return new EnvelopeError(ErrorCode.NOT_COMPRESSED, "cannot decompress an envelope that was not compressed");
148
+ }
149
+ static alreadyEncrypted() {
150
+ return new EnvelopeError(ErrorCode.ALREADY_ENCRYPTED, "envelope was already encrypted or compressed, so it cannot be encrypted");
151
+ }
152
+ static notEncrypted() {
153
+ return new EnvelopeError(ErrorCode.NOT_ENCRYPTED, "cannot decrypt an envelope that was not encrypted");
154
+ }
155
+ static notKnownValue() {
156
+ return new EnvelopeError(ErrorCode.NOT_KNOWN_VALUE, "the envelope's subject is not a known value");
157
+ }
158
+ static unknownRecipient() {
159
+ return new EnvelopeError(ErrorCode.UNKNOWN_RECIPIENT, "unknown recipient");
160
+ }
161
+ static unknownSecret() {
162
+ return new EnvelopeError(ErrorCode.UNKNOWN_SECRET, "secret not found");
163
+ }
164
+ static unverifiedSignature() {
165
+ return new EnvelopeError(ErrorCode.UNVERIFIED_SIGNATURE, "could not verify a signature");
166
+ }
167
+ static invalidOuterSignatureType() {
168
+ return new EnvelopeError(ErrorCode.INVALID_OUTER_SIGNATURE_TYPE, "unexpected outer signature object type");
169
+ }
170
+ static invalidInnerSignatureType() {
171
+ return new EnvelopeError(ErrorCode.INVALID_INNER_SIGNATURE_TYPE, "unexpected inner signature object type");
172
+ }
173
+ static unverifiedInnerSignature() {
174
+ return new EnvelopeError(ErrorCode.UNVERIFIED_INNER_SIGNATURE, "inner signature not made with same key as outer signature");
175
+ }
176
+ static invalidSignatureType() {
177
+ return new EnvelopeError(ErrorCode.INVALID_SIGNATURE_TYPE, "unexpected signature object type");
178
+ }
179
+ static invalidShares() {
180
+ return new EnvelopeError(ErrorCode.INVALID_SHARES, "invalid SSKR shares");
181
+ }
182
+ static sskr(message, cause) {
183
+ return new EnvelopeError(ErrorCode.SSKR, `sskr error: ${message}`, cause);
184
+ }
185
+ static invalidType() {
186
+ return new EnvelopeError(ErrorCode.INVALID_TYPE, "invalid type");
187
+ }
188
+ static ambiguousType() {
189
+ return new EnvelopeError(ErrorCode.AMBIGUOUS_TYPE, "ambiguous type");
190
+ }
191
+ static unexpectedResponseId() {
192
+ return new EnvelopeError(ErrorCode.UNEXPECTED_RESPONSE_ID, "unexpected response ID");
193
+ }
194
+ static invalidResponse() {
195
+ return new EnvelopeError(ErrorCode.INVALID_RESPONSE, "invalid response");
196
+ }
197
+ static cbor(message, cause) {
198
+ return new EnvelopeError(ErrorCode.CBOR, `dcbor error: ${message}`, cause);
199
+ }
200
+ static components(message, cause) {
201
+ return new EnvelopeError(ErrorCode.COMPONENTS, `components error: ${message}`, cause);
202
+ }
203
+ static general(message, cause) {
204
+ return new EnvelopeError(ErrorCode.GENERAL, `general error: ${message}`, cause);
205
+ }
206
+ static msg(message) {
207
+ return EnvelopeError.general(message);
208
+ }
209
+ };
210
+
211
+ //#endregion
212
+ //#region src/base/assertion.ts
213
+ var Assertion = class Assertion {
214
+ #predicate;
215
+ #object;
216
+ #digest;
217
+ constructor(predicate, object) {
218
+ this.#predicate = predicate instanceof Envelope ? predicate : Envelope.new(predicate);
219
+ this.#object = object instanceof Envelope ? object : Envelope.new(object);
220
+ this.#digest = Digest.fromDigests([this.#predicate.digest(), this.#object.digest()]);
221
+ }
222
+ predicate() {
223
+ return this.#predicate;
224
+ }
225
+ object() {
226
+ return this.#object;
227
+ }
228
+ digest() {
229
+ return this.#digest;
230
+ }
231
+ equals(other) {
232
+ return this.#digest.equals(other.#digest);
233
+ }
234
+ toCbor() {
235
+ const map = new CborMap();
236
+ map.set(this.#predicate.untaggedCbor(), this.#object.untaggedCbor());
237
+ return map;
238
+ }
239
+ static fromCbor(cbor$1) {
240
+ if (!(cbor$1 instanceof CborMap)) throw EnvelopeError.invalidAssertion();
241
+ return Assertion.fromCborMap(cbor$1);
242
+ }
243
+ static fromCborMap(map) {
244
+ if (map.size !== 1) throw EnvelopeError.invalidAssertion();
245
+ const firstEntry = Array.from(map.entries())[0];
246
+ if (firstEntry === void 0) throw EnvelopeError.invalidAssertion();
247
+ const [predicateCbor, objectCbor] = firstEntry;
248
+ return new Assertion(Envelope.fromUntaggedCbor(predicateCbor), Envelope.fromUntaggedCbor(objectCbor));
249
+ }
250
+ toString() {
251
+ return `Assertion(${String(this.#predicate)}: ${String(this.#object)})`;
252
+ }
253
+ clone() {
254
+ return this;
255
+ }
256
+ };
257
+
258
+ //#endregion
259
+ //#region src/extension/compress.ts
260
+ var Compressed = class Compressed {
261
+ #compressedData;
262
+ #digest;
263
+ constructor(compressedData, digest) {
264
+ this.#compressedData = compressedData;
265
+ if (digest !== void 0) this.#digest = digest;
266
+ }
267
+ static fromDecompressedData(decompressedData, digest) {
268
+ return new Compressed(pako.deflate(decompressedData), digest);
269
+ }
270
+ compressedData() {
271
+ return this.#compressedData;
272
+ }
273
+ digestOpt() {
274
+ return this.#digest;
275
+ }
276
+ decompress() {
277
+ return pako.inflate(this.#compressedData);
278
+ }
279
+ };
280
+ function registerCompressExtension() {
281
+ if (Envelope?.prototype === void 0) return;
282
+ if (typeof Envelope.prototype.compress === "function") return;
283
+ Envelope.prototype.compress = function() {
284
+ const c = this.case();
285
+ if (c.type === "compressed") return this;
286
+ if (c.type === "encrypted") throw EnvelopeError.general("Cannot compress encrypted envelope");
287
+ if (c.type === "elided") throw EnvelopeError.general("Cannot compress elided envelope");
288
+ const decompressedData = cborData(this.taggedCbor());
289
+ const compressed = Compressed.fromDecompressedData(decompressedData, this.digest());
290
+ return Envelope.fromCase({
291
+ type: "compressed",
292
+ value: compressed
293
+ });
294
+ };
295
+ Envelope.prototype.decompress = function() {
296
+ const c = this.case();
297
+ if (c.type !== "compressed") throw EnvelopeError.general("Envelope is not compressed");
298
+ const compressed = c.value;
299
+ const digest = compressed.digestOpt();
300
+ if (digest === void 0) throw EnvelopeError.general("Missing digest in compressed envelope");
301
+ if (!digest.equals(this.digest())) throw EnvelopeError.general("Invalid digest in compressed envelope");
302
+ const cbor$1 = decodeCbor(compressed.decompress());
303
+ const envelope = Envelope.fromTaggedCbor(cbor$1);
304
+ if (!envelope.digest().equals(digest)) throw EnvelopeError.general("Invalid digest after decompression");
305
+ return envelope;
306
+ };
307
+ Envelope.prototype.compressSubject = function() {
308
+ if (this.subject().isCompressed()) return this;
309
+ const subject = this.subject().compress();
310
+ return this.replaceSubject(subject);
311
+ };
312
+ Envelope.prototype.decompressSubject = function() {
313
+ if (this.subject().isCompressed()) {
314
+ const subject = this.subject().decompress();
315
+ return this.replaceSubject(subject);
316
+ }
317
+ return this;
318
+ };
319
+ Envelope.prototype.isCompressed = function() {
320
+ return this.case().type === "compressed";
321
+ };
322
+ }
323
+ registerCompressExtension();
324
+
325
+ //#endregion
326
+ //#region src/extension/encrypt.ts
327
+ function createSecureRng$1() {
328
+ return new SecureRandomNumberGenerator();
329
+ }
330
+ var SymmetricKey = class SymmetricKey {
331
+ #key;
332
+ constructor(key) {
333
+ if (key.length !== SYMMETRIC_KEY_SIZE) throw new Error(`Symmetric key must be ${SYMMETRIC_KEY_SIZE} bytes`);
334
+ this.#key = key;
335
+ }
336
+ static generate() {
337
+ return new SymmetricKey(rngRandomData(createSecureRng$1(), SYMMETRIC_KEY_SIZE));
338
+ }
339
+ static from(key) {
340
+ return new SymmetricKey(key);
341
+ }
342
+ data() {
343
+ return this.#key;
344
+ }
345
+ encrypt(plaintext, digest) {
346
+ const nonce = rngRandomData(createSecureRng$1(), SYMMETRIC_NONCE_SIZE);
347
+ const aad = digest.data();
348
+ const [ciphertext, authTag] = aeadChaCha20Poly1305EncryptWithAad(plaintext, this.#key, nonce, aad);
349
+ return new EncryptedMessage(ciphertext, nonce, authTag, digest);
350
+ }
351
+ decrypt(message) {
352
+ const digest = message.aadDigest();
353
+ if (digest === void 0) throw EnvelopeError.general("Missing digest in encrypted message");
354
+ const aad = digest.data();
355
+ try {
356
+ return aeadChaCha20Poly1305DecryptWithAad(message.ciphertext(), this.#key, message.nonce(), aad, message.authTag());
357
+ } catch (_error) {
358
+ throw EnvelopeError.general("Decryption failed: invalid key or corrupted data");
359
+ }
360
+ }
361
+ };
362
+ var EncryptedMessage = class {
363
+ #ciphertext;
364
+ #nonce;
365
+ #authTag;
366
+ #aadDigest;
367
+ constructor(ciphertext, nonce, authTag, aadDigest) {
368
+ this.#ciphertext = ciphertext;
369
+ this.#nonce = nonce;
370
+ this.#authTag = authTag;
371
+ if (aadDigest !== void 0) this.#aadDigest = aadDigest;
372
+ }
373
+ ciphertext() {
374
+ return this.#ciphertext;
375
+ }
376
+ nonce() {
377
+ return this.#nonce;
378
+ }
379
+ authTag() {
380
+ return this.#authTag;
381
+ }
382
+ aadDigest() {
383
+ return this.#aadDigest;
384
+ }
385
+ digest() {
386
+ if (this.#aadDigest === void 0) throw new Error("Encrypted message missing AAD digest");
387
+ return this.#aadDigest;
388
+ }
389
+ };
390
+ function registerEncryptExtension() {
391
+ if (Envelope?.prototype === void 0) return;
392
+ if (typeof Envelope.prototype.encryptSubject === "function") return;
393
+ Envelope.prototype.encryptSubject = function(key) {
394
+ const c = this.case();
395
+ if (c.type === "encrypted") throw EnvelopeError.general("Envelope is already encrypted");
396
+ if (c.type === "elided") throw EnvelopeError.general("Cannot encrypt elided envelope");
397
+ if (c.type === "node") {
398
+ if (c.subject.isEncrypted()) throw EnvelopeError.general("Subject is already encrypted");
399
+ const encodedCbor$1 = cborData(c.subject.taggedCbor());
400
+ const subjectDigest = c.subject.digest();
401
+ const encryptedMessage$1 = key.encrypt(encodedCbor$1, subjectDigest);
402
+ const encryptedSubject = Envelope.fromCase({
403
+ type: "encrypted",
404
+ message: encryptedMessage$1
405
+ });
406
+ return Envelope.newWithAssertions(encryptedSubject, c.assertions);
407
+ }
408
+ const encodedCbor = cborData(this.taggedCbor());
409
+ const digest = this.digest();
410
+ const encryptedMessage = key.encrypt(encodedCbor, digest);
411
+ return Envelope.fromCase({
412
+ type: "encrypted",
413
+ message: encryptedMessage
414
+ });
415
+ };
416
+ Envelope.prototype.decryptSubject = function(key) {
417
+ const subjectCase = this.subject().case();
418
+ if (subjectCase.type !== "encrypted") throw EnvelopeError.general("Subject is not encrypted");
419
+ const message = subjectCase.message;
420
+ const subjectDigest = message.aadDigest();
421
+ if (subjectDigest === void 0) throw EnvelopeError.general("Missing digest in encrypted message");
422
+ const cbor$1 = decodeCbor(key.decrypt(message));
423
+ const resultSubject = Envelope.fromTaggedCbor(cbor$1);
424
+ if (!resultSubject.digest().equals(subjectDigest)) throw EnvelopeError.general("Invalid digest after decryption");
425
+ const c = this.case();
426
+ if (c.type === "node") {
427
+ const result = Envelope.newWithAssertions(resultSubject, c.assertions);
428
+ if (!result.digest().equals(c.digest)) throw EnvelopeError.general("Invalid envelope digest after decryption");
429
+ return result;
430
+ }
431
+ return resultSubject;
432
+ };
433
+ Envelope.prototype.encrypt = function(key) {
434
+ return this.wrap().encryptSubject(key);
435
+ };
436
+ Envelope.prototype.decrypt = function(key) {
437
+ return this.decryptSubject(key).unwrap();
438
+ };
439
+ Envelope.prototype.isEncrypted = function() {
440
+ return this.case().type === "encrypted";
441
+ };
442
+ }
443
+ registerEncryptExtension();
444
+
445
+ //#endregion
446
+ //#region src/base/envelope.ts
447
+ const TAG_ENVELOPE$1 = ENVELOPE.value;
448
+ const TAG_LEAF = LEAF.value;
449
+ const TAG_ENCRYPTED = ENCRYPTED.value;
450
+ const TAG_COMPRESSED = COMPRESSED.value;
451
+ var Envelope = class Envelope {
452
+ #case;
453
+ constructor(envelopeCase) {
454
+ this.#case = envelopeCase;
455
+ }
456
+ case() {
457
+ return this.#case;
458
+ }
459
+ static new(subject) {
460
+ if (subject instanceof Envelope) return subject;
461
+ return Envelope.newLeaf(subject);
462
+ }
463
+ static newOrNull(subject) {
464
+ if (subject === void 0 || subject === null) return Envelope.null();
465
+ return Envelope.new(subject);
466
+ }
467
+ static newOrNone(subject) {
468
+ if (subject === void 0 || subject === null) return;
469
+ return Envelope.new(subject);
470
+ }
471
+ static fromCase(envelopeCase) {
472
+ return new Envelope(envelopeCase);
473
+ }
474
+ static newAssertion(predicate, object) {
475
+ const predicateEnv = predicate instanceof Envelope ? predicate : Envelope.new(predicate);
476
+ const objectEnv = object instanceof Envelope ? object : Envelope.new(object);
477
+ return Envelope.newWithAssertion(new Assertion(predicateEnv, objectEnv));
478
+ }
479
+ static null() {
480
+ return Envelope.newLeaf(null);
481
+ }
482
+ static newWithUncheckedAssertions(subject, uncheckedAssertions) {
483
+ if (uncheckedAssertions.length === 0) throw new Error("Assertions array cannot be empty");
484
+ const sortedAssertions = [...uncheckedAssertions].sort((a, b) => {
485
+ const aHex = a.digest().hex();
486
+ const bHex = b.digest().hex();
487
+ return aHex.localeCompare(bHex);
488
+ });
489
+ const digests = [subject.digest(), ...sortedAssertions.map((a) => a.digest())];
490
+ return new Envelope({
491
+ type: "node",
492
+ subject,
493
+ assertions: sortedAssertions,
494
+ digest: Digest.fromDigests(digests)
495
+ });
496
+ }
497
+ static newWithAssertions(subject, assertions) {
498
+ for (const assertion of assertions) if (!assertion.isSubjectAssertion() && !assertion.isSubjectObscured()) throw EnvelopeError.invalidFormat();
499
+ return Envelope.newWithUncheckedAssertions(subject, assertions);
500
+ }
501
+ static newWithAssertion(assertion) {
502
+ return new Envelope({
503
+ type: "assertion",
504
+ assertion
505
+ });
506
+ }
507
+ static newWithKnownValue(value) {
508
+ const knownValue = value instanceof KnownValue ? value : new KnownValue(value);
509
+ return new Envelope({
510
+ type: "knownValue",
511
+ value: knownValue,
512
+ digest: Digest.fromImage(knownValue.toCborData())
513
+ });
514
+ }
515
+ static newWithEncrypted(encryptedMessage) {
516
+ return new Envelope({
517
+ type: "encrypted",
518
+ message: encryptedMessage
519
+ });
520
+ }
521
+ static newWithCompressed(compressed) {
522
+ return new Envelope({
523
+ type: "compressed",
524
+ value: compressed
525
+ });
526
+ }
527
+ static newElided(digest) {
528
+ return new Envelope({
529
+ type: "elided",
530
+ digest
531
+ });
532
+ }
533
+ static newLeaf(value) {
534
+ const cbor$1 = Envelope.valueToCbor(value);
535
+ const cborBytes = Envelope.cborToBytes(cbor$1);
536
+ return new Envelope({
537
+ type: "leaf",
538
+ cbor: cbor$1,
539
+ digest: Digest.fromImage(cborBytes)
540
+ });
541
+ }
542
+ static newWrapped(envelope) {
543
+ return new Envelope({
544
+ type: "wrapped",
545
+ envelope,
546
+ digest: Digest.fromDigests([envelope.digest()])
547
+ });
548
+ }
549
+ digest() {
550
+ const c = this.#case;
551
+ switch (c.type) {
552
+ case "node":
553
+ case "leaf":
554
+ case "wrapped":
555
+ case "elided":
556
+ case "knownValue": return c.digest;
557
+ case "assertion": return c.assertion.digest();
558
+ case "encrypted": {
559
+ const digest = c.message.aadDigest();
560
+ if (digest === void 0) throw new Error("Encrypted envelope missing digest");
561
+ return digest;
562
+ }
563
+ case "compressed": {
564
+ const digest = c.value.digestOpt();
565
+ if (digest === void 0) throw new Error("Compressed envelope missing digest");
566
+ return digest;
567
+ }
568
+ }
569
+ }
570
+ subject() {
571
+ const c = this.#case;
572
+ switch (c.type) {
573
+ case "node": return c.subject;
574
+ case "leaf":
575
+ case "wrapped":
576
+ case "assertion":
577
+ case "elided":
578
+ case "knownValue":
579
+ case "encrypted":
580
+ case "compressed": return this;
581
+ }
582
+ }
583
+ isSubjectAssertion() {
584
+ return this.#case.type === "assertion";
585
+ }
586
+ isSubjectObscured() {
587
+ const t = this.#case.type;
588
+ return t === "elided" || t === "encrypted" || t === "compressed";
589
+ }
590
+ static valueToCbor(value) {
591
+ return cbor(value);
592
+ }
593
+ static cborToBytes(cbor$1) {
594
+ return cborData(cbor$1);
595
+ }
596
+ untaggedCbor() {
597
+ const c = this.#case;
598
+ switch (c.type) {
599
+ case "node": {
600
+ const result = [c.subject.untaggedCbor()];
601
+ for (const assertion of c.assertions) result.push(assertion.untaggedCbor());
602
+ return Envelope.valueToCbor(result);
603
+ }
604
+ case "leaf": return toTaggedValue(TAG_LEAF, c.cbor);
605
+ case "wrapped": return c.envelope.taggedCbor();
606
+ case "assertion": return c.assertion.toCbor();
607
+ case "elided": return Envelope.valueToCbor(c.digest.data());
608
+ case "knownValue": throw new Error("Known value encoding not yet implemented");
609
+ case "encrypted": {
610
+ const message = c.message;
611
+ const digest = message.aadDigest();
612
+ const arr = digest !== void 0 ? [
613
+ message.ciphertext(),
614
+ message.nonce(),
615
+ message.authTag(),
616
+ digest.data()
617
+ ] : [
618
+ message.ciphertext(),
619
+ message.nonce(),
620
+ message.authTag()
621
+ ];
622
+ return toTaggedValue(TAG_ENCRYPTED, Envelope.valueToCbor(arr));
623
+ }
624
+ case "compressed": {
625
+ const digest = c.value.digestOpt();
626
+ const data = c.value.compressedData();
627
+ const arr = digest !== void 0 ? [data, digest.data()] : [data];
628
+ return toTaggedValue(TAG_COMPRESSED, Envelope.valueToCbor(arr));
629
+ }
630
+ }
631
+ }
632
+ taggedCbor() {
633
+ return toTaggedValue(TAG_ENVELOPE$1, this.untaggedCbor());
634
+ }
635
+ static fromUntaggedCbor(cbor$1) {
636
+ const tagged = asTaggedValue(cbor$1);
637
+ if (tagged !== void 0) {
638
+ const [tag, item] = tagged;
639
+ switch (tag.value) {
640
+ case TAG_LEAF:
641
+ case TAG_ENCODED_CBOR: return Envelope.newLeaf(item);
642
+ case TAG_ENVELOPE$1: {
643
+ const envelope = Envelope.fromUntaggedCbor(item);
644
+ return Envelope.newWrapped(envelope);
645
+ }
646
+ case TAG_COMPRESSED: {
647
+ const arr = asCborArray(item);
648
+ if (arr === void 0 || arr.length < 1 || arr.length > 2) throw EnvelopeError.cbor("compressed envelope must have 1 or 2 elements");
649
+ const compressedData = asByteString(arr.get(0));
650
+ if (compressedData === void 0) throw EnvelopeError.cbor("compressed data must be byte string");
651
+ const digestBytes = arr.length === 2 ? asByteString(arr.get(1)) : void 0;
652
+ if (arr.length === 2 && digestBytes === void 0) throw EnvelopeError.cbor("digest must be byte string");
653
+ const compressed = new Compressed(compressedData, digestBytes !== void 0 ? new Digest(digestBytes) : void 0);
654
+ return Envelope.fromCase({
655
+ type: "compressed",
656
+ value: compressed
657
+ });
658
+ }
659
+ case TAG_ENCRYPTED: {
660
+ const arr = asCborArray(item);
661
+ if (arr === void 0 || arr.length < 3 || arr.length > 4) throw EnvelopeError.cbor("encrypted envelope must have 3 or 4 elements");
662
+ const ciphertext = asByteString(arr.get(0));
663
+ const nonce = asByteString(arr.get(1));
664
+ const authTag = asByteString(arr.get(2));
665
+ if (ciphertext === void 0 || nonce === void 0 || authTag === void 0) throw EnvelopeError.cbor("ciphertext, nonce, and auth must be byte strings");
666
+ const digestBytes = arr.length === 4 ? asByteString(arr.get(3)) : void 0;
667
+ if (arr.length === 4 && digestBytes === void 0) throw EnvelopeError.cbor("aad digest must be byte string");
668
+ const message = new EncryptedMessage(ciphertext, nonce, authTag, digestBytes !== void 0 ? new Digest(digestBytes) : void 0);
669
+ return Envelope.fromCase({
670
+ type: "encrypted",
671
+ message
672
+ });
673
+ }
674
+ default: throw EnvelopeError.cbor(`unknown envelope tag: ${tag.value}`);
675
+ }
676
+ }
677
+ const bytes = asByteString(cbor$1);
678
+ if (bytes !== void 0) {
679
+ if (bytes.length !== 32) throw EnvelopeError.cbor("elided digest must be 32 bytes");
680
+ return Envelope.newElided(new Digest(bytes));
681
+ }
682
+ const array = asCborArray(cbor$1);
683
+ if (array !== void 0) {
684
+ if (array.length < 2) throw EnvelopeError.cbor("node must have at least two elements");
685
+ const subjectCbor = array.get(0);
686
+ if (subjectCbor === void 0) throw EnvelopeError.cbor("node subject is missing");
687
+ const subject = Envelope.fromUntaggedCbor(subjectCbor);
688
+ const assertions = [];
689
+ for (let i = 1; i < array.length; i++) {
690
+ const assertionCbor = array.get(i);
691
+ if (assertionCbor === void 0) throw EnvelopeError.cbor(`node assertion at index ${i} is missing`);
692
+ assertions.push(Envelope.fromUntaggedCbor(assertionCbor));
693
+ }
694
+ return Envelope.newWithAssertions(subject, assertions);
695
+ }
696
+ const map = asCborMap(cbor$1);
697
+ if (map !== void 0) {
698
+ const assertion = Assertion.fromCborMap(map);
699
+ return Envelope.newWithAssertion(assertion);
700
+ }
701
+ if (cbor$1.type === MajorType.Unsigned) {
702
+ const knownValue = new KnownValue(cbor$1.value);
703
+ return Envelope.newWithKnownValue(knownValue);
704
+ }
705
+ throw EnvelopeError.cbor("invalid envelope format");
706
+ }
707
+ static fromTaggedCbor(cbor$1) {
708
+ try {
709
+ const untagged = tryExpectedTaggedValue(cbor$1, TAG_ENVELOPE$1);
710
+ return Envelope.fromUntaggedCbor(untagged);
711
+ } catch (error) {
712
+ throw EnvelopeError.cbor(`expected TAG_ENVELOPE (${TAG_ENVELOPE$1})`, error instanceof Error ? error : void 0);
713
+ }
714
+ }
715
+ addAssertion(predicate, object) {
716
+ const assertion = Envelope.newAssertion(predicate, object);
717
+ return this.addAssertionEnvelope(assertion);
718
+ }
719
+ addAssertionEnvelope(assertion) {
720
+ const c = this.#case;
721
+ if (c.type === "node") return Envelope.newWithAssertions(c.subject, [...c.assertions, assertion]);
722
+ return Envelope.newWithAssertions(this, [assertion]);
723
+ }
724
+ toString() {
725
+ return `Envelope(${this.#case.type})`;
726
+ }
727
+ clone() {
728
+ return this;
729
+ }
730
+ };
731
+
732
+ //#endregion
733
+ //#region src/base/envelope-encodable.ts
734
+ function isEnvelopeEncodable(value) {
735
+ return typeof value === "object" && value !== null && "intoEnvelope" in value && typeof value.intoEnvelope === "function";
736
+ }
737
+
738
+ //#endregion
739
+ //#region src/base/cbor.ts
740
+ const TAG_ENVELOPE = ENVELOPE.value;
741
+ var EnvelopeCBORTagged = class {
742
+ cborTags() {
743
+ return tagsForValues([TAG_ENVELOPE]);
744
+ }
745
+ static cborTags() {
746
+ return tagsForValues([TAG_ENVELOPE]).map((tag) => Number(tag.value));
747
+ }
748
+ };
749
+ var EnvelopeCBORTaggedEncodable = class {
750
+ constructor(envelope) {
751
+ this.envelope = envelope;
752
+ }
753
+ cborTags() {
754
+ return tagsForValues([TAG_ENVELOPE]);
755
+ }
756
+ untaggedCbor() {
757
+ return this.envelope.untaggedCbor();
758
+ }
759
+ taggedCbor() {
760
+ return this.envelope.taggedCbor();
761
+ }
762
+ };
763
+ var EnvelopeCBORTaggedDecodable = class {
764
+ cborTags() {
765
+ return tagsForValues([TAG_ENVELOPE]);
766
+ }
767
+ static fromUntaggedCbor(cbor$1) {
768
+ return Envelope.fromUntaggedCbor(cbor$1);
769
+ }
770
+ static fromTaggedCbor(cbor$1) {
771
+ return Envelope.fromTaggedCbor(cbor$1);
772
+ }
773
+ fromUntaggedCbor(cbor$1) {
774
+ return Envelope.fromUntaggedCbor(cbor$1);
775
+ }
776
+ fromTaggedCbor(cbor$1) {
777
+ return Envelope.fromTaggedCbor(cbor$1);
778
+ }
779
+ };
780
+ function envelopeToCbor(envelope) {
781
+ return envelope.taggedCbor();
782
+ }
783
+ function envelopeFromCbor(cbor$1) {
784
+ return Envelope.fromTaggedCbor(cbor$1);
785
+ }
786
+ function envelopeToBytes(envelope) {
787
+ return cborData(envelope.taggedCbor());
788
+ }
789
+ function envelopeFromBytes(bytes) {
790
+ const cbor$1 = decodeCbor(bytes);
791
+ return Envelope.fromTaggedCbor(cbor$1);
792
+ }
793
+
794
+ //#endregion
795
+ //#region src/base/envelope-decodable.ts
796
+ function extractString(envelope) {
797
+ const cbor$1 = envelope.tryLeaf();
798
+ try {
799
+ return tryIntoText(cbor$1);
800
+ } catch (error) {
801
+ throw EnvelopeError.cbor("envelope does not contain a string", error instanceof Error ? error : void 0);
802
+ }
803
+ }
804
+ function extractNumber(envelope) {
805
+ const cbor$1 = envelope.tryLeaf();
806
+ if ("type" in cbor$1) switch (cbor$1.type) {
807
+ case 0: return typeof cbor$1.value === "bigint" ? Number(cbor$1.value) : cbor$1.value;
808
+ case 1: return -(typeof cbor$1.value === "bigint" ? Number(cbor$1.value) : cbor$1.value) - 1;
809
+ case 7:
810
+ if (typeof cbor$1.value === "object" && cbor$1.value !== null && "type" in cbor$1.value && cbor$1.value.type === "Float") return cbor$1.value.value;
811
+ break;
812
+ case 2:
813
+ case 3:
814
+ case 4:
815
+ case 5:
816
+ case 6: break;
817
+ }
818
+ throw EnvelopeError.cbor("envelope does not contain a number");
819
+ }
820
+ function extractBoolean(envelope) {
821
+ const cbor$1 = envelope.tryLeaf();
822
+ try {
823
+ return tryIntoBool(cbor$1);
824
+ } catch (error) {
825
+ throw EnvelopeError.cbor("envelope does not contain a boolean", error instanceof Error ? error : void 0);
826
+ }
827
+ }
828
+ function extractBytes(envelope) {
829
+ const cbor$1 = envelope.tryLeaf();
830
+ try {
831
+ return tryIntoByteString(cbor$1);
832
+ } catch (error) {
833
+ throw EnvelopeError.cbor("envelope does not contain bytes", error instanceof Error ? error : void 0);
834
+ }
835
+ }
836
+ function extractNull(envelope) {
837
+ if (isNull(envelope.tryLeaf())) return null;
838
+ throw EnvelopeError.cbor("envelope does not contain null");
839
+ }
840
+ var EnvelopeDecoder = class EnvelopeDecoder {
841
+ static tryFromCbor(cbor$1) {
842
+ try {
843
+ return Envelope.fromTaggedCbor(cbor$1);
844
+ } catch (error) {
845
+ throw EnvelopeError.cbor("invalid envelope CBOR", error instanceof Error ? error : void 0);
846
+ }
847
+ }
848
+ static tryFromCborData(data) {
849
+ try {
850
+ const cbor$1 = decodeCbor(data);
851
+ return EnvelopeDecoder.tryFromCbor(cbor$1);
852
+ } catch (error) {
853
+ throw EnvelopeError.cbor("invalid envelope CBOR data", error instanceof Error ? error : void 0);
854
+ }
855
+ }
856
+ };
857
+ Envelope.prototype.tryLeaf = function() {
858
+ const c = this.case();
859
+ if (c.type !== "leaf") throw EnvelopeError.notLeaf();
860
+ return c.cbor;
861
+ };
862
+ Envelope.prototype.extractString = function() {
863
+ return extractString(this);
864
+ };
865
+ Envelope.prototype.extractNumber = function() {
866
+ return extractNumber(this);
867
+ };
868
+ Envelope.prototype.extractBoolean = function() {
869
+ return extractBoolean(this);
870
+ };
871
+ Envelope.prototype.extractBytes = function() {
872
+ return extractBytes(this);
873
+ };
874
+ Envelope.prototype.extractNull = function() {
875
+ return extractNull(this);
876
+ };
877
+
878
+ //#endregion
879
+ //#region src/base/elide.ts
880
+ let ObscureType = /* @__PURE__ */ function(ObscureType$1) {
881
+ ObscureType$1["Elided"] = "elided";
882
+ ObscureType$1["Encrypted"] = "encrypted";
883
+ ObscureType$1["Compressed"] = "compressed";
884
+ return ObscureType$1;
885
+ }({});
886
+ function elideAction() {
887
+ return { type: "elide" };
888
+ }
889
+ Envelope.prototype.elide = function() {
890
+ if (this.case().type === "elided") return this;
891
+ return Envelope.newElided(this.digest());
892
+ };
893
+ function elideSetWithAction(envelope, target, isRevealing, action) {
894
+ const selfDigest = envelope.digest();
895
+ if (Array.from(target).some((d) => d.equals(selfDigest)) !== isRevealing) {
896
+ if (action.type === "elide") return envelope.elide();
897
+ else if (action.type === "encrypt") throw new Error("Encryption not yet implemented");
898
+ else if (action.type === "compress") throw new Error("Compression not yet implemented");
899
+ }
900
+ const c = envelope.case();
901
+ if (c.type === "assertion") {
902
+ const elidedAssertion = new Assertion(elideSetWithAction(c.assertion.predicate(), target, isRevealing, action), elideSetWithAction(c.assertion.object(), target, isRevealing, action));
903
+ return Envelope.newWithAssertion(elidedAssertion);
904
+ } else if (c.type === "node") {
905
+ const elidedSubject = elideSetWithAction(c.subject, target, isRevealing, action);
906
+ const elidedAssertions = c.assertions.map((a) => elideSetWithAction(a, target, isRevealing, action));
907
+ return Envelope.newWithUncheckedAssertions(elidedSubject, elidedAssertions);
908
+ } else if (c.type === "wrapped") {
909
+ const elidedEnvelope = elideSetWithAction(c.envelope, target, isRevealing, action);
910
+ return Envelope.newWrapped(elidedEnvelope);
911
+ }
912
+ return envelope;
913
+ }
914
+ Envelope.prototype.elideRemovingSetWithAction = function(target, action) {
915
+ return elideSetWithAction(this, target, false, action);
916
+ };
917
+ Envelope.prototype.elideRemovingSet = function(target) {
918
+ return elideSetWithAction(this, target, false, elideAction());
919
+ };
920
+ Envelope.prototype.elideRemovingArrayWithAction = function(target, action) {
921
+ const targetSet = new Set(target.map((p) => p.digest()));
922
+ return elideSetWithAction(this, targetSet, false, action);
923
+ };
924
+ Envelope.prototype.elideRemovingArray = function(target) {
925
+ const targetSet = new Set(target.map((p) => p.digest()));
926
+ return elideSetWithAction(this, targetSet, false, elideAction());
927
+ };
928
+ Envelope.prototype.elideRemovingTargetWithAction = function(target, action) {
929
+ return this.elideRemovingArrayWithAction([target], action);
930
+ };
931
+ Envelope.prototype.elideRemovingTarget = function(target) {
932
+ return this.elideRemovingArray([target]);
933
+ };
934
+ Envelope.prototype.elideRevealingSetWithAction = function(target, action) {
935
+ return elideSetWithAction(this, target, true, action);
936
+ };
937
+ Envelope.prototype.elideRevealingSet = function(target) {
938
+ return elideSetWithAction(this, target, true, elideAction());
939
+ };
940
+ Envelope.prototype.elideRevealingArrayWithAction = function(target, action) {
941
+ const targetSet = new Set(target.map((p) => p.digest()));
942
+ return elideSetWithAction(this, targetSet, true, action);
943
+ };
944
+ Envelope.prototype.elideRevealingArray = function(target) {
945
+ const targetSet = new Set(target.map((p) => p.digest()));
946
+ return elideSetWithAction(this, targetSet, true, elideAction());
947
+ };
948
+ Envelope.prototype.elideRevealingTargetWithAction = function(target, action) {
949
+ return this.elideRevealingArrayWithAction([target], action);
950
+ };
951
+ Envelope.prototype.elideRevealingTarget = function(target) {
952
+ return this.elideRevealingArray([target]);
953
+ };
954
+ Envelope.prototype.unelide = function(envelope) {
955
+ if (this.digest().equals(envelope.digest())) return envelope;
956
+ throw EnvelopeError.invalidDigest();
957
+ };
958
+ Envelope.prototype.nodesMatching = function(targetDigests, obscureTypes) {
959
+ const result = /* @__PURE__ */ new Set();
960
+ const visitor = (envelope) => {
961
+ if (!(targetDigests === void 0 || Array.from(targetDigests).some((d) => d.equals(envelope.digest())))) return;
962
+ if (obscureTypes.length === 0) {
963
+ result.add(envelope.digest());
964
+ return;
965
+ }
966
+ const c = envelope.case();
967
+ if (obscureTypes.some((obscureType) => {
968
+ if (obscureType === ObscureType.Elided && c.type === "elided") return true;
969
+ if (obscureType === ObscureType.Encrypted && c.type === "encrypted") return true;
970
+ if (obscureType === ObscureType.Compressed && c.type === "compressed") return true;
971
+ return false;
972
+ })) result.add(envelope.digest());
973
+ };
974
+ walkEnvelope(this, visitor);
975
+ return result;
976
+ };
977
+ function walkEnvelope(envelope, visitor) {
978
+ visitor(envelope);
979
+ const c = envelope.case();
980
+ if (c.type === "node") {
981
+ walkEnvelope(c.subject, visitor);
982
+ for (const assertion of c.assertions) walkEnvelope(assertion, visitor);
983
+ } else if (c.type === "assertion") {
984
+ walkEnvelope(c.assertion.predicate(), visitor);
985
+ walkEnvelope(c.assertion.object(), visitor);
986
+ } else if (c.type === "wrapped") walkEnvelope(c.envelope, visitor);
987
+ }
988
+ Envelope.prototype.walkUnelide = function(envelopes) {
989
+ const envelopeMap = /* @__PURE__ */ new Map();
990
+ for (const env of envelopes) envelopeMap.set(env.digest().hex(), env);
991
+ return walkUnelideWithMap(this, envelopeMap);
992
+ };
993
+ function walkUnelideWithMap(envelope, envelopeMap) {
994
+ const c = envelope.case();
995
+ if (c.type === "elided") return envelopeMap.get(envelope.digest().hex()) ?? envelope;
996
+ if (c.type === "node") {
997
+ const newSubject = walkUnelideWithMap(c.subject, envelopeMap);
998
+ const newAssertions = c.assertions.map((a) => walkUnelideWithMap(a, envelopeMap));
999
+ if (newSubject.isIdenticalTo(c.subject) && newAssertions.every((a, i) => a.isIdenticalTo(c.assertions[i]))) return envelope;
1000
+ return Envelope.newWithUncheckedAssertions(newSubject, newAssertions);
1001
+ }
1002
+ if (c.type === "wrapped") {
1003
+ const newEnvelope = walkUnelideWithMap(c.envelope, envelopeMap);
1004
+ if (newEnvelope.isIdenticalTo(c.envelope)) return envelope;
1005
+ return Envelope.newWrapped(newEnvelope);
1006
+ }
1007
+ if (c.type === "assertion") {
1008
+ const newPredicate = walkUnelideWithMap(c.assertion.predicate(), envelopeMap);
1009
+ const newObject = walkUnelideWithMap(c.assertion.object(), envelopeMap);
1010
+ if (newPredicate.isIdenticalTo(c.assertion.predicate()) && newObject.isIdenticalTo(c.assertion.object())) return envelope;
1011
+ return Envelope.newAssertion(newPredicate, newObject);
1012
+ }
1013
+ return envelope;
1014
+ }
1015
+ Envelope.prototype.walkReplace = function(target, replacement) {
1016
+ if (Array.from(target).some((d) => d.equals(this.digest()))) return replacement;
1017
+ const c = this.case();
1018
+ if (c.type === "node") {
1019
+ const newSubject = c.subject.walkReplace(target, replacement);
1020
+ const newAssertions = c.assertions.map((a) => a.walkReplace(target, replacement));
1021
+ if (newSubject.isIdenticalTo(c.subject) && newAssertions.every((a, i) => a.isIdenticalTo(c.assertions[i]))) return this;
1022
+ return Envelope.newWithAssertions(newSubject, newAssertions);
1023
+ }
1024
+ if (c.type === "wrapped") {
1025
+ const newEnvelope = c.envelope.walkReplace(target, replacement);
1026
+ if (newEnvelope.isIdenticalTo(c.envelope)) return this;
1027
+ return Envelope.newWrapped(newEnvelope);
1028
+ }
1029
+ if (c.type === "assertion") {
1030
+ const newPredicate = c.assertion.predicate().walkReplace(target, replacement);
1031
+ const newObject = c.assertion.object().walkReplace(target, replacement);
1032
+ if (newPredicate.isIdenticalTo(c.assertion.predicate()) && newObject.isIdenticalTo(c.assertion.object())) return this;
1033
+ return Envelope.newAssertion(newPredicate, newObject);
1034
+ }
1035
+ return this;
1036
+ };
1037
+ Envelope.prototype.isIdenticalTo = function(other) {
1038
+ return this.digest().equals(other.digest()) && this.case().type === other.case().type;
1039
+ };
1040
+
1041
+ //#endregion
1042
+ //#region src/base/walk.ts
1043
+ let EdgeType = /* @__PURE__ */ function(EdgeType$1) {
1044
+ EdgeType$1["None"] = "none";
1045
+ EdgeType$1["Subject"] = "subject";
1046
+ EdgeType$1["Assertion"] = "assertion";
1047
+ EdgeType$1["Predicate"] = "predicate";
1048
+ EdgeType$1["Object"] = "object";
1049
+ EdgeType$1["Content"] = "content";
1050
+ return EdgeType$1;
1051
+ }({});
1052
+ function edgeLabel(edgeType) {
1053
+ switch (edgeType) {
1054
+ case EdgeType.Subject: return "subj";
1055
+ case EdgeType.Content: return "cont";
1056
+ case EdgeType.Predicate: return "pred";
1057
+ case EdgeType.Object: return "obj";
1058
+ case EdgeType.None:
1059
+ case EdgeType.Assertion: return;
1060
+ default: return;
1061
+ }
1062
+ }
1063
+ Envelope.prototype.walk = function(hideNodes, state, visit) {
1064
+ if (hideNodes) walkTree(this, 0, EdgeType.None, state, visit);
1065
+ else walkStructure(this, 0, EdgeType.None, state, visit);
1066
+ };
1067
+ function walkStructure(envelope, level, incomingEdge, state, visit) {
1068
+ const [newState, stop] = visit(envelope, level, incomingEdge, state);
1069
+ if (stop) return;
1070
+ const nextLevel = level + 1;
1071
+ const c = envelope.case();
1072
+ switch (c.type) {
1073
+ case "node":
1074
+ walkStructure(c.subject, nextLevel, EdgeType.Subject, newState, visit);
1075
+ for (const assertion of c.assertions) walkStructure(assertion, nextLevel, EdgeType.Assertion, newState, visit);
1076
+ break;
1077
+ case "wrapped":
1078
+ walkStructure(c.envelope, nextLevel, EdgeType.Content, newState, visit);
1079
+ break;
1080
+ case "assertion":
1081
+ walkStructure(c.assertion.predicate(), nextLevel, EdgeType.Predicate, newState, visit);
1082
+ walkStructure(c.assertion.object(), nextLevel, EdgeType.Object, newState, visit);
1083
+ break;
1084
+ case "leaf":
1085
+ case "elided":
1086
+ case "knownValue":
1087
+ case "encrypted":
1088
+ case "compressed": break;
1089
+ }
1090
+ }
1091
+ function walkTree(envelope, level, incomingEdge, state, visit) {
1092
+ let currentState = state;
1093
+ let subjectLevel = level;
1094
+ if (!envelope.isNode()) {
1095
+ const [newState, stop] = visit(envelope, level, incomingEdge, currentState);
1096
+ if (stop) return newState;
1097
+ currentState = newState;
1098
+ subjectLevel = level + 1;
1099
+ }
1100
+ const c = envelope.case();
1101
+ switch (c.type) {
1102
+ case "node": {
1103
+ const assertionState = walkTree(c.subject, subjectLevel, EdgeType.Subject, currentState, visit);
1104
+ const assertionLevel = subjectLevel + 1;
1105
+ for (const assertion of c.assertions) walkTree(assertion, assertionLevel, EdgeType.Assertion, assertionState, visit);
1106
+ break;
1107
+ }
1108
+ case "wrapped":
1109
+ walkTree(c.envelope, subjectLevel, EdgeType.Content, currentState, visit);
1110
+ break;
1111
+ case "assertion":
1112
+ walkTree(c.assertion.predicate(), subjectLevel, EdgeType.Predicate, currentState, visit);
1113
+ walkTree(c.assertion.object(), subjectLevel, EdgeType.Object, currentState, visit);
1114
+ break;
1115
+ case "leaf":
1116
+ case "elided":
1117
+ case "knownValue":
1118
+ case "encrypted":
1119
+ case "compressed": break;
1120
+ }
1121
+ return currentState;
1122
+ }
1123
+
1124
+ //#endregion
1125
+ //#region src/base/assertions.ts
1126
+ Envelope.prototype.addAssertionEnvelopes = function(assertions) {
1127
+ return assertions.reduce((result, assertion) => result.addAssertionEnvelope(assertion), this);
1128
+ };
1129
+ Envelope.prototype.addOptionalAssertionEnvelope = function(assertion) {
1130
+ if (assertion === void 0) return this;
1131
+ if (!assertion.isSubjectAssertion() && !assertion.isSubjectObscured()) throw EnvelopeError.invalidFormat();
1132
+ const c = this.case();
1133
+ if (c.type === "node") {
1134
+ if (c.assertions.some((a) => a.digest().equals(assertion.digest()))) return this;
1135
+ return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, assertion]);
1136
+ }
1137
+ return Envelope.newWithUncheckedAssertions(this.subject(), [assertion]);
1138
+ };
1139
+ Envelope.prototype.addOptionalAssertion = function(predicate, object) {
1140
+ if (object === void 0 || object === null) return this;
1141
+ return this.addAssertion(predicate, object);
1142
+ };
1143
+ Envelope.prototype.addNonemptyStringAssertion = function(predicate, str) {
1144
+ if (str.length === 0) return this;
1145
+ return this.addAssertion(predicate, str);
1146
+ };
1147
+ Envelope.prototype.addAssertions = function(envelopes) {
1148
+ return envelopes.reduce((result, envelope) => result.addAssertionEnvelope(envelope), this);
1149
+ };
1150
+ Envelope.prototype.addAssertionIf = function(condition, predicate, object) {
1151
+ if (condition) return this.addAssertion(predicate, object);
1152
+ return this;
1153
+ };
1154
+ Envelope.prototype.addAssertionEnvelopeIf = function(condition, assertionEnvelope) {
1155
+ if (condition) return this.addAssertionEnvelope(assertionEnvelope);
1156
+ return this;
1157
+ };
1158
+ Envelope.prototype.removeAssertion = function(target) {
1159
+ const assertions = this.assertions();
1160
+ const targetDigest = target.digest();
1161
+ const index = assertions.findIndex((a) => a.digest().equals(targetDigest));
1162
+ if (index === -1) return this;
1163
+ const newAssertions = [...assertions.slice(0, index), ...assertions.slice(index + 1)];
1164
+ if (newAssertions.length === 0) return this.subject();
1165
+ return Envelope.newWithUncheckedAssertions(this.subject(), newAssertions);
1166
+ };
1167
+ Envelope.prototype.replaceAssertion = function(assertion, newAssertion) {
1168
+ return this.removeAssertion(assertion).addAssertionEnvelope(newAssertion);
1169
+ };
1170
+ Envelope.prototype.replaceSubject = function(subject) {
1171
+ return this.assertions().reduce((e, a) => e.addAssertionEnvelope(a), subject);
1172
+ };
1173
+ Envelope.prototype.assertions = function() {
1174
+ const c = this.case();
1175
+ if (c.type === "node") return c.assertions;
1176
+ return [];
1177
+ };
1178
+
1179
+ //#endregion
1180
+ //#region src/base/leaf.ts
1181
+ Envelope.false = function() {
1182
+ return Envelope.newLeaf(false);
1183
+ };
1184
+ Envelope.true = function() {
1185
+ return Envelope.newLeaf(true);
1186
+ };
1187
+ Envelope.prototype.isFalse = function() {
1188
+ try {
1189
+ return this.extractBoolean() === false;
1190
+ } catch {
1191
+ return false;
1192
+ }
1193
+ };
1194
+ Envelope.prototype.isTrue = function() {
1195
+ try {
1196
+ return this.extractBoolean() === true;
1197
+ } catch {
1198
+ return false;
1199
+ }
1200
+ };
1201
+ Envelope.prototype.isBool = function() {
1202
+ try {
1203
+ return typeof this.extractBoolean() === "boolean";
1204
+ } catch {
1205
+ return false;
1206
+ }
1207
+ };
1208
+ Envelope.prototype.isNumber = function() {
1209
+ const leaf = this.asLeaf();
1210
+ if (leaf === void 0) return false;
1211
+ return isNumber(leaf);
1212
+ };
1213
+ Envelope.prototype.isSubjectNumber = function() {
1214
+ return this.subject().isNumber();
1215
+ };
1216
+ Envelope.prototype.isNaN = function() {
1217
+ const leaf = this.asLeaf();
1218
+ if (leaf === void 0) return false;
1219
+ if ("type" in leaf && leaf.type === 7) return isNaN(leaf);
1220
+ return false;
1221
+ };
1222
+ Envelope.prototype.isSubjectNaN = function() {
1223
+ return this.subject().isNaN();
1224
+ };
1225
+ Envelope.prototype.isNull = function() {
1226
+ try {
1227
+ this.extractNull();
1228
+ return true;
1229
+ } catch (_error) {
1230
+ return false;
1231
+ }
1232
+ };
1233
+ Envelope.prototype.tryByteString = function() {
1234
+ return this.extractBytes();
1235
+ };
1236
+ Envelope.prototype.asByteString = function() {
1237
+ try {
1238
+ return this.extractBytes();
1239
+ } catch {
1240
+ return;
1241
+ }
1242
+ };
1243
+ Envelope.prototype.asArray = function() {
1244
+ const leaf = this.asLeaf();
1245
+ if (leaf === void 0) return;
1246
+ return asArray(leaf);
1247
+ };
1248
+ Envelope.prototype.asMap = function() {
1249
+ const leaf = this.asLeaf();
1250
+ if (leaf === void 0) return;
1251
+ return asMap(leaf);
1252
+ };
1253
+ Envelope.prototype.asText = function() {
1254
+ const leaf = this.asLeaf();
1255
+ if (leaf === void 0) return;
1256
+ return asText(leaf);
1257
+ };
1258
+ Envelope.prototype.asLeaf = function() {
1259
+ const c = this.case();
1260
+ if (c.type === "leaf") return c.cbor;
1261
+ };
1262
+
1263
+ //#endregion
1264
+ //#region src/base/queries.ts
1265
+ Envelope.prototype.hasAssertions = function() {
1266
+ const c = this.case();
1267
+ return c.type === "node" && c.assertions.length > 0;
1268
+ };
1269
+ Envelope.prototype.asAssertion = function() {
1270
+ return this.case().type === "assertion" ? this : void 0;
1271
+ };
1272
+ Envelope.prototype.tryAssertion = function() {
1273
+ const result = this.asAssertion();
1274
+ if (result === void 0) throw EnvelopeError.notAssertion();
1275
+ return result;
1276
+ };
1277
+ Envelope.prototype.asPredicate = function() {
1278
+ const c = this.subject().case();
1279
+ if (c.type === "assertion") return c.assertion.predicate();
1280
+ };
1281
+ Envelope.prototype.tryPredicate = function() {
1282
+ const result = this.asPredicate();
1283
+ if (result === void 0) throw EnvelopeError.notAssertion();
1284
+ return result;
1285
+ };
1286
+ Envelope.prototype.asObject = function() {
1287
+ const c = this.subject().case();
1288
+ if (c.type === "assertion") return c.assertion.object();
1289
+ };
1290
+ Envelope.prototype.tryObject = function() {
1291
+ const result = this.asObject();
1292
+ if (result === void 0) throw EnvelopeError.notAssertion();
1293
+ return result;
1294
+ };
1295
+ Envelope.prototype.isAssertion = function() {
1296
+ return this.case().type === "assertion";
1297
+ };
1298
+ Envelope.prototype.isElided = function() {
1299
+ return this.case().type === "elided";
1300
+ };
1301
+ Envelope.prototype.isLeaf = function() {
1302
+ return this.case().type === "leaf";
1303
+ };
1304
+ Envelope.prototype.isNode = function() {
1305
+ return this.case().type === "node";
1306
+ };
1307
+ Envelope.prototype.isWrapped = function() {
1308
+ return this.case().type === "wrapped";
1309
+ };
1310
+ Envelope.prototype.isInternal = function() {
1311
+ const type = this.case().type;
1312
+ return type === "node" || type === "wrapped" || type === "assertion";
1313
+ };
1314
+ Envelope.prototype.isObscured = function() {
1315
+ const type = this.case().type;
1316
+ return type === "elided" || type === "encrypted" || type === "compressed";
1317
+ };
1318
+ Envelope.prototype.assertionsWithPredicate = function(predicate) {
1319
+ const predicateDigest = Envelope.new(predicate).digest();
1320
+ return this.assertions().filter((assertion) => {
1321
+ return assertion.subject().asPredicate()?.digest().equals(predicateDigest) === true;
1322
+ });
1323
+ };
1324
+ Envelope.prototype.assertionWithPredicate = function(predicate) {
1325
+ const matches = this.assertionsWithPredicate(predicate);
1326
+ if (matches.length === 0) throw EnvelopeError.nonexistentPredicate();
1327
+ if (matches.length > 1) throw EnvelopeError.ambiguousPredicate();
1328
+ return matches[0];
1329
+ };
1330
+ Envelope.prototype.optionalAssertionWithPredicate = function(predicate) {
1331
+ const matches = this.assertionsWithPredicate(predicate);
1332
+ if (matches.length === 0) return;
1333
+ if (matches.length > 1) throw EnvelopeError.ambiguousPredicate();
1334
+ return matches[0];
1335
+ };
1336
+ Envelope.prototype.objectForPredicate = function(predicate) {
1337
+ const obj = this.assertionWithPredicate(predicate).asObject();
1338
+ if (obj === void 0) throw EnvelopeError.notAssertion();
1339
+ return obj;
1340
+ };
1341
+ Envelope.prototype.optionalObjectForPredicate = function(predicate) {
1342
+ const matches = this.assertionsWithPredicate(predicate);
1343
+ if (matches.length === 0) return;
1344
+ if (matches.length > 1) throw EnvelopeError.ambiguousPredicate();
1345
+ return matches[0].subject().asObject();
1346
+ };
1347
+ Envelope.prototype.objectsForPredicate = function(predicate) {
1348
+ return this.assertionsWithPredicate(predicate).map((assertion) => {
1349
+ const obj = assertion.asObject();
1350
+ if (obj === void 0) throw EnvelopeError.notAssertion();
1351
+ return obj;
1352
+ });
1353
+ };
1354
+ Envelope.prototype.elementsCount = function() {
1355
+ let count = 1;
1356
+ const c = this.case();
1357
+ switch (c.type) {
1358
+ case "node":
1359
+ count += c.subject.elementsCount();
1360
+ for (const assertion of c.assertions) count += assertion.elementsCount();
1361
+ break;
1362
+ case "assertion":
1363
+ count += c.assertion.predicate().elementsCount();
1364
+ count += c.assertion.object().elementsCount();
1365
+ break;
1366
+ case "wrapped":
1367
+ count += c.envelope.elementsCount();
1368
+ break;
1369
+ case "leaf":
1370
+ case "elided":
1371
+ case "knownValue":
1372
+ case "encrypted":
1373
+ case "compressed": break;
1374
+ }
1375
+ return count;
1376
+ };
1377
+
1378
+ //#endregion
1379
+ //#region src/base/wrap.ts
1380
+ Envelope.prototype.wrap = function() {
1381
+ return Envelope.newWrapped(this);
1382
+ };
1383
+ Envelope.prototype.tryUnwrap = function() {
1384
+ const c = this.subject().case();
1385
+ if (c.type === "wrapped") return c.envelope;
1386
+ throw EnvelopeError.notWrapped();
1387
+ };
1388
+ Envelope.prototype.unwrap = function() {
1389
+ return this.tryUnwrap();
1390
+ };
1391
+
1392
+ //#endregion
1393
+ //#region src/extension/types.ts
1394
+ const IS_A = "isA";
1395
+ if (Envelope?.prototype) {
1396
+ Envelope.prototype.addType = function(object) {
1397
+ return this.addAssertion(IS_A, object);
1398
+ };
1399
+ Envelope.prototype.types = function() {
1400
+ return this.objectsForPredicate(IS_A);
1401
+ };
1402
+ Envelope.prototype.getType = function() {
1403
+ const t = this.types();
1404
+ if (t.length === 0) throw EnvelopeError.invalidType();
1405
+ if (t.length === 1) return t[0];
1406
+ throw EnvelopeError.ambiguousType();
1407
+ };
1408
+ Envelope.prototype.hasType = function(t) {
1409
+ const e = Envelope.new(t);
1410
+ return this.types().some((x) => x.digest().equals(e.digest()));
1411
+ };
1412
+ Envelope.prototype.checkType = function(t) {
1413
+ if (!this.hasType(t)) throw EnvelopeError.invalidType();
1414
+ };
1415
+ }
1416
+
1417
+ //#endregion
1418
+ //#region src/extension/salt.ts
1419
+ const SALT = "salt";
1420
+ const MIN_SALT_SIZE = 8;
1421
+ function createSecureRng() {
1422
+ return new SecureRandomNumberGenerator();
1423
+ }
1424
+ function generateRandomBytes(length, rng) {
1425
+ return rngRandomData(rng ?? createSecureRng(), length);
1426
+ }
1427
+ function calculateProportionalSaltSize(envelopeSize, rng) {
1428
+ const actualRng = rng ?? createSecureRng();
1429
+ const count = envelopeSize;
1430
+ const minSize = Math.max(8, Math.ceil(count * .05));
1431
+ return rngNextInClosedRangeI32(actualRng, minSize, Math.max(minSize + 8, Math.ceil(count * .25)));
1432
+ }
1433
+ if (Envelope?.prototype) {
1434
+ Envelope.prototype.addSalt = function() {
1435
+ const rng = createSecureRng();
1436
+ const envelopeSize = this.cborBytes().length;
1437
+ const saltBytes = generateRandomBytes(calculateProportionalSaltSize(envelopeSize, rng), rng);
1438
+ return this.addAssertion(SALT, saltBytes);
1439
+ };
1440
+ Envelope.prototype.addSaltWithLength = function(count) {
1441
+ if (count < MIN_SALT_SIZE) throw EnvelopeError.general(`Salt must be at least ${MIN_SALT_SIZE} bytes, got ${count}`);
1442
+ const saltBytes = generateRandomBytes(count);
1443
+ return this.addAssertion(SALT, saltBytes);
1444
+ };
1445
+ Envelope.prototype.addSaltBytes = function(saltBytes) {
1446
+ if (saltBytes.length < MIN_SALT_SIZE) throw EnvelopeError.general(`Salt must be at least ${MIN_SALT_SIZE} bytes, got ${saltBytes.length}`);
1447
+ return this.addAssertion(SALT, saltBytes);
1448
+ };
1449
+ Envelope.prototype.addSaltInRange = function(min, max) {
1450
+ if (min < MIN_SALT_SIZE) throw EnvelopeError.general(`Minimum salt size must be at least ${MIN_SALT_SIZE} bytes, got ${min}`);
1451
+ if (max < min) throw EnvelopeError.general(`Maximum salt size must be at least minimum, got min=${min} max=${max}`);
1452
+ const rng = createSecureRng();
1453
+ const saltBytes = generateRandomBytes(rngNextInClosedRangeI32(rng, min, max), rng);
1454
+ return this.addAssertion(SALT, saltBytes);
1455
+ };
1456
+ }
1457
+
1458
+ //#endregion
1459
+ //#region src/extension/signature.ts
1460
+ /**
1461
+ * Signature Extension for Gordian Envelope
1462
+ *
1463
+ * Provides functionality for digitally signing Envelopes and verifying signatures,
1464
+ * with optional metadata support.
1465
+ *
1466
+ * The signature extension allows:
1467
+ * - Signing envelope subjects to validate their authenticity
1468
+ * - Adding metadata to signatures (e.g., signer identity, date, purpose)
1469
+ * - Verification of signatures, both with and without metadata
1470
+ * - Support for multiple signatures on a single envelope
1471
+ */
1472
+ /**
1473
+ * Known value for the 'signed' predicate.
1474
+ * This is the standard predicate used for signature assertions.
1475
+ */
1476
+ const SIGNED = "signed";
1477
+ /**
1478
+ * Known value for the 'verifiedBy' predicate.
1479
+ * Used to indicate verification status.
1480
+ */
1481
+ const VERIFIED_BY = "verifiedBy";
1482
+ /**
1483
+ * Known value for the 'note' predicate.
1484
+ * Used for adding notes/comments to signatures.
1485
+ */
1486
+ const NOTE = "note";
1487
+ /**
1488
+ * Represents a cryptographic signature.
1489
+ */
1490
+ var Signature = class Signature {
1491
+ #data;
1492
+ constructor(data) {
1493
+ this.#data = data;
1494
+ }
1495
+ /**
1496
+ * Returns the raw signature bytes.
1497
+ */
1498
+ data() {
1499
+ return this.#data;
1500
+ }
1501
+ /**
1502
+ * Returns the hex-encoded signature.
1503
+ */
1504
+ hex() {
1505
+ return Array.from(this.#data).map((b) => b.toString(16).padStart(2, "0")).join("");
1506
+ }
1507
+ /**
1508
+ * Creates a Signature from hex string.
1509
+ */
1510
+ static fromHex(hex) {
1511
+ const bytes = new Uint8Array(hex.length / 2);
1512
+ for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
1513
+ return new Signature(bytes);
1514
+ }
1515
+ };
1516
+ /**
1517
+ * ECDSA signing key using secp256k1 curve.
1518
+ * Uses @bcts/crypto functions.
1519
+ */
1520
+ var SigningPrivateKey = class SigningPrivateKey {
1521
+ #privateKey;
1522
+ constructor(privateKey) {
1523
+ if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);
1524
+ this.#privateKey = privateKey;
1525
+ }
1526
+ /**
1527
+ * Generates a new random private key.
1528
+ */
1529
+ static generate() {
1530
+ return new SigningPrivateKey(rngRandomData(new SecureRandomNumberGenerator(), ECDSA_PRIVATE_KEY_SIZE));
1531
+ }
1532
+ /**
1533
+ * Creates a private key from hex string.
1534
+ */
1535
+ static fromHex(hex) {
1536
+ const bytes = new Uint8Array(hex.length / 2);
1537
+ for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
1538
+ return new SigningPrivateKey(bytes);
1539
+ }
1540
+ /**
1541
+ * Returns the corresponding public key.
1542
+ */
1543
+ publicKey() {
1544
+ return new SigningPublicKey(ecdsaPublicKeyFromPrivateKey(this.#privateKey));
1545
+ }
1546
+ /**
1547
+ * Signs data and returns a Signature.
1548
+ */
1549
+ sign(data) {
1550
+ return new Signature(ecdsaSign(this.#privateKey, data));
1551
+ }
1552
+ /**
1553
+ * Returns the raw private key bytes.
1554
+ */
1555
+ data() {
1556
+ return this.#privateKey;
1557
+ }
1558
+ };
1559
+ /**
1560
+ * ECDSA public key for signature verification using secp256k1 curve.
1561
+ * Uses @bcts/crypto functions.
1562
+ */
1563
+ var SigningPublicKey = class SigningPublicKey {
1564
+ #publicKey;
1565
+ constructor(publicKey) {
1566
+ if (publicKey.length !== ECDSA_PUBLIC_KEY_SIZE && publicKey.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${ECDSA_PUBLIC_KEY_SIZE} bytes (compressed) or ${ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE} bytes (uncompressed)`);
1567
+ this.#publicKey = publicKey;
1568
+ }
1569
+ /**
1570
+ * Creates a public key from hex string.
1571
+ */
1572
+ static fromHex(hex) {
1573
+ const bytes = new Uint8Array(hex.length / 2);
1574
+ for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
1575
+ return new SigningPublicKey(bytes);
1576
+ }
1577
+ /**
1578
+ * Verifies a signature against the provided data.
1579
+ */
1580
+ verify(data, signature) {
1581
+ try {
1582
+ return ecdsaVerify(this.#publicKey, signature.data(), data);
1583
+ } catch {
1584
+ return false;
1585
+ }
1586
+ }
1587
+ /**
1588
+ * Returns the raw public key bytes.
1589
+ */
1590
+ data() {
1591
+ return this.#publicKey;
1592
+ }
1593
+ /**
1594
+ * Returns the hex-encoded public key.
1595
+ */
1596
+ hex() {
1597
+ return Array.from(this.#publicKey).map((b) => b.toString(16).padStart(2, "0")).join("");
1598
+ }
1599
+ };
1600
+ /**
1601
+ * Metadata that can be attached to a signature.
1602
+ */
1603
+ var SignatureMetadata = class SignatureMetadata {
1604
+ #assertions = [];
1605
+ /**
1606
+ * Adds an assertion to the metadata.
1607
+ */
1608
+ withAssertion(predicate, object) {
1609
+ const metadata = new SignatureMetadata();
1610
+ metadata.#assertions.push(...this.#assertions);
1611
+ metadata.#assertions.push([predicate, object]);
1612
+ return metadata;
1613
+ }
1614
+ /**
1615
+ * Returns all assertions in the metadata.
1616
+ */
1617
+ assertions() {
1618
+ return this.#assertions;
1619
+ }
1620
+ /**
1621
+ * Returns true if this metadata has any assertions.
1622
+ */
1623
+ hasAssertions() {
1624
+ return this.#assertions.length > 0;
1625
+ }
1626
+ };
1627
+ if (Envelope?.prototype) {
1628
+ Envelope.prototype.addSignature = function(signer) {
1629
+ return this.addSignatureWithMetadata(signer, void 0);
1630
+ };
1631
+ Envelope.prototype.addSignatureWithMetadata = function(signer, metadata) {
1632
+ const digest = this.subject().digest();
1633
+ const signature = signer.sign(digest.data());
1634
+ let signatureEnvelope = Envelope.new(signature.data());
1635
+ if (metadata?.hasAssertions() === true) {
1636
+ for (const [predicate, object] of metadata.assertions()) signatureEnvelope = signatureEnvelope.addAssertion(predicate, object);
1637
+ signatureEnvelope = signatureEnvelope.wrap();
1638
+ const outerSignature = signer.sign(signatureEnvelope.digest().data());
1639
+ signatureEnvelope = signatureEnvelope.addAssertion(SIGNED, outerSignature.data());
1640
+ }
1641
+ return this.addAssertion(SIGNED, signatureEnvelope);
1642
+ };
1643
+ Envelope.prototype.addSignatures = function(signers) {
1644
+ return signers.reduce((envelope, signer) => envelope.addSignature(signer), this);
1645
+ };
1646
+ Envelope.prototype.hasSignatureFrom = function(verifier) {
1647
+ const subjectDigest = this.subject().digest();
1648
+ const signatures = this.signatures();
1649
+ for (const sigEnvelope of signatures) {
1650
+ const c = sigEnvelope.case();
1651
+ if (c.type === "leaf") try {
1652
+ const sigData = sigEnvelope.asByteString();
1653
+ if (sigData !== void 0) {
1654
+ const signature = new Signature(sigData);
1655
+ if (verifier.verify(subjectDigest.data(), signature)) return true;
1656
+ }
1657
+ } catch {
1658
+ continue;
1659
+ }
1660
+ else if (c.type === "node") {
1661
+ const outerSigs = sigEnvelope.assertions().filter((a) => {
1662
+ const aC = a.case();
1663
+ if (aC.type === "assertion") {
1664
+ const pred = aC.assertion.predicate();
1665
+ try {
1666
+ return pred.asText() === SIGNED;
1667
+ } catch {
1668
+ return false;
1669
+ }
1670
+ }
1671
+ return false;
1672
+ });
1673
+ for (const outerSig of outerSigs) {
1674
+ const outerSigCase = outerSig.case();
1675
+ if (outerSigCase.type === "assertion") {
1676
+ const outerSigObj = outerSigCase.assertion.object();
1677
+ try {
1678
+ const outerSigData = outerSigObj.asByteString();
1679
+ if (outerSigData !== void 0) {
1680
+ const outerSignature = new Signature(outerSigData);
1681
+ const nodeSubject = c.subject;
1682
+ const nodeSubjectCase = nodeSubject.case();
1683
+ if (nodeSubjectCase.type === "wrapped" && verifier.verify(nodeSubject.digest().data(), outerSignature)) {
1684
+ const innerSigData = nodeSubjectCase.envelope.subject().asByteString();
1685
+ if (innerSigData !== void 0) {
1686
+ const innerSignature = new Signature(innerSigData);
1687
+ if (verifier.verify(subjectDigest.data(), innerSignature)) return true;
1688
+ }
1689
+ }
1690
+ }
1691
+ } catch {
1692
+ continue;
1693
+ }
1694
+ }
1695
+ }
1696
+ }
1697
+ }
1698
+ return false;
1699
+ };
1700
+ Envelope.prototype.verifySignatureFrom = function(verifier) {
1701
+ if (this.hasSignatureFrom(verifier)) return this;
1702
+ throw EnvelopeError.general("No valid signature found from the given verifier");
1703
+ };
1704
+ Envelope.prototype.signatures = function() {
1705
+ return this.assertions().filter((a) => {
1706
+ const c = a.case();
1707
+ if (c.type === "assertion") {
1708
+ const pred = c.assertion.predicate();
1709
+ try {
1710
+ return pred.asText() === SIGNED;
1711
+ } catch {
1712
+ return false;
1713
+ }
1714
+ }
1715
+ return false;
1716
+ }).map((a) => {
1717
+ const c = a.case();
1718
+ if (c.type === "assertion") return c.assertion.object();
1719
+ throw EnvelopeError.general("Invalid signature assertion");
1720
+ });
1721
+ };
1722
+ }
1723
+
1724
+ //#endregion
1725
+ //#region src/extension/attachment.ts
1726
+ /**
1727
+ * Attachment Extension for Gordian Envelope
1728
+ *
1729
+ * Provides functionality for attaching vendor-specific metadata to envelopes.
1730
+ * Attachments enable flexible, extensible data storage without modifying
1731
+ * the core data model, facilitating interoperability and future compatibility.
1732
+ *
1733
+ * Each attachment has:
1734
+ * - A payload (arbitrary data)
1735
+ * - A required vendor identifier (typically a reverse domain name)
1736
+ * - An optional conformsTo URI that indicates the format of the attachment
1737
+ *
1738
+ * See BCR-2023-006: https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2023-006-envelope-attachment.md
1739
+ */
1740
+ /**
1741
+ * Known value for the 'attachment' predicate.
1742
+ */
1743
+ const ATTACHMENT = "attachment";
1744
+ /**
1745
+ * Known value for the 'vendor' predicate.
1746
+ */
1747
+ const VENDOR = "vendor";
1748
+ /**
1749
+ * Known value for the 'conformsTo' predicate.
1750
+ */
1751
+ const CONFORMS_TO = "conformsTo";
1752
+ /**
1753
+ * A container for vendor-specific metadata attachments.
1754
+ *
1755
+ * Attachments provides a flexible mechanism for attaching arbitrary metadata
1756
+ * to envelopes without modifying their core structure.
1757
+ */
1758
+ var Attachments = class Attachments {
1759
+ #envelopes = /* @__PURE__ */ new Map();
1760
+ /**
1761
+ * Creates a new empty attachments container.
1762
+ */
1763
+ constructor() {}
1764
+ /**
1765
+ * Adds a new attachment with the specified payload and metadata.
1766
+ *
1767
+ * @param payload - The data to attach
1768
+ * @param vendor - A string identifying the entity that defined the attachment format
1769
+ * @param conformsTo - Optional URI identifying the structure the payload conforms to
1770
+ */
1771
+ add(payload, vendor, conformsTo) {
1772
+ const attachment = Envelope.newAttachment(payload, vendor, conformsTo);
1773
+ this.#envelopes.set(attachment.digest().hex(), attachment);
1774
+ }
1775
+ /**
1776
+ * Retrieves an attachment by its digest.
1777
+ *
1778
+ * @param digest - The unique digest of the attachment to retrieve
1779
+ * @returns The envelope if found, or undefined
1780
+ */
1781
+ get(digest) {
1782
+ return this.#envelopes.get(digest.hex());
1783
+ }
1784
+ /**
1785
+ * Removes an attachment by its digest.
1786
+ *
1787
+ * @param digest - The unique digest of the attachment to remove
1788
+ * @returns The removed envelope if found, or undefined
1789
+ */
1790
+ remove(digest) {
1791
+ const envelope = this.#envelopes.get(digest.hex());
1792
+ this.#envelopes.delete(digest.hex());
1793
+ return envelope;
1794
+ }
1795
+ /**
1796
+ * Removes all attachments from the container.
1797
+ */
1798
+ clear() {
1799
+ this.#envelopes.clear();
1800
+ }
1801
+ /**
1802
+ * Returns whether the container has any attachments.
1803
+ */
1804
+ isEmpty() {
1805
+ return this.#envelopes.size === 0;
1806
+ }
1807
+ /**
1808
+ * Adds all attachments from this container to an envelope.
1809
+ *
1810
+ * @param envelope - The envelope to add attachments to
1811
+ * @returns A new envelope with all attachments added as assertions
1812
+ */
1813
+ addToEnvelope(envelope) {
1814
+ let result = envelope;
1815
+ for (const attachment of this.#envelopes.values()) result = result.addAssertion(ATTACHMENT, attachment);
1816
+ return result;
1817
+ }
1818
+ /**
1819
+ * Creates an Attachments container from an envelope's attachment assertions.
1820
+ *
1821
+ * @param envelope - The envelope to extract attachments from
1822
+ * @returns A new Attachments container with the envelope's attachments
1823
+ */
1824
+ static fromEnvelope(envelope) {
1825
+ const attachments = new Attachments();
1826
+ const attachmentEnvelopes = envelope.attachments();
1827
+ for (const attachment of attachmentEnvelopes) attachments.#envelopes.set(attachment.digest().hex(), attachment);
1828
+ return attachments;
1829
+ }
1830
+ };
1831
+ /**
1832
+ * Creates a new attachment envelope.
1833
+ */
1834
+ Envelope.newAttachment = function(payload, vendor, conformsTo) {
1835
+ let attachmentObj = Envelope.new(payload).wrap().addAssertion(VENDOR, vendor);
1836
+ if (conformsTo !== void 0) attachmentObj = attachmentObj.addAssertion(CONFORMS_TO, conformsTo);
1837
+ return Envelope.new(ATTACHMENT).addAssertion(ATTACHMENT, attachmentObj).assertions()[0];
1838
+ };
1839
+ /**
1840
+ * Adds an attachment to an envelope.
1841
+ */
1842
+ if (Envelope?.prototype) {
1843
+ Envelope.prototype.addAttachment = function(payload, vendor, conformsTo) {
1844
+ let attachmentObj = Envelope.new(payload).wrap().addAssertion(VENDOR, vendor);
1845
+ if (conformsTo !== void 0) attachmentObj = attachmentObj.addAssertion(CONFORMS_TO, conformsTo);
1846
+ return this.addAssertion(ATTACHMENT, attachmentObj);
1847
+ };
1848
+ /**
1849
+ * Returns the payload of an attachment envelope.
1850
+ */
1851
+ Envelope.prototype.attachmentPayload = function() {
1852
+ const c = this.case();
1853
+ if (c.type !== "assertion") throw EnvelopeError.general("Envelope is not an attachment assertion");
1854
+ return c.assertion.object().unwrap();
1855
+ };
1856
+ /**
1857
+ * Returns the vendor of an attachment envelope.
1858
+ */
1859
+ Envelope.prototype.attachmentVendor = function() {
1860
+ const c = this.case();
1861
+ if (c.type !== "assertion") throw EnvelopeError.general("Envelope is not an attachment assertion");
1862
+ const vendor = c.assertion.object().objectForPredicate(VENDOR).asText();
1863
+ if (vendor === void 0 || vendor === "") throw EnvelopeError.general("Attachment has no vendor");
1864
+ return vendor;
1865
+ };
1866
+ /**
1867
+ * Returns the conformsTo of an attachment envelope.
1868
+ */
1869
+ Envelope.prototype.attachmentConformsTo = function() {
1870
+ const c = this.case();
1871
+ if (c.type !== "assertion") throw EnvelopeError.general("Envelope is not an attachment assertion");
1872
+ const conformsToEnv = c.assertion.object().optionalObjectForPredicate(CONFORMS_TO);
1873
+ if (conformsToEnv === void 0) return;
1874
+ return conformsToEnv.asText();
1875
+ };
1876
+ /**
1877
+ * Returns all attachment assertions.
1878
+ */
1879
+ Envelope.prototype.attachments = function() {
1880
+ return this.assertionsWithPredicate(ATTACHMENT).map((a) => {
1881
+ const c = a.case();
1882
+ if (c.type === "assertion") return c.assertion.object();
1883
+ throw EnvelopeError.general("Invalid attachment assertion");
1884
+ });
1885
+ };
1886
+ /**
1887
+ * Returns attachments matching vendor and/or conformsTo.
1888
+ */
1889
+ Envelope.prototype.attachmentsWithVendorAndConformsTo = function(vendor, conformsTo) {
1890
+ return this.attachments().filter((attachment) => {
1891
+ try {
1892
+ if (vendor !== void 0) {
1893
+ if (attachment.objectForPredicate(VENDOR).asText() !== vendor) return false;
1894
+ }
1895
+ if (conformsTo !== void 0) {
1896
+ const conformsToEnv = attachment.optionalObjectForPredicate(CONFORMS_TO);
1897
+ if (conformsToEnv === void 0) return false;
1898
+ if (conformsToEnv.asText() !== conformsTo) return false;
1899
+ }
1900
+ return true;
1901
+ } catch {
1902
+ return false;
1903
+ }
1904
+ });
1905
+ };
1906
+ }
1907
+
1908
+ //#endregion
1909
+ //#region src/extension/recipient.ts
1910
+ const HAS_RECIPIENT = "hasRecipient";
1911
+ var PublicKeyBase = class PublicKeyBase {
1912
+ #publicKey;
1913
+ constructor(publicKey) {
1914
+ if (publicKey.length !== X25519_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${X25519_PUBLIC_KEY_SIZE} bytes`);
1915
+ this.#publicKey = publicKey;
1916
+ }
1917
+ data() {
1918
+ return this.#publicKey;
1919
+ }
1920
+ hex() {
1921
+ return Array.from(this.#publicKey).map((b) => b.toString(16).padStart(2, "0")).join("");
1922
+ }
1923
+ static fromHex(hex) {
1924
+ if (hex.length !== 64) throw new Error("Hex string must be 64 characters (32 bytes)");
1925
+ const bytes = new Uint8Array(32);
1926
+ for (let i = 0; i < 32; i++) bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
1927
+ return new PublicKeyBase(bytes);
1928
+ }
1929
+ };
1930
+ var PrivateKeyBase = class PrivateKeyBase {
1931
+ #privateKey;
1932
+ #publicKey;
1933
+ constructor(privateKey, publicKey) {
1934
+ this.#privateKey = privateKey;
1935
+ this.#publicKey = new PublicKeyBase(publicKey);
1936
+ }
1937
+ static generate() {
1938
+ const privateKey = x25519NewPrivateKeyUsing(new SecureRandomNumberGenerator());
1939
+ return new PrivateKeyBase(privateKey, x25519PublicKeyFromPrivateKey(privateKey));
1940
+ }
1941
+ static fromBytes(privateKey, publicKey) {
1942
+ if (privateKey.length !== X25519_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${X25519_PRIVATE_KEY_SIZE} bytes`);
1943
+ if (publicKey.length !== X25519_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${X25519_PUBLIC_KEY_SIZE} bytes`);
1944
+ return new PrivateKeyBase(privateKey, publicKey);
1945
+ }
1946
+ static fromHex(privateHex, publicHex) {
1947
+ const privateBytes = new Uint8Array(32);
1948
+ const publicBytes = new Uint8Array(32);
1949
+ for (let i = 0; i < 32; i++) {
1950
+ privateBytes[i] = parseInt(privateHex.substr(i * 2, 2), 16);
1951
+ publicBytes[i] = parseInt(publicHex.substr(i * 2, 2), 16);
1952
+ }
1953
+ return new PrivateKeyBase(privateBytes, publicBytes);
1954
+ }
1955
+ publicKeys() {
1956
+ return this.#publicKey;
1957
+ }
1958
+ data() {
1959
+ return this.#privateKey;
1960
+ }
1961
+ hex() {
1962
+ return Array.from(this.#privateKey).map((b) => b.toString(16).padStart(2, "0")).join("");
1963
+ }
1964
+ unseal(sealedMessage) {
1965
+ try {
1966
+ const decrypted = sealedMessage.decrypt(this.#privateKey, this.#publicKey.data());
1967
+ return SymmetricKey.from(decrypted);
1968
+ } catch (_error) {
1969
+ throw EnvelopeError.general("Failed to unseal message: not a recipient");
1970
+ }
1971
+ }
1972
+ };
1973
+ var SealedMessage = class SealedMessage {
1974
+ #data;
1975
+ constructor(data) {
1976
+ this.#data = data;
1977
+ }
1978
+ static seal(contentKey, recipientPublicKey) {
1979
+ const rng = new SecureRandomNumberGenerator();
1980
+ const ephemeralPrivate = x25519NewPrivateKeyUsing(rng);
1981
+ const ephemeralPublic = x25519PublicKeyFromPrivateKey(ephemeralPrivate);
1982
+ const encryptionKey = hkdfHmacSha256(x25519SharedKey(ephemeralPrivate, recipientPublicKey.data()), new TextEncoder().encode("sealed_message"), 32);
1983
+ const nonce = rngRandomData(rng, SYMMETRIC_NONCE_SIZE);
1984
+ const [ciphertext, authTag] = aeadChaCha20Poly1305EncryptWithAad(contentKey.data(), encryptionKey, nonce, new Uint8Array(0));
1985
+ const totalLength = ephemeralPublic.length + nonce.length + ciphertext.length + authTag.length;
1986
+ const sealed = new Uint8Array(totalLength);
1987
+ let offset = 0;
1988
+ sealed.set(ephemeralPublic, offset);
1989
+ offset += ephemeralPublic.length;
1990
+ sealed.set(nonce, offset);
1991
+ offset += nonce.length;
1992
+ sealed.set(ciphertext, offset);
1993
+ offset += ciphertext.length;
1994
+ sealed.set(authTag, offset);
1995
+ return new SealedMessage(sealed);
1996
+ }
1997
+ decrypt(recipientPrivate, _recipientPublic) {
1998
+ const minLength = X25519_PUBLIC_KEY_SIZE + SYMMETRIC_NONCE_SIZE + SYMMETRIC_AUTH_SIZE;
1999
+ if (this.#data.length < minLength) throw new Error("Sealed message too short");
2000
+ let offset = 0;
2001
+ const ephemeralPublic = this.#data.slice(offset, offset + X25519_PUBLIC_KEY_SIZE);
2002
+ offset += X25519_PUBLIC_KEY_SIZE;
2003
+ const nonce = this.#data.slice(offset, offset + SYMMETRIC_NONCE_SIZE);
2004
+ offset += SYMMETRIC_NONCE_SIZE;
2005
+ const ciphertextAndTag = this.#data.slice(offset);
2006
+ const ciphertext = ciphertextAndTag.slice(0, -SYMMETRIC_AUTH_SIZE);
2007
+ const authTag = ciphertextAndTag.slice(-SYMMETRIC_AUTH_SIZE);
2008
+ return aeadChaCha20Poly1305DecryptWithAad(ciphertext, hkdfHmacSha256(x25519SharedKey(recipientPrivate, ephemeralPublic), new TextEncoder().encode("sealed_message"), 32), nonce, new Uint8Array(0), authTag);
2009
+ }
2010
+ data() {
2011
+ return this.#data;
2012
+ }
2013
+ hex() {
2014
+ return Array.from(this.#data).map((b) => b.toString(16).padStart(2, "0")).join("");
2015
+ }
2016
+ static fromHex(hex) {
2017
+ const bytes = new Uint8Array(hex.length / 2);
2018
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
2019
+ return new SealedMessage(bytes);
2020
+ }
2021
+ };
2022
+ if (Envelope?.prototype) {
2023
+ Envelope.prototype.encryptSubjectToRecipient = function(recipientPublicKey) {
2024
+ const contentKey = SymmetricKey.generate();
2025
+ return this.encryptSubject(contentKey).addRecipient(recipientPublicKey, contentKey);
2026
+ };
2027
+ Envelope.prototype.encryptSubjectToRecipients = function(recipients) {
2028
+ if (recipients.length === 0) throw EnvelopeError.general("Must provide at least one recipient");
2029
+ const contentKey = SymmetricKey.generate();
2030
+ let result = this.encryptSubject(contentKey);
2031
+ for (const recipient of recipients) result = result.addRecipient(recipient, contentKey);
2032
+ return result;
2033
+ };
2034
+ Envelope.prototype.addRecipient = function(recipientPublicKey, contentKey) {
2035
+ const sealedMessage = SealedMessage.seal(contentKey, recipientPublicKey);
2036
+ return this.addAssertion(HAS_RECIPIENT, sealedMessage.data());
2037
+ };
2038
+ Envelope.prototype.decryptSubjectToRecipient = function(recipientPrivateKey) {
2039
+ if (this.subject().case().type !== "encrypted") throw EnvelopeError.general("Subject is not encrypted");
2040
+ const recipientAssertions = this.assertions().filter((assertion) => {
2041
+ try {
2042
+ const predicate = assertion.subject().asPredicate();
2043
+ if (predicate === void 0) return false;
2044
+ return predicate.asText() === HAS_RECIPIENT;
2045
+ } catch {
2046
+ return false;
2047
+ }
2048
+ });
2049
+ if (recipientAssertions.length === 0) throw EnvelopeError.general("No recipients found");
2050
+ let contentKey = null;
2051
+ for (const assertion of recipientAssertions) try {
2052
+ const obj = assertion.subject().asObject();
2053
+ if (obj === void 0) continue;
2054
+ const sealedData = obj.asByteString();
2055
+ if (sealedData === void 0) continue;
2056
+ const sealedMessage = new SealedMessage(sealedData);
2057
+ contentKey = recipientPrivateKey.unseal(sealedMessage);
2058
+ break;
2059
+ } catch {
2060
+ continue;
2061
+ }
2062
+ if (contentKey === null) throw EnvelopeError.general("Not a valid recipient");
2063
+ return this.decryptSubject(contentKey);
2064
+ };
2065
+ Envelope.prototype.decryptToRecipient = function(recipientPrivateKey) {
2066
+ return this.decryptSubjectToRecipient(recipientPrivateKey).unwrap();
2067
+ };
2068
+ Envelope.prototype.encryptToRecipients = function(recipients) {
2069
+ return this.wrap().encryptSubjectToRecipients(recipients);
2070
+ };
2071
+ Envelope.prototype.recipients = function() {
2072
+ return this.assertions().filter((assertion) => {
2073
+ try {
2074
+ const predicate = assertion.subject().asPredicate();
2075
+ if (predicate === void 0) return false;
2076
+ return predicate.asText() === HAS_RECIPIENT;
2077
+ } catch {
2078
+ return false;
2079
+ }
2080
+ }).map((assertion) => {
2081
+ const obj = assertion.subject().asObject();
2082
+ if (obj === void 0) throw EnvelopeError.general("Invalid recipient assertion");
2083
+ const sealedData = obj.asByteString();
2084
+ if (sealedData === void 0) throw EnvelopeError.general("Invalid recipient data");
2085
+ return new SealedMessage(sealedData);
2086
+ });
2087
+ };
2088
+ }
2089
+
2090
+ //#endregion
2091
+ //#region src/extension/expression.ts
2092
+ const CBOR_TAG_FUNCTION = 40006;
2093
+ const CBOR_TAG_PARAMETER = 40007;
2094
+ const CBOR_TAG_PLACEHOLDER = 40008;
2095
+ const CBOR_TAG_REPLACEMENT = 40009;
2096
+ const FUNCTION_IDS = {
2097
+ ADD: 1,
2098
+ SUB: 2,
2099
+ MUL: 3,
2100
+ DIV: 4,
2101
+ NEG: 5,
2102
+ LT: 6,
2103
+ LE: 7,
2104
+ GT: 8,
2105
+ GE: 9,
2106
+ EQ: 10,
2107
+ NE: 11,
2108
+ AND: 12,
2109
+ OR: 13,
2110
+ XOR: 14,
2111
+ NOT: 15
2112
+ };
2113
+ const PARAMETER_IDS = {
2114
+ BLANK: 1,
2115
+ LHS: 2,
2116
+ RHS: 3
2117
+ };
2118
+ var Function = class Function {
2119
+ #id;
2120
+ constructor(id) {
2121
+ this.#id = id;
2122
+ }
2123
+ id() {
2124
+ return this.#id;
2125
+ }
2126
+ isNumeric() {
2127
+ return typeof this.#id === "number";
2128
+ }
2129
+ isString() {
2130
+ return typeof this.#id === "string";
2131
+ }
2132
+ envelope() {
2133
+ const functionStr = typeof this.#id === "number" ? `«${this.#id}»` : `«"${this.#id}"»`;
2134
+ return Envelope.new(functionStr);
2135
+ }
2136
+ withParameter(param, value) {
2137
+ return new Expression(this).withParameter(param, value);
2138
+ }
2139
+ static fromNumeric(id) {
2140
+ return new Function(id);
2141
+ }
2142
+ static fromString(name) {
2143
+ return new Function(name);
2144
+ }
2145
+ toString() {
2146
+ return typeof this.#id === "number" ? `«${this.#id}»` : `«"${this.#id}"»`;
2147
+ }
2148
+ };
2149
+ var Parameter = class Parameter {
2150
+ #id;
2151
+ #value;
2152
+ constructor(id, value) {
2153
+ this.#id = id;
2154
+ this.#value = value;
2155
+ }
2156
+ id() {
2157
+ return this.#id;
2158
+ }
2159
+ value() {
2160
+ return this.#value;
2161
+ }
2162
+ isNumeric() {
2163
+ return typeof this.#id === "number";
2164
+ }
2165
+ isString() {
2166
+ return typeof this.#id === "string";
2167
+ }
2168
+ envelope() {
2169
+ const paramStr = typeof this.#id === "number" ? `❰${this.#id}❱` : `❰"${this.#id}"❱`;
2170
+ return Envelope.newAssertion(paramStr, this.#value);
2171
+ }
2172
+ static blank(value) {
2173
+ return new Parameter(PARAMETER_IDS.BLANK, Envelope.new(value));
2174
+ }
2175
+ static lhs(value) {
2176
+ return new Parameter(PARAMETER_IDS.LHS, Envelope.new(value));
2177
+ }
2178
+ static rhs(value) {
2179
+ return new Parameter(PARAMETER_IDS.RHS, Envelope.new(value));
2180
+ }
2181
+ toString() {
2182
+ return `${typeof this.#id === "number" ? `❰${this.#id}❱` : `❰"${this.#id}"❱`}: ${this.#value.asText()}`;
2183
+ }
2184
+ };
2185
+ var Expression = class Expression {
2186
+ #function;
2187
+ #parameters = /* @__PURE__ */ new Map();
2188
+ #envelope = null;
2189
+ constructor(func) {
2190
+ this.#function = func;
2191
+ }
2192
+ function() {
2193
+ return this.#function;
2194
+ }
2195
+ parameters() {
2196
+ return Array.from(this.#parameters.values());
2197
+ }
2198
+ withParameter(param, value) {
2199
+ const key = typeof param === "number" ? param.toString() : param;
2200
+ this.#parameters.set(key, new Parameter(param, Envelope.new(value)));
2201
+ this.#envelope = null;
2202
+ return this;
2203
+ }
2204
+ withParameters(params) {
2205
+ for (const [key, value] of Object.entries(params)) this.withParameter(key, value);
2206
+ return this;
2207
+ }
2208
+ getParameter(param) {
2209
+ const key = typeof param === "number" ? param.toString() : param;
2210
+ return this.#parameters.get(key)?.value();
2211
+ }
2212
+ hasParameter(param) {
2213
+ const key = typeof param === "number" ? param.toString() : param;
2214
+ return this.#parameters.has(key);
2215
+ }
2216
+ envelope() {
2217
+ if (this.#envelope !== null) return this.#envelope;
2218
+ let env = this.#function.envelope();
2219
+ for (const param of this.#parameters.values()) {
2220
+ const assertion = param.envelope().assertions()[0];
2221
+ if (assertion !== void 0) {
2222
+ const predicate = assertion.subject().asPredicate();
2223
+ const object = assertion.subject().asObject();
2224
+ if (predicate !== void 0 && object !== void 0) env = env.addAssertion(predicate.asText(), object);
2225
+ }
2226
+ }
2227
+ this.#envelope = env;
2228
+ return env;
2229
+ }
2230
+ static fromEnvelope(envelope) {
2231
+ const subjectText = envelope.subject().asText();
2232
+ if (subjectText === void 0) throw EnvelopeError.general("Not a valid function envelope");
2233
+ let funcId;
2234
+ if (subjectText.startsWith("«") && subjectText.endsWith("»")) {
2235
+ const inner = subjectText.slice(1, -1);
2236
+ if (inner.startsWith("\"") && inner.endsWith("\"")) funcId = inner.slice(1, -1);
2237
+ else funcId = parseInt(inner, 10);
2238
+ } else throw EnvelopeError.general("Not a valid function envelope");
2239
+ const expr = new Expression(new Function(funcId));
2240
+ for (const assertion of envelope.assertions()) try {
2241
+ const pred = assertion.subject().asPredicate();
2242
+ const obj = assertion.subject().asObject();
2243
+ if (pred !== void 0 && obj !== void 0) {
2244
+ const predText = pred.asText();
2245
+ if (predText !== void 0 && predText.startsWith("❰") && predText.endsWith("❱")) {
2246
+ const inner = predText.slice(1, -1);
2247
+ let paramId;
2248
+ if (inner.startsWith("\"") && inner.endsWith("\"")) paramId = inner.slice(1, -1);
2249
+ else paramId = parseInt(inner, 10);
2250
+ expr.withParameter(paramId, obj);
2251
+ }
2252
+ }
2253
+ } catch {
2254
+ continue;
2255
+ }
2256
+ return expr;
2257
+ }
2258
+ toString() {
2259
+ const params = Array.from(this.#parameters.values()).map((p) => p.toString()).join(", ");
2260
+ return `${this.#function.toString()} [${params}]`;
2261
+ }
2262
+ };
2263
+ function add(lhs, rhs) {
2264
+ return Function.fromNumeric(FUNCTION_IDS.ADD).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2265
+ }
2266
+ function sub(lhs, rhs) {
2267
+ return Function.fromNumeric(FUNCTION_IDS.SUB).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2268
+ }
2269
+ function mul(lhs, rhs) {
2270
+ return Function.fromNumeric(FUNCTION_IDS.MUL).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2271
+ }
2272
+ function div(lhs, rhs) {
2273
+ return Function.fromNumeric(FUNCTION_IDS.DIV).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2274
+ }
2275
+ function neg(value) {
2276
+ return Function.fromNumeric(FUNCTION_IDS.NEG).withParameter(PARAMETER_IDS.BLANK, value);
2277
+ }
2278
+ function lt(lhs, rhs) {
2279
+ return Function.fromNumeric(FUNCTION_IDS.LT).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2280
+ }
2281
+ function gt(lhs, rhs) {
2282
+ return Function.fromNumeric(FUNCTION_IDS.GT).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2283
+ }
2284
+ function eq(lhs, rhs) {
2285
+ return Function.fromNumeric(FUNCTION_IDS.EQ).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2286
+ }
2287
+ function and(lhs, rhs) {
2288
+ return Function.fromNumeric(FUNCTION_IDS.AND).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2289
+ }
2290
+ function or(lhs, rhs) {
2291
+ return Function.fromNumeric(FUNCTION_IDS.OR).withParameter(PARAMETER_IDS.LHS, lhs).withParameter(PARAMETER_IDS.RHS, rhs);
2292
+ }
2293
+ function not(value) {
2294
+ return Function.fromNumeric(FUNCTION_IDS.NOT).withParameter(PARAMETER_IDS.BLANK, value);
2295
+ }
2296
+
2297
+ //#endregion
2298
+ //#region src/extension/proof.ts
2299
+ if (Envelope?.prototype) {
2300
+ Envelope.prototype.proofContainsSet = function(target) {
2301
+ const revealSet = revealSetOfSet(this, target);
2302
+ if (!isSubset(target, revealSet)) return;
2303
+ return this.elideRevealingSet(revealSet).elideRemovingSet(target);
2304
+ };
2305
+ Envelope.prototype.proofContainsTarget = function(target) {
2306
+ const targetSet = new Set([target.digest()]);
2307
+ return this.proofContainsSet(targetSet);
2308
+ };
2309
+ Envelope.prototype.confirmContainsSet = function(target, proof) {
2310
+ if (this.digest().hex() !== proof.digest().hex()) return false;
2311
+ return containsAll(proof, target);
2312
+ };
2313
+ Envelope.prototype.confirmContainsTarget = function(target, proof) {
2314
+ const targetSet = new Set([target.digest()]);
2315
+ return this.confirmContainsSet(targetSet, proof);
2316
+ };
2317
+ }
2318
+ function revealSetOfSet(envelope, target) {
2319
+ const result = /* @__PURE__ */ new Set();
2320
+ revealSets(envelope, target, /* @__PURE__ */ new Set(), result);
2321
+ return result;
2322
+ }
2323
+ function revealSets(envelope, target, current, result) {
2324
+ const newCurrent = new Set(current);
2325
+ newCurrent.add(envelope.digest());
2326
+ if (containsDigest(target, envelope.digest())) for (const digest of newCurrent) result.add(digest);
2327
+ const envelopeCase = envelope.case();
2328
+ if (envelopeCase.type === "node") {
2329
+ revealSets(envelopeCase.subject, target, newCurrent, result);
2330
+ for (const assertion of envelopeCase.assertions) revealSets(assertion, target, newCurrent, result);
2331
+ } else if (envelopeCase.type === "wrapped") revealSets(envelopeCase.envelope, target, newCurrent, result);
2332
+ else if (envelopeCase.type === "assertion") {
2333
+ const predicate = envelopeCase.assertion.predicate();
2334
+ const object = envelopeCase.assertion.object();
2335
+ revealSets(predicate, target, newCurrent, result);
2336
+ revealSets(object, target, newCurrent, result);
2337
+ }
2338
+ }
2339
+ function containsAll(envelope, target) {
2340
+ const targetCopy = new Set(target);
2341
+ removeAllFound(envelope, targetCopy);
2342
+ return targetCopy.size === 0;
2343
+ }
2344
+ function removeAllFound(envelope, target) {
2345
+ if (containsDigest(target, envelope.digest())) removeDigest(target, envelope.digest());
2346
+ if (target.size === 0) return;
2347
+ const envelopeCase = envelope.case();
2348
+ if (envelopeCase.type === "node") {
2349
+ removeAllFound(envelopeCase.subject, target);
2350
+ for (const assertion of envelopeCase.assertions) {
2351
+ removeAllFound(assertion, target);
2352
+ if (target.size === 0) break;
2353
+ }
2354
+ } else if (envelopeCase.type === "wrapped") removeAllFound(envelopeCase.envelope, target);
2355
+ else if (envelopeCase.type === "assertion") {
2356
+ const predicate = envelopeCase.assertion.predicate();
2357
+ const object = envelopeCase.assertion.object();
2358
+ removeAllFound(predicate, target);
2359
+ if (target.size > 0) removeAllFound(object, target);
2360
+ }
2361
+ }
2362
+ function containsDigest(set, digest) {
2363
+ const hexToFind = digest.hex();
2364
+ for (const d of set) if (d.hex() === hexToFind) return true;
2365
+ return false;
2366
+ }
2367
+ function removeDigest(set, digest) {
2368
+ const hexToFind = digest.hex();
2369
+ for (const d of set) if (d.hex() === hexToFind) {
2370
+ set.delete(d);
2371
+ return;
2372
+ }
2373
+ }
2374
+ function isSubset(subset, superset) {
2375
+ for (const digest of subset) if (!containsDigest(superset, digest)) return false;
2376
+ return true;
2377
+ }
2378
+
2379
+ //#endregion
2380
+ //#region src/format/hex.ts
2381
+ Envelope.prototype.hex = function() {
2382
+ const bytes = this.cborBytes();
2383
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2384
+ };
2385
+ Envelope.prototype.cborBytes = function() {
2386
+ return cborData(this.taggedCbor());
2387
+ };
2388
+
2389
+ //#endregion
2390
+ //#region src/format/diagnostic.ts
2391
+ function cborToDiagnostic(cbor$1, indent = 0) {
2392
+ if (typeof cbor$1 === "object" && cbor$1 !== null && "tag" in cbor$1 && "value" in cbor$1) {
2393
+ const tagged = cbor$1;
2394
+ return `${tagged.tag}(${cborToDiagnostic(tagged.value, indent)})`;
2395
+ }
2396
+ if (Array.isArray(cbor$1)) {
2397
+ if (cbor$1.length === 0) return "[]";
2398
+ return `[${cbor$1.map((item) => cborToDiagnostic(item, indent + 2)).join(", ")}]`;
2399
+ }
2400
+ if (cbor$1 instanceof Map) {
2401
+ if (cbor$1.size === 0) return "{}";
2402
+ const entries = [];
2403
+ for (const [key, value] of cbor$1) {
2404
+ const keyStr = cborToDiagnostic(key, indent + 2);
2405
+ const valueStr = cborToDiagnostic(value, indent + 2);
2406
+ entries.push(`${keyStr}: ${valueStr}`);
2407
+ }
2408
+ return `{${entries.join(", ")}}`;
2409
+ }
2410
+ if (cbor$1 instanceof Uint8Array) return `h'${Array.from(cbor$1).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
2411
+ if (typeof cbor$1 === "string") return JSON.stringify(cbor$1);
2412
+ if (typeof cbor$1 === "object" && cbor$1 !== null && "type" in cbor$1) {
2413
+ const typed = cbor$1;
2414
+ switch (typed.type) {
2415
+ case 0: return String(typed.value);
2416
+ case 1: return String(-1 - Number(typed.value));
2417
+ case 7: {
2418
+ const simpleValue = typed.value;
2419
+ if (simpleValue !== null && typeof simpleValue === "object" && "type" in simpleValue) {
2420
+ const floatValue = simpleValue;
2421
+ if (floatValue.type === "Float") return String(floatValue.value);
2422
+ }
2423
+ if (simpleValue === 20) return "false";
2424
+ if (simpleValue === 21) return "true";
2425
+ if (simpleValue === 22) return "null";
2426
+ if (simpleValue === 23) return "undefined";
2427
+ return `simple(${String(simpleValue)})`;
2428
+ }
2429
+ }
2430
+ }
2431
+ if (typeof cbor$1 === "boolean") return String(cbor$1);
2432
+ if (typeof cbor$1 === "number") return String(cbor$1);
2433
+ if (typeof cbor$1 === "bigint") return String(cbor$1);
2434
+ if (cbor$1 === null) return "null";
2435
+ if (cbor$1 === void 0) return "undefined";
2436
+ try {
2437
+ return JSON.stringify(cbor$1);
2438
+ } catch {
2439
+ return String(cbor$1);
2440
+ }
2441
+ }
2442
+ Envelope.prototype.diagnostic = function() {
2443
+ return cborToDiagnostic(this.taggedCbor());
2444
+ };
2445
+
2446
+ //#endregion
2447
+ //#region src/format/tree.ts
2448
+ Envelope.prototype.shortId = function(format = "short") {
2449
+ const digest = this.digest();
2450
+ if (format === "full") return digest.hex();
2451
+ return digest.short();
2452
+ };
2453
+ Envelope.prototype.summary = function(maxLength = 40) {
2454
+ switch (this.case().type) {
2455
+ case "node": return "NODE";
2456
+ case "leaf": {
2457
+ try {
2458
+ const text = this.asText();
2459
+ if (text !== void 0) {
2460
+ const truncated = text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
2461
+ return JSON.stringify(truncated);
2462
+ }
2463
+ } catch {}
2464
+ try {
2465
+ const num = this.extractNumber();
2466
+ return String(num);
2467
+ } catch {}
2468
+ try {
2469
+ const bool = this.extractBoolean();
2470
+ return String(bool);
2471
+ } catch {}
2472
+ if (this.isNull()) return "null";
2473
+ const bytes = this.asByteString();
2474
+ if (bytes !== void 0 && bytes.length <= 16) return `h'${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
2475
+ return "LEAF";
2476
+ }
2477
+ case "wrapped": return "WRAPPED";
2478
+ case "assertion": return "ASSERTION";
2479
+ case "elided": return "ELIDED";
2480
+ case "encrypted": return "ENCRYPTED";
2481
+ case "compressed": return "COMPRESSED";
2482
+ case "knownValue": return "KNOWN_VALUE";
2483
+ default: return "UNKNOWN";
2484
+ }
2485
+ };
2486
+ Envelope.prototype.treeFormat = function(options = {}) {
2487
+ const hideNodes = options.hideNodes ?? false;
2488
+ const highlightDigests = options.highlightDigests ?? /* @__PURE__ */ new Set();
2489
+ const digestDisplay = options.digestDisplay ?? "short";
2490
+ const elements = [];
2491
+ this.walk(hideNodes, void 0, (envelope, level, incomingEdge, _state) => {
2492
+ const digestStr = envelope.digest().short();
2493
+ const isHighlighted = highlightDigests.has(digestStr);
2494
+ elements.push({
2495
+ level,
2496
+ envelope,
2497
+ incomingEdge,
2498
+ showId: !hideNodes,
2499
+ isHighlighted
2500
+ });
2501
+ return [void 0, false];
2502
+ });
2503
+ return elements.map((elem) => {
2504
+ const parts = [];
2505
+ if (elem.isHighlighted) parts.push("*");
2506
+ if (elem.showId) parts.push(elem.envelope.shortId(digestDisplay));
2507
+ const label = edgeLabel(elem.incomingEdge);
2508
+ if (label !== void 0 && label !== "") parts.push(label);
2509
+ parts.push(elem.envelope.summary(40));
2510
+ const line = parts.join(" ");
2511
+ return " ".repeat(elem.level * 4) + line;
2512
+ }).join("\n");
2513
+ };
2514
+
2515
+ //#endregion
2516
+ //#region src/utils/string.ts
2517
+ /**
2518
+ * String utility functions used throughout the envelope library.
2519
+ *
2520
+ * Provides helper methods for string formatting and manipulation.
2521
+ */
2522
+ /**
2523
+ * Flanks a string with specified left and right delimiters.
2524
+ *
2525
+ * @param str - The string to flank
2526
+ * @param left - The left delimiter
2527
+ * @param right - The right delimiter
2528
+ * @returns The flanked string
2529
+ *
2530
+ * @example
2531
+ * ```typescript
2532
+ * flanked('hello', '"', '"') // Returns: "hello"
2533
+ * flanked('name', "'", "'") // Returns: 'name'
2534
+ * flanked('item', '[', ']') // Returns: [item]
2535
+ * ```
2536
+ */
2537
+ function flanked(str, left, right) {
2538
+ return `${left}${str}${right}`;
2539
+ }
2540
+ String.prototype.flankedBy = function(left, right) {
2541
+ return flanked(this, left, right);
2542
+ };
2543
+
2544
+ //#endregion
2545
+ //#region src/index.ts
2546
+ registerEncryptExtension();
2547
+ registerCompressExtension();
2548
+ const VERSION = "0.37.0";
2549
+
2550
+ //#endregion
2551
+ export { ATTACHMENT, Assertion, Attachments, CBOR_TAG_FUNCTION, CBOR_TAG_PARAMETER, CBOR_TAG_PLACEHOLDER, CBOR_TAG_REPLACEMENT, CONFORMS_TO, Compressed, Digest, EdgeType, EncryptedMessage, Envelope, EnvelopeCBORTagged, EnvelopeCBORTaggedDecodable, EnvelopeCBORTaggedEncodable, EnvelopeDecoder, EnvelopeError, ErrorCode, Expression, FUNCTION_IDS, Function, HAS_RECIPIENT, IS_A, NOTE, ObscureType, PARAMETER_IDS, Parameter, PrivateKeyBase, PublicKeyBase, SALT, SIGNED, SealedMessage, Signature, SignatureMetadata, SigningPrivateKey, SigningPublicKey, SymmetricKey, VENDOR, VERIFIED_BY, VERSION, add, and, div, edgeLabel, elideAction, envelopeFromBytes, envelopeFromCbor, envelopeToBytes, envelopeToCbor, eq, extractBoolean, extractBytes, extractNull, extractNumber, extractString, flanked, gt, isEnvelopeEncodable, lt, mul, neg, not, or, registerCompressExtension, registerEncryptExtension, sub };
2552
+ //# sourceMappingURL=index.mjs.map