@bcts/envelope 1.0.0-alpha.19 → 1.0.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +30 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.iife.js +30 -10
- package/dist/index.iife.js.map +1 -1
- package/dist/index.mjs +31 -11
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
- package/src/base/error.ts +6 -0
- package/src/extension/edge.ts +39 -17
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Digest","CborMap","SecureRandomNumberGenerator","SYMMETRIC_NONCE_SIZE","TAG_ENVELOPE","ENVELOPE","LEAF","ENCRYPTED","COMPRESSED","KnownValue","Digest","TAG_ENCODED_CBOR","MajorType","ENVELOPE","UNIT","POSITION","UR","IS_A","SALT_KV","SecureRandomNumberGenerator","SaltComponent","SIGNED","SIGNED_KV","NOTE","NOTE_KV","Signature","ATTACHMENT","ATTACHMENT_KV","VENDOR","VENDOR_KV","CONFORMS_TO","CONFORMS_TO_KV","EDGE","IS_A","SOURCE","TARGET","HAS_RECIPIENT_KV","ComponentsSealedMessage","SymmetricKey","containsDigest","SymmetricKey","ComponentsSymmetricKey","EncryptedKey","HAS_SECRET","SSKR_SHARE","SSKRSecret","SSKRShareCbor","SymmetricKey","TAG_REQUEST","BODY","NOTE","DATE","ARID","UNKNOWN_VALUE","OK_VALUE","TAG_RESPONSE","RESULT","ERROR","ARID","TAG_EVENT","CONTENT","NOTE","DATE","ARID","TagsStoreClass","KnownValuesStoreClass","KNOWN_VALUES","KnownValue","TAG_KNOWN_VALUE","TAG_DIGEST","Digest","TAG_ARID","ARID","TAG_URI","URI","TAG_UUID","UUID","TAG_NONCE","TAG_SALT","TAG_SEED","TAG_SIGNATURE","Signature","SignatureScheme","TAG_SEALED_MESSAGE","SealedMessage","EncapsulationScheme","TAG_ENCRYPTED_KEY","EncryptedKey","TAG_PRIVATE_KEY_BASE","PrivateKeyBase","TAG_PRIVATE_KEYS","PrivateKeys","TAG_PUBLIC_KEYS","PublicKeys","TAG_SIGNING_PRIVATE_KEY","SigningPrivateKey","TAG_SIGNING_PUBLIC_KEY","SigningPublicKey","TAG_SSKR_SHARE","TAG_XID","XID","IS_A"],"sources":["../src/base/digest.ts","../src/base/error.ts","../src/base/assertion.ts","../src/extension/compress.ts","../src/extension/encrypt.ts","../src/base/envelope.ts","../src/base/envelope-encodable.ts","../src/base/cbor.ts","../src/base/envelope-decodable.ts","../src/base/elide.ts","../src/base/walk.ts","../src/base/assertions.ts","../src/base/leaf.ts","../src/base/queries.ts","../src/base/wrap.ts","../src/base/ur.ts","../src/extension/types.ts","../src/extension/salt.ts","../src/extension/signature.ts","../src/extension/attachment.ts","../src/extension/edge.ts","../src/extension/recipient.ts","../src/extension/expression.ts","../src/extension/proof.ts","../src/extension/secret.ts","../src/extension/sskr.ts","../src/extension/request.ts","../src/extension/response.ts","../src/extension/event.ts","../src/format/tree.ts","../src/format/format-context.ts","../src/format/envelope-summary.ts","../src/format/notation.ts","../src/format/mermaid.ts","../src/format/hex.ts","../src/format/diagnostic.ts","../src/seal.ts","../src/utils/string.ts","../src/index.ts"],"sourcesContent":["/**\n * Re-export Digest from @bcts/components for type compatibility.\n *\n * The @bcts/components Digest class is the canonical implementation with:\n * - Full CBOR support (tagged/untagged)\n * - UR support\n * - Complete factory methods and instance methods\n *\n * This re-export ensures type compatibility between @bcts/envelope\n * and @bcts/components when used together.\n */\nexport { Digest } from \"@bcts/components\";\nimport { Digest } from \"@bcts/components\";\n\n/// Trait for types that can provide a digest.\n///\n/// This is equivalent to Rust's `DigestProvider` trait. Types that\n/// implement this interface can be used in contexts where a digest\n/// is needed for identity or integrity verification.\nexport interface DigestProvider {\n /// Returns the digest of this object.\n ///\n /// The digest uniquely identifies the semantic content of the object,\n /// regardless of whether parts of it are elided, encrypted, or compressed.\n digest(): Digest;\n}\n\n/// Helper function to create a digest from a string.\n///\n/// This is a convenience function for creating digests from text strings,\n/// which are encoded as UTF-8 before hashing.\n///\n/// @param text - The text to hash\n/// @returns A new Digest instance\n///\n/// @example\n/// ```typescript\n/// const digest = digestFromString(\"Hello, world!\");\n/// ```\nexport function digestFromString(text: string): Digest {\n const encoder = new TextEncoder();\n return Digest.fromImage(encoder.encode(text));\n}\n\n/// Helper function to create a digest from a number.\n///\n/// The number is converted to a big-endian byte representation before hashing.\n///\n/// @param num - The number to hash\n/// @returns A new Digest instance\n///\n/// @example\n/// ```typescript\n/// const digest = digestFromNumber(42);\n/// ```\nexport function digestFromNumber(num: number): Digest {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n view.setFloat64(0, num, false); // big-endian\n return Digest.fromImage(new Uint8Array(buffer));\n}\n\n// Extend Digest with short() method for compatibility with bc-envelope-rust\ndeclare module \"@bcts/components\" {\n interface Digest {\n /// Returns a short 7-character hex representation of the digest.\n /// This matches the Rust bc-envelope behavior.\n short(): string;\n }\n}\n\n// Add short() method to Digest prototype\nDigest.prototype.short = function (this: Digest): string {\n // Return first 7 hex characters (matches Rust behavior)\n return this.hex().slice(0, 7);\n};\n","/// Error types returned when operating on Gordian Envelopes.\n///\n/// These errors capture various conditions that can occur when working with\n/// envelopes, including structure validation, operation constraints, and\n/// extension-specific errors.\n///\n/// The errors are organized by category, reflecting the base envelope\n/// specification and various extensions defined in the Gordian Envelope\n/// Internet Draft and Blockchain Commons Research (BCR) documents.\n\nexport enum ErrorCode {\n // Base Specification\n ALREADY_ELIDED = \"ALREADY_ELIDED\",\n AMBIGUOUS_PREDICATE = \"AMBIGUOUS_PREDICATE\",\n INVALID_DIGEST = \"INVALID_DIGEST\",\n INVALID_FORMAT = \"INVALID_FORMAT\",\n MISSING_DIGEST = \"MISSING_DIGEST\",\n NONEXISTENT_PREDICATE = \"NONEXISTENT_PREDICATE\",\n NOT_WRAPPED = \"NOT_WRAPPED\",\n NOT_LEAF = \"NOT_LEAF\",\n NOT_ASSERTION = \"NOT_ASSERTION\",\n INVALID_ASSERTION = \"INVALID_ASSERTION\",\n\n // Attachments Extension\n INVALID_ATTACHMENT = \"INVALID_ATTACHMENT\",\n NONEXISTENT_ATTACHMENT = \"NONEXISTENT_ATTACHMENT\",\n AMBIGUOUS_ATTACHMENT = \"AMBIGUOUS_ATTACHMENT\",\n\n // Edges Extension\n EDGE_MISSING_IS_A = \"EDGE_MISSING_IS_A\",\n EDGE_MISSING_SOURCE = \"EDGE_MISSING_SOURCE\",\n EDGE_MISSING_TARGET = \"EDGE_MISSING_TARGET\",\n EDGE_DUPLICATE_IS_A = \"EDGE_DUPLICATE_IS_A\",\n EDGE_DUPLICATE_SOURCE = \"EDGE_DUPLICATE_SOURCE\",\n EDGE_DUPLICATE_TARGET = \"EDGE_DUPLICATE_TARGET\",\n NONEXISTENT_EDGE = \"NONEXISTENT_EDGE\",\n AMBIGUOUS_EDGE = \"AMBIGUOUS_EDGE\",\n\n // Compression Extension\n ALREADY_COMPRESSED = \"ALREADY_COMPRESSED\",\n NOT_COMPRESSED = \"NOT_COMPRESSED\",\n\n // Symmetric Encryption Extension\n ALREADY_ENCRYPTED = \"ALREADY_ENCRYPTED\",\n NOT_ENCRYPTED = \"NOT_ENCRYPTED\",\n\n // Known Values Extension\n NOT_KNOWN_VALUE = \"NOT_KNOWN_VALUE\",\n\n // Public Key Encryption Extension\n UNKNOWN_RECIPIENT = \"UNKNOWN_RECIPIENT\",\n\n // Encrypted Key Extension\n UNKNOWN_SECRET = \"UNKNOWN_SECRET\",\n\n // Public Key Signing Extension\n UNVERIFIED_SIGNATURE = \"UNVERIFIED_SIGNATURE\",\n INVALID_OUTER_SIGNATURE_TYPE = \"INVALID_OUTER_SIGNATURE_TYPE\",\n INVALID_INNER_SIGNATURE_TYPE = \"INVALID_INNER_SIGNATURE_TYPE\",\n UNVERIFIED_INNER_SIGNATURE = \"UNVERIFIED_INNER_SIGNATURE\",\n INVALID_SIGNATURE_TYPE = \"INVALID_SIGNATURE_TYPE\",\n\n // SSKR Extension\n INVALID_SHARES = \"INVALID_SHARES\",\n SSKR = \"SSKR\",\n\n // Types Extension\n INVALID_TYPE = \"INVALID_TYPE\",\n AMBIGUOUS_TYPE = \"AMBIGUOUS_TYPE\",\n\n // Known Value Extension\n SUBJECT_NOT_UNIT = \"SUBJECT_NOT_UNIT\",\n\n // Expressions Extension\n UNEXPECTED_RESPONSE_ID = \"UNEXPECTED_RESPONSE_ID\",\n INVALID_RESPONSE = \"INVALID_RESPONSE\",\n\n // External errors\n CBOR = \"CBOR\",\n COMPONENTS = \"COMPONENTS\",\n GENERAL = \"GENERAL\",\n}\n\nexport class EnvelopeError extends Error {\n readonly code: ErrorCode;\n declare readonly cause?: Error;\n\n constructor(code: ErrorCode, message: string, cause?: Error) {\n super(message);\n this.name = \"EnvelopeError\";\n this.code = code;\n if (cause !== undefined) {\n this.cause = cause;\n }\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (\"captureStackTrace\" in Error) {\n (\n Error as {\n captureStackTrace(target: object, constructor: typeof EnvelopeError): void;\n }\n ).captureStackTrace(this, EnvelopeError);\n }\n }\n\n //\n // Base Specification\n /// Returned when attempting to compress or encrypt an envelope that has\n /// already been elided.\n ///\n /// This error occurs because an elided envelope only contains a digest\n /// reference and no longer has a subject that can be compressed or\n /// encrypted.\n static alreadyElided(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.ALREADY_ELIDED,\n \"envelope was elided, so it cannot be compressed or encrypted\",\n );\n }\n\n /// Returned when attempting to retrieve an assertion by predicate, but\n /// multiple matching assertions exist.\n ///\n /// For queries that expect a single result (like `objectForPredicate`),\n /// having multiple matching assertions is ambiguous and requires more\n /// specific targeting.\n static ambiguousPredicate(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.AMBIGUOUS_PREDICATE,\n \"more than one assertion matches the predicate\",\n );\n }\n\n /// Returned when a digest validation fails.\n ///\n /// This can occur when unwrapping an envelope, verifying signatures, or\n /// other operations that rely on the integrity of envelope digests.\n static invalidDigest(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_DIGEST, \"digest did not match\");\n }\n\n /// Returned when an envelope's format is invalid.\n ///\n /// This typically occurs during parsing or decoding of an envelope from\n /// CBOR.\n static invalidFormat(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_FORMAT, \"invalid format\");\n }\n\n /// Returned when a digest is expected but not found.\n ///\n /// This can occur when working with envelope structures that require digest\n /// information, such as when working with elided envelopes.\n static missingDigest(): EnvelopeError {\n return new EnvelopeError(ErrorCode.MISSING_DIGEST, \"a digest was expected but not found\");\n }\n\n /// Returned when attempting to retrieve an assertion by predicate, but no\n /// matching assertion exists.\n ///\n /// This error occurs with functions like `objectForPredicate` when the\n /// specified predicate doesn't match any assertion in the envelope.\n static nonexistentPredicate(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NONEXISTENT_PREDICATE, \"no assertion matches the predicate\");\n }\n\n /// Returned when attempting to unwrap an envelope that wasn't wrapped.\n ///\n /// This error occurs when calling `Envelope.tryUnwrap` on an\n /// envelope that doesn't have the wrapped format.\n static notWrapped(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_WRAPPED,\n \"cannot unwrap an envelope that was not wrapped\",\n );\n }\n\n /// Returned when expecting an envelope's subject to be a leaf, but it\n /// isn't.\n ///\n /// This error occurs when calling methods that require access to a leaf\n /// value but the envelope's subject is an assertion, node, or elided.\n static notLeaf(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NOT_LEAF, \"the envelope's subject is not a leaf\");\n }\n\n /// Returned when expecting an envelope's subject to be an assertion, but it\n /// isn't.\n ///\n /// This error occurs when calling methods that require an assertion\n /// structure but the envelope's subject has a different format.\n static notAssertion(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NOT_ASSERTION, \"the envelope's subject is not an assertion\");\n }\n\n /// Returned when assertion is invalid\n static invalidAssertion(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_ASSERTION,\n \"assertion must be a map with exactly one element\",\n );\n }\n\n //\n // Attachments Extension\n /// Returned when an attachment's format is invalid.\n ///\n /// This error occurs when an envelope contains an attachment with an\n /// invalid structure according to the Envelope Attachment specification\n /// (BCR-2023-006).\n static invalidAttachment(message?: string): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_ATTACHMENT,\n message !== undefined ? `invalid attachment: ${message}` : \"invalid attachment\",\n );\n }\n\n /// Returned when an attachment is requested but does not exist.\n ///\n /// This error occurs when attempting to retrieve an attachment by ID that\n /// doesn't exist in the envelope.\n static nonexistentAttachment(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NONEXISTENT_ATTACHMENT, \"nonexistent attachment\");\n }\n\n /// Returned when multiple attachments match a single query.\n ///\n /// This error occurs when multiple attachments have the same ID, making\n /// it ambiguous which attachment should be returned.\n static ambiguousAttachment(): EnvelopeError {\n return new EnvelopeError(ErrorCode.AMBIGUOUS_ATTACHMENT, \"ambiguous attachment\");\n }\n\n //\n // Edges Extension\n /// Returned when an edge is missing the required `'isA'` assertion.\n static edgeMissingIsA(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_MISSING_IS_A, \"edge missing 'isA' assertion\");\n }\n\n /// Returned when an edge is missing the required `'source'` assertion.\n static edgeMissingSource(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_MISSING_SOURCE, \"edge missing 'source' assertion\");\n }\n\n /// Returned when an edge is missing the required `'target'` assertion.\n static edgeMissingTarget(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_MISSING_TARGET, \"edge missing 'target' assertion\");\n }\n\n /// Returned when an edge has duplicate `'isA'` assertions.\n static edgeDuplicateIsA(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_DUPLICATE_IS_A, \"edge has duplicate 'isA' assertions\");\n }\n\n /// Returned when an edge has duplicate `'source'` assertions.\n static edgeDuplicateSource(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.EDGE_DUPLICATE_SOURCE,\n \"edge has duplicate 'source' assertions\",\n );\n }\n\n /// Returned when an edge has duplicate `'target'` assertions.\n static edgeDuplicateTarget(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.EDGE_DUPLICATE_TARGET,\n \"edge has duplicate 'target' assertions\",\n );\n }\n\n /// Returned when an edge is requested but does not exist.\n static nonexistentEdge(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NONEXISTENT_EDGE, \"nonexistent edge\");\n }\n\n /// Returned when multiple edges match a single query.\n static ambiguousEdge(): EnvelopeError {\n return new EnvelopeError(ErrorCode.AMBIGUOUS_EDGE, \"ambiguous edge\");\n }\n\n //\n // Compression Extension\n /// Returned when attempting to compress an envelope that is already\n /// compressed.\n ///\n /// This error occurs when calling compression functions on an envelope that\n /// already has compressed content, as defined in BCR-2023-005.\n static alreadyCompressed(): EnvelopeError {\n return new EnvelopeError(ErrorCode.ALREADY_COMPRESSED, \"envelope was already compressed\");\n }\n\n /// Returned when attempting to decompress an envelope that is not\n /// compressed.\n ///\n /// This error occurs when calling decompression functions on an envelope\n /// that doesn't contain compressed content.\n static notCompressed(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_COMPRESSED,\n \"cannot decompress an envelope that was not compressed\",\n );\n }\n\n //\n // Symmetric Encryption Extension\n /// Returned when attempting to encrypt an envelope that is already\n /// encrypted or compressed.\n ///\n /// This error occurs to prevent multiple layers of encryption or encryption\n /// of compressed data, which could reduce security, as defined in\n /// BCR-2023-004.\n static alreadyEncrypted(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.ALREADY_ENCRYPTED,\n \"envelope was already encrypted or compressed, so it cannot be encrypted\",\n );\n }\n\n /// Returned when attempting to decrypt an envelope that is not encrypted.\n ///\n /// This error occurs when calling decryption functions on an envelope that\n /// doesn't contain encrypted content.\n static notEncrypted(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_ENCRYPTED,\n \"cannot decrypt an envelope that was not encrypted\",\n );\n }\n\n //\n // Known Values Extension\n /// Returned when expecting an envelope's subject to be a known value, but\n /// it isn't.\n ///\n /// This error occurs when calling methods that require a known value (as\n /// defined in BCR-2023-003) but the envelope's subject is a different\n /// type.\n static notKnownValue(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_KNOWN_VALUE,\n \"the envelope's subject is not a known value\",\n );\n }\n\n //\n // Public Key Encryption Extension\n /// Returned when attempting to decrypt an envelope with a recipient that\n /// doesn't match.\n ///\n /// This error occurs when trying to use a private key to decrypt an\n /// envelope that wasn't encrypted for the corresponding public key.\n static unknownRecipient(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNKNOWN_RECIPIENT, \"unknown recipient\");\n }\n\n //\n // Encrypted Key Extension\n /// Returned when attempting to decrypt an envelope with a secret that\n /// doesn't match.\n ///\n /// This error occurs when trying to use a secret that does not correspond\n /// to the expected recipient, preventing successful decryption.\n static unknownSecret(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNKNOWN_SECRET, \"secret not found\");\n }\n\n //\n // Public Key Signing Extension\n /// Returned when a signature verification fails.\n ///\n /// This error occurs when a signature does not validate against its\n /// purported public key.\n static unverifiedSignature(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNVERIFIED_SIGNATURE, \"could not verify a signature\");\n }\n\n /// Returned when the outer signature object type is not `Signature`.\n static invalidOuterSignatureType(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_OUTER_SIGNATURE_TYPE,\n \"unexpected outer signature object type\",\n );\n }\n\n /// Returned when the inner signature object type is not `Signature`.\n static invalidInnerSignatureType(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_INNER_SIGNATURE_TYPE,\n \"unexpected inner signature object type\",\n );\n }\n\n /// Returned when the inner signature is not made with the same key as the\n /// outer signature.\n static unverifiedInnerSignature(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.UNVERIFIED_INNER_SIGNATURE,\n \"inner signature not made with same key as outer signature\",\n );\n }\n\n /// Returned when the signature object is not a `Signature`.\n static invalidSignatureType(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_SIGNATURE_TYPE, \"unexpected signature object type\");\n }\n\n //\n // SSKR Extension\n /// Returned when SSKR shares are invalid or insufficient for\n /// reconstruction.\n ///\n /// This error occurs when attempting to join SSKR shares that are\n /// malformed, from different splits, or insufficient to meet the\n /// recovery threshold.\n static invalidShares(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_SHARES, \"invalid SSKR shares\");\n }\n\n /// SSKR error wrapper\n static sskr(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.SSKR, `sskr error: ${message}`, cause);\n }\n\n //\n // Types Extension\n /// Returned when an envelope contains an invalid type.\n ///\n /// This error occurs when an envelope's type information doesn't match\n /// the expected format or value.\n static invalidType(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_TYPE, \"invalid type\");\n }\n\n /// Returned when an envelope contains ambiguous type information.\n ///\n /// This error occurs when multiple type assertions exist that conflict\n /// with each other or create ambiguity about the envelope's type.\n static ambiguousType(): EnvelopeError {\n return new EnvelopeError(ErrorCode.AMBIGUOUS_TYPE, \"ambiguous type\");\n }\n\n //\n // Known Value Extension\n /// Returned when the subject is expected to be the unit value but isn't.\n static subjectNotUnit(): EnvelopeError {\n return new EnvelopeError(ErrorCode.SUBJECT_NOT_UNIT, \"subject is not the unit value\");\n }\n\n //\n // Expressions Extension\n /// Returned when a response envelope has an unexpected ID.\n ///\n /// This error occurs when processing a response envelope and the ID doesn't\n /// match the expected request ID, as defined in BCR-2023-012.\n static unexpectedResponseId(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNEXPECTED_RESPONSE_ID, \"unexpected response ID\");\n }\n\n /// Returned when a response envelope is invalid.\n static invalidResponse(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_RESPONSE, \"invalid response\");\n }\n\n //\n // External errors\n /// dcbor error wrapper\n static cbor(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.CBOR, `dcbor error: ${message}`, cause);\n }\n\n /// Components error wrapper\n static components(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.COMPONENTS, `components error: ${message}`, cause);\n }\n\n /// General error wrapper\n static general(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.GENERAL, `general error: ${message}`, cause);\n }\n\n /// Create error with custom message (equivalent to Rust's Error::msg)\n static msg(message: string): EnvelopeError {\n return EnvelopeError.general(message);\n }\n}\n\n/// Type alias for Result type (for Rust compatibility)\nexport type Result<T> = T;\n\n/// Export for backward compatibility\nexport type { EnvelopeError as Error };\n","import { Digest, type DigestProvider } from \"./digest\";\nimport { Envelope } from \"./envelope\";\nimport { type EnvelopeEncodable } from \"./envelope-encodable\";\nimport { EnvelopeError } from \"./error\";\nimport { type Cbor, cbor as toCborValue, CborMap } from \"@bcts/dcbor\";\n\n/// A predicate-object relationship representing an assertion about a subject.\n///\n/// In Gordian Envelope, assertions are the basic building blocks for attaching\n/// information to a subject. An assertion consists of a predicate (which states\n/// what is being asserted) and an object (which provides the assertion's\n/// value).\n///\n/// Assertions can be attached to envelope subjects to form semantic statements\n/// like: \"subject hasAttribute value\" or \"document signedBy signature\".\n///\n/// Assertions are equivalent to RDF (Resource Description Framework) triples,\n/// where:\n/// - The envelope's subject is the subject of the triple\n/// - The assertion's predicate is the predicate of the triple\n/// - The assertion's object is the object of the triple\n///\n/// Generally you do not create an instance of this type directly, but\n/// instead use `Envelope.newAssertion()`, or the various functions\n/// on `Envelope` that create assertions.\nexport class Assertion implements DigestProvider {\n private readonly _predicate: Envelope;\n private readonly _object: Envelope;\n private readonly _digest: Digest;\n\n /// Creates a new assertion and calculates its digest.\n ///\n /// This constructor takes a predicate and object, both of which are\n /// converted to envelopes using the `EnvelopeEncodable` trait. It then\n /// calculates the assertion's digest by combining the digests of the\n /// predicate and object.\n ///\n /// The digest is calculated according to the Gordian Envelope\n /// specification, which ensures that semantically equivalent assertions\n /// always produce the same digest.\n ///\n /// @param predicate - The predicate of the assertion, which states what is\n /// being asserted\n /// @param object - The object of the assertion, which provides the assertion's\n /// value\n ///\n /// @returns A new assertion with the specified predicate, object, and calculated\n /// digest.\n ///\n /// @example\n /// ```typescript\n /// // Direct method - create an assertion envelope\n /// const assertionEnvelope = Envelope.newAssertion(\"name\", \"Alice\");\n ///\n /// // Or create and add an assertion to a subject\n /// const person = Envelope.new(\"person\").addAssertion(\"name\", \"Alice\");\n /// ```\n constructor(predicate: EnvelopeEncodable | Envelope, object: EnvelopeEncodable | Envelope) {\n this._predicate = predicate instanceof Envelope ? predicate : Envelope.new(predicate);\n this._object = object instanceof Envelope ? object : Envelope.new(object);\n this._digest = Digest.fromDigests([this._predicate.digest(), this._object.digest()]);\n }\n\n /// Returns the predicate of the assertion.\n ///\n /// The predicate states what is being asserted about the subject. It is\n /// typically a string or known value, but can be any envelope.\n ///\n /// @returns A clone of the assertion's predicate envelope.\n predicate(): Envelope {\n return this._predicate;\n }\n\n /// Returns the object of the assertion.\n ///\n /// The object provides the value or content of the assertion. It can be any\n /// type that can be represented as an envelope.\n ///\n /// @returns A clone of the assertion's object envelope.\n object(): Envelope {\n return this._object;\n }\n\n /// Returns the digest of this assertion.\n ///\n /// Implementation of the DigestProvider interface.\n ///\n /// @returns The assertion's digest\n digest(): Digest {\n return this._digest;\n }\n\n /// Checks if two assertions are equal based on digest equality.\n ///\n /// Two assertions are considered equal if they have the same digest,\n /// regardless of how they were constructed.\n ///\n /// @param other - The other assertion to compare with\n /// @returns `true` if the assertions are equal, `false` otherwise\n equals(other: Assertion): boolean {\n return this._digest.equals(other._digest);\n }\n\n /// Converts this assertion to CBOR.\n ///\n /// The CBOR representation of an assertion is a map with a single key-value\n /// pair, where the key is the predicate's CBOR and the value is the object's\n /// CBOR.\n ///\n /// @returns A CBOR representation of this assertion\n toCbor(): Cbor {\n const map = new CborMap();\n map.set(this._predicate.untaggedCbor(), this._object.untaggedCbor());\n return toCborValue(map);\n }\n\n /// Attempts to create an assertion from a CBOR value.\n ///\n /// The CBOR must be a map with exactly one entry, where the key represents\n /// the predicate and the value represents the object.\n ///\n /// @param cbor - The CBOR value to convert\n /// @returns A new Assertion instance\n /// @throws {EnvelopeError} If the CBOR is not a valid assertion\n static fromCbor(cbor: Cbor): Assertion {\n // Check if cbor is a Map\n if (!(cbor instanceof CborMap)) {\n throw EnvelopeError.invalidAssertion();\n }\n\n return Assertion.fromCborMap(cbor);\n }\n\n /// Attempts to create an assertion from a CBOR map.\n ///\n /// The map must have exactly one entry, where the key represents the\n /// predicate and the value represents the object. This is used in\n /// the deserialization process.\n ///\n /// @param map - The CBOR map to convert\n /// @returns A new Assertion instance\n /// @throws {EnvelopeError} If the map doesn't have exactly one entry\n static fromCborMap(map: CborMap): Assertion {\n if (map.size !== 1) {\n throw EnvelopeError.invalidAssertion();\n }\n\n const entries = Array.from(map.entries());\n const firstEntry = entries[0];\n if (firstEntry === undefined) {\n throw EnvelopeError.invalidAssertion();\n }\n const [predicateCbor, objectCbor] = firstEntry;\n\n const predicate = Envelope.fromUntaggedCbor(predicateCbor);\n\n const object = Envelope.fromUntaggedCbor(objectCbor);\n\n return new Assertion(predicate, object);\n }\n\n /// Creates a string representation of this assertion for debugging.\n ///\n /// @returns A string representation\n toString(): string {\n return `Assertion(${String(this._predicate)}: ${String(this._object)})`;\n }\n\n /// Creates a copy of this assertion.\n ///\n /// Since assertions are immutable and envelopes are cheap to clone,\n /// this returns the same instance.\n ///\n /// @returns This assertion instance\n clone(): Assertion {\n return this;\n }\n}\n","import { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { type Digest } from \"../base/digest\";\nimport * as pako from \"pako\";\nimport { cborData, decodeCbor } from \"@bcts/dcbor\";\n\n/// Extension for compressing and decompressing envelopes.\n///\n/// This module provides functionality for compressing envelopes to reduce their\n/// size while maintaining their digests. Unlike elision, which removes content,\n/// compression preserves all the information in the envelope but represents it\n/// more efficiently.\n///\n/// Compression is implemented using the DEFLATE algorithm (via pako) and preserves\n/// the envelope's digest, making it compatible with the envelope's hierarchical\n/// digest tree structure.\n///\n/// @example\n/// ```typescript\n/// // Create an envelope with some larger, compressible content\n/// const lorem = \"Lorem ipsum dolor sit amet...\".repeat(10);\n/// const envelope = Envelope.new(lorem);\n///\n/// // Compress the envelope\n/// const compressed = envelope.compress();\n///\n/// // The compressed envelope has the same digest as the original\n/// console.log(envelope.digest().equals(compressed.digest())); // true\n///\n/// // But it takes up less space when serialized\n/// console.log(compressed.cborBytes().length < envelope.cborBytes().length); // true\n///\n/// // The envelope can be decompressed to recover the original content\n/// const decompressed = compressed.decompress();\n/// console.log(decompressed.asText() === lorem); // true\n/// ```\n\n/// Represents compressed data with optional digest\nexport class Compressed {\n private readonly _compressedData: Uint8Array;\n private readonly _digest?: Digest;\n\n constructor(compressedData: Uint8Array, digest?: Digest) {\n this._compressedData = compressedData;\n if (digest !== undefined) {\n this._digest = digest;\n }\n }\n\n /// Creates a Compressed instance from decompressed data\n static fromDecompressedData(decompressedData: Uint8Array, digest?: Digest): Compressed {\n const compressed = pako.deflate(decompressedData);\n return new Compressed(compressed, digest);\n }\n\n /// Returns the compressed data\n compressedData(): Uint8Array {\n return this._compressedData;\n }\n\n /// Returns the optional digest\n digestOpt(): Digest | undefined {\n return this._digest;\n }\n\n /// Decompresses the data\n decompress(): Uint8Array {\n return pako.inflate(this._compressedData);\n }\n}\n\n/// Register compression extension methods on Envelope prototype\n/// This function is exported and called during module initialization\n/// to ensure Envelope is fully defined before attaching methods.\nexport function registerCompressExtension(): void {\n if (Envelope?.prototype === undefined) {\n return;\n }\n\n // Skip if already registered\n if (typeof Envelope.prototype.compress === \"function\") {\n return;\n }\n\n Envelope.prototype.compress = function (this: Envelope): Envelope {\n const c = this.case();\n\n // If already compressed, return as-is\n if (c.type === \"compressed\") {\n return this;\n }\n\n // Can't compress encrypted or elided envelopes\n if (c.type === \"encrypted\") {\n throw EnvelopeError.general(\"Cannot compress encrypted envelope\");\n }\n if (c.type === \"elided\") {\n throw EnvelopeError.general(\"Cannot compress elided envelope\");\n }\n\n // Compress the entire envelope\n const cbor = this.taggedCbor();\n\n const decompressedData = cborData(cbor);\n\n const compressed = Compressed.fromDecompressedData(decompressedData, this.digest());\n\n // Create a compressed envelope case\n return Envelope.fromCase({ type: \"compressed\", value: compressed });\n };\n\n /// Implementation of decompress()\n Envelope.prototype.decompress = function (this: Envelope): Envelope {\n const c = this.case();\n\n if (c.type !== \"compressed\") {\n throw EnvelopeError.general(\"Envelope is not compressed\");\n }\n\n const compressed = c.value;\n const digest = compressed.digestOpt();\n\n if (digest === undefined) {\n throw EnvelopeError.general(\"Missing digest in compressed envelope\");\n }\n\n // Verify the digest matches\n if (!digest.equals(this.digest())) {\n throw EnvelopeError.general(\"Invalid digest in compressed envelope\");\n }\n\n // Decompress the data\n const decompressedData = compressed.decompress();\n\n // Parse back to envelope\n\n const cbor = decodeCbor(decompressedData);\n const envelope = Envelope.fromTaggedCbor(cbor);\n\n // Verify the decompressed envelope has the correct digest\n if (!envelope.digest().equals(digest)) {\n throw EnvelopeError.general(\"Invalid digest after decompression\");\n }\n\n return envelope;\n };\n\n /// Implementation of compressSubject()\n Envelope.prototype.compressSubject = function (this: Envelope): Envelope {\n if (this.subject().isCompressed()) {\n return this;\n }\n\n const subject = this.subject().compress();\n return this.replaceSubject(subject);\n };\n\n /// Implementation of decompressSubject()\n Envelope.prototype.decompressSubject = function (this: Envelope): Envelope {\n if (this.subject().isCompressed()) {\n const subject = this.subject().decompress();\n return this.replaceSubject(subject);\n }\n\n return this;\n };\n\n /// Implementation of isCompressed()\n Envelope.prototype.isCompressed = function (this: Envelope): boolean {\n return this.case().type === \"compressed\";\n };\n}\n\n// Registration is handled by the main index.ts to avoid circular dependency issues.\n// The registerCompressExtension() function is called explicitly after all modules are loaded.\n","import { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { type Digest } from \"../base/digest\";\nimport { cborData, decodeCbor } from \"@bcts/dcbor\";\nimport {\n aeadChaCha20Poly1305EncryptWithAad,\n aeadChaCha20Poly1305DecryptWithAad,\n SYMMETRIC_NONCE_SIZE,\n} from \"@bcts/crypto\";\nimport { SecureRandomNumberGenerator, rngRandomData } from \"@bcts/rand\";\n\n/**\n * Re-export SymmetricKey from @bcts/components for type compatibility.\n *\n * The @bcts/components SymmetricKey class is the canonical implementation with:\n * - Full CBOR support (tagged/untagged)\n * - UR support\n * - Complete factory methods\n *\n * This re-export ensures type compatibility between @bcts/envelope\n * and @bcts/components when used together.\n */\nexport { SymmetricKey } from \"@bcts/components\";\nimport type { SymmetricKey } from \"@bcts/components\";\n\n/// Extension for encrypting and decrypting envelopes using symmetric encryption.\n///\n/// This module extends Gordian Envelope with functions for symmetric encryption\n/// and decryption using the IETF-ChaCha20-Poly1305 construct. It enables\n/// privacy-enhancing operations by allowing envelope elements to be encrypted\n/// without changing the envelope's digest, similar to elision.\n///\n/// The encryption process preserves the envelope's digest tree structure, which\n/// means signatures, proofs, and other cryptographic artifacts remain valid\n/// even when parts of the envelope are encrypted.\n\n/**\n * Encrypts plaintext with a symmetric key using the given digest as AAD.\n * This is an envelope-specific helper function that returns an envelope EncryptedMessage.\n */\nfunction encryptWithDigest(\n key: SymmetricKey,\n plaintext: Uint8Array,\n digest: Digest,\n): EncryptedMessage {\n const rng = new SecureRandomNumberGenerator();\n const nonce = rngRandomData(rng, SYMMETRIC_NONCE_SIZE);\n const aad = digest.data();\n const [ciphertext, authTag] = aeadChaCha20Poly1305EncryptWithAad(\n plaintext,\n key.data(),\n nonce,\n aad,\n );\n return new EncryptedMessage(ciphertext, nonce, authTag, digest);\n}\n\n/**\n * Decrypts an envelope EncryptedMessage with a symmetric key.\n * This is an envelope-specific helper function.\n */\nfunction decryptWithDigest(key: SymmetricKey, message: EncryptedMessage): Uint8Array {\n const digest = message.aadDigest();\n if (digest === undefined) {\n throw EnvelopeError.general(\"Missing digest in encrypted message\");\n }\n const aad = digest.data();\n try {\n return aeadChaCha20Poly1305DecryptWithAad(\n message.ciphertext(),\n key.data(),\n message.nonce(),\n aad,\n message.authTag(),\n );\n } catch (_error) {\n throw EnvelopeError.general(\"Decryption failed: invalid key or corrupted data\");\n }\n}\n\n/// Represents an encrypted message with nonce, auth tag, and optional AAD digest\n/// Matches bc-components-rust/src/symmetric/encrypted_message.rs\nexport class EncryptedMessage {\n private readonly _ciphertext: Uint8Array;\n private readonly _nonce: Uint8Array;\n private readonly _authTag: Uint8Array;\n private readonly _aadDigest?: Digest;\n\n constructor(ciphertext: Uint8Array, nonce: Uint8Array, authTag: Uint8Array, aadDigest?: Digest) {\n this._ciphertext = ciphertext;\n this._nonce = nonce;\n this._authTag = authTag;\n if (aadDigest !== undefined) {\n this._aadDigest = aadDigest;\n }\n }\n\n /// Returns the ciphertext\n ciphertext(): Uint8Array {\n return this._ciphertext;\n }\n\n /// Returns the nonce\n nonce(): Uint8Array {\n return this._nonce;\n }\n\n /// Returns the authentication tag\n authTag(): Uint8Array {\n return this._authTag;\n }\n\n /// Returns the optional AAD digest\n aadDigest(): Digest | undefined {\n return this._aadDigest;\n }\n\n /// Returns the digest of this encrypted message (the AAD digest)\n digest(): Digest {\n if (this._aadDigest === undefined) {\n throw new Error(\"Encrypted message missing AAD digest\");\n }\n return this._aadDigest;\n }\n}\n\n/// Register encryption extension methods on Envelope prototype\n/// This function is exported and called during module initialization\n/// to ensure Envelope is fully defined before attaching methods.\nexport function registerEncryptExtension(): void {\n if (Envelope?.prototype === undefined) {\n return;\n }\n\n // Skip if already registered\n if (typeof Envelope.prototype.encryptSubject === \"function\") {\n return;\n }\n\n Envelope.prototype.encryptSubject = function (this: Envelope, key: SymmetricKey): Envelope {\n const c = this.case();\n\n // Can't encrypt if already encrypted or elided\n if (c.type === \"encrypted\") {\n throw EnvelopeError.general(\"Envelope is already encrypted\");\n }\n if (c.type === \"elided\") {\n throw EnvelopeError.general(\"Cannot encrypt elided envelope\");\n }\n\n // For node case, encrypt just the subject\n if (c.type === \"node\") {\n if (c.subject.isEncrypted()) {\n throw EnvelopeError.general(\"Subject is already encrypted\");\n }\n\n // Get the subject's CBOR data\n const subjectCbor = c.subject.taggedCbor();\n const encodedCbor = cborData(subjectCbor);\n const subjectDigest = c.subject.digest();\n\n // Encrypt the subject\n const encryptedMessage = encryptWithDigest(key, encodedCbor, subjectDigest);\n\n // Create encrypted envelope\n const encryptedSubject = Envelope.fromCase({\n type: \"encrypted\",\n message: encryptedMessage,\n });\n\n // Rebuild the node with encrypted subject and same assertions\n return Envelope.newWithAssertions(encryptedSubject, c.assertions);\n }\n\n // For other cases, encrypt the entire envelope\n const cbor = this.taggedCbor();\n const encodedCbor = cborData(cbor);\n const digest = this.digest();\n\n const encryptedMessage = encryptWithDigest(key, encodedCbor, digest);\n\n return Envelope.fromCase({\n type: \"encrypted\",\n message: encryptedMessage,\n });\n };\n\n /// Implementation of decryptSubject()\n Envelope.prototype.decryptSubject = function (this: Envelope, key: SymmetricKey): Envelope {\n const subjectCase = this.subject().case();\n\n if (subjectCase.type !== \"encrypted\") {\n throw EnvelopeError.general(\"Subject is not encrypted\");\n }\n\n const message = subjectCase.message;\n const subjectDigest = message.aadDigest();\n\n if (subjectDigest === undefined) {\n throw EnvelopeError.general(\"Missing digest in encrypted message\");\n }\n\n // Decrypt the subject\n const decryptedData = decryptWithDigest(key, message);\n\n // Parse back to envelope\n const cbor = decodeCbor(decryptedData);\n const resultSubject = Envelope.fromTaggedCbor(cbor);\n\n // Verify digest\n if (!resultSubject.digest().equals(subjectDigest)) {\n throw EnvelopeError.general(\"Invalid digest after decryption\");\n }\n\n const c = this.case();\n\n // If this is a node, rebuild with decrypted subject\n if (c.type === \"node\") {\n const result = Envelope.newWithAssertions(resultSubject, c.assertions);\n if (!result.digest().equals(c.digest)) {\n throw EnvelopeError.general(\"Invalid envelope digest after decryption\");\n }\n return result;\n }\n\n // Otherwise just return the decrypted subject\n return resultSubject;\n };\n\n /// Implementation of encrypt() - convenience method\n Envelope.prototype.encrypt = function (this: Envelope, key: SymmetricKey): Envelope {\n return this.wrap().encryptSubject(key);\n };\n\n /// Implementation of decrypt() - convenience method\n Envelope.prototype.decrypt = function (this: Envelope, key: SymmetricKey): Envelope {\n const decrypted = this.decryptSubject(key);\n return decrypted.unwrap();\n };\n\n /// Implementation of isEncrypted()\n Envelope.prototype.isEncrypted = function (this: Envelope): boolean {\n return this.case().type === \"encrypted\";\n };\n}\n\n/// Encrypts an entire envelope as a unit, matching Rust's\n/// ObscureAction::Encrypt behavior in elide_set_with_action.\n/// Unlike encryptSubject which only encrypts a node's subject,\n/// this encrypts the entire envelope's tagged CBOR.\nexport function encryptWholeEnvelope(envelope: Envelope, key: SymmetricKey): Envelope {\n const c = envelope.case();\n if (c.type === \"encrypted\") {\n throw EnvelopeError.general(\"Envelope is already encrypted\");\n }\n if (c.type === \"elided\") {\n throw EnvelopeError.general(\"Cannot encrypt elided envelope\");\n }\n const cbor = envelope.taggedCbor();\n const encodedCbor = cborData(cbor);\n const digest = envelope.digest();\n const encryptedMessage = encryptWithDigest(key, encodedCbor, digest);\n return Envelope.fromCase({ type: \"encrypted\", message: encryptedMessage });\n}\n\n// Registration is handled by the main index.ts to avoid circular dependency issues.\n// The registerEncryptExtension() function is called explicitly after all modules are loaded.\n","import { Digest, type DigestProvider } from \"./digest\";\nimport { Assertion } from \"./assertion\";\nimport { EnvelopeError } from \"./error\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { KnownValue } from \"@bcts/known-values\";\nimport type { Cbor, CborMap } from \"@bcts/dcbor\";\nimport {\n cbor,\n cborData,\n toTaggedValue,\n TAG_ENCODED_CBOR,\n MajorType,\n asByteString,\n asCborArray,\n asCborMap,\n asTaggedValue,\n tryExpectedTaggedValue,\n} from \"@bcts/dcbor\";\nimport { ENVELOPE, LEAF, ENCRYPTED, COMPRESSED } from \"@bcts/components\";\n\n// Type imports for extension method declarations\n// These are imported as types only to avoid circular dependencies at runtime\nimport type { ObscureAction, ObscureType } from \"./elide\";\nimport type { Visitor } from \"./walk\";\nimport type {\n SymmetricKey,\n SealedMessage,\n Signer,\n Verifier,\n Signature,\n SignatureMetadata,\n SigningOptions,\n} from \"../extension\";\nimport type { UR } from \"@bcts/uniform-resources\";\nimport type { TreeFormatOptions } from \"../format/tree\";\nimport type { EnvelopeFormatOpts } from \"../format/notation\";\nimport type { MermaidFormatOpts } from \"../format/mermaid\";\nimport type { FormatContext } from \"../format/format-context\";\nimport type { KeyDerivationMethod, Encrypter, Decrypter, Nonce, SSKRSpec } from \"@bcts/components\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\n/// Import tag values from the tags registry\n/// These match the Rust reference implementation in bc-tags-rust\nconst TAG_ENVELOPE = ENVELOPE.value;\nconst TAG_LEAF = LEAF.value;\nconst TAG_ENCRYPTED = ENCRYPTED.value;\nconst TAG_COMPRESSED = COMPRESSED.value;\n\n/// The core structural variants of a Gordian Envelope.\n///\n/// Each variant represents a different structural form that an\n/// envelope can take, as defined in the Gordian Envelope IETF Internet Draft.\n/// The different cases provide different capabilities and serve different\n/// purposes in the envelope ecosystem.\n///\n/// The `EnvelopeCase` is the internal representation of an envelope's\n/// structure. While each case has unique properties, they all maintain a digest\n/// that ensures the integrity of the envelope.\n///\n/// It is advised to use the other Envelope APIs for most uses. Please see the\n/// queries module for more information on how to interact with envelopes.\nexport type EnvelopeCase =\n | {\n type: \"node\";\n /// The subject of the node\n subject: Envelope;\n /// The assertions attached to the subject\n assertions: Envelope[];\n /// The digest of the node\n digest: Digest;\n }\n | {\n type: \"leaf\";\n /// The CBOR value contained in the leaf\n cbor: Cbor;\n /// The digest of the leaf\n digest: Digest;\n }\n | {\n type: \"wrapped\";\n /// The envelope being wrapped\n envelope: Envelope;\n /// The digest of the wrapped envelope\n digest: Digest;\n }\n | {\n type: \"assertion\";\n /// The assertion\n assertion: Assertion;\n }\n | {\n type: \"elided\";\n /// The digest of the elided content\n digest: Digest;\n }\n | {\n type: \"knownValue\";\n /// The known value instance\n value: KnownValue;\n /// The digest of the known value\n digest: Digest;\n }\n | {\n type: \"encrypted\";\n /// The encrypted message\n message: EncryptedMessage;\n }\n | {\n type: \"compressed\";\n /// The compressed data\n value: Compressed;\n };\n\n// Import types from extension modules (will be available at runtime)\nimport { Compressed } from \"../extension/compress\";\nimport { EncryptedMessage } from \"../extension/encrypt\";\n\n/// A flexible container for structured data with built-in integrity\n/// verification.\n///\n/// Gordian Envelope is the primary data structure of this library. It provides a\n/// way to encapsulate and organize data with cryptographic integrity, privacy\n/// features, and selective disclosure capabilities.\n///\n/// Key characteristics of envelopes:\n///\n/// - **Immutability**: Envelopes are immutable. Operations that appear to\n/// \"modify\" an envelope actually create a new envelope. This immutability is\n/// fundamental to maintaining the integrity of the envelope's digest tree.\n///\n/// - **Efficient Cloning**: Envelopes use shallow copying for efficient O(1)\n/// cloning. Since they're immutable, clones share the same underlying data.\n///\n/// - **Semantic Structure**: Envelopes can represent various semantic\n/// relationships through subjects, predicates, and objects (similar to RDF\n/// triples).\n///\n/// - **Digest Tree**: Each envelope maintains a Merkle-like digest tree that\n/// ensures the integrity of its contents and enables verification of\n/// individual parts.\n///\n/// - **Privacy Features**: Envelopes support selective disclosure through\n/// elision, encryption, and compression of specific parts, while maintaining\n/// the overall integrity of the structure.\n///\n/// - **Deterministic Representation**: Envelopes use deterministic CBOR\n/// encoding to ensure consistent serialization across platforms.\n///\n/// The Gordian Envelope specification is defined in an IETF Internet Draft, and\n/// this implementation closely follows that specification.\n///\n/// @example\n/// ```typescript\n/// // Create an envelope representing a person\n/// const person = Envelope.new(\"person\")\n/// .addAssertion(\"name\", \"Alice\")\n/// .addAssertion(\"age\", 30)\n/// .addAssertion(\"email\", \"alice@example.com\");\n///\n/// // Create a partially redacted version by eliding the email\n/// const redacted = person.elideRemovingTarget(\n/// person.assertionWithPredicate(\"email\")\n/// );\n///\n/// // The digest of both envelopes remains the same\n/// assert(person.digest().equals(redacted.digest()));\n/// ```\nexport class Envelope implements DigestProvider {\n private readonly _case: EnvelopeCase;\n\n /// Private constructor. Use static factory methods to create envelopes.\n ///\n /// @param envelopeCase - The envelope case variant\n private constructor(envelopeCase: EnvelopeCase) {\n this._case = envelopeCase;\n }\n\n /// Returns a reference to the underlying envelope case.\n ///\n /// The `EnvelopeCase` enum represents the specific structural variant of\n /// this envelope. This method provides access to that underlying\n /// variant for operations that need to differentiate between the\n /// different envelope types.\n ///\n /// @returns The `EnvelopeCase` that defines this envelope's structure.\n case(): EnvelopeCase {\n return this._case;\n }\n\n /// Creates an envelope with a subject, which can be any value that\n /// can be encoded as an envelope.\n ///\n /// @param subject - The subject value\n /// @returns A new envelope containing the subject\n ///\n /// @example\n /// ```typescript\n /// const envelope = Envelope.new(\"Hello, world!\");\n /// const numberEnvelope = Envelope.new(42);\n /// const binaryEnvelope = Envelope.new(new Uint8Array([1, 2, 3]));\n /// ```\n static new(subject: EnvelopeEncodableValue): Envelope {\n // Convert the subject to an envelope\n if (subject instanceof Envelope) {\n return subject;\n }\n\n // Handle KnownValue specially to create knownValue envelopes\n if (subject instanceof KnownValue) {\n return Envelope.newWithKnownValue(subject);\n }\n\n // Handle primitives and create leaf envelopes\n return Envelope.newLeaf(subject);\n }\n\n /// Creates an envelope with a subject, or null if subject is undefined.\n ///\n /// @param subject - The optional subject value\n /// @returns A new envelope or null envelope\n static newOrNull(subject: EnvelopeEncodableValue | undefined): Envelope {\n if (subject === undefined || subject === null) {\n return Envelope.null();\n }\n return Envelope.new(subject);\n }\n\n /// Creates an envelope with a subject, or undefined if subject is undefined.\n ///\n /// @param subject - The optional subject value\n /// @returns A new envelope or undefined\n static newOrNone(subject: EnvelopeEncodableValue | undefined): Envelope | undefined {\n if (subject === undefined || subject === null) {\n return undefined;\n }\n return Envelope.new(subject);\n }\n\n /// Creates an envelope from an EnvelopeCase.\n ///\n /// This is an internal method used by extensions to create envelopes\n /// from custom case types like compressed or encrypted.\n ///\n /// @param envelopeCase - The envelope case to wrap\n /// @returns A new envelope with the given case\n static fromCase(envelopeCase: EnvelopeCase): Envelope {\n return new Envelope(envelopeCase);\n }\n\n /// Creates an assertion envelope with a predicate and object.\n ///\n /// @param predicate - The predicate of the assertion\n /// @param object - The object of the assertion\n /// @returns A new assertion envelope\n ///\n /// @example\n /// ```typescript\n /// const assertion = Envelope.newAssertion(\"name\", \"Alice\");\n /// ```\n static newAssertion(predicate: EnvelopeEncodableValue, object: EnvelopeEncodableValue): Envelope {\n const predicateEnv = predicate instanceof Envelope ? predicate : Envelope.new(predicate);\n const objectEnv = object instanceof Envelope ? object : Envelope.new(object);\n return Envelope.newWithAssertion(new Assertion(predicateEnv, objectEnv));\n }\n\n /// Creates a null envelope (containing CBOR null).\n ///\n /// @returns A null envelope\n static null(): Envelope {\n return Envelope.newLeaf(null);\n }\n\n //\n // Internal constructors\n //\n\n /// Creates an envelope with a subject and unchecked assertions.\n ///\n /// The assertions are sorted by digest and the envelope's digest is calculated.\n ///\n /// @param subject - The subject envelope\n /// @param uncheckedAssertions - The assertions to attach\n /// @returns A new node envelope\n static newWithUncheckedAssertions(subject: Envelope, uncheckedAssertions: Envelope[]): Envelope {\n if (uncheckedAssertions.length === 0) {\n throw new Error(\"Assertions array cannot be empty\");\n }\n\n // Sort assertions by digest\n const sortedAssertions = [...uncheckedAssertions].sort((a, b) => {\n const aHex = a.digest().hex();\n const bHex = b.digest().hex();\n return aHex.localeCompare(bHex);\n });\n\n // Calculate digest from subject and all assertions\n const digests = [subject.digest(), ...sortedAssertions.map((a) => a.digest())];\n const digest = Digest.fromDigests(digests);\n\n return new Envelope({\n type: \"node\",\n subject,\n assertions: sortedAssertions,\n digest,\n });\n }\n\n /// Creates an envelope with a subject and validated assertions.\n ///\n /// All assertions must be assertion or obscured envelopes.\n ///\n /// @param subject - The subject envelope\n /// @param assertions - The assertions to attach\n /// @returns A new node envelope\n /// @throws {EnvelopeError} If any assertion is not valid\n static newWithAssertions(subject: Envelope, assertions: Envelope[]): Envelope {\n // Validate that all assertions are assertion or obscured envelopes\n for (const assertion of assertions) {\n if (!assertion.isSubjectAssertion() && !assertion.isSubjectObscured()) {\n throw EnvelopeError.invalidFormat();\n }\n }\n\n return Envelope.newWithUncheckedAssertions(subject, assertions);\n }\n\n /// Creates an envelope with an assertion as its subject.\n ///\n /// @param assertion - The assertion\n /// @returns A new assertion envelope\n static newWithAssertion(assertion: Assertion): Envelope {\n return new Envelope({\n type: \"assertion\",\n assertion,\n });\n }\n\n /// Creates an envelope with a known value.\n ///\n /// @param value - The known value (can be a KnownValue instance or a number/bigint)\n /// @returns A new known value envelope\n static newWithKnownValue(value: KnownValue | number | bigint): Envelope {\n const knownValue = value instanceof KnownValue ? value : new KnownValue(value);\n // Calculate digest from CBOR encoding of the known value\n const digest = Digest.fromImage(knownValue.toCborData());\n return new Envelope({\n type: \"knownValue\",\n value: knownValue,\n digest,\n });\n }\n\n /// Creates an envelope with encrypted content.\n ///\n /// @param encryptedMessage - The encrypted message\n /// @returns A new encrypted envelope\n /// @throws {EnvelopeError} If the encrypted message doesn't have a digest\n static newWithEncrypted(encryptedMessage: EncryptedMessage): Envelope {\n // TODO: Validate that encrypted message has digest\n // if (!encryptedMessage.hasDigest()) {\n // throw EnvelopeError.missingDigest();\n // }\n return new Envelope({\n type: \"encrypted\",\n message: encryptedMessage,\n });\n }\n\n /// Creates an envelope with compressed content.\n ///\n /// @param compressed - The compressed data\n /// @returns A new compressed envelope\n /// @throws {EnvelopeError} If the compressed data doesn't have a digest\n static newWithCompressed(compressed: Compressed): Envelope {\n // TODO: Validate that compressed has digest\n // if (!compressed.hasDigest()) {\n // throw EnvelopeError.missingDigest();\n // }\n return new Envelope({\n type: \"compressed\",\n value: compressed,\n });\n }\n\n /// Creates an elided envelope containing only a digest.\n ///\n /// @param digest - The digest of the elided content\n /// @returns A new elided envelope\n static newElided(digest: Digest): Envelope {\n return new Envelope({\n type: \"elided\",\n digest,\n });\n }\n\n /// Creates a leaf envelope containing a CBOR value.\n ///\n /// @param value - The value to encode as CBOR\n /// @returns A new leaf envelope\n static newLeaf(value: unknown): Envelope {\n // Convert value to CBOR\n const cbor = Envelope.valueToCbor(value);\n\n // Calculate digest from CBOR bytes\n const cborBytes = Envelope.cborToBytes(cbor);\n const digest = Digest.fromImage(cborBytes);\n\n return new Envelope({\n type: \"leaf\",\n cbor,\n digest,\n });\n }\n\n /// Creates a wrapped envelope.\n ///\n /// @param envelope - The envelope to wrap\n /// @returns A new wrapped envelope\n static newWrapped(envelope: Envelope): Envelope {\n const digest = Digest.fromDigests([envelope.digest()]);\n return new Envelope({\n type: \"wrapped\",\n envelope,\n digest,\n });\n }\n\n /// Returns the digest of this envelope.\n ///\n /// Implementation of DigestProvider interface.\n ///\n /// @returns The envelope's digest\n digest(): Digest {\n const c = this._case;\n switch (c.type) {\n case \"node\":\n case \"leaf\":\n case \"wrapped\":\n case \"elided\":\n case \"knownValue\":\n return c.digest;\n case \"assertion\":\n return c.assertion.digest();\n case \"encrypted\": {\n // Get digest from encrypted message (AAD)\n const digest = c.message.aadDigest();\n if (digest === undefined) {\n throw new Error(\"Encrypted envelope missing digest\");\n }\n return digest;\n }\n case \"compressed\": {\n // Get digest from compressed value\n const digest = c.value.digestOpt();\n if (digest === undefined) {\n throw new Error(\"Compressed envelope missing digest\");\n }\n return digest;\n }\n }\n }\n\n /// Returns the subject of this envelope.\n ///\n /// For different envelope cases:\n /// - Node: Returns the subject envelope\n /// - Other cases: Returns the envelope itself\n ///\n /// @returns The subject envelope\n subject(): Envelope {\n const c = this._case;\n switch (c.type) {\n case \"node\":\n return c.subject;\n case \"leaf\":\n case \"wrapped\":\n case \"assertion\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n return this;\n }\n }\n\n /// Checks if the envelope's subject is an assertion.\n ///\n /// @returns `true` if the subject is an assertion, `false` otherwise\n isSubjectAssertion(): boolean {\n if (this._case.type === \"assertion\") return true;\n if (this._case.type === \"node\") return this._case.subject.isSubjectAssertion();\n return false;\n }\n\n /// Checks if the envelope's subject is obscured (elided, encrypted, or compressed).\n ///\n /// @returns `true` if the subject is obscured, `false` otherwise\n isSubjectObscured(): boolean {\n const t = this._case.type;\n return t === \"elided\" || t === \"encrypted\" || t === \"compressed\";\n }\n\n //\n // CBOR conversion helpers\n //\n\n /// Converts a value to CBOR.\n ///\n /// @param value - The value to convert\n /// @returns A CBOR representation\n private static valueToCbor(value: unknown): Cbor {\n // Import cbor function at runtime to avoid circular dependencies\n\n return cbor(value as Parameters<typeof cbor>[0]);\n }\n\n /// Converts CBOR to bytes.\n ///\n /// @param cbor - The CBOR value\n /// @returns Byte representation\n private static cborToBytes(cbor: Cbor): Uint8Array {\n // Import cborData function at runtime to avoid circular dependencies\n\n return cborData(cbor);\n }\n\n /// Returns the untagged CBOR representation of this envelope.\n ///\n /// @returns The untagged CBOR\n untaggedCbor(): Cbor {\n const c = this._case;\n switch (c.type) {\n case \"node\": {\n // Array with subject followed by assertions\n const result = [c.subject.untaggedCbor()];\n for (const assertion of c.assertions) {\n result.push(assertion.untaggedCbor());\n }\n return Envelope.valueToCbor(result);\n }\n case \"leaf\":\n // Tagged with TAG_LEAF (204)\n return toTaggedValue(TAG_LEAF, c.cbor);\n case \"wrapped\":\n // Wrapped envelopes are tagged with TAG_ENVELOPE\n return c.envelope.taggedCbor();\n case \"assertion\":\n // Assertions convert to CBOR maps\n return c.assertion.toCbor();\n case \"elided\":\n // Elided is just the digest bytes\n return Envelope.valueToCbor(c.digest.data());\n case \"knownValue\":\n // Known values are encoded as untagged unsigned integers\n // This matches Rust: value.untagged_cbor()\n return c.value.untaggedCbor();\n case \"encrypted\": {\n // Encrypted is tagged with TAG_ENCRYPTED (40002)\n // Contains: [ciphertext, nonce, auth, optional_aad_digest]\n // Per BCR-2023-004 and BCR-2022-001\n const message = c.message;\n const digest = message.aadDigest();\n const arr =\n digest !== undefined\n ? [message.ciphertext(), message.nonce(), message.authTag(), digest.data()]\n : [message.ciphertext(), message.nonce(), message.authTag()];\n return toTaggedValue(TAG_ENCRYPTED, Envelope.valueToCbor(arr));\n }\n case \"compressed\": {\n // Compressed is tagged with TAG_COMPRESSED (40003)\n // and contains an array: [compressed_data, optional_digest]\n const digest = c.value.digestOpt();\n const data = c.value.compressedData();\n const arr = digest !== undefined ? [data, digest.data()] : [data];\n return toTaggedValue(TAG_COMPRESSED, Envelope.valueToCbor(arr));\n }\n }\n }\n\n /// Returns the tagged CBOR representation of this envelope.\n ///\n /// All envelopes are tagged with TAG_ENVELOPE (200).\n ///\n /// @returns The tagged CBOR\n taggedCbor(): Cbor {\n return toTaggedValue(TAG_ENVELOPE, this.untaggedCbor());\n }\n\n /// Creates an envelope from untagged CBOR.\n ///\n /// @param cbor - The untagged CBOR value\n /// @returns A new envelope\n static fromUntaggedCbor(cbor: Cbor): Envelope {\n // Check if it's a tagged value\n const tagged = asTaggedValue(cbor);\n if (tagged !== undefined) {\n const [tag, item] = tagged;\n switch (tag.value) {\n case TAG_LEAF:\n case TAG_ENCODED_CBOR:\n // Leaf envelope\n return Envelope.newLeaf(item);\n case TAG_ENVELOPE: {\n // Wrapped envelope\n const envelope = Envelope.fromUntaggedCbor(item);\n return Envelope.newWrapped(envelope);\n }\n case TAG_COMPRESSED: {\n // Compressed envelope: array with [compressed_data, optional_digest]\n const arr = asCborArray(item);\n if (arr === undefined || arr.length < 1 || arr.length > 2) {\n throw EnvelopeError.cbor(\"compressed envelope must have 1 or 2 elements\");\n }\n // We've already checked arr.length >= 1 above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const compressedData = asByteString(arr.get(0)!);\n if (compressedData === undefined) {\n throw EnvelopeError.cbor(\"compressed data must be byte string\");\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const digestBytes = arr.length === 2 ? asByteString(arr.get(1)!) : undefined;\n if (arr.length === 2 && digestBytes === undefined) {\n throw EnvelopeError.cbor(\"digest must be byte string\");\n }\n const digest = digestBytes !== undefined ? Digest.fromData(digestBytes) : undefined;\n\n // Import Compressed class at runtime to avoid circular dependency\n\n const compressed = new Compressed(compressedData, digest);\n return Envelope.fromCase({ type: \"compressed\", value: compressed });\n }\n case TAG_ENCRYPTED: {\n // Encrypted envelope: array with [ciphertext, nonce, auth, optional_aad_digest]\n // Per BCR-2023-004 and BCR-2022-001\n const arr = asCborArray(item);\n if (arr === undefined || arr.length < 3 || arr.length > 4) {\n throw EnvelopeError.cbor(\"encrypted envelope must have 3 or 4 elements\");\n }\n // We've already checked arr.length >= 3 above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const ciphertext = asByteString(arr.get(0)!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const nonce = asByteString(arr.get(1)!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const authTag = asByteString(arr.get(2)!);\n if (ciphertext === undefined || nonce === undefined || authTag === undefined) {\n throw EnvelopeError.cbor(\"ciphertext, nonce, and auth must be byte strings\");\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const digestBytes = arr.length === 4 ? asByteString(arr.get(3)!) : undefined;\n if (arr.length === 4 && digestBytes === undefined) {\n throw EnvelopeError.cbor(\"aad digest must be byte string\");\n }\n const digest = digestBytes !== undefined ? Digest.fromData(digestBytes) : undefined;\n\n const message = new EncryptedMessage(ciphertext, nonce, authTag, digest);\n return Envelope.fromCase({ type: \"encrypted\", message });\n }\n default:\n throw EnvelopeError.cbor(`unknown envelope tag: ${tag.value}`);\n }\n }\n\n // Check if it's a byte string (elided)\n const bytes = asByteString(cbor);\n if (bytes !== undefined) {\n if (bytes.length !== 32) {\n throw EnvelopeError.cbor(\"elided digest must be 32 bytes\");\n }\n return Envelope.newElided(Digest.fromData(bytes));\n }\n\n // Check if it's an array (node)\n const array = asCborArray(cbor);\n if (array !== undefined) {\n if (array.length < 2) {\n throw EnvelopeError.cbor(\"node must have at least two elements\");\n }\n const subjectCbor = array.get(0);\n if (subjectCbor === undefined) {\n throw EnvelopeError.cbor(\"node subject is missing\");\n }\n const subject = Envelope.fromUntaggedCbor(subjectCbor);\n const assertions: Envelope[] = [];\n for (let i = 1; i < array.length; i++) {\n const assertionCbor = array.get(i);\n if (assertionCbor === undefined) {\n throw EnvelopeError.cbor(`node assertion at index ${i} is missing`);\n }\n assertions.push(Envelope.fromUntaggedCbor(assertionCbor));\n }\n return Envelope.newWithAssertions(subject, assertions);\n }\n\n // Check if it's a map (assertion)\n const map = asCborMap(cbor);\n if (map !== undefined) {\n const assertion = Assertion.fromCborMap(map);\n return Envelope.newWithAssertion(assertion);\n }\n\n // Handle known values (unsigned integers)\n if (cbor.type === MajorType.Unsigned) {\n const knownValue = new KnownValue(cbor.value as number | bigint);\n return Envelope.newWithKnownValue(knownValue);\n }\n\n throw EnvelopeError.cbor(\"invalid envelope format\");\n }\n\n /// Creates an envelope from tagged CBOR.\n ///\n /// @param cbor - The tagged CBOR value (should have TAG_ENVELOPE)\n /// @returns A new envelope\n static fromTaggedCbor(cbor: Cbor): Envelope {\n try {\n const untagged = tryExpectedTaggedValue(cbor, TAG_ENVELOPE);\n return Envelope.fromUntaggedCbor(untagged);\n } catch (error) {\n throw EnvelopeError.cbor(\n `expected TAG_ENVELOPE (${TAG_ENVELOPE})`,\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /// Adds an assertion to this envelope.\n ///\n /// @param predicate - The assertion predicate\n /// @param object - The assertion object\n /// @returns A new envelope with the assertion added\n ///\n /// @example\n /// ```typescript\n /// const person = Envelope.new(\"Alice\")\n /// .addAssertion(\"age\", 30)\n /// .addAssertion(\"city\", \"Boston\");\n /// ```\n addAssertion(predicate: EnvelopeEncodableValue, object: EnvelopeEncodableValue): Envelope {\n const assertion = Envelope.newAssertion(predicate, object);\n return this.addAssertionEnvelope(assertion);\n }\n\n /// Adds an assertion envelope to this envelope.\n ///\n /// @param assertion - The assertion envelope\n /// @returns A new envelope with the assertion added\n addAssertionEnvelope(assertion: Envelope): Envelope {\n const c = this._case;\n\n // If this is already a node, add to existing assertions\n if (c.type === \"node\") {\n return Envelope.newWithAssertions(c.subject, [...c.assertions, assertion]);\n }\n\n // Otherwise, create a new node with this envelope as subject\n return Envelope.newWithAssertions(this, [assertion]);\n }\n\n /// Creates a string representation of this envelope.\n ///\n /// @returns A string representation\n toString(): string {\n return `Envelope(${this._case.type})`;\n }\n\n /// Creates a shallow copy of this envelope.\n ///\n /// Since envelopes are immutable, this returns the same instance.\n ///\n /// @returns This envelope\n clone(): Envelope {\n return this;\n }\n\n //\n // Format methods (implemented via prototype extension in format module)\n //\n\n /// Returns a tree-formatted string representation of the envelope.\n ///\n /// The tree format displays the hierarchical structure of the envelope,\n /// showing subjects, assertions, and their relationships.\n ///\n /// @param options - Optional formatting options\n /// @returns A tree-formatted string\n declare treeFormat: (options?: TreeFormatOptions) => string;\n\n /// Returns a short identifier for this envelope based on its digest.\n ///\n /// @param format - Format for the digest ('short', 'full', or 'ur')\n /// @returns A digest identifier string\n declare shortId: (format?: \"short\" | \"full\" | \"ur\") => string;\n\n /// Returns a summary string for this envelope.\n ///\n /// @param maxLength - Maximum length of the summary\n /// @returns A summary string\n declare summary: (maxLength?: number) => string;\n\n /// Returns a hex representation of the envelope's CBOR encoding.\n ///\n /// @returns A hex string\n declare hex: () => string;\n\n /// Returns the CBOR-encoded bytes of the envelope.\n ///\n /// @returns The CBOR bytes\n declare cborBytes: () => Uint8Array;\n\n /// Returns a CBOR diagnostic notation string for the envelope.\n ///\n /// @returns A diagnostic string\n declare diagnostic: () => string;\n\n //\n // Extension methods (implemented via prototype extension in extension modules)\n // These declarations ensure TypeScript recognizes the methods when consuming the package\n //\n\n // From assertions.ts\n declare addAssertionEnvelopes: (assertions: Envelope[]) => Envelope;\n declare addOptionalAssertionEnvelope: (assertion: Envelope | undefined) => Envelope;\n declare addOptionalAssertion: (\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue | undefined,\n ) => Envelope;\n declare addNonemptyStringAssertion: (predicate: EnvelopeEncodableValue, str: string) => Envelope;\n declare addAssertions: (envelopes: Envelope[]) => Envelope;\n declare addAssertionIf: (\n condition: boolean,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n ) => Envelope;\n declare addAssertionEnvelopeIf: (condition: boolean, assertionEnvelope: Envelope) => Envelope;\n declare removeAssertion: (target: Envelope) => Envelope;\n declare replaceAssertion: (assertion: Envelope, newAssertion: Envelope) => Envelope;\n declare replaceSubject: (subject: Envelope) => Envelope;\n // From salt.ts - assertion methods with optional salting\n declare addAssertionSalted: (\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n salted: boolean,\n ) => Envelope;\n declare addAssertionEnvelopeSalted: (assertionEnvelope: Envelope, salted: boolean) => Envelope;\n declare addOptionalAssertionEnvelopeSalted: (\n assertionEnvelope: Envelope | undefined,\n salted: boolean,\n ) => Envelope;\n\n // From elide.ts\n declare elide: () => Envelope;\n declare elideRemovingSetWithAction: (target: Set<Digest>, action: ObscureAction) => Envelope;\n declare elideRemovingSet: (target: Set<Digest>) => Envelope;\n declare elideRemovingArrayWithAction: (\n target: DigestProvider[],\n action: ObscureAction,\n ) => Envelope;\n declare elideRemovingArray: (target: DigestProvider[]) => Envelope;\n declare elideRemovingTargetWithAction: (\n target: DigestProvider,\n action: ObscureAction,\n ) => Envelope;\n declare elideRemovingTarget: (target: DigestProvider) => Envelope;\n declare elideRevealingSetWithAction: (target: Set<Digest>, action: ObscureAction) => Envelope;\n declare elideRevealingSet: (target: Set<Digest>) => Envelope;\n declare elideRevealingArrayWithAction: (\n target: DigestProvider[],\n action: ObscureAction,\n ) => Envelope;\n declare elideRevealingArray: (target: DigestProvider[]) => Envelope;\n declare elideRevealingTargetWithAction: (\n target: DigestProvider,\n action: ObscureAction,\n ) => Envelope;\n declare elideRevealingTarget: (target: DigestProvider) => Envelope;\n declare unelide: (envelope: Envelope) => Envelope;\n declare nodesMatching: (\n targetDigests: Set<Digest> | undefined,\n obscureTypes: ObscureType[],\n ) => Set<Digest>;\n declare walkUnelide: (envelopes: Envelope[]) => Envelope;\n declare walkReplace: (target: Set<Digest>, replacement: Envelope) => Envelope;\n declare isEquivalentTo: (other: Envelope) => boolean;\n declare isIdenticalTo: (other: Envelope) => boolean;\n\n // From leaf.ts\n declare tryLeaf: () => Cbor;\n declare extractString: () => string;\n declare extractNumber: () => number;\n declare extractBoolean: () => boolean;\n declare extractBytes: () => Uint8Array;\n declare extractNull: () => null;\n\n // Generic typed extraction methods from envelope-decodable.ts\n declare extractSubject: <T>(decoder: (cbor: Cbor) => T) => T;\n declare tryObjectForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T;\n declare tryOptionalObjectForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T | undefined;\n declare extractObjectForPredicateWithDefault: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n defaultValue: T,\n ) => T;\n declare extractObjectsForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T[];\n declare tryObjectsForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T[];\n\n // From queries.ts\n declare isFalse: () => boolean;\n declare isTrue: () => boolean;\n declare isBool: () => boolean;\n declare isNumber: () => boolean;\n declare isSubjectNumber: () => boolean;\n declare isNaN: () => boolean;\n declare isSubjectNaN: () => boolean;\n declare isNull: () => boolean;\n declare tryByteString: () => Uint8Array;\n declare asByteString: () => Uint8Array | undefined;\n declare asArray: () => readonly Cbor[] | undefined;\n declare asMap: () => CborMap | undefined;\n declare asText: () => string | undefined;\n declare asLeaf: () => Cbor | undefined;\n declare asKnownValue: () => KnownValue | undefined;\n declare tryKnownValue: () => KnownValue;\n declare isKnownValue: () => boolean;\n declare isSubjectUnit: () => boolean;\n declare checkSubjectUnit: () => Envelope;\n declare hasAssertions: () => boolean;\n declare asAssertion: () => Envelope | undefined;\n declare tryAssertion: () => Envelope;\n declare asPredicate: () => Envelope | undefined;\n declare tryPredicate: () => Envelope;\n declare asObject: () => Envelope | undefined;\n declare tryObject: () => Envelope;\n declare isAssertion: () => boolean;\n declare isElided: () => boolean;\n declare isLeaf: () => boolean;\n declare isNode: () => boolean;\n declare isWrapped: () => boolean;\n declare isInternal: () => boolean;\n declare isObscured: () => boolean;\n declare assertions: () => Envelope[];\n declare assertionsWithPredicate: (predicate: EnvelopeEncodableValue) => Envelope[];\n declare assertionWithPredicate: (predicate: EnvelopeEncodableValue) => Envelope;\n declare optionalAssertionWithPredicate: (\n predicate: EnvelopeEncodableValue,\n ) => Envelope | undefined;\n declare objectForPredicate: (predicate: EnvelopeEncodableValue) => Envelope;\n declare optionalObjectForPredicate: (predicate: EnvelopeEncodableValue) => Envelope | undefined;\n declare objectsForPredicate: (predicate: EnvelopeEncodableValue) => Envelope[];\n declare elementsCount: () => number;\n declare isSubjectEncrypted: () => boolean;\n declare isSubjectCompressed: () => boolean;\n declare isSubjectElided: () => boolean;\n declare setPosition: (position: number) => Envelope;\n declare position: () => number;\n declare removePosition: () => Envelope;\n\n // From walk.ts\n declare walk: <State>(hideNodes: boolean, state: State, visit: Visitor<State>) => void;\n\n // Digest-related methods\n declare digests: (levelLimit: number) => Set<Digest>;\n declare shallowDigests: () => Set<Digest>;\n declare deepDigests: () => Set<Digest>;\n\n // Alias methods for Rust API compatibility\n declare object: () => Envelope;\n declare predicate: () => Envelope;\n\n // Additional elision method\n declare elideSetWithAction: (target: Set<Digest>, action: ObscureAction) => Envelope;\n\n // From ur.ts - UR (Uniform Resource) support\n declare urString: () => string;\n declare ur: () => UR;\n declare taggedCborData: () => Uint8Array;\n declare static fromUrString: (urString: string) => Envelope;\n declare static fromURString: (urString: string) => Envelope;\n declare static fromUR: (ur: UR) => Envelope;\n\n // From wrap.ts\n declare wrap: () => Envelope;\n declare tryUnwrap: () => Envelope;\n declare unwrap: () => Envelope;\n\n // From attachment.ts\n declare addAttachment: (\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n ) => Envelope;\n declare attachmentPayload: () => Envelope;\n declare attachmentVendor: () => string;\n declare attachmentConformsTo: () => string | undefined;\n declare attachments: () => Envelope[];\n declare attachmentsWithVendorAndConformsTo: (vendor?: string, conformsTo?: string) => Envelope[];\n declare attachmentWithVendorAndConformsTo: (vendor?: string, conformsTo?: string) => Envelope;\n declare validateAttachment: () => void;\n\n // From edge.ts (BCR-2026-003)\n declare addEdgeEnvelope: (edge: Envelope) => Envelope;\n declare edges: () => Envelope[];\n declare validateEdge: () => void;\n declare edgeIsA: () => Envelope;\n declare edgeSource: () => Envelope;\n declare edgeTarget: () => Envelope;\n declare edgeSubject: () => Envelope;\n declare edgesMatching: (\n isA?: Envelope,\n source?: Envelope,\n target?: Envelope,\n subject?: Envelope,\n ) => Envelope[];\n\n // From compress.ts\n declare compress: () => Envelope;\n declare decompress: () => Envelope;\n declare compressSubject: () => Envelope;\n declare decompressSubject: () => Envelope;\n declare isCompressed: () => boolean;\n\n // From encrypt.ts\n declare encryptSubject: (key: SymmetricKey) => Envelope;\n declare decryptSubject: (key: SymmetricKey) => Envelope;\n declare encrypt: (key: SymmetricKey) => Envelope;\n declare decrypt: (key: SymmetricKey) => Envelope;\n declare isEncrypted: () => boolean;\n\n // From proof.ts\n declare proofContainsSet: (target: Set<Digest>) => Envelope | undefined;\n declare proofContainsTarget: (target: Envelope) => Envelope | undefined;\n declare confirmContainsSet: (target: Set<Digest>, proof: Envelope) => boolean;\n declare confirmContainsTarget: (target: Envelope, proof: Envelope) => boolean;\n\n // From recipient.ts - uses Encrypter/Decrypter interfaces for PQ support\n declare encryptSubjectToRecipient: (recipient: Encrypter) => Envelope;\n declare encryptSubjectToRecipients: (recipients: Encrypter[]) => Envelope;\n declare addRecipient: (\n recipient: Encrypter,\n contentKey: SymmetricKey,\n testNonce?: Nonce,\n ) => Envelope;\n declare decryptSubjectToRecipient: (recipient: Decrypter) => Envelope;\n declare decryptToRecipient: (recipient: Decrypter) => Envelope;\n declare encryptToRecipients: (recipients: Encrypter[]) => Envelope;\n declare recipients: () => SealedMessage[];\n\n // From seal.ts\n declare encryptToRecipient: (recipient: Encrypter) => Envelope;\n declare seal: (sender: Signer, recipient: Encrypter) => Envelope;\n declare unseal: (senderPublicKey: Verifier, recipient: Decrypter) => Envelope;\n\n // From salt.ts\n declare addSalt: () => Envelope;\n declare addSaltWithLength: (count: number) => Envelope;\n declare addSaltWithLen: (count: number) => Envelope;\n declare addSaltBytes: (saltBytes: Uint8Array) => Envelope;\n declare addSaltInRange: (min: number, max: number) => Envelope;\n\n // From signature.ts — matches bc-envelope-rust/src/extension/signature/signature_impl.rs\n declare addSignature: (signer: Signer) => Envelope;\n declare addSignatureOpt: (\n signer: Signer,\n options?: SigningOptions,\n metadata?: SignatureMetadata,\n ) => Envelope;\n declare addSignatureWithMetadata: (signer: Signer, metadata?: SignatureMetadata) => Envelope;\n declare addSignatures: (signers: Signer[]) => Envelope;\n declare addSignaturesOpt: (\n signersWithOptions: {\n signer: Signer;\n options?: SigningOptions;\n metadata?: SignatureMetadata;\n }[],\n ) => Envelope;\n declare addSignaturesWithMetadata: (\n signersWithMetadata: { signer: Signer; metadata?: SignatureMetadata }[],\n ) => Envelope;\n declare makeSignedAssertion: (signature: Signature, note?: string) => Envelope;\n declare isVerifiedSignature: (signature: Signature, verifier: Verifier) => boolean;\n declare verifySignature: (signature: Signature, verifier: Verifier) => Envelope;\n declare hasSignatureFrom: (verifier: Verifier) => boolean;\n declare hasSignatureFromReturningMetadata: (verifier: Verifier) => Envelope | undefined;\n declare verifySignatureFrom: (verifier: Verifier) => Envelope;\n declare verifySignatureFromReturningMetadata: (verifier: Verifier) => Envelope;\n declare hasSignaturesFrom: (verifiers: Verifier[]) => boolean;\n declare hasSignaturesFromThreshold: (verifiers: Verifier[], threshold?: number) => boolean;\n declare verifySignaturesFrom: (verifiers: Verifier[]) => Envelope;\n declare verifySignaturesFromThreshold: (verifiers: Verifier[], threshold?: number) => Envelope;\n declare signatures: () => Envelope[];\n declare sign: (signer: Signer) => Envelope;\n declare signOpt: (signer: Signer, options?: SigningOptions) => Envelope;\n declare signWithMetadata: (signer: Signer, metadata?: SignatureMetadata) => Envelope;\n declare verify: (verifier: Verifier) => Envelope;\n declare verifyReturningMetadata: (verifier: Verifier) => {\n envelope: Envelope;\n metadata: Envelope;\n };\n\n // From types.ts\n declare addType: (object: EnvelopeEncodableValue) => Envelope;\n declare types: () => Envelope[];\n declare getType: () => Envelope;\n declare hasType: (t: EnvelopeEncodableValue) => boolean;\n declare checkType: (t: EnvelopeEncodableValue) => void;\n\n // Static methods from extensions\n declare static newAttachment: (\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n ) => Envelope;\n\n // Static methods from leaf.ts\n declare static unit: () => Envelope;\n\n // From format/notation.ts\n declare format: () => string;\n declare formatOpt: (opts: EnvelopeFormatOpts) => string;\n declare formatFlat: () => string;\n\n // From format/mermaid.ts\n declare mermaidFormat: () => string;\n declare mermaidFormatOpt: (opts: MermaidFormatOpts) => string;\n\n // From format/envelope-summary.ts\n declare summaryWithContext: (maxLength: number, context: FormatContext) => string;\n\n // From secret.ts\n declare lockSubject: (method: KeyDerivationMethod, secret: Uint8Array) => Envelope;\n declare unlockSubject: (secret: Uint8Array) => Envelope;\n declare isLockedWithPassword: () => boolean;\n declare isLockedWithSshAgent: () => boolean;\n declare addSecret: (\n method: KeyDerivationMethod,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n ) => Envelope;\n declare lock: (method: KeyDerivationMethod, secret: Uint8Array) => Envelope;\n declare unlock: (secret: Uint8Array) => Envelope;\n\n // From extension/sskr.ts\n declare sskrSplit: (spec: SSKRSpec, contentKey: SymmetricKey) => Envelope[][];\n declare sskrSplitFlattened: (spec: SSKRSpec, contentKey: SymmetricKey) => Envelope[];\n declare sskrSplitUsing: (\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n rng: RandomNumberGenerator,\n ) => Envelope[][];\n declare static sskrJoin: (envelopes: Envelope[]) => Envelope;\n\n // CBOR methods\n declare toCbor: () => unknown;\n declare expectLeaf: () => unknown;\n declare checkTypeValue: (type: unknown) => void;\n}\n","import type { CborTaggedEncodable } from \"@bcts/dcbor\";\nimport type { KnownValue } from \"@bcts/known-values\";\nimport type { Envelope } from \"./envelope\";\n\n/// A trait for types that can be encoded as a Gordian Envelope.\n///\n/// This interface defines the contract for converting a value into an envelope.\n/// Types implementing this interface can be used directly with envelope\n/// construction functions without explicit conversion.\n///\n/// There are numerous built-in implementations for common types including:\n/// - Primitive types (numbers, strings, booleans)\n/// - CBOR values\n/// - Cryptographic types (digests, keys, etc.)\n/// - Assertions\n/// - Other envelopes\n///\n/// @example\n/// ```typescript\n/// // String implements EnvelopeEncodable\n/// const e1 = Envelope.new(\"Hello\");\n///\n/// // Numbers implement EnvelopeEncodable\n/// const e2 = Envelope.new(42);\n///\n/// // Using in envelope construction\n/// const envelope = Envelope.new(\"subject\")\n/// .addAssertion(\"name\", \"Alice\") // Uses EnvelopeEncodable for both predicate and object\n/// .addAssertion(\"age\", 30); // Uses EnvelopeEncodable for the numeric object\n/// ```\nexport interface EnvelopeEncodable {\n /// Converts this value into a Gordian Envelope.\n ///\n /// This is the core method of the interface, converting the implementing type\n /// into an envelope representation. Most implementations will convert the\n /// value to a leaf envelope containing the value.\n ///\n /// @returns A new envelope containing the value.\n intoEnvelope(): Envelope;\n}\n\n/// Type guard to check if a value implements EnvelopeEncodable.\n///\n/// @param value - The value to check\n/// @returns `true` if the value implements EnvelopeEncodable, `false` otherwise\nexport function isEnvelopeEncodable(value: unknown): value is EnvelopeEncodable {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"intoEnvelope\" in value &&\n typeof (value as EnvelopeEncodable).intoEnvelope === \"function\"\n );\n}\n\n/// Helper type for values that can be encoded as envelopes.\n///\n/// This includes:\n/// - Types that directly implement EnvelopeEncodable\n/// - Primitive types (string, number, boolean)\n/// - Uint8Array (for binary data)\n/// - null and undefined\n///\n/// The Envelope class will handle conversion of these types automatically.\nexport type EnvelopeEncodableValue =\n | EnvelopeEncodable\n | string\n | number\n | boolean\n | bigint\n | Uint8Array\n | null\n | undefined\n | Envelope\n | KnownValue\n | CborTaggedEncodable;\n","import type { Cbor } from \"@bcts/dcbor\";\nimport {\n type CborTagged,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n tagsForValues,\n cborData,\n decodeCbor,\n} from \"@bcts/dcbor\";\nimport { ENVELOPE } from \"@bcts/components\";\nimport { Envelope } from \"./envelope\";\n\nconst TAG_ENVELOPE = ENVELOPE.value;\n\n/// Support for CBOR encoding and decoding of `Envelope`.\n///\n/// All envelopes are tagged with the `envelope` tag (200). Within that tag,\n/// each of the envelope cases has a unique CBOR signature:\n///\n/// * `.node` contains a CBOR array, the first element of which is the subject,\n/// followed by one or more assertions.\n/// * `.leaf` is tagged #6.24 (TAG_ENCODED_CBOR) or #6.204 (TAG_LEAF), which\n/// are the IANA tag for embedded CBOR.\n/// * `.wrapped` is tagged with the `envelope` tag.\n/// * `.assertion` is a single-element map `{predicate: object}`.\n/// * `.knownValue` is an unsigned 64-bit integer.\n/// * `.encrypted` is tagged with the `crypto-msg` tag.\n/// * `.elided` is a byte string of length 32 (the digest).\n/// * `.compressed` is tagged with the `compressed` tag.\n///\n/// This module provides implementations of the CBOR encoding/decoding traits\n/// for the Envelope type, matching the Rust bc-envelope implementation.\n\n/// Implements CborTagged interface for Envelope.\n///\n/// Returns the tags that should be used for CBOR encoding.\nexport class EnvelopeCBORTagged implements CborTagged {\n cborTags(): ReturnType<typeof tagsForValues> {\n return tagsForValues([TAG_ENVELOPE]);\n }\n\n static cborTags(): number[] {\n return tagsForValues([TAG_ENVELOPE]).map((tag) => Number(tag.value));\n }\n}\n\n/// Implements CborTaggedEncodable for Envelope.\n///\n/// Provides the untagged CBOR representation of an envelope.\nexport class EnvelopeCBORTaggedEncodable implements CborTaggedEncodable {\n constructor(private readonly envelope: Envelope) {}\n\n cborTags(): ReturnType<typeof tagsForValues> {\n return tagsForValues([TAG_ENVELOPE]);\n }\n\n untaggedCbor(): Cbor {\n return this.envelope.untaggedCbor();\n }\n\n taggedCbor(): Cbor {\n return this.envelope.taggedCbor();\n }\n}\n\n/// Implements CborTaggedDecodable for Envelope.\n///\n/// Provides the ability to decode an envelope from untagged CBOR.\nexport class EnvelopeCBORTaggedDecodable<T = Envelope> implements CborTaggedDecodable<T> {\n cborTags(): ReturnType<typeof tagsForValues> {\n return tagsForValues([TAG_ENVELOPE]);\n }\n\n static fromUntaggedCbor(cbor: Cbor): Envelope {\n return Envelope.fromUntaggedCbor(cbor);\n }\n\n static fromTaggedCbor(cbor: Cbor): Envelope {\n return Envelope.fromTaggedCbor(cbor);\n }\n\n fromUntaggedCbor(cbor: Cbor): T {\n return Envelope.fromUntaggedCbor(cbor) as T;\n }\n\n fromTaggedCbor(cbor: Cbor): T {\n return Envelope.fromTaggedCbor(cbor) as T;\n }\n}\n\n/// Convenience function to convert an Envelope to CBOR.\n///\n/// @param envelope - The envelope to convert\n/// @returns The CBOR representation (tagged)\nexport function envelopeToCbor(envelope: Envelope): Cbor {\n return envelope.taggedCbor();\n}\n\n/// Convenience function to create an Envelope from CBOR.\n///\n/// @param cbor - The CBOR value (expected to be tagged with TAG_ENVELOPE)\n/// @returns A new Envelope\nexport function envelopeFromCbor(cbor: Cbor): Envelope {\n return Envelope.fromTaggedCbor(cbor);\n}\n\n/// Convenience function to encode an Envelope to CBOR bytes.\n///\n/// @param envelope - The envelope to encode\n/// @returns The CBOR bytes\nexport function envelopeToBytes(envelope: Envelope): Uint8Array {\n return cborData(envelope.taggedCbor());\n}\n\n/// Convenience function to decode an Envelope from CBOR bytes.\n///\n/// @param bytes - The CBOR bytes\n/// @returns A new Envelope\nexport function envelopeFromBytes(bytes: Uint8Array): Envelope {\n const cbor = decodeCbor(bytes);\n return Envelope.fromTaggedCbor(cbor);\n}\n","import type { Cbor } from \"@bcts/dcbor\";\nimport { tryIntoText, tryIntoBool, tryIntoByteString, isNull, decodeCbor } from \"@bcts/dcbor\";\nimport { Envelope } from \"./envelope\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { EnvelopeError, ErrorCode } from \"./error\";\n\n/// Provides functions for extracting typed values from envelopes.\n///\n/// This module defines conversion functions that parallel Rust's `TryFrom<Envelope>`\n/// implementations. These allow extracting specific types from envelope leaf values.\n///\n/// In the Rust version, a macro (`impl_envelope_decodable!`) is used to generate\n/// these implementations for many types. In TypeScript, we provide explicit\n/// conversion functions instead.\n\n/// Extracts a string value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The string value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractString(envelope: Envelope): string {\n const cbor = envelope.tryLeaf();\n try {\n return tryIntoText(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"envelope does not contain a string\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n\n/// Extracts a number value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The number value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractNumber(envelope: Envelope): number {\n const cbor = envelope.tryLeaf();\n\n // Handle unsigned, negative, and simple (float) types\n if (\"type\" in cbor) {\n switch (cbor.type) {\n case 0: // MajorType.Unsigned\n return typeof cbor.value === \"bigint\" ? Number(cbor.value) : cbor.value;\n case 1: {\n // MajorType.Negative\n // Negative values are stored as magnitude, convert back\n const magnitude = typeof cbor.value === \"bigint\" ? Number(cbor.value) : cbor.value;\n return -magnitude - 1;\n }\n case 7: // MajorType.Simple\n if (\n typeof cbor.value === \"object\" &&\n cbor.value !== null &&\n \"type\" in cbor.value &&\n cbor.value.type === \"Float\"\n ) {\n return cbor.value.value;\n }\n break;\n case 2: // MajorType.ByteString\n case 3: // MajorType.TextString\n case 4: // MajorType.Array\n case 5: // MajorType.Map\n case 6: // MajorType.Tag\n // These CBOR types don't represent numbers\n break;\n }\n }\n\n throw EnvelopeError.cbor(\"envelope does not contain a number\");\n}\n\n/// Extracts a boolean value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The boolean value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractBoolean(envelope: Envelope): boolean {\n const cbor = envelope.tryLeaf();\n try {\n return tryIntoBool(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"envelope does not contain a boolean\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n\n/// Extracts a byte array value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The byte array value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractBytes(envelope: Envelope): Uint8Array {\n const cbor = envelope.tryLeaf();\n try {\n return tryIntoByteString(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"envelope does not contain bytes\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n\n/// Extracts null from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @throws {EnvelopeError} If the envelope is not a leaf containing null\nexport function extractNull(envelope: Envelope): null {\n const cbor = envelope.tryLeaf();\n if (isNull(cbor)) {\n return null;\n }\n throw EnvelopeError.cbor(\"envelope does not contain null\");\n}\n\n/// Static methods for creating envelopes from CBOR data.\n///\n/// These are convenience methods that mirror the Rust implementation.\nexport class EnvelopeDecoder {\n /// Creates an envelope from a CBOR value.\n ///\n /// @param cbor - The CBOR value to convert into an envelope\n /// @returns A new envelope created from the CBOR data\n /// @throws {EnvelopeError} If the CBOR does not represent a valid envelope\n static tryFromCbor(cbor: Cbor): Envelope {\n try {\n return Envelope.fromTaggedCbor(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\"invalid envelope CBOR\", error instanceof Error ? error : undefined);\n }\n }\n\n /// Creates an envelope from raw CBOR binary data.\n ///\n /// @param data - The raw CBOR binary data to convert into an envelope\n /// @returns A new envelope created from the CBOR data\n /// @throws {EnvelopeError} If the data is not valid CBOR or does not\n /// represent a valid envelope structure\n static tryFromCborData(data: Uint8Array): Envelope {\n try {\n const cbor = decodeCbor(data);\n return EnvelopeDecoder.tryFromCbor(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"invalid envelope CBOR data\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n}\n\n/// Add the tryLeaf method to Envelope prototype.\n///\n/// This extracts the leaf CBOR value from an envelope.\nEnvelope.prototype.tryLeaf = function (this: Envelope): Cbor {\n const c = this.case();\n if (c.type !== \"leaf\") {\n throw EnvelopeError.notLeaf();\n }\n return c.cbor;\n};\n\n/// Add extraction convenience methods to Envelope prototype\nEnvelope.prototype.extractString = function (this: Envelope): string {\n return extractString(this);\n};\n\nEnvelope.prototype.extractNumber = function (this: Envelope): number {\n return extractNumber(this);\n};\n\nEnvelope.prototype.extractBoolean = function (this: Envelope): boolean {\n return extractBoolean(this);\n};\n\nEnvelope.prototype.extractBytes = function (this: Envelope): Uint8Array {\n return extractBytes(this);\n};\n\nEnvelope.prototype.extractNull = function (this: Envelope): null {\n return extractNull(this);\n};\n\n// ============================================================================\n// Generic Typed Extraction Methods\n// ============================================================================\n\n/// Type for CBOR decoder functions\nexport type CborDecoder<T> = (cbor: Cbor) => T;\n\n/// Extracts the subject of an envelope as type T using a decoder function.\n///\n/// This is the TypeScript equivalent of Rust's `TryFrom<Envelope>` trait bound.\n/// Since TypeScript doesn't have trait bounds on generics, we pass a decoder\n/// function explicitly.\n///\n/// Handles all envelope case types:\n/// - leaf: decodes the CBOR value\n/// - knownValue: converts to tagged CBOR then decodes\n/// - wrapped: recurses into the inner envelope\n/// - node: recurses on the subject\n///\n/// @example\n/// ```typescript\n/// const envelope = Envelope.new(myEncryptedKey.taggedCbor());\n/// const extracted = envelope.extractSubject(EncryptedKey.fromTaggedCbor);\n/// ```\n///\n/// @param decoder - Function to decode CBOR to type T\n/// @returns The decoded value of type T\n/// @throws {EnvelopeError} If the envelope case is unsupported or decoding fails\nexport function extractSubject<T>(envelope: Envelope, decoder: CborDecoder<T>): T {\n const subject = envelope.subject();\n const c = subject.case();\n\n switch (c.type) {\n case \"leaf\":\n try {\n return decoder(c.cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"failed to decode subject\",\n error instanceof Error ? error : undefined,\n );\n }\n case \"knownValue\":\n try {\n return decoder(c.value.taggedCbor());\n } catch (error) {\n throw EnvelopeError.cbor(\n \"failed to decode subject\",\n error instanceof Error ? error : undefined,\n );\n }\n case \"wrapped\":\n return extractSubject(c.envelope, decoder);\n case \"node\":\n return extractSubject(c.subject, decoder);\n case \"assertion\":\n try {\n return decoder(c.assertion.toCbor());\n } catch {\n throw EnvelopeError.invalidFormat();\n }\n case \"elided\":\n try {\n return decoder(c.digest.taggedCbor());\n } catch {\n throw EnvelopeError.invalidFormat();\n }\n case \"encrypted\":\n throw EnvelopeError.invalidFormat();\n case \"compressed\":\n throw EnvelopeError.invalidFormat();\n }\n}\n\n/// Add extractSubject method to Envelope prototype\nEnvelope.prototype.extractSubject = function <T>(this: Envelope, decoder: CborDecoder<T>): T {\n return extractSubject(this, decoder);\n};\n\n/// Extracts the object for a predicate as type T using a decoder function.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns The decoded value of type T\n/// @throws {EnvelopeError} If predicate not found or decoding fails\nexport function tryObjectForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T {\n const obj = envelope.objectForPredicate(predicate);\n return extractSubject(obj, decoder);\n}\n\n/// Add tryObjectForPredicate method to Envelope prototype\nEnvelope.prototype.tryObjectForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T {\n return tryObjectForPredicate(this, predicate, decoder);\n};\n\n/// Extracts the optional object for a predicate as type T using a decoder function.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns The decoded value of type T, or undefined if predicate not found\n/// @throws {EnvelopeError} If decoding fails (but not if predicate not found)\nexport function tryOptionalObjectForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T | undefined {\n const obj = envelope.optionalObjectForPredicate(predicate);\n if (obj === undefined) {\n return undefined;\n }\n return extractSubject(obj, decoder);\n}\n\n/// Add tryOptionalObjectForPredicate method to Envelope prototype\nEnvelope.prototype.tryOptionalObjectForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T | undefined {\n return tryOptionalObjectForPredicate(this, predicate, decoder);\n};\n\n/// Extracts the object for a predicate as type T, with a default value if not found.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @param defaultValue - Value to return if predicate not found\n/// @returns The decoded value of type T, or the default value\n/// @throws {EnvelopeError} If decoding fails (but not if predicate not found)\nexport function extractObjectForPredicateWithDefault<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n defaultValue: T,\n): T {\n const result = tryOptionalObjectForPredicate(envelope, predicate, decoder);\n return result ?? defaultValue;\n}\n\n/// Add extractObjectForPredicateWithDefault method to Envelope prototype\nEnvelope.prototype.extractObjectForPredicateWithDefault = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n defaultValue: T,\n): T {\n return extractObjectForPredicateWithDefault(this, predicate, decoder, defaultValue);\n};\n\n/// Extracts all objects for a predicate as type T using a decoder function.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns Array of decoded values of type T\n/// @throws {EnvelopeError} If any decoding fails\nexport function extractObjectsForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n const objects = envelope.objectsForPredicate(predicate);\n return objects.map((obj) => extractSubject(obj, decoder));\n}\n\n/// Add extractObjectsForPredicate method to Envelope prototype\nEnvelope.prototype.extractObjectsForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n return extractObjectsForPredicate(this, predicate, decoder);\n};\n\n/// Extracts all objects for a predicate as type T, returning empty array if none found.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns Array of decoded values of type T (empty if no matches)\n/// @throws {EnvelopeError} If any decoding fails\nexport function tryObjectsForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n try {\n return extractObjectsForPredicate(envelope, predicate, decoder);\n } catch (error) {\n // If it's a nonexistent predicate error, return empty array\n if (error instanceof EnvelopeError && error.code === ErrorCode.NONEXISTENT_PREDICATE) {\n return [];\n }\n throw error;\n }\n}\n\n/// Add tryObjectsForPredicate method to Envelope prototype\nEnvelope.prototype.tryObjectsForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n return tryObjectsForPredicate(this, predicate, decoder);\n};\n","import { type Digest, type DigestProvider } from \"./digest\";\nimport { Envelope } from \"./envelope\";\nimport { Assertion } from \"./assertion\";\nimport { EnvelopeError } from \"./error\";\n\n/// Types of obscuration that can be applied to envelope elements.\n///\n/// This enum identifies the different ways an envelope element can be obscured.\nexport enum ObscureType {\n /// The element has been elided, showing only its digest.\n Elided = \"elided\",\n\n /// The element has been encrypted using symmetric encryption.\n /// TODO: Implement when encrypt feature is added\n Encrypted = \"encrypted\",\n\n /// The element has been compressed to reduce its size.\n /// TODO: Implement when compress feature is added\n Compressed = \"compressed\",\n}\n\n/// Actions that can be performed on parts of an envelope to obscure them.\n///\n/// Gordian Envelope supports several ways to obscure parts of an envelope while\n/// maintaining its semantic integrity and digest tree.\nexport type ObscureAction =\n | { type: \"elide\" }\n | { type: \"encrypt\"; key: unknown }\n | { type: \"compress\" };\n\n/// Helper to create elide action\nexport function elideAction(): ObscureAction {\n return { type: \"elide\" };\n}\n\n/// Late-binding handler for the encrypt obscure action.\n/// Registered by extension/encrypt.ts to avoid circular dependencies.\nlet _obscureEncryptHandler: ((envelope: Envelope, key: unknown) => Envelope) | undefined;\n\n/// Registers the handler for the encrypt obscure action.\n/// Called by registerEncryptExtension() during module initialization.\nexport function registerObscureEncryptHandler(\n handler: (envelope: Envelope, key: unknown) => Envelope,\n): void {\n _obscureEncryptHandler = handler;\n}\n\n/// Implementation of elide()\nEnvelope.prototype.elide = function (this: Envelope): Envelope {\n const c = this.case();\n if (c.type === \"elided\") {\n return this;\n }\n return Envelope.newElided(this.digest());\n};\n\n/// Core elision logic\nfunction elideSetWithAction(\n envelope: Envelope,\n target: Set<Digest>,\n isRevealing: boolean,\n action: ObscureAction,\n): Envelope {\n const selfDigest = envelope.digest();\n const targetContainsSelf = Array.from(target).some((d) => d.equals(selfDigest));\n\n // Target Matches isRevealing elide\n // false false false\n // false true true\n // true false true\n // true true false\n\n if (targetContainsSelf !== isRevealing) {\n // Should obscure this envelope\n if (action.type === \"elide\") {\n return envelope.elide();\n } else if (action.type === \"encrypt\") {\n if (_obscureEncryptHandler === undefined) {\n throw new Error(\"Encrypt action handler not registered\");\n }\n return _obscureEncryptHandler(envelope, action.key);\n } else if (action.type === \"compress\") {\n return envelope.compress();\n }\n }\n\n const c = envelope.case();\n\n // Recursively process structure\n if (c.type === \"assertion\") {\n const predicate = elideSetWithAction(c.assertion.predicate(), target, isRevealing, action);\n const object = elideSetWithAction(c.assertion.object(), target, isRevealing, action);\n const elidedAssertion = new Assertion(predicate, object);\n return Envelope.newWithAssertion(elidedAssertion);\n } else if (c.type === \"node\") {\n const elidedSubject = elideSetWithAction(c.subject, target, isRevealing, action);\n const elidedAssertions = c.assertions.map((a) =>\n elideSetWithAction(a, target, isRevealing, action),\n );\n return Envelope.newWithUncheckedAssertions(elidedSubject, elidedAssertions);\n } else if (c.type === \"wrapped\") {\n const elidedEnvelope = elideSetWithAction(c.envelope, target, isRevealing, action);\n return Envelope.newWrapped(elidedEnvelope);\n }\n\n return envelope;\n}\n\n/// Implementation of elideRemovingSetWithAction\nEnvelope.prototype.elideRemovingSetWithAction = function (\n this: Envelope,\n target: Set<Digest>,\n action: ObscureAction,\n): Envelope {\n return elideSetWithAction(this, target, false, action);\n};\n\n/// Implementation of elideSetWithAction (for revealing mode)\nEnvelope.prototype.elideSetWithAction = function (\n this: Envelope,\n target: Set<Digest>,\n action: ObscureAction,\n): Envelope {\n return elideSetWithAction(this, target, true, action);\n};\n\n/// Implementation of elideRemovingSet\nEnvelope.prototype.elideRemovingSet = function (this: Envelope, target: Set<Digest>): Envelope {\n return elideSetWithAction(this, target, false, elideAction());\n};\n\n/// Implementation of elideRemovingArrayWithAction\nEnvelope.prototype.elideRemovingArrayWithAction = function (\n this: Envelope,\n target: DigestProvider[],\n action: ObscureAction,\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, false, action);\n};\n\n/// Implementation of elideRemovingArray\nEnvelope.prototype.elideRemovingArray = function (\n this: Envelope,\n target: DigestProvider[],\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, false, elideAction());\n};\n\n/// Implementation of elideRemovingTargetWithAction\nEnvelope.prototype.elideRemovingTargetWithAction = function (\n this: Envelope,\n target: DigestProvider,\n action: ObscureAction,\n): Envelope {\n return this.elideRemovingArrayWithAction([target], action);\n};\n\n/// Implementation of elideRemovingTarget\nEnvelope.prototype.elideRemovingTarget = function (\n this: Envelope,\n target: DigestProvider,\n): Envelope {\n return this.elideRemovingArray([target]);\n};\n\n/// Implementation of elideRevealingSetWithAction\nEnvelope.prototype.elideRevealingSetWithAction = function (\n this: Envelope,\n target: Set<Digest>,\n action: ObscureAction,\n): Envelope {\n return elideSetWithAction(this, target, true, action);\n};\n\n/// Implementation of elideRevealingSet\nEnvelope.prototype.elideRevealingSet = function (this: Envelope, target: Set<Digest>): Envelope {\n return elideSetWithAction(this, target, true, elideAction());\n};\n\n/// Implementation of elideRevealingArrayWithAction\nEnvelope.prototype.elideRevealingArrayWithAction = function (\n this: Envelope,\n target: DigestProvider[],\n action: ObscureAction,\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, true, action);\n};\n\n/// Implementation of elideRevealingArray\nEnvelope.prototype.elideRevealingArray = function (\n this: Envelope,\n target: DigestProvider[],\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, true, elideAction());\n};\n\n/// Implementation of elideRevealingTargetWithAction\nEnvelope.prototype.elideRevealingTargetWithAction = function (\n this: Envelope,\n target: DigestProvider,\n action: ObscureAction,\n): Envelope {\n return this.elideRevealingArrayWithAction([target], action);\n};\n\n/// Implementation of elideRevealingTarget\nEnvelope.prototype.elideRevealingTarget = function (\n this: Envelope,\n target: DigestProvider,\n): Envelope {\n return this.elideRevealingArray([target]);\n};\n\n/// Implementation of unelide\nEnvelope.prototype.unelide = function (this: Envelope, envelope: Envelope): Envelope {\n if (this.digest().equals(envelope.digest())) {\n return envelope;\n }\n throw EnvelopeError.invalidDigest();\n};\n\n/// Implementation of nodesMatching\nEnvelope.prototype.nodesMatching = function (\n this: Envelope,\n targetDigests: Set<Digest> | undefined,\n obscureTypes: ObscureType[],\n): Set<Digest> {\n const result = new Set<Digest>();\n\n const visitor = (envelope: Envelope): void => {\n // Check if this node matches the target digests\n const digestMatches =\n targetDigests === undefined ||\n Array.from(targetDigests).some((d) => d.equals(envelope.digest()));\n\n if (!digestMatches) {\n return;\n }\n\n // If no obscure types specified, include all nodes\n if (obscureTypes.length === 0) {\n result.add(envelope.digest());\n return;\n }\n\n // Check if this node matches any of the specified obscure types\n const c = envelope.case();\n const typeMatches = obscureTypes.some((obscureType) => {\n if (obscureType === ObscureType.Elided && c.type === \"elided\") {\n return true;\n }\n if (obscureType === ObscureType.Encrypted && c.type === \"encrypted\") {\n return true;\n }\n if (obscureType === ObscureType.Compressed && c.type === \"compressed\") {\n return true;\n }\n return false;\n });\n\n if (typeMatches) {\n result.add(envelope.digest());\n }\n };\n\n // Walk the envelope tree\n walkEnvelope(this, visitor);\n\n return result;\n};\n\n/// Helper to walk envelope tree\nfunction walkEnvelope(envelope: Envelope, visitor: (e: Envelope) => void): void {\n visitor(envelope);\n\n const c = envelope.case();\n if (c.type === \"node\") {\n walkEnvelope(c.subject, visitor);\n for (const assertion of c.assertions) {\n walkEnvelope(assertion, visitor);\n }\n } else if (c.type === \"assertion\") {\n walkEnvelope(c.assertion.predicate(), visitor);\n walkEnvelope(c.assertion.object(), visitor);\n } else if (c.type === \"wrapped\") {\n walkEnvelope(c.envelope, visitor);\n }\n}\n\n/// Implementation of walkUnelide\nEnvelope.prototype.walkUnelide = function (this: Envelope, envelopes: Envelope[]): Envelope {\n // Build a lookup map of digest -> envelope\n const envelopeMap = new Map<string, Envelope>();\n for (const env of envelopes) {\n envelopeMap.set(env.digest().hex(), env);\n }\n\n return walkUnelideWithMap(this, envelopeMap);\n};\n\n/// Helper for walkUnelide with map\nfunction walkUnelideWithMap(envelope: Envelope, envelopeMap: Map<string, Envelope>): Envelope {\n const c = envelope.case();\n\n if (c.type === \"elided\") {\n // Try to find a matching envelope to restore\n const replacement = envelopeMap.get(envelope.digest().hex());\n return replacement ?? envelope;\n }\n\n if (c.type === \"node\") {\n const newSubject = walkUnelideWithMap(c.subject, envelopeMap);\n const newAssertions = c.assertions.map((a) => walkUnelideWithMap(a, envelopeMap));\n\n if (\n newSubject.isIdenticalTo(c.subject) &&\n newAssertions.every((a, i) => a.isIdenticalTo(c.assertions[i]))\n ) {\n return envelope;\n }\n\n return Envelope.newWithUncheckedAssertions(newSubject, newAssertions);\n }\n\n if (c.type === \"wrapped\") {\n const newEnvelope = walkUnelideWithMap(c.envelope, envelopeMap);\n if (newEnvelope.isIdenticalTo(c.envelope)) {\n return envelope;\n }\n return Envelope.newWrapped(newEnvelope);\n }\n\n if (c.type === \"assertion\") {\n const newPredicate = walkUnelideWithMap(c.assertion.predicate(), envelopeMap);\n const newObject = walkUnelideWithMap(c.assertion.object(), envelopeMap);\n\n if (\n newPredicate.isIdenticalTo(c.assertion.predicate()) &&\n newObject.isIdenticalTo(c.assertion.object())\n ) {\n return envelope;\n }\n\n return Envelope.newAssertion(newPredicate, newObject);\n }\n\n return envelope;\n}\n\n/// Implementation of walkReplace\nEnvelope.prototype.walkReplace = function (\n this: Envelope,\n target: Set<Digest>,\n replacement: Envelope,\n): Envelope {\n // Check if this node matches the target\n if (Array.from(target).some((d) => d.equals(this.digest()))) {\n return replacement;\n }\n\n const c = this.case();\n\n if (c.type === \"node\") {\n const newSubject = c.subject.walkReplace(target, replacement);\n const newAssertions = c.assertions.map((a) => a.walkReplace(target, replacement));\n\n if (\n newSubject.isIdenticalTo(c.subject) &&\n newAssertions.every((a, i) => a.isIdenticalTo(c.assertions[i]))\n ) {\n return this;\n }\n\n // Validate that all assertions are either assertions or obscured\n return Envelope.newWithAssertions(newSubject, newAssertions);\n }\n\n if (c.type === \"wrapped\") {\n const newEnvelope = c.envelope.walkReplace(target, replacement);\n if (newEnvelope.isIdenticalTo(c.envelope)) {\n return this;\n }\n return Envelope.newWrapped(newEnvelope);\n }\n\n if (c.type === \"assertion\") {\n const newPredicate = c.assertion.predicate().walkReplace(target, replacement);\n const newObject = c.assertion.object().walkReplace(target, replacement);\n\n if (\n newPredicate.isIdenticalTo(c.assertion.predicate()) &&\n newObject.isIdenticalTo(c.assertion.object())\n ) {\n return this;\n }\n\n return Envelope.newAssertion(newPredicate, newObject);\n }\n\n return this;\n};\n\n/// Implementation of isEquivalentTo\n///\n/// Two envelopes are equivalent if they have the same digest (semantic equivalence).\n/// This is a weaker comparison than `isIdenticalTo` which also checks the case type.\n///\n/// Equivalent to Rust's `is_equivalent_to()` in `src/base/digest.rs`.\nEnvelope.prototype.isEquivalentTo = function (this: Envelope, other: Envelope): boolean {\n return this.digest().equals(other.digest());\n};\n\n/// Implementation of isIdenticalTo\nEnvelope.prototype.isIdenticalTo = function (this: Envelope, other: Envelope): boolean {\n // Two envelopes are identical if they have the same digest\n // and the same case type (to handle wrapped vs unwrapped with same content)\n return this.digest().equals(other.digest()) && this.case().type === other.case().type;\n};\n","import { Envelope } from \"./envelope\";\nimport type { Digest } from \"./digest\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\n\n/// Functions for traversing and manipulating the envelope hierarchy.\n///\n/// This module provides functionality for traversing the hierarchical structure\n/// of envelopes, allowing for operations such as inspection, transformation,\n/// and extraction of specific elements. It implements a visitor pattern that\n/// enables executing arbitrary code on each element of an envelope in a\n/// structured way.\n///\n/// The traversal can be performed in two modes:\n/// - Structure-based traversal: Visits every element in the envelope hierarchy\n/// - Tree-based traversal: Skips node elements and focuses on the semantic\n/// content\n\n/// The type of incoming edge provided to the visitor.\n///\n/// This enum identifies how an envelope element is connected to its parent in\n/// the hierarchy during traversal. It helps the visitor function understand the\n/// semantic relationship between elements.\nexport enum EdgeType {\n /// No incoming edge (root)\n None = \"none\",\n /// Element is the subject of a node\n Subject = \"subject\",\n /// Element is an assertion on a node\n Assertion = \"assertion\",\n /// Element is the predicate of an assertion\n Predicate = \"predicate\",\n /// Element is the object of an assertion\n Object = \"object\",\n /// Element is the content wrapped by another envelope\n Content = \"content\",\n}\n\n/// Returns a short text label for the edge type, or undefined if no label is\n/// needed.\n///\n/// This is primarily used for tree formatting to identify relationships\n/// between elements.\n///\n/// @param edgeType - The edge type\n/// @returns A short label or undefined\nexport function edgeLabel(edgeType: EdgeType): string | undefined {\n switch (edgeType) {\n case EdgeType.Subject:\n return \"subj\";\n case EdgeType.Content:\n return \"cont\";\n case EdgeType.Predicate:\n return \"pred\";\n case EdgeType.Object:\n return \"obj\";\n case EdgeType.None:\n case EdgeType.Assertion:\n return undefined;\n default:\n return undefined;\n }\n}\n\n/// A visitor function that is called for each element in the envelope.\n///\n/// The visitor function takes the following parameters:\n/// - `envelope`: The current envelope element being visited\n/// - `level`: The depth level in the hierarchy (0 for root)\n/// - `incomingEdge`: The type of edge connecting this element to its parent\n/// - `state`: Optional context passed down from the parent's visitor call\n///\n/// The visitor returns a tuple of:\n/// - The state that will be passed to child elements\n/// - A boolean indicating whether to stop traversal (true = stop)\n///\n/// This enables accumulating state or passing context during traversal.\nexport type Visitor<State> = (\n envelope: Envelope,\n level: number,\n incomingEdge: EdgeType,\n state: State,\n) => [State, boolean];\n\n/// Implementation of walk()\nEnvelope.prototype.walk = function <State>(\n this: Envelope,\n hideNodes: boolean,\n state: State,\n visit: Visitor<State>,\n): void {\n if (hideNodes) {\n walkTree(this, 0, EdgeType.None, state, visit);\n } else {\n walkStructure(this, 0, EdgeType.None, state, visit);\n }\n};\n\n/// Recursive implementation of structure-based traversal.\n///\n/// This internal function performs the actual recursive traversal of the\n/// envelope structure, visiting every element and maintaining the\n/// correct level and edge relationships.\nfunction walkStructure<State>(\n envelope: Envelope,\n level: number,\n incomingEdge: EdgeType,\n state: State,\n visit: Visitor<State>,\n): void {\n // Visit this envelope\n const [newState, stop] = visit(envelope, level, incomingEdge, state);\n if (stop) {\n return;\n }\n\n const nextLevel = level + 1;\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\":\n // Visit subject\n walkStructure(c.subject, nextLevel, EdgeType.Subject, newState, visit);\n // Visit all assertions\n for (const assertion of c.assertions) {\n walkStructure(assertion, nextLevel, EdgeType.Assertion, newState, visit);\n }\n break;\n\n case \"wrapped\":\n // Visit wrapped envelope\n walkStructure(c.envelope, nextLevel, EdgeType.Content, newState, visit);\n break;\n\n case \"assertion\":\n // Visit predicate and object\n walkStructure(c.assertion.predicate(), nextLevel, EdgeType.Predicate, newState, visit);\n walkStructure(c.assertion.object(), nextLevel, EdgeType.Object, newState, visit);\n break;\n\n case \"leaf\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n // Leaf nodes and other types have no children\n break;\n }\n}\n\n/// Recursive implementation of tree-based traversal.\n///\n/// This internal function performs the actual recursive traversal of the\n/// envelope's semantic tree, skipping node containers and focusing on\n/// the semantic content elements. It maintains the correct level and\n/// edge relationships while skipping structural elements.\nfunction walkTree<State>(\n envelope: Envelope,\n level: number,\n incomingEdge: EdgeType,\n state: State,\n visit: Visitor<State>,\n): State {\n let currentState = state;\n let subjectLevel = level;\n\n // Skip visiting if this is a node\n if (!envelope.isNode()) {\n const [newState, stop] = visit(envelope, level, incomingEdge, currentState);\n if (stop) {\n return newState;\n }\n currentState = newState;\n subjectLevel = level + 1;\n }\n\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\": {\n // Visit subject\n const assertionState = walkTree(\n c.subject,\n subjectLevel,\n EdgeType.Subject,\n currentState,\n visit,\n );\n // Visit all assertions\n const assertionLevel = subjectLevel + 1;\n for (const assertion of c.assertions) {\n walkTree(assertion, assertionLevel, EdgeType.Assertion, assertionState, visit);\n }\n break;\n }\n\n case \"wrapped\":\n // Visit wrapped envelope\n walkTree(c.envelope, subjectLevel, EdgeType.Content, currentState, visit);\n break;\n\n case \"assertion\":\n // Visit predicate and object\n walkTree(c.assertion.predicate(), subjectLevel, EdgeType.Predicate, currentState, visit);\n walkTree(c.assertion.object(), subjectLevel, EdgeType.Object, currentState, visit);\n break;\n\n case \"leaf\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n // Leaf nodes and other types have no children\n break;\n }\n\n return currentState;\n}\n\n// ============================================================================\n// Digest collection methods\n// ============================================================================\n\n/// Implementation of digests()\n/// Returns the set of digests in the envelope, down to the specified level.\nEnvelope.prototype.digests = function (this: Envelope, levelLimit: number): Set<Digest> {\n const result = new Set<Digest>();\n\n const visitor = (\n envelope: Envelope,\n level: number,\n _incomingEdge: EdgeType,\n _state: undefined,\n ): [undefined, boolean] => {\n if (level < levelLimit) {\n result.add(envelope.digest());\n result.add(envelope.subject().digest());\n }\n return [undefined, false]; // Continue walking\n };\n\n this.walk(false, undefined, visitor);\n return result;\n};\n\n/// Implementation of deepDigests()\n/// Returns all digests in the envelope at all levels.\nEnvelope.prototype.deepDigests = function (this: Envelope): Set<Digest> {\n return this.digests(Number.MAX_SAFE_INTEGER);\n};\n\n/// Implementation of shallowDigests()\n/// Returns the digests in the envelope down to its second level.\nEnvelope.prototype.shallowDigests = function (this: Envelope): Set<Digest> {\n return this.digests(2);\n};\n\n// ============================================================================\n// Alias methods for Rust API compatibility\n// ============================================================================\n\n/// Implementation of object() - alias for tryObject()\nEnvelope.prototype.object = function (this: Envelope): Envelope {\n return this.tryObject();\n};\n\n/// Implementation of predicate() - alias for tryPredicate()\nEnvelope.prototype.predicate = function (this: Envelope): Envelope {\n return this.tryPredicate();\n};\n\n// ============================================================================\n// CBOR helper methods\n// ============================================================================\n\n/// Implementation of toCbor() - alias for taggedCbor()\nEnvelope.prototype.toCbor = function (this: Envelope): unknown {\n return this.taggedCbor();\n};\n\n/// Implementation of expectLeaf() - returns the leaf CBOR value or throws\nEnvelope.prototype.expectLeaf = function (this: Envelope): unknown {\n return this.tryLeaf();\n};\n\n/// Implementation of checkTypeValue() - validates the envelope has a specific type\nEnvelope.prototype.checkTypeValue = function (this: Envelope, type: unknown): void {\n this.checkType(type as EnvelopeEncodableValue);\n};\n","import { Envelope } from \"./envelope\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { EnvelopeError } from \"./error\";\n\n/// Support for adding assertions.\n///\n/// Assertions are predicate-object pairs that make statements about an\n/// envelope's subject. This implementation provides methods for adding various\n/// types of assertions to envelopes.\n///\n/// These methods extend the Envelope class to provide a rich API for\n/// working with assertions, matching the Rust bc-envelope implementation.\n\n/// Implementation of addAssertionEnvelopes\nEnvelope.prototype.addAssertionEnvelopes = function (\n this: Envelope,\n assertions: Envelope[],\n): Envelope {\n return assertions.reduce((result, assertion) => result.addAssertionEnvelope(assertion), this);\n};\n\n/// Implementation of addOptionalAssertionEnvelope\nEnvelope.prototype.addOptionalAssertionEnvelope = function (\n this: Envelope,\n assertion: Envelope | undefined,\n): Envelope {\n if (assertion === undefined) {\n return this;\n }\n\n // Validate that the assertion is a valid assertion or obscured envelope\n if (!assertion.isSubjectAssertion() && !assertion.isSubjectObscured()) {\n throw EnvelopeError.invalidFormat();\n }\n\n const c = this.case();\n\n // Check if this is already a node\n if (c.type === \"node\") {\n // Check for duplicate assertions\n const isDuplicate = c.assertions.some((a) => a.digest().equals(assertion.digest()));\n if (isDuplicate) {\n return this;\n }\n\n // Add the new assertion\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, assertion]);\n }\n\n // Otherwise, create a new node with this envelope as subject\n return Envelope.newWithUncheckedAssertions(this.subject(), [assertion]);\n};\n\n/// Implementation of addOptionalAssertion\nEnvelope.prototype.addOptionalAssertion = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue | undefined,\n): Envelope {\n if (object === undefined || object === null) {\n return this;\n }\n return this.addAssertion(predicate, object);\n};\n\n/// Implementation of addNonemptyStringAssertion\nEnvelope.prototype.addNonemptyStringAssertion = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n str: string,\n): Envelope {\n if (str.length === 0) {\n return this;\n }\n return this.addAssertion(predicate, str);\n};\n\n/// Implementation of addAssertions\nEnvelope.prototype.addAssertions = function (this: Envelope, envelopes: Envelope[]): Envelope {\n return envelopes.reduce((result, envelope) => result.addAssertionEnvelope(envelope), this);\n};\n\n/// Implementation of addAssertionIf\nEnvelope.prototype.addAssertionIf = function (\n this: Envelope,\n condition: boolean,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n): Envelope {\n if (condition) {\n return this.addAssertion(predicate, object);\n }\n return this;\n};\n\n/// Implementation of addAssertionEnvelopeIf\nEnvelope.prototype.addAssertionEnvelopeIf = function (\n this: Envelope,\n condition: boolean,\n assertionEnvelope: Envelope,\n): Envelope {\n if (condition) {\n return this.addAssertionEnvelope(assertionEnvelope);\n }\n return this;\n};\n\n/// Implementation of removeAssertion\nEnvelope.prototype.removeAssertion = function (this: Envelope, target: Envelope): Envelope {\n const assertions = this.assertions();\n const targetDigest = target.digest();\n\n const index = assertions.findIndex((a) => a.digest().equals(targetDigest));\n\n if (index === -1) {\n // Assertion not found, return unchanged\n return this;\n }\n\n // Remove the assertion\n const newAssertions = [...assertions.slice(0, index), ...assertions.slice(index + 1)];\n\n if (newAssertions.length === 0) {\n // No assertions left, return just the subject\n return this.subject();\n }\n\n // Return envelope with remaining assertions\n return Envelope.newWithUncheckedAssertions(this.subject(), newAssertions);\n};\n\n/// Implementation of replaceAssertion\nEnvelope.prototype.replaceAssertion = function (\n this: Envelope,\n assertion: Envelope,\n newAssertion: Envelope,\n): Envelope {\n return this.removeAssertion(assertion).addAssertionEnvelope(newAssertion);\n};\n\n/// Implementation of replaceSubject\nEnvelope.prototype.replaceSubject = function (this: Envelope, subject: Envelope): Envelope {\n return this.assertions().reduce((e, a) => e.addAssertionEnvelope(a), subject);\n};\n\n/// Implementation of assertions\nEnvelope.prototype.assertions = function (this: Envelope): Envelope[] {\n const c = this.case();\n if (c.type === \"node\") {\n return c.assertions;\n }\n return [];\n};\n\n// Note: addAssertionSalted, addAssertionEnvelopeSalted, and addOptionalAssertionEnvelopeSalted\n// are implemented in extension/salt.ts to keep all salt-related functionality together.\n","import type { Cbor } from \"@bcts/dcbor\";\nimport { isNumber, isNaN, asArray, asMap, asText } from \"@bcts/dcbor\";\nimport type { KnownValue } from \"@bcts/known-values\";\nimport { UNIT } from \"@bcts/known-values\";\nimport { Envelope } from \"./envelope\";\nimport { EnvelopeError } from \"./error\";\n\n/// Provides methods for working with envelope leaf nodes,\n/// which are dCBOR values of any kind.\n///\n/// This module extends the Envelope class with convenience methods for\n/// working with leaf values, including type checking and extraction.\n\n// Note: Static methods Envelope.false() and Envelope.true() are implemented below\n// but cannot be declared in TypeScript module augmentation due to reserved keywords.\n\n/// Implementation of static false()\n(Envelope as unknown as { false: () => Envelope }).false = function (): Envelope {\n return Envelope.newLeaf(false);\n};\n\n/// Implementation of static true()\n(Envelope as unknown as { true: () => Envelope }).true = function (): Envelope {\n return Envelope.newLeaf(true);\n};\n\n/// Implementation of isFalse()\nEnvelope.prototype.isFalse = function (this: Envelope): boolean {\n try {\n return this.extractBoolean() === false;\n } catch {\n return false;\n }\n};\n\n/// Implementation of isTrue()\nEnvelope.prototype.isTrue = function (this: Envelope): boolean {\n try {\n return this.extractBoolean() === true;\n } catch {\n return false;\n }\n};\n\n/// Implementation of isBool()\nEnvelope.prototype.isBool = function (this: Envelope): boolean {\n try {\n const value = this.extractBoolean();\n return typeof value === \"boolean\";\n } catch {\n return false;\n }\n};\n\n/// Implementation of isNumber()\nEnvelope.prototype.isNumber = function (this: Envelope): boolean {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return false;\n }\n\n return isNumber(leaf);\n};\n\n/// Implementation of isSubjectNumber()\nEnvelope.prototype.isSubjectNumber = function (this: Envelope): boolean {\n return this.subject().isNumber();\n};\n\n/// Implementation of isNaN()\nEnvelope.prototype.isNaN = function (this: Envelope): boolean {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return false;\n }\n\n // Check for NaN in CBOR simple types\n if (\"type\" in leaf && leaf.type === 7) {\n return isNaN(leaf as unknown as Parameters<typeof isNaN>[0]);\n }\n return false;\n};\n\n/// Implementation of isSubjectNaN()\nEnvelope.prototype.isSubjectNaN = function (this: Envelope): boolean {\n return this.subject().isNaN();\n};\n\n/// Implementation of isNull()\nEnvelope.prototype.isNull = function (this: Envelope): boolean {\n try {\n this.extractNull();\n return true;\n } catch (_error) {\n return false;\n }\n};\n\n/// Implementation of tryByteString()\nEnvelope.prototype.tryByteString = function (this: Envelope): Uint8Array {\n return this.extractBytes();\n};\n\n/// Implementation of asByteString()\nEnvelope.prototype.asByteString = function (this: Envelope): Uint8Array | undefined {\n try {\n return this.extractBytes();\n } catch {\n return undefined;\n }\n};\n\n/// Implementation of asArray()\nEnvelope.prototype.asArray = function (this: Envelope): readonly Cbor[] | undefined {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return undefined;\n }\n\n return asArray(leaf);\n};\n\n/// Implementation of asMap()\nEnvelope.prototype.asMap = function (this: Envelope) {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return undefined;\n }\n\n return asMap(leaf);\n};\n\n/// Implementation of asText()\nEnvelope.prototype.asText = function (this: Envelope): string | undefined {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return undefined;\n }\n\n return asText(leaf);\n};\n\n/// Implementation of asLeaf()\nEnvelope.prototype.asLeaf = function (this: Envelope): Cbor | undefined {\n const c = this.case();\n if (c.type === \"leaf\") {\n return c.cbor;\n }\n return undefined;\n};\n\n// ============================================================================\n// Known Value Methods\n// ============================================================================\n\n/// Implementation of static unit()\n/// Unit envelopes have the known value ''. They represent a position\n/// where no meaningful data *can* exist. In this sense they make a\n/// semantically stronger assertion than `null`, which represents a\n/// position where no meaningful data currently exists, but could exist in\n/// the future.\n(Envelope as unknown as { unit: () => Envelope }).unit = function (): Envelope {\n return Envelope.new(UNIT);\n};\n\n/// Implementation of asKnownValue()\nEnvelope.prototype.asKnownValue = function (this: Envelope): KnownValue | undefined {\n const c = this.case();\n if (c.type === \"knownValue\") {\n return c.value;\n }\n return undefined;\n};\n\n/// Implementation of tryKnownValue()\nEnvelope.prototype.tryKnownValue = function (this: Envelope): KnownValue {\n const kv = this.asKnownValue();\n if (kv === undefined) {\n throw EnvelopeError.notKnownValue();\n }\n return kv;\n};\n\n/// Implementation of isKnownValue()\nEnvelope.prototype.isKnownValue = function (this: Envelope): boolean {\n return this.case().type === \"knownValue\";\n};\n\n/// Implementation of isSubjectUnit()\nEnvelope.prototype.isSubjectUnit = function (this: Envelope): boolean {\n const kv = this.subject().asKnownValue();\n if (kv === undefined) {\n return false;\n }\n return kv.equals(UNIT);\n};\n\n/// Implementation of checkSubjectUnit()\nEnvelope.prototype.checkSubjectUnit = function (this: Envelope): Envelope {\n if (this.isSubjectUnit()) {\n return this;\n }\n throw EnvelopeError.subjectNotUnit();\n};\n","// Cbor type available if needed later\nimport { Envelope } from \"./envelope\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { EnvelopeError } from \"./error\";\nimport { POSITION } from \"@bcts/known-values\";\n\n/// Provides methods for querying envelope structure and extracting data.\n///\n/// The `queries` module contains methods for:\n///\n/// 1. **Structural queries**: Methods for examining the envelope's structure\n/// (`subject()`, `assertions()`)\n/// 2. **Type queries**: Methods for determining the envelope's type\n/// (`isLeaf()`, `isNode()`, etc.)\n/// 3. **Content extraction**: Methods for extracting typed content from\n/// envelopes (`extractSubject()`, `extractObjectForPredicate()`)\n/// 4. **Assertion queries**: Methods for finding assertions with specific\n/// predicates (`assertionWithPredicate()`)\n///\n/// These methods enable traversal and inspection of envelope hierarchies,\n/// allowing for flexible manipulation and access to envelope data structures.\n\n/// Implementation of hasAssertions()\nEnvelope.prototype.hasAssertions = function (this: Envelope): boolean {\n const c = this.case();\n return c.type === \"node\" && c.assertions.length > 0;\n};\n\n/// Implementation of asAssertion()\nEnvelope.prototype.asAssertion = function (this: Envelope): Envelope | undefined {\n const c = this.case();\n return c.type === \"assertion\" ? this : undefined;\n};\n\n/// Implementation of tryAssertion()\nEnvelope.prototype.tryAssertion = function (this: Envelope): Envelope {\n const result = this.asAssertion();\n if (result === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return result;\n};\n\n/// Implementation of asPredicate()\nEnvelope.prototype.asPredicate = function (this: Envelope): Envelope | undefined {\n // Refer to subject in case the assertion is a node and therefore has\n // its own assertions\n const subj = this.subject();\n const c = subj.case();\n if (c.type === \"assertion\") {\n return c.assertion.predicate();\n }\n return undefined;\n};\n\n/// Implementation of tryPredicate()\nEnvelope.prototype.tryPredicate = function (this: Envelope): Envelope {\n const result = this.asPredicate();\n if (result === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return result;\n};\n\n/// Implementation of asObject()\nEnvelope.prototype.asObject = function (this: Envelope): Envelope | undefined {\n // Refer to subject in case the assertion is a node and therefore has\n // its own assertions\n const subj = this.subject();\n const c = subj.case();\n if (c.type === \"assertion\") {\n return c.assertion.object();\n }\n return undefined;\n};\n\n/// Implementation of tryObject()\nEnvelope.prototype.tryObject = function (this: Envelope): Envelope {\n const result = this.asObject();\n if (result === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return result;\n};\n\n/// Implementation of isAssertion()\nEnvelope.prototype.isAssertion = function (this: Envelope): boolean {\n return this.case().type === \"assertion\";\n};\n\n/// Implementation of isElided()\nEnvelope.prototype.isElided = function (this: Envelope): boolean {\n return this.case().type === \"elided\";\n};\n\n/// Implementation of isLeaf()\nEnvelope.prototype.isLeaf = function (this: Envelope): boolean {\n return this.case().type === \"leaf\";\n};\n\n/// Implementation of isNode()\nEnvelope.prototype.isNode = function (this: Envelope): boolean {\n return this.case().type === \"node\";\n};\n\n/// Implementation of isWrapped()\nEnvelope.prototype.isWrapped = function (this: Envelope): boolean {\n return this.case().type === \"wrapped\";\n};\n\n/// Implementation of isInternal()\nEnvelope.prototype.isInternal = function (this: Envelope): boolean {\n const type = this.case().type;\n return type === \"node\" || type === \"wrapped\" || type === \"assertion\";\n};\n\n/// Implementation of isObscured()\nEnvelope.prototype.isObscured = function (this: Envelope): boolean {\n const type = this.case().type;\n return type === \"elided\" || type === \"encrypted\" || type === \"compressed\";\n};\n\n/// Implementation of assertionsWithPredicate()\nEnvelope.prototype.assertionsWithPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope[] {\n const predicateEnv = Envelope.new(predicate);\n const predicateDigest = predicateEnv.digest();\n\n return this.assertions().filter((assertion) => {\n const pred = assertion.subject().asPredicate();\n return pred?.digest().equals(predicateDigest) === true;\n });\n};\n\n/// Implementation of assertionWithPredicate()\nEnvelope.prototype.assertionWithPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope {\n const matches = this.assertionsWithPredicate(predicate);\n\n if (matches.length === 0) {\n throw EnvelopeError.nonexistentPredicate();\n }\n if (matches.length > 1) {\n throw EnvelopeError.ambiguousPredicate();\n }\n\n return matches[0];\n};\n\n/// Implementation of optionalAssertionWithPredicate()\nEnvelope.prototype.optionalAssertionWithPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope | undefined {\n const matches = this.assertionsWithPredicate(predicate);\n\n if (matches.length === 0) {\n return undefined;\n }\n if (matches.length > 1) {\n throw EnvelopeError.ambiguousPredicate();\n }\n\n return matches[0];\n};\n\n/// Implementation of objectForPredicate()\nEnvelope.prototype.objectForPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope {\n const assertion = this.assertionWithPredicate(predicate);\n const obj = assertion.asObject();\n if (obj === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return obj;\n};\n\n/// Implementation of optionalObjectForPredicate()\nEnvelope.prototype.optionalObjectForPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope | undefined {\n const matches = this.assertionsWithPredicate(predicate);\n\n if (matches.length === 0) {\n return undefined;\n }\n if (matches.length > 1) {\n throw EnvelopeError.ambiguousPredicate();\n }\n\n const obj = matches[0].subject().asObject();\n return obj;\n};\n\n/// Implementation of objectsForPredicate()\nEnvelope.prototype.objectsForPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope[] {\n return this.assertionsWithPredicate(predicate).map((assertion) => {\n const obj = assertion.asObject();\n if (obj === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return obj;\n });\n};\n\n/// Implementation of elementsCount()\nEnvelope.prototype.elementsCount = function (this: Envelope): number {\n let count = 1; // Count this envelope\n\n const c = this.case();\n switch (c.type) {\n case \"node\":\n count += c.subject.elementsCount();\n for (const assertion of c.assertions) {\n count += assertion.elementsCount();\n }\n break;\n case \"assertion\":\n count += c.assertion.predicate().elementsCount();\n count += c.assertion.object().elementsCount();\n break;\n case \"wrapped\":\n count += c.envelope.elementsCount();\n break;\n case \"leaf\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n // These cases don't contribute additional elements\n break;\n }\n\n return count;\n};\n\n// ============================================================================\n// Subject State Queries\n// ============================================================================\n\n/// Implementation of isSubjectEncrypted()\nEnvelope.prototype.isSubjectEncrypted = function (this: Envelope): boolean {\n const c = this.case();\n if (c.type === \"encrypted\") {\n return true;\n }\n if (c.type === \"node\") {\n return c.subject.isSubjectEncrypted();\n }\n return false;\n};\n\n/// Implementation of isSubjectCompressed()\nEnvelope.prototype.isSubjectCompressed = function (this: Envelope): boolean {\n const c = this.case();\n if (c.type === \"compressed\") {\n return true;\n }\n if (c.type === \"node\") {\n return c.subject.isSubjectCompressed();\n }\n return false;\n};\n\n/// Implementation of isSubjectElided()\nEnvelope.prototype.isSubjectElided = function (this: Envelope): boolean {\n const c = this.case();\n if (c.type === \"elided\") {\n return true;\n }\n if (c.type === \"node\") {\n return c.subject.isSubjectElided();\n }\n return false;\n};\n\n// ============================================================================\n// Position Management\n// ============================================================================\n\n/// Implementation of setPosition()\nEnvelope.prototype.setPosition = function (this: Envelope, position: number): Envelope {\n // Find all POSITION assertions\n const positionAssertions = this.assertionsWithPredicate(POSITION);\n\n // If there is more than one POSITION assertion, throw an error\n if (positionAssertions.length > 1) {\n throw EnvelopeError.invalidFormat();\n }\n\n // If there is a single POSITION assertion, remove it and add the new position\n // Otherwise, just add the new position to this envelope\n const baseEnvelope =\n positionAssertions.length === 1 ? this.removeAssertion(positionAssertions[0]) : this;\n\n // Add a new POSITION assertion with the given position\n return baseEnvelope.addAssertion(POSITION, position);\n};\n\n/// Implementation of position()\nEnvelope.prototype.position = function (this: Envelope): number {\n // Find the POSITION assertion in the envelope\n const positionEnvelope = this.objectForPredicate(POSITION);\n\n // Extract the position value\n const positionValue = positionEnvelope.extractNumber();\n return positionValue;\n};\n\n/// Implementation of removePosition()\nEnvelope.prototype.removePosition = function (this: Envelope): Envelope {\n // Find all POSITION assertions\n const positionAssertions = this.assertionsWithPredicate(POSITION);\n\n // If there is more than one POSITION assertion, throw an error\n if (positionAssertions.length > 1) {\n throw EnvelopeError.invalidFormat();\n }\n\n // If there is a single POSITION assertion, remove it\n if (positionAssertions.length === 1) {\n return this.removeAssertion(positionAssertions[0]);\n }\n\n // No POSITION assertion, return unchanged\n return this;\n};\n","import { Envelope } from \"./envelope\";\nimport { EnvelopeError } from \"./error\";\n\n/// Support for wrapping and unwrapping envelopes.\n///\n/// Wrapping allows treating an envelope (including its assertions) as a single\n/// unit, making it possible to add assertions about the envelope as a whole.\n\n/// Implementation of wrap()\nEnvelope.prototype.wrap = function (this: Envelope): Envelope {\n return Envelope.newWrapped(this);\n};\n\n/// Implementation of tryUnwrap()\nEnvelope.prototype.tryUnwrap = function (this: Envelope): Envelope {\n const c = this.subject().case();\n if (c.type === \"wrapped\") {\n return c.envelope;\n }\n throw EnvelopeError.notWrapped();\n};\n\n/// Implementation of unwrap() - alias for tryUnwrap()\nEnvelope.prototype.unwrap = function (this: Envelope): Envelope {\n return this.tryUnwrap();\n};\n","/// UR (Uniform Resource) support for Gordian Envelope.\n///\n/// This module adds urString() and fromUrString() methods to the Envelope class,\n/// enabling serialization to and from UR format as specified in BCR-2020-005.\n\nimport { UR } from \"@bcts/uniform-resources\";\nimport { Envelope } from \"./envelope\";\n\n// ============================================================================\n// Envelope Prototype Extensions for UR Support\n// ============================================================================\n\n/// Implementation of urString\nEnvelope.prototype.urString = function (this: Envelope): string {\n // Use untaggedCbor() per Rust implementation - the UR type \"envelope\" implies the tag\n const ur = UR.new(\"envelope\", this.untaggedCbor());\n return ur.string();\n};\n\n/// Implementation of ur\nEnvelope.prototype.ur = function (this: Envelope): UR {\n // Use untaggedCbor() per Rust implementation - the UR type \"envelope\" implies the tag\n return UR.new(\"envelope\", this.untaggedCbor());\n};\n\n/// Implementation of taggedCborData (alias for cborBytes)\nEnvelope.prototype.taggedCborData = function (this: Envelope): Uint8Array {\n return this.cborBytes();\n};\n\n/// Implementation of fromUrString\nEnvelope.fromUrString = function (urString: string): Envelope {\n const ur = UR.fromURString(urString);\n return Envelope.fromUR(ur);\n};\n\n/// Implementation of fromURString (alias)\nEnvelope.fromURString = Envelope.fromUrString;\n\n/// Implementation of fromUR\nEnvelope.fromUR = function (ur: UR): Envelope {\n ur.checkType(\"envelope\");\n // Use fromUntaggedCbor() per Rust implementation - the UR type \"envelope\" implies the tag\n return Envelope.fromUntaggedCbor(ur.cbor());\n};\n","import { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\nimport { IS_A } from \"@bcts/known-values\";\n\n/// Type system for Gordian Envelopes.\n///\n/// This module provides functionality for adding, querying, and verifying types\n/// within envelopes. In Gordian Envelope, types are implemented using the\n/// special `'isA'` KnownValue predicate (value 1), which is semantically\n/// equivalent to the RDF `rdf:type` concept.\n///\n/// Type information enables:\n/// - Semantic classification of envelopes\n/// - Type verification before processing content\n/// - Conversion between domain objects and envelopes\n/// - Schema validation\n///\n/// ## Type Representation\n///\n/// Types are represented as assertions with the `'isA'` predicate and an object\n/// that specifies the type. The type object is typically a string or an envelope.\n///\n/// ## Usage Patterns\n///\n/// The type system is commonly used in two ways:\n///\n/// 1. **Type Tagging**: Adding type information to envelopes to indicate their\n/// semantic meaning\n///\n/// ```typescript\n/// // Create an envelope representing a person\n/// const person = Envelope.new(\"Alice\")\n/// .addType(\"Person\")\n/// .addAssertion(\"age\", 30);\n/// ```\n///\n/// 2. **Type Checking**: Verifying that an envelope has the expected type\n/// before processing\n///\n/// ```typescript\n/// function processPerson(envelope: Envelope): void {\n/// // Verify this is a person before processing\n/// envelope.checkType(\"Person\");\n///\n/// // Now we can safely extract person-specific information\n/// const name = envelope.subject().extractString();\n/// const age = envelope.objectForPredicate(\"age\").extractNumber();\n///\n/// console.log(`${name} is ${age} years old`);\n/// }\n/// ```\n\n/// Implementation of addType()\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.addType = function (this: Envelope, object: EnvelopeEncodableValue): Envelope {\n return this.addAssertion(IS_A, object);\n };\n\n /// Implementation of types()\n Envelope.prototype.types = function (this: Envelope): Envelope[] {\n return this.objectsForPredicate(IS_A);\n };\n\n /// Implementation of getType()\n Envelope.prototype.getType = function (this: Envelope): Envelope {\n const t = this.types();\n if (t.length === 0) {\n throw EnvelopeError.invalidType();\n }\n if (t.length === 1) {\n return t[0];\n }\n throw EnvelopeError.ambiguousType();\n };\n\n /// Implementation of hasType()\n Envelope.prototype.hasType = function (this: Envelope, t: EnvelopeEncodableValue): boolean {\n const e = Envelope.new(t);\n return this.types().some((x) => x.digest().equals(e.digest()));\n };\n\n /// Implementation of checkType()\n Envelope.prototype.checkType = function (this: Envelope, t: EnvelopeEncodableValue): void {\n if (!this.hasType(t)) {\n throw EnvelopeError.invalidType();\n }\n };\n}\n","import { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport type { EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport {\n SecureRandomNumberGenerator,\n rngRandomData,\n rngNextInClosedRangeI32,\n type RandomNumberGenerator,\n} from \"@bcts/rand\";\nimport { SALT as SALT_KV } from \"@bcts/known-values\";\nimport { Salt as SaltComponent } from \"@bcts/components\";\n\n/// Extension for adding salt to envelopes to prevent correlation.\n///\n/// This module provides functionality for decorrelating envelopes by adding\n/// random salt. Salt is added as an assertion with the predicate 'salt' and\n/// a random value. When an envelope is elided, this salt ensures that the\n/// digest of the elided envelope cannot be correlated with other elided\n/// envelopes containing the same information.\n///\n/// Decorrelation is an important privacy feature that prevents third parties\n/// from determining whether two elided envelopes originally contained the same\n/// information by comparing their digests.\n///\n/// Based on bc-envelope-rust/src/extension/salt.rs and bc-components-rust/src/salt.rs\n///\n/// @example\n/// ```typescript\n/// // Create a simple envelope\n/// const envelope = Envelope.new(\"Hello\");\n///\n/// // Create a decorrelated version by adding salt\n/// const salted = envelope.addSalt();\n///\n/// // The salted envelope has a different digest than the original\n/// console.log(envelope.digest().equals(salted.digest())); // false\n/// ```\n\n// ============================================================================\n// Envelope Prototype Extensions for Salted Assertions\n// ============================================================================\n\n/// The standard predicate for salt assertions (KnownValue matching Rust)\nexport const SALT = SALT_KV;\n\n/// Minimum salt size in bytes (64 bits)\nconst MIN_SALT_SIZE = 8;\n\n/// Creates a new SecureRandomNumberGenerator instance\nfunction createSecureRng(): RandomNumberGenerator {\n return new SecureRandomNumberGenerator();\n}\n\n/// Generates random bytes using the rand package\nfunction generateRandomBytes(length: number, rng?: RandomNumberGenerator): Uint8Array {\n const actualRng = rng ?? createSecureRng();\n return rngRandomData(actualRng, length);\n}\n\n/// Calculates salt size proportional to envelope size\n/// This matches the Rust implementation in bc-components-rust/src/salt.rs\nfunction calculateProportionalSaltSize(envelopeSize: number, rng?: RandomNumberGenerator): number {\n const actualRng = rng ?? createSecureRng();\n const count = envelopeSize;\n const minSize = Math.max(8, Math.ceil(count * 0.05));\n const maxSize = Math.max(minSize + 8, Math.ceil(count * 0.25));\n return rngNextInClosedRangeI32(actualRng, minSize, maxSize);\n}\n\n/// Implementation of addSalt()\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.addSalt = function (this: Envelope): Envelope {\n const rng = createSecureRng();\n const envelopeSize = this.cborBytes().length;\n const saltSize = calculateProportionalSaltSize(envelopeSize, rng);\n const saltBytes = generateRandomBytes(saltSize, rng);\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Implementation of addSaltWithLength()\n Envelope.prototype.addSaltWithLength = function (this: Envelope, count: number): Envelope {\n if (count < MIN_SALT_SIZE) {\n throw EnvelopeError.general(`Salt must be at least ${MIN_SALT_SIZE} bytes, got ${count}`);\n }\n const saltBytes = generateRandomBytes(count);\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Alias for addSaltWithLength (Rust API compatibility)\n Envelope.prototype.addSaltWithLen = Envelope.prototype.addSaltWithLength;\n\n /// Implementation of addSaltBytes()\n Envelope.prototype.addSaltBytes = function (this: Envelope, saltBytes: Uint8Array): Envelope {\n if (saltBytes.length < MIN_SALT_SIZE) {\n throw EnvelopeError.general(\n `Salt must be at least ${MIN_SALT_SIZE} bytes, got ${saltBytes.length}`,\n );\n }\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Implementation of addSaltInRange()\n Envelope.prototype.addSaltInRange = function (\n this: Envelope,\n min: number,\n max: number,\n ): Envelope {\n if (min < MIN_SALT_SIZE) {\n throw EnvelopeError.general(\n `Minimum salt size must be at least ${MIN_SALT_SIZE} bytes, got ${min}`,\n );\n }\n if (max < min) {\n throw EnvelopeError.general(\n `Maximum salt size must be at least minimum, got min=${min} max=${max}`,\n );\n }\n const rng = createSecureRng();\n const saltSize = rngNextInClosedRangeI32(rng, min, max);\n const saltBytes = generateRandomBytes(saltSize, rng);\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Implementation of addAssertionSalted()\n Envelope.prototype.addAssertionSalted = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n salted: boolean,\n ): Envelope {\n // Create the assertion envelope\n const assertion = Envelope.newAssertion(predicate, object);\n\n // If not salted, use the normal addAssertionEnvelope\n if (!salted) {\n return this.addAssertionEnvelope(assertion);\n }\n\n // Add salt to the assertion envelope (this creates a node with assertion as subject)\n const saltedAssertion = assertion.addSalt();\n\n // When salted, we need to use newWithUncheckedAssertions because the salted\n // assertion is a node (not pure assertion type) and would fail normal validation\n const c = this.case();\n if (c.type === \"node\") {\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);\n }\n return Envelope.newWithUncheckedAssertions(this, [saltedAssertion]);\n };\n\n /// Implementation of addAssertionEnvelopeSalted()\n Envelope.prototype.addAssertionEnvelopeSalted = function (\n this: Envelope,\n assertionEnvelope: Envelope,\n salted: boolean,\n ): Envelope {\n // If not salted, use the normal addAssertionEnvelope\n if (!salted) {\n return this.addAssertionEnvelope(assertionEnvelope);\n }\n\n // Add salt to the assertion envelope (this creates a node with assertion as subject)\n const saltedAssertion = assertionEnvelope.addSalt();\n\n // When salted, we need to use newWithUncheckedAssertions because the salted\n // assertion is a node (not pure assertion type) and would fail normal validation\n const c = this.case();\n if (c.type === \"node\") {\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);\n }\n return Envelope.newWithUncheckedAssertions(this, [saltedAssertion]);\n };\n\n /// Implementation of addOptionalAssertionEnvelopeSalted()\n Envelope.prototype.addOptionalAssertionEnvelopeSalted = function (\n this: Envelope,\n assertionEnvelope: Envelope | undefined,\n salted: boolean,\n ): Envelope {\n if (assertionEnvelope === undefined) {\n return this;\n }\n\n // If not salted, use the normal addOptionalAssertionEnvelope\n if (!salted) {\n return this.addOptionalAssertionEnvelope(assertionEnvelope);\n }\n\n // Add salt to the assertion envelope (this creates a node with assertion as subject)\n const saltedAssertion = assertionEnvelope.addSalt();\n\n // When salted, we need to use newWithUncheckedAssertions because the salted\n // assertion is a node (not pure assertion type) and would fail normal validation\n const c = this.case();\n if (c.type === \"node\") {\n // Check for duplicate assertions\n const isDuplicate = c.assertions.some((a) => a.digest().equals(saltedAssertion.digest()));\n if (isDuplicate) {\n return this;\n }\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);\n }\n return Envelope.newWithUncheckedAssertions(this.subject(), [saltedAssertion]);\n };\n}\n","/**\n * Signature Extension for Gordian Envelope\n *\n * Provides functionality for digitally signing Envelopes and verifying signatures,\n * with optional metadata support.\n *\n * The signature extension allows:\n * - Signing envelope subjects to validate their authenticity\n * - Adding metadata to signatures (e.g., signer identity, date, purpose)\n * - Verification of signatures, both with and without metadata\n * - Support for multiple signatures on a single envelope\n *\n * Ported from bc-envelope-rust/src/extension/signature/\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport type { EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SIGNED as SIGNED_KV, NOTE as NOTE_KV } from \"@bcts/known-values\";\n\n/**\n * Re-export signing types from @bcts/components for type compatibility.\n */\nexport {\n Signature,\n SigningPrivateKey,\n SigningPublicKey,\n type Signer,\n type Verifier,\n type SigningOptions,\n} from \"@bcts/components\";\nimport { Signature, type Signer, type Verifier, type SigningOptions } from \"@bcts/components\";\n\n/**\n * Known value for the 'signed' predicate.\n * This is the standard predicate used for signature assertions.\n */\nexport const SIGNED = SIGNED_KV;\n\n/**\n * Known value for the 'note' predicate.\n * Used for adding notes/comments to signatures.\n */\nexport const NOTE = NOTE_KV;\n\n/**\n * Metadata associated with a signature in a Gordian Envelope.\n *\n * `SignatureMetadata` provides a way to attach additional information to\n * signatures, such as the signer's identity, the signing date, or the purpose\n * of the signature. When used with the signature extension, this metadata is\n * included in a structured way that is also signed, ensuring the metadata\n * cannot be tampered with without invalidating the signature.\n *\n * Ported from bc-envelope-rust/src/extension/signature/signature_metadata.rs\n */\nexport class SignatureMetadata {\n private readonly _assertions: [EnvelopeEncodableValue, unknown][] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n private constructor() {}\n\n /**\n * Creates a new empty SignatureMetadata.\n */\n static new(): SignatureMetadata {\n return new SignatureMetadata();\n }\n\n /**\n * Adds an assertion to the metadata.\n *\n * @param predicate - The predicate for the assertion (accepts KnownValue, string, etc.)\n * @param object - The object for the assertion\n * @returns A new SignatureMetadata with the assertion added\n */\n withAssertion(predicate: EnvelopeEncodableValue, object: unknown): SignatureMetadata {\n const metadata = new SignatureMetadata();\n metadata._assertions.push(...this._assertions);\n metadata._assertions.push([predicate, object]);\n return metadata;\n }\n\n /**\n * Returns all assertions in this metadata.\n */\n assertions(): readonly [EnvelopeEncodableValue, unknown][] {\n return this._assertions;\n }\n\n /**\n * Returns whether this metadata contains any assertions.\n */\n hasAssertions(): boolean {\n return this._assertions.length > 0;\n }\n}\n\n// ============================================================================\n// Note: Type declarations for signature methods are in ../base/envelope.ts\n// to ensure they are included in bundled type definitions.\n// ============================================================================\n\n// ============================================================================\n// Envelope Extension Methods for Signatures\n// ============================================================================\n\n/// Creates a signature for the envelope's subject and returns a new\n/// envelope with a `'signed': Signature` assertion.\n///\n/// Matches Rust: add_signature_opt()\nEnvelope.prototype.addSignatureOpt = function (\n this: Envelope,\n signer: Signer,\n options?: SigningOptions,\n metadata?: SignatureMetadata,\n): Envelope {\n const digest = this.subject().digest();\n let signatureEnvelope = Envelope.new(signer.signWithOptions(digest.data(), options));\n\n if (metadata?.hasAssertions() === true) {\n // Add metadata assertions to the signature envelope\n for (const [predicate, object] of metadata.assertions()) {\n signatureEnvelope = signatureEnvelope.addAssertion(\n predicate,\n object as EnvelopeEncodableValue,\n );\n }\n\n // Wrap the signature envelope (cryptographic binding)\n signatureEnvelope = signatureEnvelope.wrap();\n\n // Sign the wrapped structure with the same key\n const outerSignature = Envelope.new(\n signer.signWithOptions(signatureEnvelope.digest().data(), options),\n );\n\n // Add the outer signature assertion\n signatureEnvelope = signatureEnvelope.addAssertion(SIGNED, outerSignature);\n }\n\n return this.addAssertion(SIGNED, signatureEnvelope);\n};\n\n/// Creates a signature without options or metadata.\n///\n/// Matches Rust: add_signature()\nEnvelope.prototype.addSignature = function (this: Envelope, signer: Signer): Envelope {\n return this.addSignatureOpt(signer, undefined, undefined);\n};\n\n/// Creates a signature with optional metadata but no options.\n///\n/// Convenience method matching the common use case.\nEnvelope.prototype.addSignatureWithMetadata = function (\n this: Envelope,\n signer: Signer,\n metadata?: SignatureMetadata,\n): Envelope {\n return this.addSignatureOpt(signer, undefined, metadata);\n};\n\n/// Creates several signatures for the envelope's subject.\n///\n/// Matches Rust: add_signatures()\nEnvelope.prototype.addSignatures = function (this: Envelope, signers: Signer[]): Envelope {\n return signers.reduce<Envelope>((envelope, signer) => envelope.addSignature(signer), this);\n};\n\n/// Creates several signatures with individual options and metadata.\n///\n/// Matches Rust: add_signatures_opt()\nEnvelope.prototype.addSignaturesOpt = function (\n this: Envelope,\n signersWithOptions: { signer: Signer; options?: SigningOptions; metadata?: SignatureMetadata }[],\n): Envelope {\n return signersWithOptions.reduce<Envelope>(\n (envelope, { signer, options, metadata }) =>\n envelope.addSignatureOpt(signer, options, metadata),\n this,\n );\n};\n\n/// Creates several signatures with metadata (no options).\nEnvelope.prototype.addSignaturesWithMetadata = function (\n this: Envelope,\n signersWithMetadata: { signer: Signer; metadata?: SignatureMetadata }[],\n): Envelope {\n return signersWithMetadata.reduce<Envelope>(\n (envelope, { signer, metadata }) => envelope.addSignatureWithMetadata(signer, metadata),\n this,\n );\n};\n\n/// Convenience constructor for a `'signed': Signature` assertion envelope.\n///\n/// Matches Rust: make_signed_assertion()\nEnvelope.prototype.makeSignedAssertion = function (\n this: Envelope,\n signature: Signature,\n note?: string,\n): Envelope {\n let envelope = Envelope.newAssertion(SIGNED, signature as unknown as EnvelopeEncodableValue);\n if (note !== undefined) {\n envelope = envelope.addAssertion(NOTE, note);\n }\n return envelope;\n};\n\n/// Returns whether the given signature is valid.\n///\n/// Matches Rust: is_verified_signature()\nEnvelope.prototype.isVerifiedSignature = function (\n this: Envelope,\n signature: Signature,\n verifier: Verifier,\n): boolean {\n return verifier.verify(signature, this.subject().digest().data());\n};\n\n/// Checks whether the given signature is valid for the given public key.\n///\n/// Matches Rust: verify_signature()\nEnvelope.prototype.verifySignature = function (\n this: Envelope,\n signature: Signature,\n verifier: Verifier,\n): Envelope {\n if (!verifier.verify(signature, this.subject().digest().data())) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n// ============================================================================\n// Internal: Core signature verification with metadata support\n// ============================================================================\n\n/// Returns the signature metadata envelope if the given verifier has signed\n/// this envelope, or undefined if no matching signature is found.\n///\n/// Handles both simple signatures and wrapped (double-signed) signatures\n/// with metadata.\n///\n/// Matches Rust: has_some_signature_from_key_returning_metadata()\nEnvelope.prototype.hasSignatureFromReturningMetadata = function (\n this: Envelope,\n verifier: Verifier,\n): Envelope | undefined {\n // Valid signature objects are either:\n // - `Signature` objects, or\n // - `Signature` objects with additional metadata assertions, wrapped\n // and then signed by the same key.\n const signatureObjects = this.objectsForPredicate(SIGNED);\n\n for (const signatureObject of signatureObjects) {\n const signatureObjectSubject = signatureObject.subject();\n\n if (signatureObjectSubject.isWrapped()) {\n // Wrapped case: signature with metadata\n // The structure is:\n // {Signature ['note': \"...\"]} ['signed': OuterSignature]\n\n // Step 1: Verify outer signature if present\n let outerSigFound = false;\n try {\n const outerSignatureObject = signatureObject.objectForPredicate(SIGNED);\n outerSigFound = true;\n const outerSignature = outerSignatureObject.extractSubject((cbor) =>\n Signature.fromTaggedCbor(cbor),\n );\n if (!verifier.verify(outerSignature, signatureObjectSubject.digest().data())) {\n continue; // Outer signature doesn't match key, try next\n }\n } catch (_e) {\n if (outerSigFound) {\n // Found 'signed' assertion but couldn't extract Signature\n throw EnvelopeError.invalidOuterSignatureType();\n }\n // No 'signed' assertion on the signature object — skip outer check\n // (object_for_predicate failed with NONEXISTENT_PREDICATE)\n }\n\n // Step 2: Unwrap and verify inner signature\n const signatureMetadataEnvelope = signatureObjectSubject.tryUnwrap();\n try {\n const innerSignature = signatureMetadataEnvelope.extractSubject((cbor) =>\n Signature.fromTaggedCbor(cbor),\n );\n if (!verifier.verify(innerSignature, this.subject().digest().data())) {\n throw EnvelopeError.unverifiedInnerSignature();\n }\n return signatureMetadataEnvelope;\n } catch (e) {\n if (e instanceof EnvelopeError) throw e;\n throw EnvelopeError.invalidInnerSignatureType();\n }\n } else {\n // Simple case: no metadata\n try {\n const signature = signatureObject.extractSubject((cbor) => Signature.fromTaggedCbor(cbor));\n if (verifier.verify(signature, this.subject().digest().data())) {\n return signatureObject;\n }\n } catch {\n throw EnvelopeError.invalidSignatureType();\n }\n }\n }\n\n return undefined;\n};\n\n/// Returns whether the envelope's subject has a valid signature from the\n/// given public key.\n///\n/// Matches Rust: has_signature_from()\nEnvelope.prototype.hasSignatureFrom = function (this: Envelope, verifier: Verifier): boolean {\n return this.hasSignatureFromReturningMetadata(verifier) !== undefined;\n};\n\n/// Returns whether the envelope's subject has a valid signature from all\n/// the given public keys.\n///\n/// Matches Rust: has_signatures_from()\nEnvelope.prototype.hasSignaturesFrom = function (this: Envelope, verifiers: Verifier[]): boolean {\n return verifiers.every((verifier) => this.hasSignatureFrom(verifier));\n};\n\n/// Returns whether the envelope's subject has some threshold of signatures.\n///\n/// Matches Rust: has_signatures_from_threshold()\nEnvelope.prototype.hasSignaturesFromThreshold = function (\n this: Envelope,\n verifiers: Verifier[],\n threshold?: number,\n): boolean {\n const t = threshold ?? verifiers.length;\n let count = 0;\n for (const verifier of verifiers) {\n if (this.hasSignatureFrom(verifier)) {\n count++;\n if (count >= t) {\n return true;\n }\n }\n }\n return false;\n};\n\n/// Checks whether the envelope's subject has a valid signature from the\n/// given public key.\n///\n/// Matches Rust: verify_signature_from()\nEnvelope.prototype.verifySignatureFrom = function (this: Envelope, verifier: Verifier): Envelope {\n if (!this.hasSignatureFrom(verifier)) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n/// Verifies signature and returns the metadata envelope.\n///\n/// Matches Rust: verify_signature_from_returning_metadata()\nEnvelope.prototype.verifySignatureFromReturningMetadata = function (\n this: Envelope,\n verifier: Verifier,\n): Envelope {\n const metadata = this.hasSignatureFromReturningMetadata(verifier);\n if (metadata === undefined) {\n throw EnvelopeError.unverifiedSignature();\n }\n return metadata;\n};\n\n/// Checks whether the envelope's subject has a set of signatures.\n///\n/// Matches Rust: verify_signatures_from()\nEnvelope.prototype.verifySignaturesFrom = function (\n this: Envelope,\n verifiers: Verifier[],\n): Envelope {\n if (!this.hasSignaturesFrom(verifiers)) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n/// Checks whether the envelope's subject has some threshold of signatures.\n///\n/// Matches Rust: verify_signatures_from_threshold()\nEnvelope.prototype.verifySignaturesFromThreshold = function (\n this: Envelope,\n verifiers: Verifier[],\n threshold?: number,\n): Envelope {\n const t = threshold ?? verifiers.length;\n if (!this.hasSignaturesFromThreshold(verifiers, t)) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n/// Returns all signature assertion objects.\n///\n/// Matches Rust: objects_for_predicate(SIGNED) via signatures()\nEnvelope.prototype.signatures = function (this: Envelope): Envelope[] {\n return this.objectsForPredicate(SIGNED);\n};\n\n// ============================================================================\n// Convenience methods for signing and verifying entire envelopes.\n//\n// These wrap the envelope before signing, ensuring all assertions are\n// included in the signature.\n// ============================================================================\n\n/// Signs the entire envelope by wrapping it first.\n///\n/// Matches Rust: sign()\nEnvelope.prototype.sign = function (this: Envelope, signer: Signer): Envelope {\n return this.signOpt(signer, undefined);\n};\n\n/// Signs the entire envelope with options but no metadata.\n///\n/// Matches Rust: sign_opt()\nEnvelope.prototype.signOpt = function (\n this: Envelope,\n signer: Signer,\n options?: SigningOptions,\n): Envelope {\n return this.wrap().addSignatureOpt(signer, options, undefined);\n};\n\n/// Signs the entire envelope with optional metadata.\nEnvelope.prototype.signWithMetadata = function (\n this: Envelope,\n signer: Signer,\n metadata?: SignatureMetadata,\n): Envelope {\n return this.wrap().addSignatureOpt(signer, undefined, metadata);\n};\n\n/// Verifies that the envelope has a valid signature from the specified\n/// verifier, and unwraps it.\n///\n/// Matches Rust: verify()\nEnvelope.prototype.verify = function (this: Envelope, verifier: Verifier): Envelope {\n return this.verifySignatureFrom(verifier).tryUnwrap();\n};\n\n/// Verifies the envelope's signature and returns both the unwrapped\n/// envelope and signature metadata.\n///\n/// Matches Rust: verify_returning_metadata()\nEnvelope.prototype.verifyReturningMetadata = function (\n this: Envelope,\n verifier: Verifier,\n): { envelope: Envelope; metadata: Envelope } {\n const metadata = this.verifySignatureFromReturningMetadata(verifier);\n return { envelope: this.tryUnwrap(), metadata };\n};\n","/**\n * Attachment Extension for Gordian Envelope\n *\n * Provides functionality for attaching vendor-specific metadata to envelopes.\n * Attachments enable flexible, extensible data storage without modifying\n * the core data model, facilitating interoperability and future compatibility.\n *\n * Each attachment has:\n * - A payload (arbitrary data)\n * - A required vendor identifier (typically a reverse domain name)\n * - An optional conformsTo URI that indicates the format of the attachment\n *\n * See BCR-2023-006: https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2023-006-envelope-attachment.md\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport { type Digest } from \"../base/digest\";\nimport { EnvelopeError } from \"../base/error\";\nimport type { EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport {\n ATTACHMENT as ATTACHMENT_KV,\n VENDOR as VENDOR_KV,\n CONFORMS_TO as CONFORMS_TO_KV,\n} from \"@bcts/known-values\";\n\n/**\n * Known value for the 'attachment' predicate.\n */\nexport const ATTACHMENT = ATTACHMENT_KV;\n\n/**\n * Known value for the 'vendor' predicate.\n */\nexport const VENDOR = VENDOR_KV;\n\n/**\n * Known value for the 'conformsTo' predicate.\n */\nexport const CONFORMS_TO = CONFORMS_TO_KV;\n\n/**\n * A container for vendor-specific metadata attachments.\n *\n * Attachments provides a flexible mechanism for attaching arbitrary metadata\n * to envelopes without modifying their core structure.\n */\nexport class Attachments {\n private readonly _envelopes = new Map<string, Envelope>();\n\n /**\n * Creates a new empty attachments container.\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n constructor() {}\n\n /**\n * Adds a new attachment with the specified payload and metadata.\n *\n * @param payload - The data to attach\n * @param vendor - A string identifying the entity that defined the attachment format\n * @param conformsTo - Optional URI identifying the structure the payload conforms to\n */\n add(payload: EnvelopeEncodableValue, vendor: string, conformsTo?: string): void {\n const attachment = Envelope.newAttachment(payload, vendor, conformsTo);\n this._envelopes.set(attachment.digest().hex(), attachment);\n }\n\n /**\n * Adds a pre-constructed attachment envelope directly.\n *\n * @param envelope - The attachment envelope to add\n */\n addEnvelope(envelope: Envelope): void {\n this._envelopes.set(envelope.digest().hex(), envelope);\n }\n\n /**\n * Retrieves an attachment by its digest.\n *\n * @param digest - The unique digest of the attachment to retrieve\n * @returns The envelope if found, or undefined\n */\n get(digest: Digest): Envelope | undefined {\n return this._envelopes.get(digest.hex());\n }\n\n /**\n * Removes an attachment by its digest.\n *\n * @param digest - The unique digest of the attachment to remove\n * @returns The removed envelope if found, or undefined\n */\n remove(digest: Digest): Envelope | undefined {\n const envelope = this._envelopes.get(digest.hex());\n this._envelopes.delete(digest.hex());\n return envelope;\n }\n\n /**\n * Removes all attachments from the container.\n */\n clear(): void {\n this._envelopes.clear();\n }\n\n /**\n * Returns whether the container has any attachments.\n */\n isEmpty(): boolean {\n return this._envelopes.size === 0;\n }\n\n /**\n * Returns the number of attachments in the container.\n */\n len(): number {\n return this._envelopes.size;\n }\n\n /**\n * Returns an iterator over all attachment envelopes.\n */\n iter(): IterableIterator<[string, Envelope]> {\n return this._envelopes.entries();\n }\n\n /**\n * Check equality with another Attachments container.\n */\n equals(other: Attachments): boolean {\n if (this._envelopes.size !== other._envelopes.size) return false;\n for (const [key] of this._envelopes) {\n if (!other._envelopes.has(key)) return false;\n }\n return true;\n }\n\n /**\n * Adds all attachments from this container to an envelope.\n *\n * @param envelope - The envelope to add attachments to\n * @returns A new envelope with all attachments added as assertions\n */\n addToEnvelope(envelope: Envelope): Envelope {\n let result = envelope;\n for (const attachment of this._envelopes.values()) {\n result = result.addAssertion(ATTACHMENT, attachment);\n }\n return result;\n }\n\n /**\n * Creates an Attachments container from an envelope's attachment assertions.\n *\n * @param envelope - The envelope to extract attachments from\n * @returns A new Attachments container with the envelope's attachments\n */\n static fromEnvelope(envelope: Envelope): Attachments {\n const attachments = new Attachments();\n const attachmentEnvelopes = envelope.attachments();\n\n for (const attachment of attachmentEnvelopes) {\n attachments._envelopes.set(attachment.digest().hex(), attachment);\n }\n\n return attachments;\n }\n}\n\n// Implementation\n\n/**\n * Creates a new attachment envelope.\n */\nEnvelope.newAttachment = function (\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n): Envelope {\n // Create the payload envelope wrapped with vendor assertion\n let attachmentObj = Envelope.new(payload).wrap().addAssertion(VENDOR, vendor);\n\n // Add optional conformsTo\n if (conformsTo !== undefined) {\n attachmentObj = attachmentObj.addAssertion(CONFORMS_TO, conformsTo);\n }\n\n // Create an assertion with 'attachment' as predicate and the wrapped payload as object\n // This returns an assertion envelope\n const attachmentPredicate = Envelope.new(ATTACHMENT);\n return attachmentPredicate.addAssertion(ATTACHMENT, attachmentObj).assertions()[0];\n};\n\n/**\n * Adds an attachment to an envelope.\n */\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.addAttachment = function (\n this: Envelope,\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n ): Envelope {\n let attachmentObj = Envelope.new(payload).wrap().addAssertion(VENDOR, vendor);\n\n if (conformsTo !== undefined) {\n attachmentObj = attachmentObj.addAssertion(CONFORMS_TO, conformsTo);\n }\n\n return this.addAssertion(ATTACHMENT, attachmentObj);\n };\n\n /**\n * Returns the payload of an attachment envelope.\n */\n Envelope.prototype.attachmentPayload = function (this: Envelope): Envelope {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.general(\"Envelope is not an attachment assertion\");\n }\n\n const obj = c.assertion.object();\n return obj.unwrap();\n };\n\n /**\n * Returns the vendor of an attachment envelope.\n */\n Envelope.prototype.attachmentVendor = function (this: Envelope): string {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.general(\"Envelope is not an attachment assertion\");\n }\n\n const obj = c.assertion.object();\n const vendorEnv = obj.objectForPredicate(VENDOR);\n const vendor = vendorEnv.asText();\n\n if (vendor === undefined || vendor === \"\") {\n throw EnvelopeError.general(\"Attachment has no vendor\");\n }\n\n return vendor;\n };\n\n /**\n * Returns the conformsTo of an attachment envelope.\n */\n Envelope.prototype.attachmentConformsTo = function (this: Envelope): string | undefined {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.general(\"Envelope is not an attachment assertion\");\n }\n\n const obj = c.assertion.object();\n const conformsToEnv = obj.optionalObjectForPredicate(CONFORMS_TO);\n\n if (conformsToEnv === undefined) {\n return undefined;\n }\n\n return conformsToEnv.asText();\n };\n\n /**\n * Returns all attachment assertions.\n */\n Envelope.prototype.attachments = function (this: Envelope): Envelope[] {\n return this.assertionsWithPredicate(ATTACHMENT).map((a) => {\n const c = a.case();\n if (c.type === \"assertion\") {\n return c.assertion.object();\n }\n throw EnvelopeError.general(\"Invalid attachment assertion\");\n });\n };\n\n /**\n * Returns attachments matching vendor and/or conformsTo.\n */\n Envelope.prototype.attachmentsWithVendorAndConformsTo = function (\n this: Envelope,\n vendor?: string,\n conformsTo?: string,\n ): Envelope[] {\n const allAttachments = this.attachments();\n\n return allAttachments.filter((attachment) => {\n try {\n // The attachment is already a wrapped envelope with vendor/conformsTo assertions\n // Check vendor if specified\n if (vendor !== undefined) {\n const vendorEnv = attachment.objectForPredicate(VENDOR);\n const attachmentVendor = vendorEnv.asText();\n if (attachmentVendor !== vendor) {\n return false;\n }\n }\n\n // Check conformsTo if specified\n if (conformsTo !== undefined) {\n const conformsToEnv = attachment.optionalObjectForPredicate(CONFORMS_TO);\n if (conformsToEnv === undefined) {\n return false;\n }\n const conformsToText = conformsToEnv.asText();\n if (conformsToText !== conformsTo) {\n return false;\n }\n }\n\n return true;\n } catch {\n return false;\n }\n });\n };\n\n /**\n * Validates that this envelope is a valid attachment.\n *\n * An attachment is valid if:\n * 1. The envelope is an assertion with 'attachment' as predicate\n * 2. The object contains a wrapped payload with vendor assertion\n * 3. Reconstructing the attachment yields an equivalent envelope\n *\n * @throws EnvelopeError if the envelope is not a valid attachment\n */\n Envelope.prototype.validateAttachment = function (this: Envelope): void {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.invalidAttachment(\"Envelope is not an assertion\");\n }\n\n // Verify predicate is 'attachment' (using digest comparison for KnownValue predicates)\n const predicate = c.assertion.predicate();\n const expectedPredicate = Envelope.new(ATTACHMENT);\n if (!predicate.digest().equals(expectedPredicate.digest())) {\n throw EnvelopeError.invalidAttachment(\"Assertion predicate is not 'attachment'\");\n }\n\n // Extract components\n const payload = this.attachmentPayload();\n const vendor = this.attachmentVendor();\n const conformsTo = this.attachmentConformsTo();\n\n // Reconstruct the attachment\n const reconstructed = Envelope.newAttachment(payload, vendor, conformsTo);\n\n // Check equivalence (same digest = semantically equivalent)\n if (!this.digest().equals(reconstructed.digest())) {\n throw EnvelopeError.invalidAttachment(\"Attachment structure is invalid\");\n }\n };\n\n /**\n * Finds a single attachment matching the given vendor and conformsTo.\n *\n * Unlike `attachmentsWithVendorAndConformsTo` which returns an array,\n * this method requires exactly one attachment to match.\n *\n * @param vendor - Optional vendor identifier to match\n * @param conformsTo - Optional conformsTo URI to match\n * @returns The matching attachment envelope\n * @throws EnvelopeError if not exactly one attachment matches\n */\n Envelope.prototype.attachmentWithVendorAndConformsTo = function (\n this: Envelope,\n vendor?: string,\n conformsTo?: string,\n ): Envelope {\n const matches = this.attachmentsWithVendorAndConformsTo(vendor, conformsTo);\n\n if (matches.length === 0) {\n throw EnvelopeError.general(\"No matching attachment found\");\n }\n if (matches.length > 1) {\n throw EnvelopeError.general(`Expected exactly one attachment, found ${matches.length}`);\n }\n\n return matches[0];\n };\n}\n","/**\n * Edge Extension for Gordian Envelope (BCR-2026-003)\n *\n * Provides functionality for creating and managing edge envelopes that\n * represent verifiable relationships between entities. An edge envelope\n * contains three required assertions:\n * - `'isA'`: The type of relationship\n * - `'source'`: The source entity\n * - `'target'`: The target entity\n *\n * Edges may optionally be wrapped and signed. When accessing edge properties,\n * the implementation handles both wrapped (signed) and unwrapped edges\n * transparently.\n *\n * Equivalent to Rust's `src/extension/edge/` module.\n *\n * @module edge\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport { type Digest } from \"../base/digest\";\nimport { EnvelopeError } from \"../base/error\";\nimport { EDGE, IS_A, SOURCE, TARGET } from \"@bcts/known-values\";\n\n// -------------------------------------------------------------------\n// Edges Container\n// -------------------------------------------------------------------\n\n/**\n * A container for edge envelopes on a document.\n *\n * `Edges` stores pre-constructed edge envelopes keyed by their digest,\n * mirroring the `Attachments` container but for edges as defined in\n * BCR-2026-003.\n *\n * Equivalent to Rust's `Edges` struct in `src/extension/edge/edges.rs`.\n */\nexport class Edges {\n private readonly _envelopes: Map<string, Envelope>;\n\n /**\n * Creates a new empty edges container.\n */\n constructor() {\n this._envelopes = new Map();\n }\n\n /**\n * Adds a pre-constructed edge envelope.\n *\n * @param edgeEnvelope - The edge envelope to add\n */\n add(edgeEnvelope: Envelope): void {\n const digest = edgeEnvelope.digest();\n this._envelopes.set(digest.hex(), edgeEnvelope);\n }\n\n /**\n * Retrieves an edge by its digest.\n *\n * @param digest - The digest of the edge to retrieve\n * @returns The edge envelope if found, or undefined\n */\n get(digest: Digest): Envelope | undefined {\n return this._envelopes.get(digest.hex());\n }\n\n /**\n * Removes an edge by its digest.\n *\n * @param digest - The digest of the edge to remove\n * @returns The removed edge envelope if found, or undefined\n */\n remove(digest: Digest): Envelope | undefined {\n const key = digest.hex();\n const envelope = this._envelopes.get(key);\n this._envelopes.delete(key);\n return envelope;\n }\n\n /**\n * Removes all edges from the container.\n */\n clear(): void {\n this._envelopes.clear();\n }\n\n /**\n * Returns whether the container has no edges.\n */\n isEmpty(): boolean {\n return this._envelopes.size === 0;\n }\n\n /**\n * Returns the number of edges in the container.\n */\n len(): number {\n return this._envelopes.size;\n }\n\n /**\n * Returns an iterator over all edge envelopes.\n */\n iter(): IterableIterator<[string, Envelope]> {\n return this._envelopes.entries();\n }\n\n /**\n * Check equality with another Edges container.\n */\n equals(other: Edges): boolean {\n if (this._envelopes.size !== other._envelopes.size) return false;\n for (const [key] of this._envelopes) {\n if (!other._envelopes.has(key)) return false;\n }\n return true;\n }\n\n /**\n * Adds all edges as `'edge'` assertion envelopes to the given envelope.\n *\n * @param envelope - The envelope to add edges to\n * @returns A new envelope with all edges added as assertions\n */\n addToEnvelope(envelope: Envelope): Envelope {\n let result = envelope;\n for (const edgeEnvelope of this._envelopes.values()) {\n result = result.addAssertion(EDGE, edgeEnvelope);\n }\n return result;\n }\n\n /**\n * Extracts edges from an envelope's `'edge'` assertions.\n *\n * Equivalent to Rust's `Edges::try_from_envelope()`.\n *\n * @param envelope - The envelope to extract edges from\n * @returns A new Edges container with the envelope's edges\n */\n static fromEnvelope(envelope: Envelope): Edges {\n const edgeEnvelopes = envelope.edges();\n const edges = new Edges();\n for (const edge of edgeEnvelopes) {\n edges._envelopes.set(edge.digest().hex(), edge);\n }\n return edges;\n }\n}\n\n// -------------------------------------------------------------------\n// Edgeable Interface\n// -------------------------------------------------------------------\n\n/**\n * A trait for types that can have edges.\n *\n * `Edgeable` provides a consistent interface for working with edges.\n * Types implementing this interface can store and retrieve edge envelopes\n * representing verifiable claims as defined in BCR-2026-003.\n *\n * Equivalent to Rust's `Edgeable` trait in `src/extension/edge/edges.rs`.\n */\nexport interface Edgeable {\n /** Returns a reference to the edges container. */\n edges(): Edges;\n /** Returns a mutable reference to the edges container. */\n edgesMut(): Edges;\n /** Adds a pre-constructed edge envelope. */\n addEdge(edgeEnvelope: Envelope): void;\n /** Retrieves an edge by its digest. */\n getEdge(digest: Digest): Envelope | undefined;\n /** Removes an edge by its digest. */\n removeEdge(digest: Digest): Envelope | undefined;\n /** Removes all edges. */\n clearEdges(): void;\n /** Returns whether the object has any edges. */\n hasEdges(): boolean;\n}\n\n// -------------------------------------------------------------------\n// Envelope Prototype Methods\n// -------------------------------------------------------------------\n\n/**\n * Returns a new envelope with an added `'edge': <edge>` assertion.\n *\n * Equivalent to Rust's `Envelope::add_edge_envelope()`.\n */\nEnvelope.prototype.addEdgeEnvelope = function (this: Envelope, edge: Envelope): Envelope {\n return this.addAssertion(EDGE, edge);\n};\n\n/**\n * Returns all edge object envelopes (assertions with predicate `'edge'`).\n *\n * Equivalent to Rust's `Envelope::edges()`.\n */\nEnvelope.prototype.edges = function (this: Envelope): Envelope[] {\n return this.objectsForPredicate(EDGE);\n};\n\n/**\n * Validates an edge envelope's structure per BCR-2026-003.\n *\n * An edge may be wrapped (signed) or unwrapped. The inner envelope\n * must have exactly three assertion predicates: `'isA'`, `'source'`,\n * and `'target'`.\n *\n * Equivalent to Rust's `Envelope::validate_edge()`.\n *\n * @throws {EnvelopeError} If the edge structure is invalid\n */\nEnvelope.prototype.validateEdge = function (this: Envelope): void {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n\n const isACount = inner.assertionsWithPredicate(IS_A).length;\n const sourceCount = inner.assertionsWithPredicate(SOURCE).length;\n const targetCount = inner.assertionsWithPredicate(TARGET).length;\n\n if (isACount === 0) {\n throw EnvelopeError.edgeMissingIsA();\n }\n if (sourceCount === 0) {\n throw EnvelopeError.edgeMissingSource();\n }\n if (targetCount === 0) {\n throw EnvelopeError.edgeMissingTarget();\n }\n if (isACount > 1) {\n throw EnvelopeError.edgeDuplicateIsA();\n }\n if (sourceCount > 1) {\n throw EnvelopeError.edgeDuplicateSource();\n }\n if (targetCount > 1) {\n throw EnvelopeError.edgeDuplicateTarget();\n }\n};\n\n/**\n * Extracts the `'isA'` assertion object from an edge envelope.\n *\n * Equivalent to Rust's `Envelope::edge_is_a()`.\n */\nEnvelope.prototype.edgeIsA = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.objectForPredicate(IS_A);\n};\n\n/**\n * Extracts the `'source'` assertion object from an edge envelope.\n *\n * Equivalent to Rust's `Envelope::edge_source()`.\n */\nEnvelope.prototype.edgeSource = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.objectForPredicate(SOURCE);\n};\n\n/**\n * Extracts the `'target'` assertion object from an edge envelope.\n *\n * Equivalent to Rust's `Envelope::edge_target()`.\n */\nEnvelope.prototype.edgeTarget = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.objectForPredicate(TARGET);\n};\n\n/**\n * Extracts the edge's subject identifier (the inner envelope's subject).\n *\n * Equivalent to Rust's `Envelope::edge_subject()`.\n */\nEnvelope.prototype.edgeSubject = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.subject();\n};\n\n/**\n * Filters edges by optional criteria.\n *\n * Each parameter is optional. When provided, only edges matching\n * all specified criteria are returned.\n *\n * Equivalent to Rust's `Envelope::edges_matching()`.\n *\n * @param isA - Optional `'isA'` envelope to match\n * @param source - Optional `'source'` envelope to match\n * @param target - Optional `'target'` envelope to match\n * @param subject - Optional subject envelope to match\n * @returns Array of matching edge envelopes\n */\nEnvelope.prototype.edgesMatching = function (\n this: Envelope,\n isA?: Envelope,\n source?: Envelope,\n target?: Envelope,\n subject?: Envelope,\n): Envelope[] {\n const allEdges = this.edges();\n const matching: Envelope[] = [];\n\n for (const edge of allEdges) {\n if (isA !== undefined) {\n try {\n const edgeIsA = edge.edgeIsA();\n if (!edgeIsA.isEquivalentTo(isA)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n if (source !== undefined) {\n try {\n const edgeSource = edge.edgeSource();\n if (!edgeSource.isEquivalentTo(source)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n if (target !== undefined) {\n try {\n const edgeTarget = edge.edgeTarget();\n if (!edgeTarget.isEquivalentTo(target)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n if (subject !== undefined) {\n try {\n const edgeSubject = edge.edgeSubject();\n if (!edgeSubject.isEquivalentTo(subject)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n matching.push(edge);\n }\n\n return matching;\n};\n","/**\n * Public key encryption extension for Gordian Envelope.\n *\n * This module implements public key encryption for Gordian Envelope, allowing\n * encrypted content to be selectively shared with one or more recipients. Each\n * recipient needs their own public/private key pair, and only recipients with\n * the corresponding private key can decrypt the envelope's content.\n *\n * The recipient extension builds on the basic envelope encryption capabilities\n * by adding:\n *\n * - **Multiple Recipients** - A single envelope can be encrypted to multiple\n * recipients\n * - **Content Key Distribution** - Uses public key cryptography to securely\n * distribute the symmetric key that encrypts the actual content\n * - **Privacy** - Recipients can decrypt the envelope independently without\n * revealing their identity or access to other recipients\n *\n * ## How It Works\n *\n * The envelope's subject is encrypted using a random symmetric key (the\n * \"content key\"), and then this content key is encrypted to each recipient's\n * public key using a `SealedMessage`. Each encrypted content key is attached\n * to the envelope with a `hasRecipient` assertion.\n *\n * When recipients want to decrypt the envelope, they use their private key to\n * decrypt the content key from the appropriate `SealedMessage`, and then use\n * that content key to decrypt the envelope's subject.\n *\n * Ported from bc-envelope-rust/src/extension/recipient.rs\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SymmetricKey } from \"./encrypt\";\nimport {\n type Encrypter,\n type Decrypter,\n type Nonce,\n SealedMessage as ComponentsSealedMessage,\n isEncrypter,\n} from \"@bcts/components\";\nimport { HAS_RECIPIENT as HAS_RECIPIENT_KV } from \"@bcts/known-values\";\n\n/**\n * Predicate constant for recipient assertions.\n * This is the known value 'hasRecipient' used to identify recipient assertions.\n */\nexport const HAS_RECIPIENT = HAS_RECIPIENT_KV;\n\n/**\n * Re-export the SealedMessage from @bcts/components for compatibility.\n * This is the proper implementation that supports both X25519 and MLKEM.\n */\nexport { SealedMessage as ComponentsSealedMessage } from \"@bcts/components\";\n\n/**\n * Re-export Encrypter and Decrypter types for convenience.\n */\nexport type { Encrypter, Decrypter } from \"@bcts/components\";\n\n/**\n * Legacy PublicKeyBase class for backwards compatibility.\n * New code should use Encrypter interface directly.\n *\n * @deprecated Use Encrypter interface from @bcts/components instead\n */\nexport { EncapsulationPublicKey as PublicKeyBase } from \"@bcts/components\";\n\n/**\n * Legacy PrivateKeyBase class for backwards compatibility.\n * New code should use Decrypter interface or PrivateKeys from @bcts/components instead.\n *\n * Note: This now exports PrivateKeys (which includes both signing and encapsulation keys)\n * instead of just EncapsulationPrivateKey to match the expected API with .publicKeys() method.\n *\n * @deprecated Use Decrypter interface or PrivateKeys from @bcts/components instead\n */\nexport { PrivateKeys as PrivateKeyBase } from \"@bcts/components\";\n\n/**\n * SealedMessage wrapping the sealed content key for a recipient.\n * This is the proper implementation from @bcts/components that supports\n * both X25519 and MLKEM encryption schemes.\n */\nexport class SealedMessage {\n private readonly _inner: ComponentsSealedMessage;\n\n constructor(sealedMessage: ComponentsSealedMessage) {\n this._inner = sealedMessage;\n }\n\n /**\n * Creates a sealed message by encrypting a symmetric key to a recipient.\n * Uses the Encrypter interface which supports both X25519 and MLKEM.\n *\n * @param contentKey - The symmetric key to encrypt\n * @param recipient - The recipient's public key (implements Encrypter)\n * @param testNonce - Optional nonce for deterministic testing\n * @returns A sealed message containing the encrypted content key\n */\n static seal(contentKey: SymmetricKey, recipient: Encrypter, testNonce?: Nonce): SealedMessage {\n // Get the encapsulation public key from the Encrypter\n const encapsulationPublicKey = recipient.encapsulationPublicKey();\n\n // Use the SealedMessage.newOpt from components which properly handles\n // both X25519 and MLKEM encapsulation\n const inner = ComponentsSealedMessage.newOpt(\n contentKey.data(),\n encapsulationPublicKey,\n new Uint8Array(0), // No AAD\n testNonce,\n );\n\n return new SealedMessage(inner);\n }\n\n /**\n * Decrypts this sealed message using recipient's private key.\n *\n * @param recipient - The recipient's private key (implements Decrypter)\n * @returns The decrypted content key data\n */\n decrypt(recipient: Decrypter): Uint8Array {\n const encapsulationPrivateKey = recipient.encapsulationPrivateKey();\n return this._inner.decrypt(encapsulationPrivateKey);\n }\n\n /**\n * Returns the underlying SealedMessage from components.\n */\n inner(): ComponentsSealedMessage {\n return this._inner;\n }\n\n /**\n * Returns the CBOR-encoded data of this sealed message.\n */\n data(): Uint8Array {\n return this._inner.taggedCborData();\n }\n\n /**\n * Creates a SealedMessage from CBOR-encoded data.\n */\n static fromData(data: Uint8Array): SealedMessage {\n const inner = ComponentsSealedMessage.fromTaggedCborData(data);\n return new SealedMessage(inner);\n }\n}\n\n// ============================================================================\n// Envelope Extension Methods\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n /**\n * Adds a recipient assertion to this envelope.\n *\n * This method adds a `hasRecipient` assertion containing a `SealedMessage`\n * that holds the content key encrypted to the recipient's public key.\n *\n * @param recipient - The recipient's public key (implements Encrypter)\n * @param contentKey - The symmetric key used to encrypt the envelope's subject\n * @param testNonce - Optional nonce for deterministic testing\n * @returns A new envelope with the recipient assertion added\n */\n Envelope.prototype.addRecipient = function (\n this: Envelope,\n recipient: Encrypter,\n contentKey: SymmetricKey,\n testNonce?: Nonce,\n ): Envelope {\n const sealedMessage = SealedMessage.seal(contentKey, recipient, testNonce);\n // Store the sealed message as CBOR data in the assertion\n return this.addAssertion(HAS_RECIPIENT, sealedMessage.inner());\n };\n\n /**\n * Encrypts the envelope's subject and adds a recipient assertion.\n *\n * This is a convenience method that:\n * 1. Generates a random content key\n * 2. Encrypts the subject with the content key\n * 3. Adds a recipient assertion with the sealed content key\n *\n * @param recipient - The recipient's public key (implements Encrypter)\n * @returns A new envelope with encrypted subject and recipient assertion\n */\n Envelope.prototype.encryptSubjectToRecipient = function (\n this: Envelope,\n recipient: Encrypter,\n ): Envelope {\n // Validate that recipient implements Encrypter\n if (!isEncrypter(recipient)) {\n throw EnvelopeError.general(\n \"Recipient must implement Encrypter interface. \" +\n \"Use PublicKeys or EncapsulationPublicKey from @bcts/components.\",\n );\n }\n\n // Generate a random content key\n const contentKey = SymmetricKey.new();\n\n // Encrypt the subject with the content key\n const encrypted = this.encryptSubject(contentKey);\n\n // Add the recipient\n return encrypted.addRecipient(recipient, contentKey);\n };\n\n /**\n * Encrypts the envelope's subject and adds recipient assertions for multiple recipients.\n *\n * @param recipients - Array of recipient public keys (each implements Encrypter)\n * @returns A new envelope with encrypted subject and recipient assertions\n */\n Envelope.prototype.encryptSubjectToRecipients = function (\n this: Envelope,\n recipients: Encrypter[],\n ): Envelope {\n if (recipients.length === 0) {\n throw EnvelopeError.general(\"Must provide at least one recipient\");\n }\n\n // Generate a random content key\n const contentKey = SymmetricKey.new();\n\n // Encrypt the subject with the content key\n let result = this.encryptSubject(contentKey);\n\n // Add each recipient\n for (const recipient of recipients) {\n if (!isEncrypter(recipient)) {\n throw EnvelopeError.general(\n \"All recipients must implement Encrypter interface. \" +\n \"Use PublicKeys or EncapsulationPublicKey from @bcts/components.\",\n );\n }\n result = result.addRecipient(recipient, contentKey);\n }\n\n return result;\n };\n\n /**\n * Returns all SealedMessages from the envelope's `hasRecipient` assertions.\n *\n * @returns Array of SealedMessage objects\n */\n Envelope.prototype.recipients = function (this: Envelope): SealedMessage[] {\n const recipientAssertions = this.assertions().filter((assertion) => {\n try {\n const predicate = assertion.subject().asPredicate();\n if (predicate === undefined) return false;\n // Check if it's the hasRecipient known value\n const knownValue = predicate.asKnownValue();\n if (knownValue !== undefined) {\n return knownValue.equals(HAS_RECIPIENT);\n }\n // Also check string form for backwards compatibility\n const text = predicate.asText();\n return text === \"hasRecipient\";\n } catch {\n return false;\n }\n });\n\n return recipientAssertions.map((assertion) => {\n // Get the object from the assertion case\n const assertionCase = assertion.case();\n if (assertionCase.type !== \"assertion\") {\n throw EnvelopeError.general(\"Invalid recipient assertion structure\");\n }\n\n const obj = assertionCase.assertion.object();\n\n // Try to decode as SealedMessage from components\n try {\n // The object should be a leaf envelope containing a SealedMessage\n // Get the underlying CBOR from the leaf envelope\n const leafCbor = obj.asLeaf();\n if (leafCbor !== undefined) {\n // Convert the CBOR to bytes and decode as SealedMessage\n const cborData = leafCbor.toData();\n const inner = ComponentsSealedMessage.fromTaggedCborData(cborData);\n return new SealedMessage(inner);\n }\n\n // Try extracting from the full envelope CBOR as fallback\n const cborData = obj.taggedCborData();\n const inner = ComponentsSealedMessage.fromTaggedCborData(cborData);\n return new SealedMessage(inner);\n } catch {\n // Try legacy format: raw bytes\n try {\n const sealedData = obj.asByteString();\n if (sealedData !== undefined) {\n return SealedMessage.fromData(sealedData);\n }\n } catch {\n // Fall through to error\n }\n throw EnvelopeError.general(\"Invalid recipient sealed message format\");\n }\n });\n };\n\n /**\n * Decrypts the envelope's subject using the recipient's private key.\n *\n * This method:\n * 1. Finds all `hasRecipient` assertions\n * 2. Tries to decrypt each sealed message until one succeeds\n * 3. Uses the recovered content key to decrypt the subject\n *\n * @param recipient - The recipient's private key (implements Decrypter)\n * @returns A new envelope with decrypted subject\n */\n Envelope.prototype.decryptSubjectToRecipient = function (\n this: Envelope,\n recipient: Decrypter,\n ): Envelope {\n // Check that the subject is encrypted\n const subjectCase = this.subject().case();\n if (subjectCase.type !== \"encrypted\") {\n throw EnvelopeError.general(\"Subject is not encrypted\");\n }\n\n // Get all sealed messages from recipient assertions\n const sealedMessages = this.recipients();\n\n if (sealedMessages.length === 0) {\n throw EnvelopeError.general(\"No recipients found\");\n }\n\n // Try each sealed message until one decrypts successfully\n let contentKeyData: Uint8Array | null = null;\n\n for (const sealedMessage of sealedMessages) {\n try {\n contentKeyData = sealedMessage.decrypt(recipient);\n break; // Success!\n } catch {\n // Not for us, try next one\n continue;\n }\n }\n\n if (contentKeyData === null) {\n throw EnvelopeError.general(\"Not a valid recipient\");\n }\n\n // Create SymmetricKey from the decrypted content key\n const contentKey = SymmetricKey.from(contentKeyData);\n\n // Decrypt the subject using the content key\n return this.decryptSubject(contentKey);\n };\n\n /**\n * Decrypts an envelope that was encrypted to a recipient and unwraps it.\n *\n * This is a convenience method that:\n * 1. Decrypts the subject using the recipient's private key\n * 2. Unwraps the resulting envelope\n *\n * @param recipient - The recipient's private key (implements Decrypter)\n * @returns The unwrapped, decrypted envelope\n */\n Envelope.prototype.decryptToRecipient = function (\n this: Envelope,\n recipient: Decrypter,\n ): Envelope {\n const decrypted = this.decryptSubjectToRecipient(recipient);\n return decrypted.unwrap();\n };\n\n /**\n * Wraps and encrypts an envelope to multiple recipients.\n *\n * @param recipients - Array of recipient public keys (each implements Encrypter)\n * @returns A wrapped and encrypted envelope\n */\n Envelope.prototype.encryptToRecipients = function (\n this: Envelope,\n recipients: Encrypter[],\n ): Envelope {\n return this.wrap().encryptSubjectToRecipients(recipients);\n };\n}\n\n// Import side-effect to register prototype extensions\nexport {};\n","import { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\n\n/// Extension for envelope expressions.\n///\n/// This module implements the Gordian Envelope expression syntax as specified\n/// in BCR-2023-012. Expressions enable encoding of machine-evaluatable\n/// expressions using envelopes, providing a foundation for distributed\n/// function calls and computation.\n///\n/// ## Expression Structure\n///\n/// An expression consists of:\n/// - A function identifier (the subject)\n/// - Zero or more parameters (as assertions)\n/// - Optional metadata (non-parameter assertions)\n///\n/// ## CBOR Tags\n///\n/// - Function: #6.40006\n/// - Parameter: #6.40007\n/// - Placeholder: #6.40008\n/// - Replacement: #6.40009\n///\n/// @example\n/// ```typescript\n/// // Create a simple addition expression: add(lhs: 2, rhs: 3)\n/// const expr = new Function('add')\n/// .withParameter('lhs', 2)\n/// .withParameter('rhs', 3);\n///\n/// const envelope = expr.envelope();\n/// ```\n\n/// CBOR tag for function identifiers\nexport const CBOR_TAG_FUNCTION = 40006;\n\n/// CBOR tag for parameter identifiers\nexport const CBOR_TAG_PARAMETER = 40007;\n\n/// CBOR tag for placeholder identifiers\nexport const CBOR_TAG_PLACEHOLDER = 40008;\n\n/// CBOR tag for replacement identifiers\nexport const CBOR_TAG_REPLACEMENT = 40009;\n\n/// Well-known function identifiers (numeric)\nexport const FUNCTION_IDS = {\n ADD: 1, // addition\n SUB: 2, // subtraction\n MUL: 3, // multiplication\n DIV: 4, // division\n NEG: 5, // unary negation\n LT: 6, // less than\n LE: 7, // less than or equal\n GT: 8, // greater than\n GE: 9, // greater than or equal\n EQ: 10, // equal to\n NE: 11, // not equal to\n AND: 12, // logical and\n OR: 13, // logical or\n XOR: 14, // logical xor\n NOT: 15, // logical not\n} as const;\n\n/// Well-known parameter identifiers (numeric)\nexport const PARAMETER_IDS = {\n BLANK: 1, // blank/implicit parameter (_)\n LHS: 2, // left-hand side\n RHS: 3, // right-hand side\n} as const;\n\n/// Type for function identifier (number or string)\nexport type FunctionID = number | string;\n\n/// Type for parameter identifier (number or string)\nexport type ParameterID = number | string;\n\n//------------------------------------------------------------------------------\n// Function class - matches Rust's Function enum\n//------------------------------------------------------------------------------\n\n/// Type tag for function variant\ntype FunctionVariant = \"known\" | \"named\";\n\n/// Represents a function identifier in an expression.\n///\n/// In Gordian Envelope, a function appears as the subject of an expression\n/// envelope, with its parameters as assertions on that envelope.\n///\n/// Functions can be identified in two ways:\n/// 1. By a numeric ID (for well-known functions) - Known variant\n/// 2. By a string name (for application-specific functions) - Named variant\n///\n/// When encoded in CBOR, functions are tagged with #6.40006.\nexport class Function implements EnvelopeEncodable {\n private readonly _variant: FunctionVariant;\n private readonly _value: number; // Only used for 'known' variant\n private readonly _name: string | undefined;\n\n private constructor(variant: FunctionVariant, value: number, name?: string) {\n this._variant = variant;\n this._value = value;\n this._name = name;\n }\n\n /// Creates a new known function with a numeric ID and optional name.\n static newKnown(value: number, name?: string): Function {\n return new Function(\"known\", value, name);\n }\n\n /// Creates a new named function identified by a string.\n static newNamed(name: string): Function {\n return new Function(\"named\", 0, name);\n }\n\n /// Creates a function from a numeric ID (convenience method).\n static fromNumeric(id: number): Function {\n return Function.newKnown(id);\n }\n\n /// Creates a function from a string name (convenience method).\n static fromString(name: string): Function {\n return Function.newNamed(name);\n }\n\n /// Returns true if this is a known (numeric) function.\n isKnown(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a named (string) function.\n isNamed(): boolean {\n return this._variant === \"named\";\n }\n\n /// Returns the numeric value for known functions.\n value(): number | undefined {\n return this._variant === \"known\" ? this._value : undefined;\n }\n\n /// Returns the function identifier (number for known, string for named).\n id(): FunctionID {\n if (this._variant === \"known\") {\n return this._value;\n }\n // For named variant, name is always set during construction\n if (this._name === undefined) {\n throw new Error(\"Invalid named function: missing name\");\n }\n return this._name;\n }\n\n /// Returns the display name of the function.\n ///\n /// For known functions with a name, returns the name.\n /// For known functions without a name, returns the numeric ID as a string.\n /// For named functions, returns the name enclosed in quotes.\n name(): string {\n if (this._variant === \"known\") {\n return this._name ?? this._value.toString();\n } else {\n return `\"${this._name}\"`;\n }\n }\n\n /// Returns the raw name for named functions, or undefined for known functions.\n namedName(): string | undefined {\n return this._variant === \"named\" ? this._name : undefined;\n }\n\n /// Returns the assigned name if present (for known functions only).\n assignedName(): string | undefined {\n return this._variant === \"known\" ? this._name : undefined;\n }\n\n /// Returns true if this is a numeric function ID (legacy compatibility).\n isNumeric(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a string function ID (legacy compatibility).\n isString(): boolean {\n return this._variant === \"named\";\n }\n\n /// Creates an expression envelope with this function as the subject.\n envelope(): Envelope {\n const functionStr = this._variant === \"known\" ? `«${this._value}»` : `«\"${this._name}\"»`;\n return Envelope.new(functionStr);\n }\n\n /// Converts this function into an envelope (EnvelopeEncodable implementation).\n intoEnvelope(): Envelope {\n return this.envelope();\n }\n\n /// Creates an expression with a parameter.\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Expression {\n const expr = new Expression(this);\n return expr.withParameter(param, value);\n }\n\n /// Checks equality based on value (for known) or name (for named).\n equals(other: Function): boolean {\n if (this._variant !== other._variant) return false;\n if (this._variant === \"known\") {\n return this._value === other._value;\n } else {\n return this._name === other._name;\n }\n }\n\n /// Returns a hash code for this function.\n hashCode(): number {\n if (this._variant === \"known\") {\n return this._value;\n } else {\n // Simple string hash\n let hash = 0;\n for (let i = 0; i < (this._name?.length ?? 0); i++) {\n hash = (hash * 31 + (this._name?.charCodeAt(i) ?? 0)) | 0;\n }\n return hash;\n }\n }\n\n /// Returns a string representation for display.\n toString(): string {\n return this._variant === \"known\" ? `«${this._value}»` : `«\"${this._name}\"»`;\n }\n}\n\n//------------------------------------------------------------------------------\n// FunctionsStore class - matches Rust's FunctionsStore\n//------------------------------------------------------------------------------\n\n/// A store that maps functions to their assigned names.\n///\n/// FunctionsStore maintains a registry of functions and their human-readable\n/// names, which is useful for displaying and debugging expression functions.\nexport class FunctionsStore {\n private readonly _dict = new Map<number | string, Function>();\n\n /// Creates a new FunctionsStore with the given functions.\n constructor(functions: Iterable<Function> = []) {\n for (const func of functions) {\n this.insert(func);\n }\n }\n\n /// Inserts a function into the store.\n insert(func: Function): void {\n if (func.isKnown()) {\n const value = func.value();\n if (value !== undefined) {\n this._dict.set(value, func);\n }\n } else {\n const name = func.namedName();\n if (name !== undefined) {\n this._dict.set(name, func);\n }\n }\n }\n\n /// Returns the assigned name for a function, if it exists in the store.\n assignedName(func: Function): string | undefined {\n let key: number | string | undefined;\n if (func.isKnown()) {\n key = func.value();\n } else {\n key = func.namedName();\n }\n if (key === undefined) return undefined;\n const stored = this._dict.get(key);\n return stored?.assignedName();\n }\n\n /// Returns the name for a function, either from this store or from the function itself.\n name(func: Function): string {\n const assigned = this.assignedName(func);\n return assigned ?? func.name();\n }\n\n /// Static method that returns the name of a function, using an optional store.\n static nameForFunction(func: Function, store?: FunctionsStore): string {\n if (store !== undefined) {\n const assigned = store.assignedName(func);\n if (assigned !== undefined && assigned !== \"\") return assigned;\n }\n return func.name();\n }\n}\n\n//------------------------------------------------------------------------------\n// Parameter class - matches Rust's Parameter enum\n//------------------------------------------------------------------------------\n\n/// Type tag for parameter variant\ntype ParameterVariant = \"known\" | \"named\";\n\n/// Represents a parameter identifier in an expression.\n///\n/// In Gordian Envelope, a parameter appears as a predicate in an assertion on\n/// an expression envelope. The parameter identifies the name of the argument,\n/// and the object of the assertion is the argument value.\n///\n/// Parameters can be identified in two ways:\n/// 1. By a numeric ID (for well-known parameters) - Known variant\n/// 2. By a string name (for application-specific parameters) - Named variant\n///\n/// When encoded in CBOR, parameters are tagged with #6.40007.\nexport class Parameter implements EnvelopeEncodable {\n private readonly _variant: ParameterVariant;\n private readonly _value: number; // Only used for 'known' variant, or 0 for 'named'\n private readonly _name: string | undefined;\n private readonly _paramValue: Envelope | undefined; // The parameter's value envelope\n\n private constructor(\n variant: ParameterVariant,\n value: number,\n name?: string,\n paramValue?: Envelope,\n ) {\n this._variant = variant;\n this._value = value;\n this._name = name;\n this._paramValue = paramValue;\n }\n\n /// Creates a new known parameter with a numeric ID and optional name.\n static newKnown(value: number, name?: string): Parameter {\n return new Parameter(\"known\", value, name);\n }\n\n /// Creates a new named parameter identified by a string.\n static newNamed(name: string): Parameter {\n return new Parameter(\"named\", 0, name);\n }\n\n /// Creates a parameter with a value envelope (internal use).\n static withValue(id: ParameterID, value: Envelope): Parameter {\n if (typeof id === \"number\") {\n return new Parameter(\"known\", id, undefined, value);\n } else {\n return new Parameter(\"named\", 0, id, value);\n }\n }\n\n /// Returns true if this is a known (numeric) parameter.\n isKnown(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a named (string) parameter.\n isNamed(): boolean {\n return this._variant === \"named\";\n }\n\n /// Returns the numeric value for known parameters.\n value(): number | undefined {\n return this._variant === \"known\" ? this._value : undefined;\n }\n\n /// Returns the parameter identifier (number for known, string for named).\n id(): ParameterID {\n if (this._variant === \"known\") {\n return this._value;\n }\n // For named variant, name is always set during construction\n if (this._name === undefined) {\n throw new Error(\"Invalid named parameter: missing name\");\n }\n return this._name;\n }\n\n /// Returns the display name of the parameter.\n ///\n /// For known parameters with a name, returns the name.\n /// For known parameters without a name, returns the numeric ID as a string.\n /// For named parameters, returns the name enclosed in quotes.\n name(): string {\n if (this._variant === \"known\") {\n return this._name ?? this._value.toString();\n } else {\n return `\"${this._name}\"`;\n }\n }\n\n /// Returns the raw name for named parameters, or undefined for known parameters.\n namedName(): string | undefined {\n return this._variant === \"named\" ? this._name : undefined;\n }\n\n /// Returns the assigned name if present (for known parameters only).\n assignedName(): string | undefined {\n return this._variant === \"known\" ? this._name : undefined;\n }\n\n /// Returns the parameter value as an envelope, if set.\n paramValue(): Envelope | undefined {\n return this._paramValue;\n }\n\n /// Returns true if this is a numeric parameter ID (legacy compatibility).\n isNumeric(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a string parameter ID (legacy compatibility).\n isString(): boolean {\n return this._variant === \"named\";\n }\n\n /// Creates a parameter envelope.\n envelope(): Envelope {\n const paramStr = this._variant === \"known\" ? `❰${this._value}❱` : `❰\"${this._name}\"❱`;\n if (this._paramValue !== undefined) {\n return Envelope.newAssertion(paramStr, this._paramValue);\n }\n return Envelope.new(paramStr);\n }\n\n /// Converts this parameter into an envelope (EnvelopeEncodable implementation).\n intoEnvelope(): Envelope {\n return this.envelope();\n }\n\n /// Checks equality based on value (for known) or name (for named).\n equals(other: Parameter): boolean {\n if (this._variant !== other._variant) return false;\n if (this._variant === \"known\") {\n return this._value === other._value;\n } else {\n return this._name === other._name;\n }\n }\n\n /// Returns a hash code for this parameter.\n hashCode(): number {\n if (this._variant === \"known\") {\n return this._value;\n } else {\n let hash = 0;\n for (let i = 0; i < (this._name?.length ?? 0); i++) {\n hash = (hash * 31 + (this._name?.charCodeAt(i) ?? 0)) | 0;\n }\n return hash;\n }\n }\n\n /// Returns a string representation for display.\n toString(): string {\n const idStr = this._variant === \"known\" ? `❰${this._value}❱` : `❰\"${this._name}\"❱`;\n if (this._paramValue !== undefined) {\n return `${idStr}: ${this._paramValue.asText()}`;\n }\n return idStr;\n }\n\n // Convenience static methods for standard parameters\n static blank(value: EnvelopeEncodableValue): Parameter {\n return Parameter.withValue(PARAMETER_IDS.BLANK, Envelope.new(value));\n }\n\n static lhs(value: EnvelopeEncodableValue): Parameter {\n return Parameter.withValue(PARAMETER_IDS.LHS, Envelope.new(value));\n }\n\n static rhs(value: EnvelopeEncodableValue): Parameter {\n return Parameter.withValue(PARAMETER_IDS.RHS, Envelope.new(value));\n }\n}\n\n//------------------------------------------------------------------------------\n// ParametersStore class - matches Rust's ParametersStore\n//------------------------------------------------------------------------------\n\n/// A store that maps parameters to their assigned names.\n///\n/// ParametersStore maintains a registry of parameters and their human-readable\n/// names, which is useful for displaying and debugging expression parameters.\nexport class ParametersStore {\n private readonly _dict = new Map<number | string, Parameter>();\n\n /// Creates a new ParametersStore with the given parameters.\n constructor(parameters: Iterable<Parameter> = []) {\n for (const param of parameters) {\n this.insert(param);\n }\n }\n\n /// Inserts a parameter into the store.\n insert(param: Parameter): void {\n if (param.isKnown()) {\n const value = param.value();\n if (value !== undefined) {\n this._dict.set(value, param);\n }\n } else {\n const name = param.namedName();\n if (name !== undefined) {\n this._dict.set(name, param);\n }\n }\n }\n\n /// Returns the assigned name for a parameter, if it exists in the store.\n assignedName(param: Parameter): string | undefined {\n let key: number | string | undefined;\n if (param.isKnown()) {\n key = param.value();\n } else {\n key = param.namedName();\n }\n if (key === undefined) return undefined;\n const stored = this._dict.get(key);\n return stored?.assignedName();\n }\n\n /// Returns the name for a parameter, either from this store or from the parameter itself.\n name(param: Parameter): string {\n const assigned = this.assignedName(param);\n return assigned ?? param.name();\n }\n\n /// Static method that returns the name of a parameter, using an optional store.\n static nameForParameter(param: Parameter, store?: ParametersStore): string {\n if (store !== undefined) {\n const assigned = store.assignedName(param);\n if (assigned !== undefined && assigned !== \"\") return assigned;\n }\n return param.name();\n }\n}\n\n//------------------------------------------------------------------------------\n// Well-known function constants (matching Rust's function_constant! macro)\n//------------------------------------------------------------------------------\n\n/// Standard arithmetic and logical functions\nexport const ADD = Function.newKnown(FUNCTION_IDS.ADD, \"add\");\nexport const SUB = Function.newKnown(FUNCTION_IDS.SUB, \"sub\");\nexport const MUL = Function.newKnown(FUNCTION_IDS.MUL, \"mul\");\nexport const DIV = Function.newKnown(FUNCTION_IDS.DIV, \"div\");\nexport const NEG = Function.newKnown(FUNCTION_IDS.NEG, \"neg\");\nexport const LT = Function.newKnown(FUNCTION_IDS.LT, \"lt\");\nexport const LE = Function.newKnown(FUNCTION_IDS.LE, \"le\");\nexport const GT = Function.newKnown(FUNCTION_IDS.GT, \"gt\");\nexport const GE = Function.newKnown(FUNCTION_IDS.GE, \"ge\");\nexport const EQ = Function.newKnown(FUNCTION_IDS.EQ, \"eq\");\nexport const NE = Function.newKnown(FUNCTION_IDS.NE, \"ne\");\nexport const AND = Function.newKnown(FUNCTION_IDS.AND, \"and\");\nexport const OR = Function.newKnown(FUNCTION_IDS.OR, \"or\");\nexport const XOR = Function.newKnown(FUNCTION_IDS.XOR, \"xor\");\nexport const NOT = Function.newKnown(FUNCTION_IDS.NOT, \"not\");\n\n/// Raw value constants (matching Rust's _VALUE suffix constants)\nexport const ADD_VALUE = FUNCTION_IDS.ADD;\nexport const SUB_VALUE = FUNCTION_IDS.SUB;\nexport const MUL_VALUE = FUNCTION_IDS.MUL;\nexport const DIV_VALUE = FUNCTION_IDS.DIV;\nexport const NEG_VALUE = FUNCTION_IDS.NEG;\nexport const LT_VALUE = FUNCTION_IDS.LT;\nexport const LE_VALUE = FUNCTION_IDS.LE;\nexport const GT_VALUE = FUNCTION_IDS.GT;\nexport const GE_VALUE = FUNCTION_IDS.GE;\nexport const EQ_VALUE = FUNCTION_IDS.EQ;\nexport const NE_VALUE = FUNCTION_IDS.NE;\nexport const AND_VALUE = FUNCTION_IDS.AND;\nexport const OR_VALUE = FUNCTION_IDS.OR;\nexport const XOR_VALUE = FUNCTION_IDS.XOR;\nexport const NOT_VALUE = FUNCTION_IDS.NOT;\n\n//------------------------------------------------------------------------------\n// Well-known parameter constants (matching Rust's parameter_constant! macro)\n//------------------------------------------------------------------------------\n\n/// Standard parameters\nexport const BLANK = Parameter.newKnown(PARAMETER_IDS.BLANK, \"_\");\nexport const LHS = Parameter.newKnown(PARAMETER_IDS.LHS, \"lhs\");\nexport const RHS = Parameter.newKnown(PARAMETER_IDS.RHS, \"rhs\");\n\n/// Raw value constants\nexport const BLANK_VALUE = PARAMETER_IDS.BLANK;\nexport const LHS_VALUE = PARAMETER_IDS.LHS;\nexport const RHS_VALUE = PARAMETER_IDS.RHS;\n\n//------------------------------------------------------------------------------\n// Global stores (matching Rust's GLOBAL_FUNCTIONS and GLOBAL_PARAMETERS)\n//------------------------------------------------------------------------------\n\n/// Lazy initialization helper for global stores\nexport class LazyStore<T> {\n private _store: T | undefined;\n private readonly _initializer: () => T;\n\n constructor(initializer: () => T) {\n this._initializer = initializer;\n }\n\n get(): T {\n this._store ??= this._initializer();\n return this._store;\n }\n}\n\n/// The global shared store of known functions.\nexport const GLOBAL_FUNCTIONS = new LazyStore(\n () => new FunctionsStore([ADD, SUB, MUL, DIV, NEG, LT, LE, GT, GE, EQ, NE, AND, OR, XOR, NOT]),\n);\n\n/// The global shared store of known parameters.\nexport const GLOBAL_PARAMETERS = new LazyStore(() => new ParametersStore([BLANK, LHS, RHS]));\n\n//------------------------------------------------------------------------------\n// Expression class\n//------------------------------------------------------------------------------\n\n/// Represents a complete expression with function and parameters.\nexport class Expression implements EnvelopeEncodable {\n private readonly _function: Function;\n private readonly _parameters = new Map<string, Parameter>();\n private _envelope: Envelope | null = null;\n\n constructor(func: Function) {\n this._function = func;\n }\n\n /// Returns the function.\n function(): Function {\n return this._function;\n }\n\n /// Returns all parameters.\n parameters(): Parameter[] {\n return Array.from(this._parameters.values());\n }\n\n /// Adds a parameter to the expression.\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Expression {\n const key = typeof param === \"number\" ? param.toString() : param;\n this._parameters.set(key, Parameter.withValue(param, Envelope.new(value)));\n this._envelope = null; // Invalidate cached envelope\n return this;\n }\n\n /// Adds multiple parameters at once.\n withParameters(params: Record<string, EnvelopeEncodableValue>): Expression {\n for (const [key, value] of Object.entries(params)) {\n this.withParameter(key, value);\n }\n return this;\n }\n\n /// Gets a parameter value by ID.\n getParameter(param: ParameterID): Envelope | undefined {\n const key = typeof param === \"number\" ? param.toString() : param;\n return this._parameters.get(key)?.paramValue();\n }\n\n /// Checks if a parameter exists.\n hasParameter(param: ParameterID): boolean {\n const key = typeof param === \"number\" ? param.toString() : param;\n return this._parameters.has(key);\n }\n\n /// Converts the expression to an envelope.\n envelope(): Envelope {\n if (this._envelope !== null) {\n return this._envelope;\n }\n\n // Start with function envelope\n let env = this._function.envelope();\n\n // Add all parameters as assertions\n for (const param of this._parameters.values()) {\n const paramEnv = param.envelope();\n // The paramEnv is itself an assertion envelope - extract predicate and object directly\n const paramCase = paramEnv.case();\n if (paramCase.type === \"assertion\") {\n const predicate = paramCase.assertion.predicate();\n const object = paramCase.assertion.object();\n const predText = predicate.asText();\n if (predText !== undefined) {\n env = env.addAssertion(predText, object);\n }\n }\n }\n\n this._envelope = env;\n return env;\n }\n\n /// Converts this expression into an envelope (EnvelopeEncodable implementation).\n intoEnvelope(): Envelope {\n return this.envelope();\n }\n\n /// Creates an expression from an envelope.\n static fromEnvelope(envelope: Envelope): Expression {\n // Extract function from subject\n const subject = envelope.subject();\n const subjectText = subject.asText();\n if (subjectText === undefined) {\n throw EnvelopeError.general(\"Not a valid function envelope\");\n }\n\n // Parse function identifier\n let func: Function;\n if (subjectText.startsWith(\"«\") && subjectText.endsWith(\"»\")) {\n const inner = subjectText.slice(1, -1);\n if (inner.startsWith('\"') && inner.endsWith('\"')) {\n func = Function.newNamed(inner.slice(1, -1));\n } else {\n func = Function.newKnown(parseInt(inner, 10));\n }\n } else {\n throw EnvelopeError.general(\"Not a valid function envelope\");\n }\n\n const expr = new Expression(func);\n\n // Extract parameters from assertions\n for (const assertion of envelope.assertions()) {\n try {\n const pred = assertion.subject().asPredicate();\n const obj = assertion.asObject();\n\n if (pred !== undefined && obj !== undefined) {\n const predText = pred.asText();\n if (predText !== undefined && predText.startsWith(\"❰\") && predText.endsWith(\"❱\")) {\n const inner = predText.slice(1, -1);\n let paramId: ParameterID;\n if (inner.startsWith('\"') && inner.endsWith('\"')) {\n paramId = inner.slice(1, -1);\n } else {\n paramId = parseInt(inner, 10);\n }\n expr.withParameter(paramId, obj);\n }\n }\n } catch {\n // Skip non-parameter assertions\n continue;\n }\n }\n\n return expr;\n }\n\n /// Returns a string representation for display.\n toString(): string {\n const params = Array.from(this._parameters.values())\n .map((p) => p.toString())\n .join(\", \");\n return `${this._function.toString()} [${params}]`;\n }\n}\n\n//------------------------------------------------------------------------------\n// Helper functions for creating common expressions\n//------------------------------------------------------------------------------\n\n/// Creates an addition expression: lhs + rhs\nexport function add(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(ADD)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a subtraction expression: lhs - rhs\nexport function sub(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(SUB)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a multiplication expression: lhs * rhs\nexport function mul(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(MUL)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a division expression: lhs / rhs\nexport function div(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(DIV)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a negation expression: -value\nexport function neg(value: EnvelopeEncodableValue): Expression {\n return new Expression(NEG).withParameter(PARAMETER_IDS.BLANK, value);\n}\n\n/// Creates a less-than expression: lhs < rhs\nexport function lt(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(LT)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a less-than-or-equal expression: lhs <= rhs\nexport function le(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(LE)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a greater-than expression: lhs > rhs\nexport function gt(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(GT)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a greater-than-or-equal expression: lhs >= rhs\nexport function ge(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(GE)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates an equality expression: lhs == rhs\nexport function eq(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(EQ)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a not-equal expression: lhs != rhs\nexport function ne(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(NE)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical AND expression: lhs && rhs\nexport function and(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(AND)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical OR expression: lhs || rhs\nexport function or(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(OR)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical XOR expression: lhs ^ rhs\nexport function xor(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(XOR)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical NOT expression: !value\nexport function not(value: EnvelopeEncodableValue): Expression {\n return new Expression(NOT).withParameter(PARAMETER_IDS.BLANK, value);\n}\n","import { Envelope } from \"../base/envelope\";\nimport { type Digest } from \"../base/digest\";\n\n/// Extension for envelope inclusion proofs.\n///\n/// Inclusion proofs allow a holder of an envelope to prove that specific\n/// elements exist within the envelope without revealing the entire contents.\n/// This is particularly useful for selective disclosure of information in\n/// privacy-preserving scenarios.\n///\n/// ## How Inclusion Proofs Work\n///\n/// The inclusion proof mechanism leverages the Merkle-like digest tree\n/// structure of envelopes:\n/// - The holder creates a minimal structure containing only the digests\n/// necessary to validate the proof\n/// - A verifier with a trusted root digest can confirm that the specific\n/// elements exist in the original envelope\n/// - All other content can remain elided, preserving privacy\n///\n/// For enhanced privacy, elements can be salted to prevent correlation attacks.\n///\n/// @example\n/// ```typescript\n/// // Create an envelope with multiple assertions\n/// const aliceFriends = Envelope.new('Alice')\n/// .addAssertion('knows', 'Bob')\n/// .addAssertion('knows', 'Carol')\n/// .addAssertion('knows', 'Dan');\n///\n/// // Create a representation of just the root digest\n/// const aliceFriendsRoot = aliceFriends.elideRevealingSet(new Set());\n///\n/// // Create the target we want to prove exists\n/// const knowsBobAssertion = Envelope.newAssertion('knows', 'Bob');\n///\n/// // Generate a proof that Alice knows Bob\n/// const aliceKnowsBobProof = aliceFriends.proofContainsTarget(knowsBobAssertion);\n///\n/// // A third party can verify the proof against the trusted root\n/// if (aliceKnowsBobProof) {\n/// const isValid = aliceFriendsRoot.confirmContainsTarget(\n/// knowsBobAssertion,\n/// aliceKnowsBobProof\n/// );\n/// console.log('Proof is valid:', isValid);\n/// }\n/// ```\n\n/// Implementation of proof methods on Envelope prototype\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.proofContainsSet = function (target: Set<Digest>): Envelope | undefined {\n const revealSet = revealSetOfSet(this, target);\n\n // Check if all targets can be revealed\n if (!isSubset(target, revealSet)) {\n return undefined;\n }\n\n // Create a proof by revealing only what's necessary, then eliding the targets\n const revealed = this.elideRevealingSet(revealSet);\n return revealed.elideRemovingSet(target);\n };\n\n Envelope.prototype.proofContainsTarget = function (target: Envelope): Envelope | undefined {\n const targetSet = new Set<Digest>([target.digest()]);\n return this.proofContainsSet(targetSet);\n };\n\n Envelope.prototype.confirmContainsSet = function (target: Set<Digest>, proof: Envelope): boolean {\n // Verify the proof has the same digest as this envelope\n if (this.digest().hex() !== proof.digest().hex()) {\n return false;\n }\n\n // Verify the proof contains all target elements\n return containsAll(proof, target);\n };\n\n Envelope.prototype.confirmContainsTarget = function (target: Envelope, proof: Envelope): boolean {\n const targetSet = new Set<Digest>([target.digest()]);\n return this.confirmContainsSet(targetSet, proof);\n };\n}\n\n/// Internal helper functions\n\n/// Builds a set of all digests needed to reveal the target set.\n///\n/// This collects all digests in the path from the envelope's root to each\n/// target element.\nfunction revealSetOfSet(envelope: Envelope, target: Set<Digest>): Set<Digest> {\n const result = new Set<Digest>();\n revealSets(envelope, target, new Set<Digest>(), result);\n return result;\n}\n\n/// Recursively traverses the envelope to collect all digests needed to\n/// reveal the target set.\n///\n/// Builds the set of digests forming the path from the root to each target element.\nfunction revealSets(\n envelope: Envelope,\n target: Set<Digest>,\n current: Set<Digest>,\n result: Set<Digest>,\n): void {\n // Add current envelope's digest to the path\n const newCurrent = new Set(current);\n newCurrent.add(envelope.digest());\n\n // If this is a target, add the entire path to the result\n if (containsDigest(target, envelope.digest())) {\n for (const digest of newCurrent) {\n result.add(digest);\n }\n }\n\n // Traverse the envelope structure\n const envelopeCase = envelope.case();\n\n if (envelopeCase.type === \"node\") {\n // Traverse subject\n revealSets(envelopeCase.subject, target, newCurrent, result);\n\n // Traverse all assertions\n for (const assertion of envelopeCase.assertions) {\n revealSets(assertion, target, newCurrent, result);\n }\n } else if (envelopeCase.type === \"wrapped\") {\n // Traverse wrapped envelope\n revealSets(envelopeCase.envelope, target, newCurrent, result);\n } else if (envelopeCase.type === \"assertion\") {\n // Traverse predicate and object\n const predicate = envelopeCase.assertion.predicate();\n const object = envelopeCase.assertion.object();\n revealSets(predicate, target, newCurrent, result);\n revealSets(object, target, newCurrent, result);\n }\n // For leaf envelopes (elided, encrypted, compressed, leaf), no further traversal needed\n}\n\n/// Checks if this envelope contains all elements in the target set.\n///\n/// Used during proof verification to confirm all target elements exist in the proof.\nfunction containsAll(envelope: Envelope, target: Set<Digest>): boolean {\n const targetCopy = new Set(target);\n removeAllFound(envelope, targetCopy);\n return targetCopy.size === 0;\n}\n\n/// Recursively traverses the envelope and removes found target elements from the set.\n///\n/// Used during proof verification to confirm all target elements are present.\nfunction removeAllFound(envelope: Envelope, target: Set<Digest>): void {\n // Check if this envelope's digest is in the target set\n if (containsDigest(target, envelope.digest())) {\n removeDigest(target, envelope.digest());\n }\n\n // Early exit if all targets found\n if (target.size === 0) {\n return;\n }\n\n // Traverse the envelope structure\n const envelopeCase = envelope.case();\n\n if (envelopeCase.type === \"node\") {\n // Traverse subject\n removeAllFound(envelopeCase.subject, target);\n\n // Traverse all assertions\n for (const assertion of envelopeCase.assertions) {\n removeAllFound(assertion, target);\n if (target.size === 0) break;\n }\n } else if (envelopeCase.type === \"wrapped\") {\n // Traverse wrapped envelope\n removeAllFound(envelopeCase.envelope, target);\n } else if (envelopeCase.type === \"assertion\") {\n // Traverse predicate and object\n const predicate = envelopeCase.assertion.predicate();\n const object = envelopeCase.assertion.object();\n removeAllFound(predicate, target);\n if (target.size > 0) {\n removeAllFound(object, target);\n }\n }\n // For leaf envelopes (elided, encrypted, compressed, leaf), no further traversal needed\n}\n\n/// Helper function to check if a set contains a digest (by hex comparison)\nfunction containsDigest(set: Set<Digest>, digest: Digest): boolean {\n const hexToFind = digest.hex();\n for (const d of set) {\n if (d.hex() === hexToFind) {\n return true;\n }\n }\n return false;\n}\n\n/// Helper function to remove a digest from a set (by hex comparison)\nfunction removeDigest(set: Set<Digest>, digest: Digest): void {\n const hexToFind = digest.hex();\n for (const d of set) {\n if (d.hex() === hexToFind) {\n set.delete(d);\n return;\n }\n }\n}\n\n/// Helper function to check if one set is a subset of another (by hex comparison)\nfunction isSubset(subset: Set<Digest>, superset: Set<Digest>): boolean {\n for (const digest of subset) {\n if (!containsDigest(superset, digest)) {\n return false;\n }\n }\n return true;\n}\n\n/// Register proof extension on Envelope prototype.\n/// This function is exported to allow explicit registration.\nexport function registerProofExtension(): void {\n // Methods are already registered above when this module loads\n}\n","/// Secret-based envelope locking and unlocking.\n///\n/// This module provides functionality for encrypting envelope subjects using\n/// password-based or key-based derivation methods, allowing envelopes to be\n/// locked with secrets and later unlocked.\n///\n/// The implementation uses `EncryptedKey` from bc-components for key\n/// derivation and encryption.\n\nimport {\n SymmetricKey as ComponentsSymmetricKey,\n EncryptedKey,\n type KeyDerivationMethod,\n} from \"@bcts/components\";\nimport { HAS_SECRET } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SymmetricKey } from \"./encrypt\";\n\n// ============================================================================\n// Envelope Prototype Extensions for Secret Locking\n// ============================================================================\n\n/// Implementation of lockSubject\nEnvelope.prototype.lockSubject = function (\n this: Envelope,\n method: KeyDerivationMethod,\n secret: Uint8Array,\n): Envelope {\n // Generate a new content key using local SymmetricKey\n const contentKey = SymmetricKey.new();\n\n // Convert to components SymmetricKey for EncryptedKey.lock\n const componentsKey = ComponentsSymmetricKey.fromData(contentKey.data());\n\n // Lock the content key using the specified derivation method\n const encryptedKey = EncryptedKey.lock(method, secret, componentsKey);\n\n // Encrypt the subject and add the hasSecret assertion\n const encrypted = this.encryptSubject(contentKey);\n return encrypted.addAssertion(HAS_SECRET, encryptedKey);\n};\n\n/// Implementation of unlockSubject\nEnvelope.prototype.unlockSubject = function (this: Envelope, secret: Uint8Array): Envelope {\n // Find all hasSecret assertions\n const assertions = this.assertionsWithPredicate(HAS_SECRET);\n\n // Try each one until we find one that unlocks\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n // Skip obscured (elided/encrypted/compressed) assertions\n if (obj.isObscured()) continue;\n\n try {\n // Try to extract the EncryptedKey\n const encryptedKey = obj.extractSubject((cbor) => EncryptedKey.fromTaggedCbor(cbor));\n\n // Try to unlock with the provided secret (returns ComponentsSymmetricKey)\n const componentsKey = encryptedKey.unlock(secret);\n\n // Convert to local SymmetricKey for decryptSubject\n const contentKey = SymmetricKey.from(componentsKey.data());\n\n // If successful, decrypt the subject\n return this.decryptSubject(contentKey);\n } catch {\n // This assertion didn't work, try the next one\n continue;\n }\n }\n\n // No matching secret found\n throw EnvelopeError.unknownSecret();\n};\n\n/// Implementation of isLockedWithPassword\nEnvelope.prototype.isLockedWithPassword = function (this: Envelope): boolean {\n const assertions = this.assertionsWithPredicate(HAS_SECRET);\n\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n try {\n const encryptedKey = obj.extractSubject((cbor) => EncryptedKey.fromTaggedCbor(cbor));\n if (encryptedKey.isPasswordBased()) {\n return true;\n }\n } catch {\n continue;\n }\n }\n\n return false;\n};\n\n/// Implementation of isLockedWithSshAgent\nEnvelope.prototype.isLockedWithSshAgent = function (this: Envelope): boolean {\n const assertions = this.assertionsWithPredicate(HAS_SECRET);\n\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n try {\n const encryptedKey = obj.extractSubject((cbor) => EncryptedKey.fromTaggedCbor(cbor));\n if (encryptedKey.isSshAgent()) {\n return true;\n }\n } catch {\n continue;\n }\n }\n\n return false;\n};\n\n/// Implementation of addSecret\nEnvelope.prototype.addSecret = function (\n this: Envelope,\n method: KeyDerivationMethod,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n): Envelope {\n // Convert to components SymmetricKey for EncryptedKey.lock\n const componentsKey = ComponentsSymmetricKey.fromData(contentKey.data());\n\n // Lock the content key using the specified derivation method\n const encryptedKey = EncryptedKey.lock(method, secret, componentsKey);\n\n // Add a hasSecret assertion with the EncryptedKey\n return this.addAssertion(HAS_SECRET, encryptedKey);\n};\n\n/// Implementation of lock\nEnvelope.prototype.lock = function (\n this: Envelope,\n method: KeyDerivationMethod,\n secret: Uint8Array,\n): Envelope {\n return this.wrap().lockSubject(method, secret);\n};\n\n/// Implementation of unlock\nEnvelope.prototype.unlock = function (this: Envelope, secret: Uint8Array): Envelope {\n return this.unlockSubject(secret).tryUnwrap();\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the secret extension\nexport const registerSecretExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","/// SSKR-based envelope splitting and joining.\n///\n/// This module provides functionality for splitting encrypted envelopes\n/// using SSKR (Sharded Secret Key Reconstruction), which is an implementation\n/// of Shamir's Secret Sharing. SSKR allows splitting a secret (the symmetric\n/// encryption key) into multiple shares, with a threshold required for\n/// reconstruction.\n///\n/// SSKR provides social recovery for encrypted envelopes by allowing the owner\n/// to distribute shares to trusted individuals or storage locations, with a\n/// specified threshold required to reconstruct the original envelope.\n\nimport {\n SSKRShareCbor,\n SSKRSecret,\n SSKRSpec,\n SSKRGroupSpec,\n sskrGenerateShares,\n sskrCombineShares,\n sskrGenerateUsing,\n} from \"@bcts/components\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SSKR_SHARE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SymmetricKey } from \"./encrypt\";\n\n// Re-export useful types\nexport { SSKRSpec, SSKRGroupSpec, SSKRShareCbor, SSKRSecret };\n\n// ============================================================================\n// Envelope Prototype Extensions for SSKR\n// ============================================================================\n\n/// Helper function to add an SSKR share assertion to the envelope\nconst addSskrShare = (envelope: Envelope, share: SSKRShareCbor): Envelope => {\n return envelope.addAssertion(SSKR_SHARE, share);\n};\n\n/// Implementation of sskrSplit\nEnvelope.prototype.sskrSplit = function (\n this: Envelope,\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n): Envelope[][] {\n // Convert symmetric key to SSKR secret\n const masterSecret = SSKRSecret.new(contentKey.data());\n\n // Generate SSKR shares with CBOR wrappers\n const shareGroups: SSKRShareCbor[][] = sskrGenerateShares(spec, masterSecret);\n\n // Create envelope copies with SSKR share assertions\n const result: Envelope[][] = [];\n for (const group of shareGroups) {\n const groupResult: Envelope[] = [];\n for (const share of group) {\n const shareEnvelope = addSskrShare(this, share);\n groupResult.push(shareEnvelope);\n }\n result.push(groupResult);\n }\n\n return result;\n};\n\n/// Implementation of sskrSplitFlattened\nEnvelope.prototype.sskrSplitFlattened = function (\n this: Envelope,\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n): Envelope[] {\n return this.sskrSplit(spec, contentKey).flat();\n};\n\n/// Implementation of sskrSplitUsing (with custom RNG)\nEnvelope.prototype.sskrSplitUsing = function (\n this: Envelope,\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n rng: RandomNumberGenerator,\n): Envelope[][] {\n // Convert symmetric key to SSKR secret\n const masterSecret = SSKRSecret.new(contentKey.data());\n\n // Generate SSKR shares using custom RNG\n const shareGroups = sskrGenerateUsing(spec, masterSecret, rng);\n\n // Convert raw bytes to SSKRShareCbor and create envelope copies\n const result: Envelope[][] = [];\n for (const group of shareGroups) {\n const groupResult: Envelope[] = [];\n for (const shareData of group) {\n const share = SSKRShareCbor.fromData(shareData);\n const shareEnvelope = addSskrShare(this, share);\n groupResult.push(shareEnvelope);\n }\n result.push(groupResult);\n }\n\n return result;\n};\n\n/// Helper function to extract SSKR shares from envelopes, grouped by identifier\nconst extractSskrSharesGrouped = (envelopes: Envelope[]): Map<number, SSKRShareCbor[]> => {\n const result = new Map<number, SSKRShareCbor[]>();\n\n for (const envelope of envelopes) {\n const assertions = envelope.assertionsWithPredicate(SSKR_SHARE);\n\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n // Skip obscured (elided/encrypted/compressed) assertions\n if (obj.isObscured()) continue;\n\n try {\n // Try to extract the SSKRShareCbor\n const share = obj.extractSubject((cbor) => SSKRShareCbor.fromTaggedCbor(cbor));\n const identifier = share.identifier();\n\n const existing = result.get(identifier);\n if (existing !== undefined) {\n existing.push(share);\n } else {\n result.set(identifier, [share]);\n }\n } catch {\n // This assertion didn't contain a valid SSKR share, skip it\n continue;\n }\n }\n }\n\n return result;\n};\n\n/// Implementation of sskrJoin (static method)\n(Envelope as unknown as { sskrJoin: (envelopes: Envelope[]) => Envelope }).sskrJoin = function (\n envelopes: Envelope[],\n): Envelope {\n if (envelopes.length === 0) {\n throw EnvelopeError.invalidShares();\n }\n\n // Extract and group shares by identifier\n const groupedShares = extractSskrSharesGrouped(envelopes);\n\n // Try each group of shares (shares with same identifier)\n for (const shares of groupedShares.values()) {\n try {\n // Try to combine the shares\n const secret: SSKRSecret = sskrCombineShares(shares);\n\n // Convert secret back to symmetric key (local SymmetricKey uses `from`)\n const contentKey = SymmetricKey.from(secret.getData());\n\n // Try to decrypt the envelope subject\n const decrypted = envelopes[0].decryptSubject(contentKey);\n\n // Return the decrypted subject\n return decrypted.subject();\n } catch {\n // This group of shares didn't work, try the next one\n continue;\n }\n }\n\n // No valid combination found\n throw EnvelopeError.invalidShares();\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the SSKR extension\nexport const registerSskrExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","/**\n * Request type for distributed function calls.\n *\n * Ported from bc-envelope-rust/src/extension/expressions/request.rs\n *\n * A Request represents a message requesting execution of a function with\n * parameters. Requests are part of the expression system that enables\n * distributed function calls and communication between systems.\n *\n * Each request:\n * - Contains a body (an Expression) that represents the function to be executed\n * - Has a unique identifier (ARID) for tracking and correlation\n * - May include optional metadata like a note and timestamp\n *\n * Requests are designed to be paired with Response objects that contain the\n * results of executing the requested function.\n *\n * When serialized to an envelope, requests are tagged with REQUEST tag.\n */\n\nimport { ARID } from \"@bcts/components\";\nimport { REQUEST as TAG_REQUEST } from \"@bcts/tags\";\nimport { toTaggedValue } from \"@bcts/dcbor\";\nimport { BODY, NOTE, DATE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\nimport { Expression, Function, type ParameterID } from \"./expression\";\n\n/**\n * Interface that defines the behavior of a request.\n *\n * This interface extends expression behavior to add methods specific to requests,\n * including metadata management and access to request properties.\n */\nexport interface RequestBehavior {\n /**\n * Adds a parameter to the request.\n */\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Request;\n\n /**\n * Adds a note to the request.\n */\n withNote(note: string): Request;\n\n /**\n * Adds a date to the request.\n */\n withDate(date: Date): Request;\n\n /**\n * Returns the body of the request (the expression to be evaluated).\n */\n body(): Expression;\n\n /**\n * Returns the unique identifier (ARID) of the request.\n */\n id(): ARID;\n\n /**\n * Returns the note attached to the request, or an empty string if none exists.\n */\n note(): string;\n\n /**\n * Returns the date attached to the request, if any.\n */\n date(): Date | undefined;\n\n /**\n * Returns the function of the request.\n */\n function(): Function;\n\n /**\n * Returns the expression envelope of the request.\n */\n expressionEnvelope(): Envelope;\n\n /**\n * Converts the request to an envelope.\n */\n toEnvelope(): Envelope;\n}\n\n/**\n * A Request represents a message requesting execution of a function with parameters.\n *\n * @example\n * ```typescript\n * import { Request, ARID } from '@bcts/envelope';\n *\n * // Create a random request ID\n * const requestId = ARID.new();\n *\n * // Create a request to execute a function with parameters\n * const request = Request.new(\"getBalance\", requestId)\n * .withParameter(\"account\", \"alice\")\n * .withParameter(\"currency\", \"USD\")\n * .withNote(\"Monthly balance check\");\n *\n * // Convert to an envelope\n * const envelope = request.toEnvelope();\n * ```\n */\nexport class Request implements RequestBehavior, EnvelopeEncodable {\n private readonly _body: Expression;\n private readonly _id: ARID;\n private _note: string;\n private _date: Date | undefined;\n\n private constructor(body: Expression, id: ARID, note = \"\", date?: Date) {\n this._body = body;\n this._id = id;\n this._note = note;\n this._date = date;\n }\n\n /**\n * Creates a new request with the specified expression body and ID.\n */\n static newWithBody(body: Expression, id: ARID): Request {\n return new Request(body, id);\n }\n\n /**\n * Creates a new request with a function and ID.\n *\n * This is a convenience method that creates an expression from the\n * function and then creates a request with that expression.\n */\n static new(func: Function | string | number, id: ARID): Request {\n const f =\n typeof func === \"string\"\n ? Function.newNamed(func)\n : typeof func === \"number\"\n ? Function.newKnown(func)\n : func;\n return Request.newWithBody(new Expression(f), id);\n }\n\n /**\n * Returns a human-readable summary of the request.\n */\n summary(): string {\n return `id: ${this._id.shortDescription()}, body: ${this._body.envelope().formatFlat()}`;\n }\n\n // RequestBehavior implementation\n\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Request {\n this._body.withParameter(param, value);\n return this;\n }\n\n withNote(note: string): Request {\n this._note = note;\n return this;\n }\n\n withDate(date: Date): Request {\n this._date = date;\n return this;\n }\n\n body(): Expression {\n return this._body;\n }\n\n id(): ARID {\n return this._id;\n }\n\n note(): string {\n return this._note;\n }\n\n date(): Date | undefined {\n return this._date;\n }\n\n function(): Function {\n return this._body.function();\n }\n\n expressionEnvelope(): Envelope {\n return this._body.envelope();\n }\n\n /**\n * Converts the request to an envelope.\n *\n * The envelope's subject is the request's ID tagged with TAG_REQUEST,\n * and assertions include the request's body, note (if not empty), and date (if present).\n */\n toEnvelope(): Envelope {\n // Create the tagged ARID as the subject\n const taggedArid = toTaggedValue(TAG_REQUEST, this._id.untaggedCbor());\n\n let envelope = Envelope.newLeaf(taggedArid).addAssertion(BODY, this._body.envelope());\n\n if (this._note !== \"\") {\n envelope = envelope.addAssertion(NOTE, this._note);\n }\n\n if (this._date !== undefined) {\n envelope = envelope.addAssertion(DATE, this._date.toISOString());\n }\n\n return envelope;\n }\n\n /**\n * Converts this request into an envelope (EnvelopeEncodable implementation).\n */\n intoEnvelope(): Envelope {\n return this.toEnvelope();\n }\n\n /**\n * Creates a request from an envelope.\n */\n static fromEnvelope(envelope: Envelope, expectedFunction?: Function): Request {\n // Extract the body\n const bodyEnvelope = envelope.objectForPredicate(BODY);\n if (bodyEnvelope === undefined) {\n throw EnvelopeError.general(\"Request envelope missing body\");\n }\n\n // Parse the expression from the body\n const body = Expression.fromEnvelope(bodyEnvelope);\n\n // Validate function if expected\n if (expectedFunction !== undefined && !body.function().equals(expectedFunction)) {\n throw EnvelopeError.general(\"Request function mismatch\");\n }\n\n // Extract the ARID from the subject\n const subject = envelope.subject();\n const leaf = subject.asLeaf();\n if (leaf === undefined) {\n throw EnvelopeError.general(\"Request envelope has invalid subject\");\n }\n\n // The subject is TAG_REQUEST(ARID_bytes)\n // First expect the REQUEST tag, then extract the ARID from the content\n const aridCbor = leaf.expectTag(TAG_REQUEST);\n const aridBytes = aridCbor.toByteString();\n const id = ARID.fromData(aridBytes);\n\n // Extract optional note\n let note = \"\";\n try {\n const noteObj = envelope.objectForPredicate(NOTE);\n if (noteObj !== undefined) {\n note = noteObj.asText() ?? \"\";\n }\n } catch {\n // Note is optional\n }\n\n // Extract optional date\n let date: Date | undefined;\n try {\n const dateObj = envelope.objectForPredicate(DATE);\n if (dateObj !== undefined) {\n const dateStr = dateObj.asText();\n if (dateStr !== undefined) {\n date = new Date(dateStr);\n }\n }\n } catch {\n // Date is optional\n }\n\n return new Request(body, id, note, date);\n }\n\n /**\n * Returns a string representation of the request.\n */\n toString(): string {\n return `Request(${this.summary()})`;\n }\n\n /**\n * Checks equality with another request.\n */\n equals(other: Request): boolean {\n return (\n this._id.equals(other._id) &&\n this._note === other._note &&\n this._date?.getTime() === other._date?.getTime()\n );\n }\n}\n","/**\n * Response type for distributed function calls.\n *\n * Ported from bc-envelope-rust/src/extension/expressions/response.rs\n *\n * A Response represents a reply to a Request containing either a\n * successful result or an error.\n *\n * Responses are part of the expression system that enables distributed\n * function calls. Each response contains:\n * - A reference to the original request's ID (ARID) for correlation\n * - Either a successful result or an error message\n *\n * When serialized to an envelope, responses are tagged with RESPONSE tag.\n */\n\nimport { ARID } from \"@bcts/components\";\nimport { RESPONSE as TAG_RESPONSE } from \"@bcts/tags\";\nimport { toTaggedValue } from \"@bcts/dcbor\";\nimport { RESULT, ERROR, OK_VALUE, UNKNOWN_VALUE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\n\n/**\n * Type representing a successful response: (ARID, result envelope)\n */\ninterface SuccessResult {\n ok: true;\n id: ARID;\n result: Envelope;\n}\n\n/**\n * Type representing a failed response: (optional ARID, error envelope)\n */\ninterface FailureResult {\n ok: false;\n id: ARID | undefined;\n error: Envelope;\n}\n\n/**\n * Internal result type for Response\n */\ntype ResponseResult = SuccessResult | FailureResult;\n\n/**\n * Interface that defines the behavior of a response.\n */\nexport interface ResponseBehavior {\n /**\n * Sets the result value for a successful response.\n * @throws Error if called on a failure response.\n */\n withResult(result: EnvelopeEncodableValue): Response;\n\n /**\n * Sets the error value for a failure response.\n * @throws Error if called on a successful response.\n */\n withError(error: EnvelopeEncodableValue): Response;\n\n /**\n * Returns true if this is a successful response.\n */\n isOk(): boolean;\n\n /**\n * Returns true if this is a failure response.\n */\n isErr(): boolean;\n\n /**\n * Returns the ID of the request this response corresponds to, if known.\n */\n id(): ARID | undefined;\n\n /**\n * Returns the result envelope if this is a successful response.\n * @throws Error if this is a failure response.\n */\n result(): Envelope;\n\n /**\n * Returns the error envelope if this is a failure response.\n * @throws Error if this is a successful response.\n */\n error(): Envelope;\n\n /**\n * Converts the response to an envelope.\n */\n toEnvelope(): Envelope;\n}\n\n/**\n * A Response represents a reply to a Request containing either a\n * successful result or an error.\n *\n * @example\n * ```typescript\n * import { Response, ARID } from '@bcts/envelope';\n *\n * // Create a request ID (normally this would come from the original request)\n * const requestId = ARID.new();\n *\n * // Create a successful response\n * const successResponse = Response.newSuccess(requestId)\n * .withResult(\"Transaction completed\");\n *\n * // Create an error response\n * const errorResponse = Response.newFailure(requestId)\n * .withError(\"Insufficient funds\");\n *\n * // Convert to envelopes\n * const successEnvelope = successResponse.toEnvelope();\n * const errorEnvelope = errorResponse.toEnvelope();\n * ```\n */\nexport class Response implements ResponseBehavior, EnvelopeEncodable {\n private _result: ResponseResult;\n\n private constructor(result: ResponseResult) {\n this._result = result;\n }\n\n /**\n * Creates a new successful response with the specified request ID.\n *\n * By default, the result will be the 'OK' known value. Use `withResult`\n * to set a specific result value.\n */\n static newSuccess(id: ARID): Response {\n return new Response({\n ok: true,\n id,\n result: Response.ok(),\n });\n }\n\n /**\n * Creates a new failure response with the specified request ID.\n *\n * By default, the error will be the 'Unknown' known value. Use\n * `withError` to set a specific error message.\n */\n static newFailure(id: ARID): Response {\n return new Response({\n ok: false,\n id,\n error: Response.unknown(),\n });\n }\n\n /**\n * Creates a new early failure response without a request ID.\n *\n * An early failure occurs when the error happens before the request\n * has been fully processed, so the request ID is not known.\n */\n static newEarlyFailure(): Response {\n return new Response({\n ok: false,\n id: undefined,\n error: Response.unknown(),\n });\n }\n\n /**\n * Creates an envelope containing the 'Unknown' known value.\n */\n static unknown(): Envelope {\n return Envelope.new(UNKNOWN_VALUE);\n }\n\n /**\n * Creates an envelope containing the 'OK' known value.\n */\n static ok(): Envelope {\n return Envelope.new(OK_VALUE);\n }\n\n /**\n * Returns a human-readable summary of the response.\n */\n summary(): string {\n if (this._result.ok) {\n return `id: ${this._result.id.shortDescription()}, result: ${this._result.result.formatFlat()}`;\n } else {\n const idStr =\n this._result.id !== undefined ? this._result.id.shortDescription() : \"'Unknown'\";\n return `id: ${idStr}, error: ${this._result.error.formatFlat()}`;\n }\n }\n\n // ResponseBehavior implementation\n\n withResult(result: EnvelopeEncodableValue): Response {\n if (!this._result.ok) {\n throw new Error(\"Cannot set result on a failed response\");\n }\n this._result = {\n ok: true,\n id: this._result.id,\n result: Envelope.new(result),\n };\n return this;\n }\n\n withOptionalResult(result: EnvelopeEncodableValue | undefined): Response {\n if (result !== undefined) {\n return this.withResult(result);\n }\n return this.withResult(null);\n }\n\n withError(error: EnvelopeEncodableValue): Response {\n if (this._result.ok) {\n throw new Error(\"Cannot set error on a successful response\");\n }\n this._result = {\n ok: false,\n id: this._result.id,\n error: Envelope.new(error),\n };\n return this;\n }\n\n withOptionalError(error: EnvelopeEncodableValue | undefined): Response {\n if (error !== undefined) {\n return this.withError(error);\n }\n return this;\n }\n\n isOk(): boolean {\n return this._result.ok;\n }\n\n isErr(): boolean {\n return !this._result.ok;\n }\n\n id(): ARID | undefined {\n return this._result.id;\n }\n\n expectId(): ARID {\n const id = this.id();\n if (id === undefined) {\n throw new Error(\"Expected an ID\");\n }\n return id;\n }\n\n result(): Envelope {\n if (!this._result.ok) {\n throw EnvelopeError.general(\"Cannot get result from failed response\");\n }\n return this._result.result;\n }\n\n error(): Envelope {\n if (this._result.ok) {\n throw EnvelopeError.general(\"Cannot get error from successful response\");\n }\n return this._result.error;\n }\n\n /**\n * Extracts a typed result value from a successful response.\n */\n extractResult<T>(decoder: (cbor: unknown) => T): T {\n return this.result().extractSubject(decoder);\n }\n\n /**\n * Extracts a typed error value from a failure response.\n */\n extractError<T>(decoder: (cbor: unknown) => T): T {\n return this.error().extractSubject(decoder);\n }\n\n /**\n * Converts the response to an envelope.\n *\n * Successful responses have the request ID as the subject and a 'result'\n * assertion. Failure responses have the request ID (or 'Unknown' if not known)\n * as the subject and an 'error' assertion.\n */\n toEnvelope(): Envelope {\n if (this._result.ok) {\n const taggedArid = toTaggedValue(TAG_RESPONSE, this._result.id.untaggedCbor());\n return Envelope.newLeaf(taggedArid).addAssertion(RESULT, this._result.result);\n } else {\n let subject: Envelope;\n if (this._result.id !== undefined) {\n const taggedArid = toTaggedValue(TAG_RESPONSE, this._result.id.untaggedCbor());\n subject = Envelope.newLeaf(taggedArid);\n } else {\n const taggedUnknown = toTaggedValue(TAG_RESPONSE, UNKNOWN_VALUE.untaggedCbor());\n subject = Envelope.newLeaf(taggedUnknown);\n }\n return subject.addAssertion(ERROR, this._result.error);\n }\n }\n\n /**\n * Converts this response into an envelope (EnvelopeEncodable implementation).\n */\n intoEnvelope(): Envelope {\n return this.toEnvelope();\n }\n\n /**\n * Creates a response from an envelope.\n */\n static fromEnvelope(envelope: Envelope): Response {\n // Check for result or error assertion\n let hasResult = false;\n let hasError = false;\n\n try {\n const resultObj = envelope.objectForPredicate(RESULT);\n hasResult = resultObj !== undefined;\n } catch {\n // No result\n }\n\n try {\n const errorObj = envelope.objectForPredicate(ERROR);\n hasError = errorObj !== undefined;\n } catch {\n // No error\n }\n\n // Must have exactly one of result or error\n if (hasResult === hasError) {\n throw EnvelopeError.invalidResponse();\n }\n\n // Extract ARID from tagged subject\n // Subject is TAG_RESPONSE(ARID_bytes) or TAG_RESPONSE(UNKNOWN_VALUE)\n const subject = envelope.subject();\n const leaf = subject.asLeaf();\n if (leaf === undefined) {\n throw EnvelopeError.general(\"Response envelope has invalid subject\");\n }\n\n // Expect the RESPONSE tag\n const content = leaf.expectTag(TAG_RESPONSE);\n\n // Try to extract ARID from byte string; if it's a KnownValue, ID is undefined\n let id: ARID | undefined;\n const bytes = content.asByteString();\n if (bytes !== undefined) {\n id = ARID.fromData(bytes);\n }\n // If bytes is undefined, the content is UNKNOWN_VALUE, so id remains undefined\n\n if (hasResult) {\n const resultEnvelope = envelope.objectForPredicate(RESULT);\n if (id === undefined) {\n throw EnvelopeError.general(\"Successful response must have an ID\");\n }\n return new Response({\n ok: true,\n id,\n result: resultEnvelope ?? Response.ok(),\n });\n } else {\n const errorEnvelope = envelope.objectForPredicate(ERROR);\n return new Response({\n ok: false,\n id,\n error: errorEnvelope ?? Response.unknown(),\n });\n }\n }\n\n /**\n * Returns a string representation of the response.\n */\n toString(): string {\n return `Response(${this.summary()})`;\n }\n\n /**\n * Checks equality with another response.\n */\n equals(other: Response): boolean {\n if (this._result.ok !== other._result.ok) return false;\n\n if (this._result.ok && other._result.ok) {\n return this._result.id.equals(other._result.id);\n }\n\n if (!this._result.ok && !other._result.ok) {\n if (this._result.id === undefined && other._result.id === undefined) {\n return true;\n }\n if (this._result.id !== undefined && other._result.id !== undefined) {\n return this._result.id.equals(other._result.id);\n }\n return false;\n }\n\n return false;\n }\n}\n","/**\n * Event type for notifications and messages.\n *\n * Ported from bc-envelope-rust/src/extension/expressions/event.rs\n *\n * An Event represents a notification or message that doesn't expect a\n * response.\n *\n * Unlike Request and Response which form a pair, an Event is a\n * standalone message that can be used for broadcasting information, logging,\n * or publishing notifications. Events are used when the sender does not expect\n * or require a response from the recipients.\n *\n * Each event contains:\n * - Content of a generic type that holds the event payload\n * - A unique identifier (ARID) for tracking and correlation\n * - Optional metadata like a note and timestamp\n *\n * When serialized to an envelope, events are tagged with EVENT tag.\n */\n\nimport { ARID } from \"@bcts/components\";\nimport { EVENT as TAG_EVENT } from \"@bcts/tags\";\nimport { toTaggedValue } from \"@bcts/dcbor\";\nimport { CONTENT, NOTE, DATE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\n\n/**\n * Interface that defines the behavior of an event.\n */\nexport interface EventBehavior<T extends EnvelopeEncodableValue> {\n /**\n * Adds a note to the event.\n */\n withNote(note: string): Event<T>;\n\n /**\n * Adds a date to the event.\n */\n withDate(date: Date): Event<T>;\n\n /**\n * Returns the content of the event.\n */\n content(): T;\n\n /**\n * Returns the unique identifier (ARID) of the event.\n */\n id(): ARID;\n\n /**\n * Returns the note attached to the event, or an empty string if none exists.\n */\n note(): string;\n\n /**\n * Returns the date attached to the event, if any.\n */\n date(): Date | undefined;\n\n /**\n * Converts the event to an envelope.\n */\n toEnvelope(): Envelope;\n}\n\n/**\n * An Event represents a notification or message that doesn't expect a response.\n *\n * @example\n * ```typescript\n * import { Event, ARID } from '@bcts/envelope';\n *\n * // Create a status update event\n * const eventId = ARID.new();\n * const timestamp = new Date(\"2024-08-15T13:45:30Z\");\n *\n * const statusEvent = Event.new(\"System online\", eventId)\n * .withNote(\"Regular status update\")\n * .withDate(timestamp);\n *\n * // Convert to an envelope for transmission\n * const envelope = statusEvent.toEnvelope();\n * ```\n *\n * @typeParam T - The type of content this event carries\n */\nexport class Event<T extends EnvelopeEncodableValue>\n implements EventBehavior<T>, EnvelopeEncodable\n{\n private readonly _content: T;\n private readonly _id: ARID;\n private _note: string;\n private _date: Date | undefined;\n\n private constructor(content: T, id: ARID, note = \"\", date?: Date) {\n this._content = content;\n this._id = id;\n this._note = note;\n this._date = date;\n }\n\n /**\n * Creates a new event with the specified content and ID.\n */\n static new<T extends EnvelopeEncodableValue>(content: T, id: ARID): Event<T> {\n return new Event(content, id);\n }\n\n /**\n * Returns a human-readable summary of the event.\n */\n summary(): string {\n const contentEnvelope = Envelope.new(this._content);\n return `id: ${this._id.shortDescription()}, content: ${contentEnvelope.formatFlat()}`;\n }\n\n // EventBehavior implementation\n\n withNote(note: string): Event<T> {\n this._note = note;\n return this;\n }\n\n withDate(date: Date): Event<T> {\n this._date = date;\n return this;\n }\n\n content(): T {\n return this._content;\n }\n\n id(): ARID {\n return this._id;\n }\n\n note(): string {\n return this._note;\n }\n\n date(): Date | undefined {\n return this._date;\n }\n\n /**\n * Converts the event to an envelope.\n *\n * The envelope's subject is the event's ID tagged with TAG_EVENT,\n * and assertions include the event's content, note (if not empty), and date\n * (if present).\n */\n toEnvelope(): Envelope {\n const taggedArid = toTaggedValue(TAG_EVENT, this._id.untaggedCbor());\n const contentEnvelope = Envelope.new(this._content);\n\n let envelope = Envelope.newLeaf(taggedArid).addAssertion(CONTENT, contentEnvelope);\n\n if (this._note !== \"\") {\n envelope = envelope.addAssertion(NOTE, this._note);\n }\n\n if (this._date !== undefined) {\n envelope = envelope.addAssertion(DATE, this._date.toISOString());\n }\n\n return envelope;\n }\n\n /**\n * Converts this event into an envelope (EnvelopeEncodable implementation).\n */\n intoEnvelope(): Envelope {\n return this.toEnvelope();\n }\n\n /**\n * Creates an event from an envelope.\n *\n * @typeParam T - The type to extract the content as\n */\n static fromEnvelope<T extends EnvelopeEncodableValue>(\n envelope: Envelope,\n contentExtractor: (env: Envelope) => T,\n ): Event<T> {\n // Extract content\n const contentEnvelope = envelope.objectForPredicate(CONTENT);\n if (contentEnvelope === undefined) {\n throw EnvelopeError.general(\"Event envelope missing content\");\n }\n const content = contentExtractor(contentEnvelope);\n\n // Extract the ARID from the subject\n // Subject is TAG_EVENT(ARID_bytes)\n const subject = envelope.subject();\n const leaf = subject.asLeaf();\n if (leaf === undefined) {\n throw EnvelopeError.general(\"Event envelope has invalid subject\");\n }\n\n // Expect the EVENT tag and extract the ARID\n const aridCbor = leaf.expectTag(TAG_EVENT);\n const aridBytes = aridCbor.toByteString();\n const id = ARID.fromData(aridBytes);\n\n // Extract optional note\n let note = \"\";\n try {\n const noteObj = envelope.objectForPredicate(NOTE);\n if (noteObj !== undefined) {\n note = noteObj.asText() ?? \"\";\n }\n } catch {\n // Note is optional\n }\n\n // Extract optional date\n let date: Date | undefined;\n try {\n const dateObj = envelope.objectForPredicate(DATE);\n if (dateObj !== undefined) {\n const dateStr = dateObj.asText();\n if (dateStr !== undefined) {\n date = new Date(dateStr);\n }\n }\n } catch {\n // Date is optional\n }\n\n return new Event(content, id, note, date);\n }\n\n /**\n * Creates a string event from an envelope.\n */\n static stringFromEnvelope(envelope: Envelope): Event<string> {\n return Event.fromEnvelope<string>(envelope, (env) => env.asText() ?? \"\");\n }\n\n /**\n * Returns a string representation of the event.\n */\n toString(): string {\n return `Event(${this.summary()})`;\n }\n\n /**\n * Checks equality with another event.\n */\n equals(other: Event<T>): boolean {\n return (\n this._id.equals(other._id) &&\n this._note === other._note &&\n this._date?.getTime() === other._date?.getTime()\n );\n }\n}\n","import { Envelope } from \"../base/envelope\";\nimport { type EdgeType, edgeLabel } from \"../base/walk\";\n\n// ============================================================================\n// DigestDisplayFormat - Enum for digest display formatting\n// ============================================================================\n\n/**\n * Specifies the format for displaying envelope digests in tree output.\n *\n * Ported from bc-envelope-rust/src/format/tree/format/digest.rs\n */\nexport enum DigestDisplayFormat {\n /**\n * Short format: first 7 hex characters of the digest.\n * This is the default format.\n */\n Short = \"short\",\n\n /**\n * Full format: complete 64 hex character digest.\n */\n Full = \"full\",\n\n /**\n * UR format: digest encoded as a UR string.\n */\n UR = \"ur\",\n}\n\n/// Tree formatting for Gordian Envelopes.\n///\n/// This module provides functionality for creating textual tree\n/// representations of envelopes, which is useful for debugging and visualizing\n/// the hierarchical structure of complex envelopes.\n///\n/// The tree format displays each component of an envelope (subject and\n/// assertions) as nodes in a tree, making it easy to understand the\n/// hierarchical structure of nested envelopes. Each node includes:\n///\n/// - The first 8 characters of the element's digest (for easy reference)\n/// - The type of the element (NODE, ASSERTION, ELIDED, etc.)\n/// - The content of the element (for leaf nodes)\n\n/// Options for tree formatting\nexport interface TreeFormatOptions {\n /// If true, hides NODE identifiers and only shows semantic content\n hideNodes?: boolean;\n /// Set of digest strings to highlight in the tree\n highlightDigests?: Set<string>;\n /// Format for displaying digests: \"short\" (7 hex chars), \"full\" (64 hex chars), or \"ur\" (UR string)\n digestDisplay?: DigestDisplayFormat | \"short\" | \"full\" | \"ur\";\n}\n\n/// Represents an element in the tree representation\ninterface TreeElement {\n /// Indentation level\n level: number;\n /// The envelope element\n envelope: Envelope;\n /// Type of incoming edge\n incomingEdge: EdgeType;\n /// Whether to show the digest ID\n showId: boolean;\n /// Whether this element is highlighted\n isHighlighted: boolean;\n}\n\n// Note: Method declarations are in the base Envelope class.\n// This module provides the prototype implementations.\n\n/// Implementation of shortId()\nEnvelope.prototype.shortId = function (\n this: Envelope,\n format: \"short\" | \"full\" | \"ur\" = \"short\",\n): string {\n const digest = this.digest();\n if (format === \"full\") {\n return digest.hex();\n }\n if (format === \"ur\") {\n return digest.urString();\n }\n return digest.short();\n};\n\n/// Implementation of summary()\nEnvelope.prototype.summary = function (this: Envelope, maxLength = 40): string {\n const c = this.case();\n\n switch (c.type) {\n case \"node\":\n return \"NODE\";\n case \"leaf\": {\n // Try to extract a readable value\n try {\n const text = this.asText();\n if (text !== undefined) {\n const truncated = text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;\n return JSON.stringify(truncated);\n }\n } catch {\n // Fall through\n }\n\n try {\n const num = this.extractNumber();\n return String(num);\n } catch {\n // Fall through\n }\n\n try {\n const bool = this.extractBoolean();\n return String(bool);\n } catch {\n // Fall through\n }\n\n if (this.isNull()) {\n return \"null\";\n }\n\n // Fallback: show byte string\n const bytes = this.asByteString();\n if (bytes !== undefined && bytes.length <= 16) {\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `h'${hex}'`;\n }\n\n return \"LEAF\";\n }\n case \"wrapped\":\n return \"WRAPPED\";\n case \"assertion\":\n return \"ASSERTION\";\n case \"elided\":\n return \"ELIDED\";\n case \"encrypted\":\n return \"ENCRYPTED\";\n case \"compressed\":\n return \"COMPRESSED\";\n case \"knownValue\":\n return \"KNOWN_VALUE\";\n default:\n return \"UNKNOWN\";\n }\n};\n\n/// Implementation of treeFormat()\nEnvelope.prototype.treeFormat = function (this: Envelope, options: TreeFormatOptions = {}): string {\n const hideNodes = options.hideNodes ?? false;\n const highlightDigests = options.highlightDigests ?? new Set<string>();\n const digestDisplay = options.digestDisplay ?? \"short\";\n\n const elements: TreeElement[] = [];\n\n // Walk the envelope and collect elements\n this.walk(hideNodes, undefined, (envelope, level, incomingEdge, _state) => {\n const digestStr = envelope.digest().short();\n const isHighlighted = highlightDigests.has(digestStr);\n\n elements.push({\n level,\n envelope,\n incomingEdge,\n showId: !hideNodes,\n isHighlighted,\n });\n\n return [undefined, false];\n });\n\n // Format each element as a line\n const lines = elements.map((elem) => {\n const parts: string[] = [];\n\n if (elem.isHighlighted) {\n parts.push(\"*\");\n }\n\n if (elem.showId) {\n parts.push(elem.envelope.shortId(digestDisplay));\n }\n\n const label = edgeLabel(elem.incomingEdge);\n if (label !== undefined && label !== \"\") {\n parts.push(label);\n }\n\n parts.push(elem.envelope.summary(40));\n\n const line = parts.join(\" \");\n const indent = \" \".repeat(elem.level * 4);\n return indent + line;\n });\n\n return lines.join(\"\\n\");\n};\n","/// Format context for Gordian Envelopes with annotations.\n///\n/// The FormatContext provides information about CBOR tags, known values,\n/// functions, and parameters that are used to annotate the output of envelope\n/// formatting functions. This context enables human-readable output when\n/// converting envelopes to string representations like diagnostic notation.\n\nimport {\n type TagsStore,\n type TagsStoreTrait,\n type Tag,\n type CborNumber,\n type CborSummarizer,\n TagsStore as TagsStoreClass,\n getGlobalTagsStore,\n toTaggedValue,\n} from \"@bcts/dcbor\";\nimport {\n type KnownValuesStore,\n KnownValuesStore as KnownValuesStoreClass,\n KnownValue,\n KNOWN_VALUES,\n TAG_KNOWN_VALUE,\n} from \"@bcts/known-values\";\nimport {\n registerTags as registerBcTags,\n DIGEST as TAG_DIGEST,\n ARID as TAG_ARID,\n URI as TAG_URI,\n UUID as TAG_UUID,\n NONCE as TAG_NONCE,\n SALT as TAG_SALT,\n SEED as TAG_SEED,\n SIGNATURE as TAG_SIGNATURE,\n SEALED_MESSAGE as TAG_SEALED_MESSAGE,\n ENCRYPTED_KEY as TAG_ENCRYPTED_KEY,\n PRIVATE_KEY_BASE as TAG_PRIVATE_KEY_BASE,\n PRIVATE_KEYS as TAG_PRIVATE_KEYS,\n PUBLIC_KEYS as TAG_PUBLIC_KEYS,\n SIGNING_PRIVATE_KEY as TAG_SIGNING_PRIVATE_KEY,\n SIGNING_PUBLIC_KEY as TAG_SIGNING_PUBLIC_KEY,\n SSKR_SHARE as TAG_SSKR_SHARE,\n XID as TAG_XID,\n} from \"@bcts/tags\";\nimport {\n Digest,\n ARID,\n URI,\n UUID,\n Nonce,\n Salt,\n Seed,\n Signature,\n SignatureScheme,\n SealedMessage,\n EncapsulationScheme,\n EncryptedKey,\n PrivateKeyBase,\n PrivateKeys,\n PublicKeys,\n SigningPrivateKey,\n SigningPublicKey,\n SSKRShareCbor,\n XID,\n} from \"@bcts/components\";\n\n// ============================================================================\n// FormatContextOpt - Option type for format context\n// ============================================================================\n\n/// Option type for format context, similar to Rust's FormatContextOpt<'a>.\nexport type FormatContextOpt =\n | { type: \"none\" }\n | { type: \"global\" }\n | { type: \"custom\"; context: FormatContext };\n\n/// Create a FormatContextOpt with no context\nexport const formatContextNone = (): FormatContextOpt => ({ type: \"none\" });\n\n/// Create a FormatContextOpt with global context\nexport const formatContextGlobal = (): FormatContextOpt => ({ type: \"global\" });\n\n/// Create a FormatContextOpt with custom context\nexport const formatContextCustom = (context: FormatContext): FormatContextOpt => ({\n type: \"custom\",\n context,\n});\n\n// ============================================================================\n// FormatContext - Main formatting context class\n// ============================================================================\n\n/// Context object for formatting Gordian Envelopes with annotations.\n///\n/// The FormatContext provides information about CBOR tags, known values,\n/// functions, and parameters that are used to annotate the output of envelope\n/// formatting functions.\nexport class FormatContext implements TagsStoreTrait {\n private readonly _tags: TagsStore;\n private readonly _knownValues: KnownValuesStore;\n\n constructor(tags?: TagsStore, knownValues?: KnownValuesStore) {\n this._tags = tags ?? new TagsStoreClass();\n this._knownValues = knownValues ?? new KnownValuesStoreClass();\n }\n\n /// Returns a reference to the CBOR tags registry.\n tags(): TagsStore {\n return this._tags;\n }\n\n /// Returns a reference to the known values registry.\n knownValues(): KnownValuesStore {\n return this._knownValues;\n }\n\n // Implement TagsStoreTrait by delegating to internal tags store\n assignedNameForTag(tag: Tag): string | undefined {\n return this._tags.assignedNameForTag(tag);\n }\n\n nameForTag(tag: Tag): string {\n return this._tags.nameForTag(tag);\n }\n\n tagForValue(value: CborNumber): Tag | undefined {\n return this._tags.tagForValue(value);\n }\n\n tagForName(name: string): Tag | undefined {\n return this._tags.tagForName(name);\n }\n\n nameForValue(value: CborNumber): string {\n return this._tags.nameForValue(value);\n }\n\n summarizer(tag: CborNumber): CborSummarizer | undefined {\n return this._tags.summarizer(tag);\n }\n\n /// Register a tag with a name\n registerTag(value: number | bigint, name: string): void {\n this._tags.insert({ value: BigInt(value), name });\n }\n\n /// Create a clone of this context\n clone(): FormatContext {\n // Note: This creates a shallow copy - tags and knownValues are shared\n // For a full deep copy, we would need to clone the stores\n return new FormatContext(this._tags, this._knownValues);\n }\n}\n\n// ============================================================================\n// Global Format Context\n// ============================================================================\n\n/// Global singleton instance of FormatContext for application-wide use.\nlet _globalFormatContextInstance: FormatContext | undefined;\nlet isInitialized = false;\n\n/// Get the global format context instance, initializing it if necessary.\nexport const getGlobalFormatContext = (): FormatContext => {\n if (!isInitialized) {\n // Register all known tags (dcbor + BC component tags) in the global tags store\n registerBcTags();\n\n // Get the global stores\n const tags = getGlobalTagsStore();\n const knownValues = KNOWN_VALUES.get();\n\n _globalFormatContextInstance = new FormatContext(tags, knownValues);\n isInitialized = true;\n\n // Set up known value summarizer\n setupKnownValueSummarizer(_globalFormatContextInstance);\n\n // Set up component tag summarizers\n setupComponentSummarizers(_globalFormatContextInstance);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Safe: initialized in the if block above\n return _globalFormatContextInstance!;\n};\n\n/// Execute a function with access to the global format context.\nexport const withFormatContext = <T>(action: (context: FormatContext) => T): T => {\n return action(getGlobalFormatContext());\n};\n\n/// Execute a function with mutable access to the global format context.\nexport const withFormatContextMut = <T>(action: (context: FormatContext) => T): T => {\n return action(getGlobalFormatContext());\n};\n\n// ============================================================================\n// Tag Registration\n// ============================================================================\n\n/// Set up the known value summarizer in a format context\nconst setupKnownValueSummarizer = (context: FormatContext): void => {\n const knownValues = context.knownValues();\n const tags = context.tags();\n\n // Known value summarizer - formats known values with single quotes\n const summarizer: CborSummarizer = (cbor, _flat) => {\n try {\n // Try to extract the known value from the CBOR\n const kv = KnownValue.fromUntaggedCbor(cbor);\n const name = knownValues.name(kv);\n return { ok: true, value: `'${name}'` };\n } catch {\n return { ok: true, value: \"'<unknown>'\" };\n }\n };\n\n tags.setSummarizer(BigInt(TAG_KNOWN_VALUE), summarizer);\n};\n\n/// Registers standard tags and summarizers in a format context.\nexport const registerTagsIn = (context: FormatContext): void => {\n // Register all known tags (dcbor + BC component tags)\n registerBcTags();\n\n // Set up known value summarizer\n setupKnownValueSummarizer(context);\n\n // Set up component tag summarizers\n setupComponentSummarizers(context);\n};\n\n/// Registers standard tags in the global format context.\nexport const registerTags = (): void => {\n withFormatContextMut((context) => {\n registerTagsIn(context);\n });\n};\n\n// ============================================================================\n// Component Tag Summarizers\n// ============================================================================\n\n/// Helper to create an error result for summarizers\nconst summarizerError = (e: unknown): { ok: false; error: { type: \"Custom\"; message: string } } => {\n const message = e instanceof Error ? e.message : String(e);\n return { ok: false as const, error: { type: \"Custom\" as const, message } };\n};\n\n/// Set up component tag summarizers matching Rust bc-components-rust/src/tags_registry.rs\nconst setupComponentSummarizers = (context: FormatContext): void => {\n const tags = context.tags();\n\n // Digest: \"Digest(shortDesc)\"\n tags.setSummarizer(TAG_DIGEST.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_DIGEST.value, cbor);\n const digest = Digest.fromTaggedCbor(tagged);\n return { ok: true, value: `Digest(${digest.shortDescription()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // ARID: \"ARID(shortDesc)\"\n tags.setSummarizer(TAG_ARID.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_ARID.value, cbor);\n const arid = ARID.fromTaggedCbor(tagged);\n return { ok: true, value: `ARID(${arid.shortDescription()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // URI: \"URI(uri)\"\n tags.setSummarizer(TAG_URI.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_URI.value, cbor);\n const uri = URI.fromTaggedCbor(tagged);\n return { ok: true, value: `URI(${uri.toString()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // UUID: \"UUID(uuid)\"\n tags.setSummarizer(TAG_UUID.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_UUID.value, cbor);\n const uuid = UUID.fromTaggedCbor(tagged);\n return { ok: true, value: `UUID(${uuid.toString()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Nonce: \"Nonce\"\n tags.setSummarizer(TAG_NONCE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_NONCE.value, cbor);\n Nonce.fromTaggedCbor(tagged);\n return { ok: true, value: \"Nonce\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Salt: \"Salt\"\n tags.setSummarizer(TAG_SALT.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SALT.value, cbor);\n Salt.fromTaggedCbor(tagged);\n return { ok: true, value: \"Salt\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Seed: \"Seed\"\n tags.setSummarizer(TAG_SEED.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SEED.value, cbor);\n Seed.fromTaggedCbor(tagged);\n return { ok: true, value: \"Seed\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Signature: \"Signature\" for Ed25519/Schnorr (defaults), \"Signature(scheme)\" otherwise\n tags.setSummarizer(TAG_SIGNATURE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SIGNATURE.value, cbor);\n const sig = Signature.fromTaggedCbor(tagged);\n const scheme = sig.scheme();\n // Match Rust: default scheme shows just \"Signature\"\n if (scheme === SignatureScheme.Ed25519 || scheme === SignatureScheme.Schnorr) {\n return { ok: true, value: \"Signature\" };\n }\n return { ok: true, value: `Signature(${sig.signatureType()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SealedMessage: \"SealedMessage\" for X25519 (default), \"SealedMessage(scheme)\" otherwise\n tags.setSummarizer(TAG_SEALED_MESSAGE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SEALED_MESSAGE.value, cbor);\n const msg = SealedMessage.fromTaggedCbor(tagged);\n const scheme = msg.encapsulationScheme();\n if (scheme === EncapsulationScheme.X25519) {\n return { ok: true, value: \"SealedMessage\" };\n }\n return { ok: true, value: `SealedMessage(${scheme})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // EncryptedKey: toString()\n tags.setSummarizer(TAG_ENCRYPTED_KEY.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_ENCRYPTED_KEY.value, cbor);\n const ek = EncryptedKey.fromTaggedCbor(tagged);\n return { ok: true, value: ek.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // PrivateKeyBase: toString()\n tags.setSummarizer(TAG_PRIVATE_KEY_BASE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_PRIVATE_KEY_BASE.value, cbor);\n const pkb = PrivateKeyBase.fromTaggedCbor(tagged);\n return { ok: true, value: pkb.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // PrivateKeys: toString()\n tags.setSummarizer(TAG_PRIVATE_KEYS.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_PRIVATE_KEYS.value, cbor);\n const pk = PrivateKeys.fromTaggedCbor(tagged);\n return { ok: true, value: pk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // PublicKeys: toString()\n tags.setSummarizer(TAG_PUBLIC_KEYS.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_PUBLIC_KEYS.value, cbor);\n const pk = PublicKeys.fromTaggedCbor(tagged);\n return { ok: true, value: pk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SigningPrivateKey: toString()\n tags.setSummarizer(TAG_SIGNING_PRIVATE_KEY.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SIGNING_PRIVATE_KEY.value, cbor);\n const spk = SigningPrivateKey.fromTaggedCbor(tagged);\n return { ok: true, value: spk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SigningPublicKey: toString()\n tags.setSummarizer(TAG_SIGNING_PUBLIC_KEY.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SIGNING_PUBLIC_KEY.value, cbor);\n const spk = SigningPublicKey.fromTaggedCbor(tagged);\n return { ok: true, value: spk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SSKRShare: \"SSKRShare\"\n tags.setSummarizer(TAG_SSKR_SHARE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SSKR_SHARE.value, cbor);\n SSKRShareCbor.fromTaggedCbor(tagged);\n return { ok: true, value: \"SSKRShare\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // XID: \"XID(shortDesc)\"\n tags.setSummarizer(TAG_XID.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_XID.value, cbor);\n const xid = XID.fromTaggedCbor(tagged);\n return { ok: true, value: `XID(${xid.shortDescription()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\n/// Alias function for getGlobalFormatContext\nexport const globalFormatContext = getGlobalFormatContext;\n\n/// Object-style access to global format context\nexport const GLOBAL_FORMAT_CONTEXT = {\n get: getGlobalFormatContext,\n};\n","/// Envelope summary functionality for generating short text representations.\n///\n/// This module provides the EnvelopeSummary interface and implementations\n/// for generating concise text summaries of CBOR values and envelopes.\n\nimport type { Cbor } from \"@bcts/dcbor\";\nimport {\n isUnsigned,\n isNegative,\n isBytes,\n isText,\n isSimple,\n isArray,\n isMap,\n isTagged,\n asText,\n diagnosticOpt,\n type DiagFormatOpts,\n} from \"@bcts/dcbor\";\nimport { Envelope } from \"../base/envelope\";\nimport {\n type FormatContext,\n type FormatContextOpt,\n getGlobalFormatContext,\n} from \"./format-context\";\n\n// ============================================================================\n// EnvelopeSummary Interface\n// ============================================================================\n\n/// Interface for types that can produce envelope summary strings.\nexport interface EnvelopeSummary {\n envelopeSummary(maxLength: number, context: FormatContextOpt): string;\n}\n\n// ============================================================================\n// CBOR Summary Implementation\n// ============================================================================\n\n/// Helper to flank a string with prefix and suffix\nconst flankedBy = (s: string, prefix: string, suffix: string): string => {\n return `${prefix}${s}${suffix}`;\n};\n\n/// Generate an envelope summary for a CBOR value.\nexport const cborEnvelopeSummary = (\n cbor: Cbor,\n maxLength: number,\n context: FormatContextOpt,\n): string => {\n // Handle unsigned integers\n if (isUnsigned(cbor)) {\n return String(cbor);\n }\n\n // Handle negative integers\n if (isNegative(cbor)) {\n // In CBOR, negative integers are stored as -(n+1), so we need to compute the actual value\n const n = cbor.value;\n return typeof n === \"bigint\" ? String(-1n - n) : String(-1 - n);\n }\n\n // Handle byte strings\n if (isBytes(cbor)) {\n const bytes = cbor.value;\n return `Bytes(${bytes.length})`;\n }\n\n // Handle text strings\n if (isText(cbor)) {\n let text = asText(cbor) ?? \"\";\n if (text.length > maxLength) {\n text = `${text.substring(0, maxLength)}…`;\n }\n // Replace newlines with escaped version\n text = text.replace(/\\n/g, \"\\\\n\");\n return flankedBy(text, '\"', '\"');\n }\n\n // Handle simple values (bool, null, undefined, float)\n if (isSimple(cbor)) {\n const value = cbor as unknown;\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return \"NaN\";\n if (!Number.isFinite(value)) return value > 0 ? \"Infinity\" : \"-Infinity\";\n return String(value);\n }\n // Fallback for other simple values - use diagnostic notation\n return diagnosticOpt(cbor, { summarize: true });\n }\n\n // Handle arrays, maps, and tagged values - use diagnostic notation\n if (isArray(cbor) || isMap(cbor) || isTagged(cbor)) {\n const opts: DiagFormatOpts = { summarize: true };\n\n // Get appropriate tags store based on context\n if (context.type === \"custom\") {\n return diagnosticOpt(cbor, { ...opts, tags: context.context.tags() });\n } else if (context.type === \"global\") {\n const ctx = getGlobalFormatContext();\n return diagnosticOpt(cbor, { ...opts, tags: ctx.tags() });\n } else {\n return diagnosticOpt(cbor, opts);\n }\n }\n\n // Fallback\n return String(cbor);\n};\n\n// ============================================================================\n// Envelope Summary Method Extension\n// ============================================================================\n\n/// Implementation of summaryWithContext\nEnvelope.prototype.summaryWithContext = function (\n this: Envelope,\n maxLength: number,\n context: FormatContext,\n): string {\n const c = this.case();\n\n switch (c.type) {\n case \"node\":\n return \"NODE\";\n\n case \"leaf\":\n return cborEnvelopeSummary(c.cbor, maxLength, {\n type: \"custom\",\n context,\n });\n\n case \"wrapped\":\n return \"WRAPPED\";\n\n case \"assertion\":\n return \"ASSERTION\";\n\n case \"elided\":\n return \"ELIDED\";\n\n case \"knownValue\": {\n const knownValues = context.knownValues();\n const name = knownValues.name(c.value);\n return flankedBy(name, \"'\", \"'\");\n }\n\n case \"encrypted\":\n return \"ENCRYPTED\";\n\n case \"compressed\":\n return \"COMPRESSED\";\n\n default:\n return \"UNKNOWN\";\n }\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { cborEnvelopeSummary as envelopeSummary };\n","/// Envelope notation formatting.\n///\n/// This module provides functionality for formatting envelopes in human-readable\n/// envelope notation, which shows the semantic structure of an envelope.\n///\n/// # Examples\n///\n/// ```typescript\n/// const envelope = Envelope.new(\"Alice\")\n/// .addAssertion(\"knows\", \"Bob\")\n/// .addAssertion(\"knows\", \"Carol\");\n///\n/// // Format the envelope as human-readable envelope notation\n/// const formatted = envelope.format();\n/// // Will output: \"Alice\" [ \"knows\": \"Bob\", \"knows\": \"Carol\" ]\n/// ```\n\nimport type { Cbor } from \"@bcts/dcbor\";\nimport { isTagged, tagValue } from \"@bcts/dcbor\";\nimport { IS_A } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport type { Assertion } from \"../base/assertion\";\nimport {\n type FormatContextOpt,\n getGlobalFormatContext,\n formatContextGlobal,\n} from \"./format-context\";\nimport { cborEnvelopeSummary } from \"./envelope-summary\";\n\n// ============================================================================\n// EnvelopeFormatOpts - Options for envelope formatting\n// ============================================================================\n\n/// Options for envelope notation formatting.\nexport interface EnvelopeFormatOpts {\n /// If true, format as a single line without indentation\n flat: boolean;\n /// The format context to use\n context: FormatContextOpt;\n}\n\n/// Create default format options\nexport const defaultFormatOpts = (): EnvelopeFormatOpts => ({\n flat: false,\n context: formatContextGlobal(),\n});\n\n/// Create format options with flat formatting\nexport const flatFormatOpts = (): EnvelopeFormatOpts => ({\n flat: true,\n context: formatContextGlobal(),\n});\n\n// ============================================================================\n// EnvelopeFormatItem - Format item types\n// ============================================================================\n\n/// Type returned by EnvelopeFormat implementations.\nexport type EnvelopeFormatItem =\n | { type: \"begin\"; value: string }\n | { type: \"end\"; value: string }\n | { type: \"item\"; value: string }\n | { type: \"separator\" }\n | { type: \"list\"; items: EnvelopeFormatItem[] };\n\n/// Create a Begin item\nexport const formatBegin = (value: string): EnvelopeFormatItem => ({\n type: \"begin\",\n value,\n});\n\n/// Create an End item\nexport const formatEnd = (value: string): EnvelopeFormatItem => ({\n type: \"end\",\n value,\n});\n\n/// Create an Item\nexport const formatItem = (value: string): EnvelopeFormatItem => ({\n type: \"item\",\n value,\n});\n\n/// Create a Separator\nexport const formatSeparator = (): EnvelopeFormatItem => ({ type: \"separator\" });\n\n/// Create a List\nexport const formatList = (items: EnvelopeFormatItem[]): EnvelopeFormatItem => ({\n type: \"list\",\n items,\n});\n\n// ============================================================================\n// EnvelopeFormatItem Utilities\n// ============================================================================\n\n/// Flatten a format item into a flat array\nconst flatten = (item: EnvelopeFormatItem): EnvelopeFormatItem[] => {\n if (item.type === \"list\") {\n return item.items.flatMap(flatten);\n }\n return [item];\n};\n\n/// Nicen the format items by combining adjacent End/Begin pairs\nconst nicen = (items: EnvelopeFormatItem[]): EnvelopeFormatItem[] => {\n const input = [...items];\n const result: EnvelopeFormatItem[] = [];\n\n while (input.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Array length checked above\n const current = input.shift()!;\n if (input.length === 0) {\n result.push(current);\n break;\n }\n\n if (current.type === \"end\" && input[0]?.type === \"begin\") {\n const endString = current.value;\n const beginString = input[0].value;\n result.push(formatEnd(`${endString} ${beginString}`));\n result.push(formatBegin(\"\"));\n input.shift();\n } else {\n result.push(current);\n }\n }\n\n return result;\n};\n\n/// Create indentation string\nconst indent = (level: number): string => \" \".repeat(level * 4);\n\n/// Add space at end if needed\nconst addSpaceAtEndIfNeeded = (s: string): string => {\n if (s.length === 0) return \" \";\n if (s.endsWith(\" \")) return s;\n return `${s} `;\n};\n\n/// Format items in flat mode (single line)\nconst formatFlat = (item: EnvelopeFormatItem): string => {\n let line = \"\";\n const items = flatten(item);\n\n for (const i of items) {\n switch (i.type) {\n case \"begin\":\n if (!line.endsWith(\" \")) line += \" \";\n line += `${i.value} `;\n break;\n case \"end\":\n if (!line.endsWith(\" \")) line += \" \";\n line += `${i.value} `;\n break;\n case \"item\":\n line += i.value;\n break;\n case \"separator\":\n line = `${line.trimEnd()}, `;\n break;\n case \"list\":\n for (const subItem of i.items) {\n line += formatFlat(subItem);\n }\n break;\n }\n }\n\n return line;\n};\n\n/// Format items in hierarchical mode (with indentation)\nconst formatHierarchical = (item: EnvelopeFormatItem): string => {\n const lines: string[] = [];\n let level = 0;\n let currentLine = \"\";\n const items = nicen(flatten(item));\n\n for (const i of items) {\n switch (i.type) {\n case \"begin\": {\n const delimiter = i.value;\n if (delimiter.length > 0) {\n const c =\n currentLine.length === 0\n ? delimiter\n : `${addSpaceAtEndIfNeeded(currentLine)}${delimiter}`;\n lines.push(`${indent(level)}${c}\\n`);\n }\n level += 1;\n currentLine = \"\";\n break;\n }\n case \"end\": {\n const delimiter = i.value;\n if (currentLine.length > 0) {\n lines.push(`${indent(level)}${currentLine}\\n`);\n currentLine = \"\";\n }\n level -= 1;\n lines.push(`${indent(level)}${delimiter}\\n`);\n break;\n }\n case \"item\":\n currentLine += i.value;\n break;\n case \"separator\":\n if (currentLine.length > 0) {\n lines.push(`${indent(level)}${currentLine}\\n`);\n currentLine = \"\";\n }\n break;\n case \"list\":\n lines.push(\"<list>\");\n break;\n }\n }\n\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n\n return lines.join(\"\");\n};\n\n/// Format a format item according to options\nconst formatFormatItem = (item: EnvelopeFormatItem, opts: EnvelopeFormatOpts): string => {\n if (opts.flat) {\n return formatFlat(item);\n }\n return formatHierarchical(item);\n};\n\n// ============================================================================\n// EnvelopeFormat Interface and Implementations\n// ============================================================================\n\n/// Format a CBOR value as an envelope format item\nexport const formatCbor = (cbor: Cbor, opts: EnvelopeFormatOpts): EnvelopeFormatItem => {\n // Check if this is a tagged envelope\n if (isTagged(cbor)) {\n const tag = tagValue(cbor);\n // Envelope tag is 200\n if (tag === 200n || tag === 200) {\n try {\n const envelope = Envelope.fromTaggedCbor(cbor);\n return formatEnvelope(envelope, opts);\n } catch {\n return formatItem(\"<error>\");\n }\n }\n }\n\n // For non-envelope CBOR, use summary\n const summary = cborEnvelopeSummary(cbor, Number.MAX_SAFE_INTEGER, opts.context);\n return formatItem(summary);\n};\n\n/// Format an Assertion as an envelope format item\nexport const formatAssertion = (\n assertion: Assertion,\n opts: EnvelopeFormatOpts,\n): EnvelopeFormatItem => {\n return formatList([\n formatEnvelope(assertion.predicate(), opts),\n formatItem(\": \"),\n formatEnvelope(assertion.object(), opts),\n ]);\n};\n\n/// Format an Envelope as an envelope format item\nexport const formatEnvelope = (\n envelope: Envelope,\n opts: EnvelopeFormatOpts,\n): EnvelopeFormatItem => {\n const c = envelope.case();\n\n switch (c.type) {\n case \"leaf\":\n return formatCbor(c.cbor, opts);\n\n case \"wrapped\":\n return formatList([formatBegin(\"{\"), formatEnvelope(c.envelope, opts), formatEnd(\"}\")]);\n\n case \"assertion\":\n return formatAssertion(c.assertion, opts);\n\n case \"knownValue\": {\n // Get the name from context\n let name: string;\n if (opts.context.type === \"custom\") {\n const knownValues = opts.context.context.knownValues();\n const assignedName = knownValues.assignedName(c.value);\n name = assignedName ?? c.value.name();\n } else if (opts.context.type === \"global\") {\n const ctx = getGlobalFormatContext();\n const knownValues = ctx.knownValues();\n const assignedName = knownValues.assignedName(c.value);\n name = assignedName ?? c.value.name();\n } else {\n name = c.value.name();\n }\n return formatItem(`'${name}'`);\n }\n\n case \"encrypted\":\n return formatItem(\"ENCRYPTED\");\n\n case \"compressed\":\n return formatItem(\"COMPRESSED\");\n\n case \"elided\":\n return formatItem(\"ELIDED\");\n\n case \"node\": {\n const items: EnvelopeFormatItem[] = [];\n const subjectItem = formatEnvelope(c.subject, opts);\n\n let elidedCount = 0;\n let encryptedCount = 0;\n let compressedCount = 0;\n const typeAssertionItems: EnvelopeFormatItem[][] = [];\n const assertionItems: EnvelopeFormatItem[][] = [];\n\n for (const assertion of c.assertions) {\n const assertionCase = assertion.case();\n\n switch (assertionCase.type) {\n case \"elided\":\n elidedCount += 1;\n break;\n case \"encrypted\":\n encryptedCount += 1;\n break;\n case \"compressed\":\n compressedCount += 1;\n break;\n case \"node\":\n case \"leaf\":\n case \"wrapped\":\n case \"assertion\":\n case \"knownValue\": {\n const item = [formatEnvelope(assertion, opts)];\n\n // Check if this is a type assertion (isA predicate)\n let isTypeAssertion = false;\n const predicate = assertion.asPredicate();\n if (predicate?.subject().asKnownValue()?.equals(IS_A) === true) {\n isTypeAssertion = true;\n }\n\n if (isTypeAssertion) {\n typeAssertionItems.push(item);\n } else {\n assertionItems.push(item);\n }\n break;\n }\n }\n }\n\n // Sort assertion items\n typeAssertionItems.sort((a, b) => compareFormatItems(a[0], b[0]));\n assertionItems.sort((a, b) => compareFormatItems(a[0], b[0]));\n\n // Add type assertions first\n const allAssertionItems = [...typeAssertionItems, ...assertionItems];\n\n // Add compressed count\n if (compressedCount > 1) {\n allAssertionItems.push([formatItem(`COMPRESSED (${compressedCount})`)]);\n } else if (compressedCount > 0) {\n allAssertionItems.push([formatItem(\"COMPRESSED\")]);\n }\n\n // Add elided count\n if (elidedCount > 1) {\n allAssertionItems.push([formatItem(`ELIDED (${elidedCount})`)]);\n } else if (elidedCount > 0) {\n allAssertionItems.push([formatItem(\"ELIDED\")]);\n }\n\n // Add encrypted count\n if (encryptedCount > 1) {\n allAssertionItems.push([formatItem(`ENCRYPTED (${encryptedCount})`)]);\n } else if (encryptedCount > 0) {\n allAssertionItems.push([formatItem(\"ENCRYPTED\")]);\n }\n\n // Intersperse with separators\n const joinedAssertionItems: EnvelopeFormatItem[] = [];\n for (let i = 0; i < allAssertionItems.length; i++) {\n if (i > 0) {\n joinedAssertionItems.push(formatSeparator());\n }\n joinedAssertionItems.push(...allAssertionItems[i]);\n }\n\n // Check if subject needs braces (if it's an assertion)\n const needsBraces = c.subject.isSubjectAssertion();\n\n if (needsBraces) {\n items.push(formatBegin(\"{\"));\n }\n items.push(subjectItem);\n if (needsBraces) {\n items.push(formatEnd(\"}\"));\n }\n items.push(formatBegin(\"[\"));\n items.push(...joinedAssertionItems);\n items.push(formatEnd(\"]\"));\n\n return formatList(items);\n }\n }\n};\n\n/// Compare format items for sorting\nconst compareFormatItems = (a: EnvelopeFormatItem, b: EnvelopeFormatItem): number => {\n const getIndex = (item: EnvelopeFormatItem): number => {\n switch (item.type) {\n case \"begin\":\n return 1;\n case \"end\":\n return 2;\n case \"item\":\n return 3;\n case \"separator\":\n return 4;\n case \"list\":\n return 5;\n }\n };\n\n const aIndex = getIndex(a);\n const bIndex = getIndex(b);\n\n if (aIndex !== bIndex) {\n return aIndex - bIndex;\n }\n\n // Same type, compare values\n if (a.type === \"item\" && b.type === \"item\") {\n return a.value.localeCompare(b.value);\n }\n if (a.type === \"begin\" && b.type === \"begin\") {\n return a.value.localeCompare(b.value);\n }\n if (a.type === \"end\" && b.type === \"end\") {\n return a.value.localeCompare(b.value);\n }\n\n return 0;\n};\n\n// ============================================================================\n// Envelope Prototype Extensions\n// ============================================================================\n\n/// Implementation of formatOpt\nEnvelope.prototype.formatOpt = function (this: Envelope, opts: EnvelopeFormatOpts): string {\n const item = formatEnvelope(this, opts);\n return formatFormatItem(item, opts).trim();\n};\n\n/// Implementation of format\nEnvelope.prototype.format = function (this: Envelope): string {\n return this.formatOpt(defaultFormatOpts());\n};\n\n/// Implementation of formatFlat\nEnvelope.prototype.formatFlat = function (this: Envelope): string {\n return this.formatOpt(flatFormatOpts());\n};\n\n// All exports are done inline above with 'export const' and 'export interface'\n","/// Mermaid diagram formatting for Gordian Envelopes.\n///\n/// This module provides functionality for creating Mermaid flowchart diagrams\n/// of envelopes, which is useful for visualizing the hierarchical structure\n/// of complex envelopes in documentation and debugging.\n///\n/// The Mermaid format displays each component of an envelope as nodes in a\n/// flowchart graph, with edges showing relationships between components.\n\nimport { Envelope } from \"../base/envelope\";\nimport { EdgeType, edgeLabel } from \"../base/walk\";\nimport type { Digest } from \"../base/digest\";\nimport { withFormatContext } from \"./format-context\";\n\n// ============================================================================\n// Mermaid Types\n// ============================================================================\n\n/// The orientation of the Mermaid flowchart.\nexport enum MermaidOrientation {\n LeftToRight = \"LR\",\n TopToBottom = \"TB\",\n RightToLeft = \"RL\",\n BottomToTop = \"BT\",\n}\n\n/// The theme for the Mermaid flowchart.\nexport enum MermaidTheme {\n Default = \"default\",\n Neutral = \"neutral\",\n Dark = \"dark\",\n Forest = \"forest\",\n Base = \"base\",\n}\n\n/// Options for Mermaid diagram formatting.\nexport interface MermaidFormatOpts {\n /// Whether to hide NODE identifiers in the diagram (default: false)\n hideNodes?: boolean;\n /// Whether to use monochrome colors (default: false)\n monochrome?: boolean;\n /// The theme for the diagram (default: Default)\n theme?: MermaidTheme;\n /// The orientation of the diagram (default: LeftToRight)\n orientation?: MermaidOrientation;\n /// Set of digests to highlight in the diagram\n highlightingTarget?: Set<Digest>;\n}\n\n/// Default options for Mermaid formatting\nexport const defaultMermaidOpts = (): MermaidFormatOpts => ({\n hideNodes: false,\n monochrome: false,\n theme: MermaidTheme.Default,\n orientation: MermaidOrientation.LeftToRight,\n highlightingTarget: new Set(),\n});\n\n// ============================================================================\n// Internal Types\n// ============================================================================\n\n/// Represents an element in the Mermaid diagram\ninterface MermaidElement {\n id: number;\n level: number;\n envelope: Envelope;\n incomingEdge: EdgeType;\n showId: boolean;\n isHighlighted: boolean;\n parent: MermaidElement | undefined;\n}\n\n// ============================================================================\n// Envelope Prototype Extensions\n// ============================================================================\n\n/// Implementation of mermaidFormat\nEnvelope.prototype.mermaidFormat = function (this: Envelope): string {\n return this.mermaidFormatOpt(defaultMermaidOpts());\n};\n\n/// Implementation of mermaidFormatOpt\nEnvelope.prototype.mermaidFormatOpt = function (this: Envelope, opts: MermaidFormatOpts): string {\n const hideNodes = opts.hideNodes ?? false;\n const monochrome = opts.monochrome ?? false;\n const theme = opts.theme ?? MermaidTheme.Default;\n const orientation = opts.orientation ?? MermaidOrientation.LeftToRight;\n const highlightingTarget = opts.highlightingTarget ?? new Set<Digest>();\n\n const elements: MermaidElement[] = [];\n let nextId = 0;\n\n // Build a stack to track parent elements during traversal\n const parentStack: MermaidElement[] = [];\n\n // Walk the envelope and collect elements\n this.walk(hideNodes, undefined, (envelope, level, incomingEdge, _state) => {\n const id = nextId++;\n\n // Find the parent (last element at level - 1)\n let parent: MermaidElement | undefined;\n while (parentStack.length > 0 && parentStack[parentStack.length - 1].level >= level) {\n parentStack.pop();\n }\n if (parentStack.length > 0) {\n parent = parentStack[parentStack.length - 1];\n }\n\n const isHighlighted = containsDigest(highlightingTarget, envelope.digest());\n\n const elem: MermaidElement = {\n id,\n level,\n envelope,\n incomingEdge,\n showId: !hideNodes,\n isHighlighted,\n parent,\n };\n\n elements.push(elem);\n parentStack.push(elem);\n\n return [undefined, false];\n });\n\n // Track which element IDs have been formatted\n const formattedIds = new Set<number>();\n\n // Build output lines\n const lines: string[] = [\n `%%{ init: { 'theme': '${theme}', 'flowchart': { 'curve': 'basis' } } }%%`,\n `graph ${orientation}`,\n ];\n\n const nodeStyles: string[] = [];\n const linkStyles: string[] = [];\n let linkIndex = 0;\n\n for (const element of elements) {\n const indent = \" \".repeat(element.level);\n\n let content: string;\n if (element.parent !== undefined) {\n // Format as edge\n const thisLinkStyles: string[] = [];\n\n if (!monochrome) {\n const strokeColor = linkStrokeColor(element.incomingEdge);\n if (strokeColor !== undefined) {\n thisLinkStyles.push(`stroke:${strokeColor}`);\n }\n }\n\n if (element.isHighlighted && element.parent.isHighlighted) {\n thisLinkStyles.push(\"stroke-width:4px\");\n } else {\n thisLinkStyles.push(\"stroke-width:2px\");\n }\n\n if (thisLinkStyles.length > 0) {\n linkStyles.push(`linkStyle ${linkIndex} ${thisLinkStyles.join(\",\")}`);\n }\n linkIndex++;\n\n content = formatEdge(element, formattedIds);\n } else {\n // Format as node (root)\n content = formatNode(element, formattedIds);\n }\n\n // Node styles\n const thisNodeStyles: string[] = [];\n if (!monochrome) {\n const strokeColor = nodeColor(element.envelope);\n thisNodeStyles.push(`stroke:${strokeColor}`);\n }\n\n if (element.isHighlighted) {\n thisNodeStyles.push(\"stroke-width:6px\");\n } else {\n thisNodeStyles.push(\"stroke-width:4px\");\n }\n\n if (thisNodeStyles.length > 0) {\n nodeStyles.push(`style ${element.id} ${thisNodeStyles.join(\",\")}`);\n }\n\n lines.push(`${indent}${content}`);\n }\n\n // Add styles\n for (const style of nodeStyles) {\n lines.push(style);\n }\n for (const style of linkStyles) {\n lines.push(style);\n }\n\n return lines.join(\"\\n\");\n};\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/// Check if a set of Digests contains a specific digest\nconst containsDigest = (set: Set<Digest>, digest: Digest): boolean => {\n for (const d of set) {\n if (d.equals(digest)) {\n return true;\n }\n }\n return false;\n};\n\n/// Format a node element\nconst formatNode = (element: MermaidElement, formattedIds: Set<number>): string => {\n if (!formattedIds.has(element.id)) {\n formattedIds.add(element.id);\n\n const lines: string[] = [];\n\n // Get summary\n const summary = withFormatContext((ctx) => {\n return element.envelope.summaryWithContext(20, ctx).replace(/\"/g, \""\");\n });\n lines.push(summary);\n\n // Add digest if showing IDs\n if (element.showId) {\n const id = element.envelope.digest().short();\n lines.push(id);\n }\n\n const content = lines.join(\"<br>\");\n const [frameL, frameR] = mermaidFrame(element.envelope);\n return `${element.id}${frameL}\"${content}\"${frameR}`;\n } else {\n return `${element.id}`;\n }\n};\n\n/// Format an edge element\nconst formatEdge = (element: MermaidElement, formattedIds: Set<number>): string => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Parent is always defined for edge elements\n const parent = element.parent!;\n const label = edgeLabel(element.incomingEdge);\n const arrow = label !== undefined ? `-- ${label} -->` : \"-->\";\n\n return `${formatNode(parent, formattedIds)} ${arrow} ${formatNode(element, formattedIds)}`;\n};\n\n/// Get the Mermaid frame characters for an envelope type\nconst mermaidFrame = (envelope: Envelope): [string, string] => {\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\":\n return [\"((\", \"))\"];\n case \"leaf\":\n return [\"[\", \"]\"];\n case \"wrapped\":\n return [\"[/\", \"\\\\]\"];\n case \"assertion\":\n return [\"([\", \"])\"];\n case \"elided\":\n return [\"{{\", \"}}\"];\n case \"knownValue\":\n return [\"[/\", \"/]\"];\n case \"encrypted\":\n return [\">\", \"]\"];\n case \"compressed\":\n return [\"[[\", \"]]\"];\n default:\n return [\"[\", \"]\"];\n }\n};\n\n/// Get the node color for an envelope type\nconst nodeColor = (envelope: Envelope): string => {\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\":\n return \"red\";\n case \"leaf\":\n return \"teal\";\n case \"wrapped\":\n return \"blue\";\n case \"assertion\":\n return \"green\";\n case \"elided\":\n return \"gray\";\n case \"knownValue\":\n return \"goldenrod\";\n case \"encrypted\":\n return \"coral\";\n case \"compressed\":\n return \"purple\";\n default:\n return \"gray\";\n }\n};\n\n/// Get the link stroke color for an edge type\nconst linkStrokeColor = (edgeType: EdgeType): string | undefined => {\n switch (edgeType) {\n case EdgeType.Subject:\n return \"red\";\n case EdgeType.Content:\n return \"blue\";\n case EdgeType.Predicate:\n return \"cyan\";\n case EdgeType.Object:\n return \"magenta\";\n case EdgeType.None:\n case EdgeType.Assertion:\n return undefined;\n }\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the mermaid format extension\nexport const registerMermaidExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","import { Envelope } from \"../base/envelope\";\nimport { cborData } from \"@bcts/dcbor\";\n\n/// Hex formatting for Gordian Envelopes.\n///\n/// This module provides methods for converting envelopes to hexadecimal\n/// representations of their CBOR encoding, useful for debugging and\n/// low-level inspection.\n\n// Note: Method declarations are in the base Envelope class.\n// This module provides the prototype implementations.\n\n/// Implementation of hex()\nEnvelope.prototype.hex = function (this: Envelope): string {\n const bytes = this.cborBytes();\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n};\n\n/// Implementation of cborBytes()\nEnvelope.prototype.cborBytes = function (this: Envelope): Uint8Array {\n const cbor = this.taggedCbor();\n return cborData(cbor);\n};\n","import { Envelope } from \"../base/envelope\";\n\n// Type for CBOR values that can appear in diagnostic notation\ntype CborValue =\n | string\n | number\n | boolean\n | null\n | Uint8Array\n | CborValue[]\n | Map<CborValue, CborValue>\n | { tag: number; value: CborValue }\n | { type: number; value: unknown };\n\n/// Diagnostic notation formatting for Gordian Envelopes.\n///\n/// This module provides methods for converting envelopes to CBOR diagnostic\n/// notation, a human-readable text format defined in RFC 8949 §8.\n///\n/// See [RFC-8949 §8](https://www.rfc-editor.org/rfc/rfc8949.html#name-diagnostic-notation)\n/// for information on CBOR diagnostic notation.\n\n// Note: Method declarations are in the base Envelope class.\n// This module provides the prototype implementations.\n\n/// Converts a CBOR value to diagnostic notation\nfunction cborToDiagnostic(cbor: CborValue, indent = 0): string {\n // Handle tagged values (CBOR tags)\n if (typeof cbor === \"object\" && cbor !== null && \"tag\" in cbor && \"value\" in cbor) {\n const tagged = cbor as { tag: number; value: CborValue };\n return `${tagged.tag}(${cborToDiagnostic(tagged.value, indent)})`;\n }\n\n // Handle arrays\n if (Array.isArray(cbor)) {\n if (cbor.length === 0) {\n return \"[]\";\n }\n const items = cbor.map((item) => cborToDiagnostic(item, indent + 2));\n return `[${items.join(\", \")}]`;\n }\n\n // Handle Maps\n if (cbor instanceof Map) {\n if (cbor.size === 0) {\n return \"{}\";\n }\n const entries: string[] = [];\n for (const [key, value] of cbor) {\n const keyStr = cborToDiagnostic(key, indent + 2);\n const valueStr = cborToDiagnostic(value, indent + 2);\n entries.push(`${keyStr}: ${valueStr}`);\n }\n return `{${entries.join(\", \")}}`;\n }\n\n // Handle Uint8Array (byte strings)\n if (cbor instanceof Uint8Array) {\n const hex = Array.from(cbor)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `h'${hex}'`;\n }\n\n // Handle strings\n if (typeof cbor === \"string\") {\n return JSON.stringify(cbor);\n }\n\n // Handle CBOR objects with type information\n if (typeof cbor === \"object\" && cbor !== null && \"type\" in cbor) {\n const typed = cbor as { type: number; value: unknown };\n switch (typed.type) {\n case 0: // Unsigned\n return String(typed.value);\n case 1: // Negative\n return String(-1 - Number(typed.value));\n case 7: {\n // Simple\n const simpleValue = typed.value;\n if (simpleValue !== null && typeof simpleValue === \"object\" && \"type\" in simpleValue) {\n const floatValue = simpleValue as { type: string; value: unknown };\n if (floatValue.type === \"Float\") {\n return String(floatValue.value);\n }\n }\n if (simpleValue === 20) return \"false\";\n if (simpleValue === 21) return \"true\";\n if (simpleValue === 22) return \"null\";\n if (simpleValue === 23) return \"undefined\";\n return `simple(${String(simpleValue)})`;\n }\n }\n }\n\n // Fallback for primitives\n if (typeof cbor === \"boolean\") return String(cbor);\n if (typeof cbor === \"number\") return String(cbor);\n if (typeof cbor === \"bigint\") return String(cbor);\n if (cbor === null) return \"null\";\n if (cbor === undefined) return \"undefined\";\n\n // Unknown type - try JSON stringify\n try {\n return JSON.stringify(cbor);\n } catch {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return String(cbor);\n }\n}\n\n/// Implementation of diagnostic()\nEnvelope.prototype.diagnostic = function (this: Envelope): string {\n const cbor = this.taggedCbor();\n return cborToDiagnostic(cbor);\n};\n","/// Envelope Sealing and Unsealing\n///\n/// This module provides convenience functions for combining signing and\n/// encryption operations in a single step, creating secure, authenticated\n/// envelopes.\n///\n/// ## Sealing\n///\n/// Sealing an envelope:\n/// 1. Signs the envelope with the sender's private key\n/// 2. Encrypts the signed envelope to the recipient's public key\n///\n/// This creates a secure container where:\n/// - The recipient can verify who sent the envelope (authentication)\n/// - Only the intended recipient can decrypt the content (confidentiality)\n/// - The signature ensures the content hasn't been modified (integrity)\n///\n/// ## Unsealing\n///\n/// Unsealing performs these operations in reverse:\n/// 1. Decrypts the envelope using the recipient's private key\n/// 2. Verifies the signature using the sender's public key\n\nimport { Envelope } from \"./base/envelope\";\nimport type { Signer, Verifier } from \"./extension/signature\";\nimport type { Encrypter, Decrypter } from \"@bcts/components\";\n\n// ============================================================================\n// Envelope Prototype Extensions for Sealing\n// ============================================================================\n\n/// Implementation of encryptToRecipient\nEnvelope.prototype.encryptToRecipient = function (this: Envelope, recipient: Encrypter): Envelope {\n return this.wrap().encryptSubjectToRecipient(recipient);\n};\n\n/// Implementation of seal\nEnvelope.prototype.seal = function (\n this: Envelope,\n sender: Signer,\n recipient: Encrypter,\n): Envelope {\n return this.addSignature(sender).encryptToRecipient(recipient);\n};\n\n/// Implementation of unseal\nEnvelope.prototype.unseal = function (\n this: Envelope,\n senderPublicKey: Verifier,\n recipient: Decrypter,\n): Envelope {\n return this.decryptToRecipient(recipient).verifySignatureFrom(senderPublicKey);\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the seal extension\nexport const registerSealExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","/**\n * String utility functions used throughout the envelope library.\n *\n * Provides helper methods for string formatting and manipulation.\n */\n\n/**\n * Flanks a string with specified left and right delimiters.\n *\n * @param str - The string to flank\n * @param left - The left delimiter\n * @param right - The right delimiter\n * @returns The flanked string\n *\n * @example\n * ```typescript\n * flanked('hello', '\"', '\"') // Returns: \"hello\"\n * flanked('name', \"'\", \"'\") // Returns: 'name'\n * flanked('item', '[', ']') // Returns: [item]\n * ```\n */\nexport function flanked(str: string, left: string, right: string): string {\n return `${left}${str}${right}`;\n}\n\n/**\n * Extension methods for String objects to support fluent API style.\n */\ndeclare global {\n interface String {\n /**\n * Flanks this string with specified left and right delimiters.\n *\n * @param left - The left delimiter\n * @param right - The right delimiter\n * @returns The flanked string\n */\n flankedBy(left: string, right: string): string;\n }\n}\n\n// Extend String prototype with flankedBy method\nString.prototype.flankedBy = function (this: string, left: string, right: string): string {\n return flanked(this, left, right);\n};\n\n// Export the extension for side-effects\nexport {};\n","/// Gordian Envelope TypeScript Library\n///\n/// A TypeScript implementation of Blockchain Commons' Gordian Envelope\n/// specification for structured, privacy-focused data containers.\n///\n/// This is a 1:1 port of the Rust bc-envelope library, maintaining the same\n/// API structure and functionality.\n///\n/// @module bc-envelope\n\n// Re-export everything from the base module\nexport * from \"./base\";\n\n// Re-export everything from the extension module\nexport * from \"./extension\";\n\n// Import registration functions and call them to ensure proper initialization order\nimport { registerEncryptExtension, encryptWholeEnvelope } from \"./extension/encrypt\";\nimport { registerCompressExtension } from \"./extension/compress\";\nimport { registerProofExtension } from \"./extension/proof\";\nimport { registerSecretExtension } from \"./extension/secret\";\nimport { registerSskrExtension } from \"./extension/sskr\";\nimport { registerObscureEncryptHandler } from \"./base/elide\";\nimport type { SymmetricKey } from \"@bcts/components\";\nregisterEncryptExtension();\nregisterCompressExtension();\nregisterProofExtension();\nregisterSecretExtension();\nregisterSskrExtension();\n// Wire up obscure action handlers after all extensions are registered\nregisterObscureEncryptHandler((env, key) => encryptWholeEnvelope(env, key as SymmetricKey));\n\n// Re-export everything from the format module\n// Import for side effects (registers prototype extensions like treeFormat)\nimport \"./format\";\nexport * from \"./format\";\n\n// Import edge module for side effects (registers prototype extensions)\nimport \"./extension/edge\";\n\n// Import seal module for side effects (registers prototype extensions)\nimport \"./seal\";\nexport { registerSealExtension } from \"./seal\";\n\n// Re-export everything from the utils module\nexport * from \"./utils\";\n\n// Version information\nexport const VERSION = \"0.37.0\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,wBAAO,UAAU,QAAQ,WAAgC;AAEvD,QAAO,KAAK,KAAK,CAAC,MAAM,GAAG,EAAE;;;;;AChE/B,IAAY,gDAAL;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AAGA;AACA;AAGA;AAGA;AAGA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AAGA;AACA;AAGA;AAGA;AACA;AAGA;AACA;AACA;;;AAGF,IAAa,gBAAb,MAAa,sBAAsB,MAAM;CACvC,AAAS;CAGT,YA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ACxF,QAAO,QAAQ,MAAM,MAAM,MAAM;;;;;ACnBnC,0BAA0B;AAC1B,2BAA2B;AAK3B,+BAA+B,KAAK,QAAQ,qBAAqB,KAAK,IAAoB,CAAC;AAkB3F,MAAa,UAAU"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Digest","CborMap","SecureRandomNumberGenerator","SYMMETRIC_NONCE_SIZE","TAG_ENVELOPE","ENVELOPE","LEAF","ENCRYPTED","COMPRESSED","KnownValue","Digest","TAG_ENCODED_CBOR","MajorType","ENVELOPE","UNIT","POSITION","UR","IS_A","SALT_KV","SecureRandomNumberGenerator","SaltComponent","SIGNED","SIGNED_KV","NOTE","NOTE_KV","Signature","ATTACHMENT","ATTACHMENT_KV","VENDOR","VENDOR_KV","CONFORMS_TO","CONFORMS_TO_KV","EDGE","IS_A_RAW","SOURCE_RAW","TARGET_RAW","IS_A","SOURCE","TARGET","HAS_RECIPIENT_KV","ComponentsSealedMessage","SymmetricKey","containsDigest","SymmetricKey","ComponentsSymmetricKey","EncryptedKey","HAS_SECRET","SSKR_SHARE","SSKRSecret","SSKRShareCbor","SymmetricKey","TAG_REQUEST","BODY","NOTE","DATE","ARID","UNKNOWN_VALUE","OK_VALUE","TAG_RESPONSE","RESULT","ERROR","ARID","TAG_EVENT","CONTENT","NOTE","DATE","ARID","TagsStoreClass","KnownValuesStoreClass","KNOWN_VALUES","KnownValue","TAG_KNOWN_VALUE","TAG_DIGEST","Digest","TAG_ARID","ARID","TAG_URI","URI","TAG_UUID","UUID","TAG_NONCE","TAG_SALT","TAG_SEED","TAG_SIGNATURE","Signature","SignatureScheme","TAG_SEALED_MESSAGE","SealedMessage","EncapsulationScheme","TAG_ENCRYPTED_KEY","EncryptedKey","TAG_PRIVATE_KEY_BASE","PrivateKeyBase","TAG_PRIVATE_KEYS","PrivateKeys","TAG_PUBLIC_KEYS","PublicKeys","TAG_SIGNING_PRIVATE_KEY","SigningPrivateKey","TAG_SIGNING_PUBLIC_KEY","SigningPublicKey","TAG_SSKR_SHARE","TAG_XID","XID","IS_A"],"sources":["../src/base/digest.ts","../src/base/error.ts","../src/base/assertion.ts","../src/extension/compress.ts","../src/extension/encrypt.ts","../src/base/envelope.ts","../src/base/envelope-encodable.ts","../src/base/cbor.ts","../src/base/envelope-decodable.ts","../src/base/elide.ts","../src/base/walk.ts","../src/base/assertions.ts","../src/base/leaf.ts","../src/base/queries.ts","../src/base/wrap.ts","../src/base/ur.ts","../src/extension/types.ts","../src/extension/salt.ts","../src/extension/signature.ts","../src/extension/attachment.ts","../src/extension/edge.ts","../src/extension/recipient.ts","../src/extension/expression.ts","../src/extension/proof.ts","../src/extension/secret.ts","../src/extension/sskr.ts","../src/extension/request.ts","../src/extension/response.ts","../src/extension/event.ts","../src/format/tree.ts","../src/format/format-context.ts","../src/format/envelope-summary.ts","../src/format/notation.ts","../src/format/mermaid.ts","../src/format/hex.ts","../src/format/diagnostic.ts","../src/seal.ts","../src/utils/string.ts","../src/index.ts"],"sourcesContent":["/**\n * Re-export Digest from @bcts/components for type compatibility.\n *\n * The @bcts/components Digest class is the canonical implementation with:\n * - Full CBOR support (tagged/untagged)\n * - UR support\n * - Complete factory methods and instance methods\n *\n * This re-export ensures type compatibility between @bcts/envelope\n * and @bcts/components when used together.\n */\nexport { Digest } from \"@bcts/components\";\nimport { Digest } from \"@bcts/components\";\n\n/// Trait for types that can provide a digest.\n///\n/// This is equivalent to Rust's `DigestProvider` trait. Types that\n/// implement this interface can be used in contexts where a digest\n/// is needed for identity or integrity verification.\nexport interface DigestProvider {\n /// Returns the digest of this object.\n ///\n /// The digest uniquely identifies the semantic content of the object,\n /// regardless of whether parts of it are elided, encrypted, or compressed.\n digest(): Digest;\n}\n\n/// Helper function to create a digest from a string.\n///\n/// This is a convenience function for creating digests from text strings,\n/// which are encoded as UTF-8 before hashing.\n///\n/// @param text - The text to hash\n/// @returns A new Digest instance\n///\n/// @example\n/// ```typescript\n/// const digest = digestFromString(\"Hello, world!\");\n/// ```\nexport function digestFromString(text: string): Digest {\n const encoder = new TextEncoder();\n return Digest.fromImage(encoder.encode(text));\n}\n\n/// Helper function to create a digest from a number.\n///\n/// The number is converted to a big-endian byte representation before hashing.\n///\n/// @param num - The number to hash\n/// @returns A new Digest instance\n///\n/// @example\n/// ```typescript\n/// const digest = digestFromNumber(42);\n/// ```\nexport function digestFromNumber(num: number): Digest {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n view.setFloat64(0, num, false); // big-endian\n return Digest.fromImage(new Uint8Array(buffer));\n}\n\n// Extend Digest with short() method for compatibility with bc-envelope-rust\ndeclare module \"@bcts/components\" {\n interface Digest {\n /// Returns a short 7-character hex representation of the digest.\n /// This matches the Rust bc-envelope behavior.\n short(): string;\n }\n}\n\n// Add short() method to Digest prototype\nDigest.prototype.short = function (this: Digest): string {\n // Return first 7 hex characters (matches Rust behavior)\n return this.hex().slice(0, 7);\n};\n","/// Error types returned when operating on Gordian Envelopes.\n///\n/// These errors capture various conditions that can occur when working with\n/// envelopes, including structure validation, operation constraints, and\n/// extension-specific errors.\n///\n/// The errors are organized by category, reflecting the base envelope\n/// specification and various extensions defined in the Gordian Envelope\n/// Internet Draft and Blockchain Commons Research (BCR) documents.\n\nexport enum ErrorCode {\n // Base Specification\n ALREADY_ELIDED = \"ALREADY_ELIDED\",\n AMBIGUOUS_PREDICATE = \"AMBIGUOUS_PREDICATE\",\n INVALID_DIGEST = \"INVALID_DIGEST\",\n INVALID_FORMAT = \"INVALID_FORMAT\",\n MISSING_DIGEST = \"MISSING_DIGEST\",\n NONEXISTENT_PREDICATE = \"NONEXISTENT_PREDICATE\",\n NOT_WRAPPED = \"NOT_WRAPPED\",\n NOT_LEAF = \"NOT_LEAF\",\n NOT_ASSERTION = \"NOT_ASSERTION\",\n INVALID_ASSERTION = \"INVALID_ASSERTION\",\n\n // Attachments Extension\n INVALID_ATTACHMENT = \"INVALID_ATTACHMENT\",\n NONEXISTENT_ATTACHMENT = \"NONEXISTENT_ATTACHMENT\",\n AMBIGUOUS_ATTACHMENT = \"AMBIGUOUS_ATTACHMENT\",\n\n // Edges Extension\n EDGE_MISSING_IS_A = \"EDGE_MISSING_IS_A\",\n EDGE_MISSING_SOURCE = \"EDGE_MISSING_SOURCE\",\n EDGE_MISSING_TARGET = \"EDGE_MISSING_TARGET\",\n EDGE_DUPLICATE_IS_A = \"EDGE_DUPLICATE_IS_A\",\n EDGE_DUPLICATE_SOURCE = \"EDGE_DUPLICATE_SOURCE\",\n EDGE_DUPLICATE_TARGET = \"EDGE_DUPLICATE_TARGET\",\n EDGE_UNEXPECTED_ASSERTION = \"EDGE_UNEXPECTED_ASSERTION\",\n NONEXISTENT_EDGE = \"NONEXISTENT_EDGE\",\n AMBIGUOUS_EDGE = \"AMBIGUOUS_EDGE\",\n\n // Compression Extension\n ALREADY_COMPRESSED = \"ALREADY_COMPRESSED\",\n NOT_COMPRESSED = \"NOT_COMPRESSED\",\n\n // Symmetric Encryption Extension\n ALREADY_ENCRYPTED = \"ALREADY_ENCRYPTED\",\n NOT_ENCRYPTED = \"NOT_ENCRYPTED\",\n\n // Known Values Extension\n NOT_KNOWN_VALUE = \"NOT_KNOWN_VALUE\",\n\n // Public Key Encryption Extension\n UNKNOWN_RECIPIENT = \"UNKNOWN_RECIPIENT\",\n\n // Encrypted Key Extension\n UNKNOWN_SECRET = \"UNKNOWN_SECRET\",\n\n // Public Key Signing Extension\n UNVERIFIED_SIGNATURE = \"UNVERIFIED_SIGNATURE\",\n INVALID_OUTER_SIGNATURE_TYPE = \"INVALID_OUTER_SIGNATURE_TYPE\",\n INVALID_INNER_SIGNATURE_TYPE = \"INVALID_INNER_SIGNATURE_TYPE\",\n UNVERIFIED_INNER_SIGNATURE = \"UNVERIFIED_INNER_SIGNATURE\",\n INVALID_SIGNATURE_TYPE = \"INVALID_SIGNATURE_TYPE\",\n\n // SSKR Extension\n INVALID_SHARES = \"INVALID_SHARES\",\n SSKR = \"SSKR\",\n\n // Types Extension\n INVALID_TYPE = \"INVALID_TYPE\",\n AMBIGUOUS_TYPE = \"AMBIGUOUS_TYPE\",\n\n // Known Value Extension\n SUBJECT_NOT_UNIT = \"SUBJECT_NOT_UNIT\",\n\n // Expressions Extension\n UNEXPECTED_RESPONSE_ID = \"UNEXPECTED_RESPONSE_ID\",\n INVALID_RESPONSE = \"INVALID_RESPONSE\",\n\n // External errors\n CBOR = \"CBOR\",\n COMPONENTS = \"COMPONENTS\",\n GENERAL = \"GENERAL\",\n}\n\nexport class EnvelopeError extends Error {\n readonly code: ErrorCode;\n declare readonly cause?: Error;\n\n constructor(code: ErrorCode, message: string, cause?: Error) {\n super(message);\n this.name = \"EnvelopeError\";\n this.code = code;\n if (cause !== undefined) {\n this.cause = cause;\n }\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (\"captureStackTrace\" in Error) {\n (\n Error as {\n captureStackTrace(target: object, constructor: typeof EnvelopeError): void;\n }\n ).captureStackTrace(this, EnvelopeError);\n }\n }\n\n //\n // Base Specification\n /// Returned when attempting to compress or encrypt an envelope that has\n /// already been elided.\n ///\n /// This error occurs because an elided envelope only contains a digest\n /// reference and no longer has a subject that can be compressed or\n /// encrypted.\n static alreadyElided(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.ALREADY_ELIDED,\n \"envelope was elided, so it cannot be compressed or encrypted\",\n );\n }\n\n /// Returned when attempting to retrieve an assertion by predicate, but\n /// multiple matching assertions exist.\n ///\n /// For queries that expect a single result (like `objectForPredicate`),\n /// having multiple matching assertions is ambiguous and requires more\n /// specific targeting.\n static ambiguousPredicate(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.AMBIGUOUS_PREDICATE,\n \"more than one assertion matches the predicate\",\n );\n }\n\n /// Returned when a digest validation fails.\n ///\n /// This can occur when unwrapping an envelope, verifying signatures, or\n /// other operations that rely on the integrity of envelope digests.\n static invalidDigest(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_DIGEST, \"digest did not match\");\n }\n\n /// Returned when an envelope's format is invalid.\n ///\n /// This typically occurs during parsing or decoding of an envelope from\n /// CBOR.\n static invalidFormat(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_FORMAT, \"invalid format\");\n }\n\n /// Returned when a digest is expected but not found.\n ///\n /// This can occur when working with envelope structures that require digest\n /// information, such as when working with elided envelopes.\n static missingDigest(): EnvelopeError {\n return new EnvelopeError(ErrorCode.MISSING_DIGEST, \"a digest was expected but not found\");\n }\n\n /// Returned when attempting to retrieve an assertion by predicate, but no\n /// matching assertion exists.\n ///\n /// This error occurs with functions like `objectForPredicate` when the\n /// specified predicate doesn't match any assertion in the envelope.\n static nonexistentPredicate(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NONEXISTENT_PREDICATE, \"no assertion matches the predicate\");\n }\n\n /// Returned when attempting to unwrap an envelope that wasn't wrapped.\n ///\n /// This error occurs when calling `Envelope.tryUnwrap` on an\n /// envelope that doesn't have the wrapped format.\n static notWrapped(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_WRAPPED,\n \"cannot unwrap an envelope that was not wrapped\",\n );\n }\n\n /// Returned when expecting an envelope's subject to be a leaf, but it\n /// isn't.\n ///\n /// This error occurs when calling methods that require access to a leaf\n /// value but the envelope's subject is an assertion, node, or elided.\n static notLeaf(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NOT_LEAF, \"the envelope's subject is not a leaf\");\n }\n\n /// Returned when expecting an envelope's subject to be an assertion, but it\n /// isn't.\n ///\n /// This error occurs when calling methods that require an assertion\n /// structure but the envelope's subject has a different format.\n static notAssertion(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NOT_ASSERTION, \"the envelope's subject is not an assertion\");\n }\n\n /// Returned when assertion is invalid\n static invalidAssertion(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_ASSERTION,\n \"assertion must be a map with exactly one element\",\n );\n }\n\n //\n // Attachments Extension\n /// Returned when an attachment's format is invalid.\n ///\n /// This error occurs when an envelope contains an attachment with an\n /// invalid structure according to the Envelope Attachment specification\n /// (BCR-2023-006).\n static invalidAttachment(message?: string): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_ATTACHMENT,\n message !== undefined ? `invalid attachment: ${message}` : \"invalid attachment\",\n );\n }\n\n /// Returned when an attachment is requested but does not exist.\n ///\n /// This error occurs when attempting to retrieve an attachment by ID that\n /// doesn't exist in the envelope.\n static nonexistentAttachment(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NONEXISTENT_ATTACHMENT, \"nonexistent attachment\");\n }\n\n /// Returned when multiple attachments match a single query.\n ///\n /// This error occurs when multiple attachments have the same ID, making\n /// it ambiguous which attachment should be returned.\n static ambiguousAttachment(): EnvelopeError {\n return new EnvelopeError(ErrorCode.AMBIGUOUS_ATTACHMENT, \"ambiguous attachment\");\n }\n\n //\n // Edges Extension\n /// Returned when an edge is missing the required `'isA'` assertion.\n static edgeMissingIsA(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_MISSING_IS_A, \"edge missing 'isA' assertion\");\n }\n\n /// Returned when an edge is missing the required `'source'` assertion.\n static edgeMissingSource(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_MISSING_SOURCE, \"edge missing 'source' assertion\");\n }\n\n /// Returned when an edge is missing the required `'target'` assertion.\n static edgeMissingTarget(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_MISSING_TARGET, \"edge missing 'target' assertion\");\n }\n\n /// Returned when an edge has duplicate `'isA'` assertions.\n static edgeDuplicateIsA(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_DUPLICATE_IS_A, \"edge has duplicate 'isA' assertions\");\n }\n\n /// Returned when an edge has duplicate `'source'` assertions.\n static edgeDuplicateSource(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.EDGE_DUPLICATE_SOURCE,\n \"edge has duplicate 'source' assertions\",\n );\n }\n\n /// Returned when an edge has duplicate `'target'` assertions.\n static edgeDuplicateTarget(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.EDGE_DUPLICATE_TARGET,\n \"edge has duplicate 'target' assertions\",\n );\n }\n\n /// Returned when an edge has an unexpected assertion (per BCR-2026-003).\n static edgeUnexpectedAssertion(): EnvelopeError {\n return new EnvelopeError(ErrorCode.EDGE_UNEXPECTED_ASSERTION, \"edge has unexpected assertion\");\n }\n\n /// Returned when an edge is requested but does not exist.\n static nonexistentEdge(): EnvelopeError {\n return new EnvelopeError(ErrorCode.NONEXISTENT_EDGE, \"nonexistent edge\");\n }\n\n /// Returned when multiple edges match a single query.\n static ambiguousEdge(): EnvelopeError {\n return new EnvelopeError(ErrorCode.AMBIGUOUS_EDGE, \"ambiguous edge\");\n }\n\n //\n // Compression Extension\n /// Returned when attempting to compress an envelope that is already\n /// compressed.\n ///\n /// This error occurs when calling compression functions on an envelope that\n /// already has compressed content, as defined in BCR-2023-005.\n static alreadyCompressed(): EnvelopeError {\n return new EnvelopeError(ErrorCode.ALREADY_COMPRESSED, \"envelope was already compressed\");\n }\n\n /// Returned when attempting to decompress an envelope that is not\n /// compressed.\n ///\n /// This error occurs when calling decompression functions on an envelope\n /// that doesn't contain compressed content.\n static notCompressed(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_COMPRESSED,\n \"cannot decompress an envelope that was not compressed\",\n );\n }\n\n //\n // Symmetric Encryption Extension\n /// Returned when attempting to encrypt an envelope that is already\n /// encrypted or compressed.\n ///\n /// This error occurs to prevent multiple layers of encryption or encryption\n /// of compressed data, which could reduce security, as defined in\n /// BCR-2023-004.\n static alreadyEncrypted(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.ALREADY_ENCRYPTED,\n \"envelope was already encrypted or compressed, so it cannot be encrypted\",\n );\n }\n\n /// Returned when attempting to decrypt an envelope that is not encrypted.\n ///\n /// This error occurs when calling decryption functions on an envelope that\n /// doesn't contain encrypted content.\n static notEncrypted(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_ENCRYPTED,\n \"cannot decrypt an envelope that was not encrypted\",\n );\n }\n\n //\n // Known Values Extension\n /// Returned when expecting an envelope's subject to be a known value, but\n /// it isn't.\n ///\n /// This error occurs when calling methods that require a known value (as\n /// defined in BCR-2023-003) but the envelope's subject is a different\n /// type.\n static notKnownValue(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.NOT_KNOWN_VALUE,\n \"the envelope's subject is not a known value\",\n );\n }\n\n //\n // Public Key Encryption Extension\n /// Returned when attempting to decrypt an envelope with a recipient that\n /// doesn't match.\n ///\n /// This error occurs when trying to use a private key to decrypt an\n /// envelope that wasn't encrypted for the corresponding public key.\n static unknownRecipient(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNKNOWN_RECIPIENT, \"unknown recipient\");\n }\n\n //\n // Encrypted Key Extension\n /// Returned when attempting to decrypt an envelope with a secret that\n /// doesn't match.\n ///\n /// This error occurs when trying to use a secret that does not correspond\n /// to the expected recipient, preventing successful decryption.\n static unknownSecret(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNKNOWN_SECRET, \"secret not found\");\n }\n\n //\n // Public Key Signing Extension\n /// Returned when a signature verification fails.\n ///\n /// This error occurs when a signature does not validate against its\n /// purported public key.\n static unverifiedSignature(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNVERIFIED_SIGNATURE, \"could not verify a signature\");\n }\n\n /// Returned when the outer signature object type is not `Signature`.\n static invalidOuterSignatureType(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_OUTER_SIGNATURE_TYPE,\n \"unexpected outer signature object type\",\n );\n }\n\n /// Returned when the inner signature object type is not `Signature`.\n static invalidInnerSignatureType(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.INVALID_INNER_SIGNATURE_TYPE,\n \"unexpected inner signature object type\",\n );\n }\n\n /// Returned when the inner signature is not made with the same key as the\n /// outer signature.\n static unverifiedInnerSignature(): EnvelopeError {\n return new EnvelopeError(\n ErrorCode.UNVERIFIED_INNER_SIGNATURE,\n \"inner signature not made with same key as outer signature\",\n );\n }\n\n /// Returned when the signature object is not a `Signature`.\n static invalidSignatureType(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_SIGNATURE_TYPE, \"unexpected signature object type\");\n }\n\n //\n // SSKR Extension\n /// Returned when SSKR shares are invalid or insufficient for\n /// reconstruction.\n ///\n /// This error occurs when attempting to join SSKR shares that are\n /// malformed, from different splits, or insufficient to meet the\n /// recovery threshold.\n static invalidShares(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_SHARES, \"invalid SSKR shares\");\n }\n\n /// SSKR error wrapper\n static sskr(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.SSKR, `sskr error: ${message}`, cause);\n }\n\n //\n // Types Extension\n /// Returned when an envelope contains an invalid type.\n ///\n /// This error occurs when an envelope's type information doesn't match\n /// the expected format or value.\n static invalidType(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_TYPE, \"invalid type\");\n }\n\n /// Returned when an envelope contains ambiguous type information.\n ///\n /// This error occurs when multiple type assertions exist that conflict\n /// with each other or create ambiguity about the envelope's type.\n static ambiguousType(): EnvelopeError {\n return new EnvelopeError(ErrorCode.AMBIGUOUS_TYPE, \"ambiguous type\");\n }\n\n //\n // Known Value Extension\n /// Returned when the subject is expected to be the unit value but isn't.\n static subjectNotUnit(): EnvelopeError {\n return new EnvelopeError(ErrorCode.SUBJECT_NOT_UNIT, \"subject is not the unit value\");\n }\n\n //\n // Expressions Extension\n /// Returned when a response envelope has an unexpected ID.\n ///\n /// This error occurs when processing a response envelope and the ID doesn't\n /// match the expected request ID, as defined in BCR-2023-012.\n static unexpectedResponseId(): EnvelopeError {\n return new EnvelopeError(ErrorCode.UNEXPECTED_RESPONSE_ID, \"unexpected response ID\");\n }\n\n /// Returned when a response envelope is invalid.\n static invalidResponse(): EnvelopeError {\n return new EnvelopeError(ErrorCode.INVALID_RESPONSE, \"invalid response\");\n }\n\n //\n // External errors\n /// dcbor error wrapper\n static cbor(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.CBOR, `dcbor error: ${message}`, cause);\n }\n\n /// Components error wrapper\n static components(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.COMPONENTS, `components error: ${message}`, cause);\n }\n\n /// General error wrapper\n static general(message: string, cause?: Error): EnvelopeError {\n return new EnvelopeError(ErrorCode.GENERAL, `general error: ${message}`, cause);\n }\n\n /// Create error with custom message (equivalent to Rust's Error::msg)\n static msg(message: string): EnvelopeError {\n return EnvelopeError.general(message);\n }\n}\n\n/// Type alias for Result type (for Rust compatibility)\nexport type Result<T> = T;\n\n/// Export for backward compatibility\nexport type { EnvelopeError as Error };\n","import { Digest, type DigestProvider } from \"./digest\";\nimport { Envelope } from \"./envelope\";\nimport { type EnvelopeEncodable } from \"./envelope-encodable\";\nimport { EnvelopeError } from \"./error\";\nimport { type Cbor, cbor as toCborValue, CborMap } from \"@bcts/dcbor\";\n\n/// A predicate-object relationship representing an assertion about a subject.\n///\n/// In Gordian Envelope, assertions are the basic building blocks for attaching\n/// information to a subject. An assertion consists of a predicate (which states\n/// what is being asserted) and an object (which provides the assertion's\n/// value).\n///\n/// Assertions can be attached to envelope subjects to form semantic statements\n/// like: \"subject hasAttribute value\" or \"document signedBy signature\".\n///\n/// Assertions are equivalent to RDF (Resource Description Framework) triples,\n/// where:\n/// - The envelope's subject is the subject of the triple\n/// - The assertion's predicate is the predicate of the triple\n/// - The assertion's object is the object of the triple\n///\n/// Generally you do not create an instance of this type directly, but\n/// instead use `Envelope.newAssertion()`, or the various functions\n/// on `Envelope` that create assertions.\nexport class Assertion implements DigestProvider {\n private readonly _predicate: Envelope;\n private readonly _object: Envelope;\n private readonly _digest: Digest;\n\n /// Creates a new assertion and calculates its digest.\n ///\n /// This constructor takes a predicate and object, both of which are\n /// converted to envelopes using the `EnvelopeEncodable` trait. It then\n /// calculates the assertion's digest by combining the digests of the\n /// predicate and object.\n ///\n /// The digest is calculated according to the Gordian Envelope\n /// specification, which ensures that semantically equivalent assertions\n /// always produce the same digest.\n ///\n /// @param predicate - The predicate of the assertion, which states what is\n /// being asserted\n /// @param object - The object of the assertion, which provides the assertion's\n /// value\n ///\n /// @returns A new assertion with the specified predicate, object, and calculated\n /// digest.\n ///\n /// @example\n /// ```typescript\n /// // Direct method - create an assertion envelope\n /// const assertionEnvelope = Envelope.newAssertion(\"name\", \"Alice\");\n ///\n /// // Or create and add an assertion to a subject\n /// const person = Envelope.new(\"person\").addAssertion(\"name\", \"Alice\");\n /// ```\n constructor(predicate: EnvelopeEncodable | Envelope, object: EnvelopeEncodable | Envelope) {\n this._predicate = predicate instanceof Envelope ? predicate : Envelope.new(predicate);\n this._object = object instanceof Envelope ? object : Envelope.new(object);\n this._digest = Digest.fromDigests([this._predicate.digest(), this._object.digest()]);\n }\n\n /// Returns the predicate of the assertion.\n ///\n /// The predicate states what is being asserted about the subject. It is\n /// typically a string or known value, but can be any envelope.\n ///\n /// @returns A clone of the assertion's predicate envelope.\n predicate(): Envelope {\n return this._predicate;\n }\n\n /// Returns the object of the assertion.\n ///\n /// The object provides the value or content of the assertion. It can be any\n /// type that can be represented as an envelope.\n ///\n /// @returns A clone of the assertion's object envelope.\n object(): Envelope {\n return this._object;\n }\n\n /// Returns the digest of this assertion.\n ///\n /// Implementation of the DigestProvider interface.\n ///\n /// @returns The assertion's digest\n digest(): Digest {\n return this._digest;\n }\n\n /// Checks if two assertions are equal based on digest equality.\n ///\n /// Two assertions are considered equal if they have the same digest,\n /// regardless of how they were constructed.\n ///\n /// @param other - The other assertion to compare with\n /// @returns `true` if the assertions are equal, `false` otherwise\n equals(other: Assertion): boolean {\n return this._digest.equals(other._digest);\n }\n\n /// Converts this assertion to CBOR.\n ///\n /// The CBOR representation of an assertion is a map with a single key-value\n /// pair, where the key is the predicate's CBOR and the value is the object's\n /// CBOR.\n ///\n /// @returns A CBOR representation of this assertion\n toCbor(): Cbor {\n const map = new CborMap();\n map.set(this._predicate.untaggedCbor(), this._object.untaggedCbor());\n return toCborValue(map);\n }\n\n /// Attempts to create an assertion from a CBOR value.\n ///\n /// The CBOR must be a map with exactly one entry, where the key represents\n /// the predicate and the value represents the object.\n ///\n /// @param cbor - The CBOR value to convert\n /// @returns A new Assertion instance\n /// @throws {EnvelopeError} If the CBOR is not a valid assertion\n static fromCbor(cbor: Cbor): Assertion {\n // Check if cbor is a Map\n if (!(cbor instanceof CborMap)) {\n throw EnvelopeError.invalidAssertion();\n }\n\n return Assertion.fromCborMap(cbor);\n }\n\n /// Attempts to create an assertion from a CBOR map.\n ///\n /// The map must have exactly one entry, where the key represents the\n /// predicate and the value represents the object. This is used in\n /// the deserialization process.\n ///\n /// @param map - The CBOR map to convert\n /// @returns A new Assertion instance\n /// @throws {EnvelopeError} If the map doesn't have exactly one entry\n static fromCborMap(map: CborMap): Assertion {\n if (map.size !== 1) {\n throw EnvelopeError.invalidAssertion();\n }\n\n const entries = Array.from(map.entries());\n const firstEntry = entries[0];\n if (firstEntry === undefined) {\n throw EnvelopeError.invalidAssertion();\n }\n const [predicateCbor, objectCbor] = firstEntry;\n\n const predicate = Envelope.fromUntaggedCbor(predicateCbor);\n\n const object = Envelope.fromUntaggedCbor(objectCbor);\n\n return new Assertion(predicate, object);\n }\n\n /// Creates a string representation of this assertion for debugging.\n ///\n /// @returns A string representation\n toString(): string {\n return `Assertion(${String(this._predicate)}: ${String(this._object)})`;\n }\n\n /// Creates a copy of this assertion.\n ///\n /// Since assertions are immutable and envelopes are cheap to clone,\n /// this returns the same instance.\n ///\n /// @returns This assertion instance\n clone(): Assertion {\n return this;\n }\n}\n","import { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { type Digest } from \"../base/digest\";\nimport * as pako from \"pako\";\nimport { cborData, decodeCbor } from \"@bcts/dcbor\";\n\n/// Extension for compressing and decompressing envelopes.\n///\n/// This module provides functionality for compressing envelopes to reduce their\n/// size while maintaining their digests. Unlike elision, which removes content,\n/// compression preserves all the information in the envelope but represents it\n/// more efficiently.\n///\n/// Compression is implemented using the DEFLATE algorithm (via pako) and preserves\n/// the envelope's digest, making it compatible with the envelope's hierarchical\n/// digest tree structure.\n///\n/// @example\n/// ```typescript\n/// // Create an envelope with some larger, compressible content\n/// const lorem = \"Lorem ipsum dolor sit amet...\".repeat(10);\n/// const envelope = Envelope.new(lorem);\n///\n/// // Compress the envelope\n/// const compressed = envelope.compress();\n///\n/// // The compressed envelope has the same digest as the original\n/// console.log(envelope.digest().equals(compressed.digest())); // true\n///\n/// // But it takes up less space when serialized\n/// console.log(compressed.cborBytes().length < envelope.cborBytes().length); // true\n///\n/// // The envelope can be decompressed to recover the original content\n/// const decompressed = compressed.decompress();\n/// console.log(decompressed.asText() === lorem); // true\n/// ```\n\n/// Represents compressed data with optional digest\nexport class Compressed {\n private readonly _compressedData: Uint8Array;\n private readonly _digest?: Digest;\n\n constructor(compressedData: Uint8Array, digest?: Digest) {\n this._compressedData = compressedData;\n if (digest !== undefined) {\n this._digest = digest;\n }\n }\n\n /// Creates a Compressed instance from decompressed data\n static fromDecompressedData(decompressedData: Uint8Array, digest?: Digest): Compressed {\n const compressed = pako.deflate(decompressedData);\n return new Compressed(compressed, digest);\n }\n\n /// Returns the compressed data\n compressedData(): Uint8Array {\n return this._compressedData;\n }\n\n /// Returns the optional digest\n digestOpt(): Digest | undefined {\n return this._digest;\n }\n\n /// Decompresses the data\n decompress(): Uint8Array {\n return pako.inflate(this._compressedData);\n }\n}\n\n/// Register compression extension methods on Envelope prototype\n/// This function is exported and called during module initialization\n/// to ensure Envelope is fully defined before attaching methods.\nexport function registerCompressExtension(): void {\n if (Envelope?.prototype === undefined) {\n return;\n }\n\n // Skip if already registered\n if (typeof Envelope.prototype.compress === \"function\") {\n return;\n }\n\n Envelope.prototype.compress = function (this: Envelope): Envelope {\n const c = this.case();\n\n // If already compressed, return as-is\n if (c.type === \"compressed\") {\n return this;\n }\n\n // Can't compress encrypted or elided envelopes\n if (c.type === \"encrypted\") {\n throw EnvelopeError.general(\"Cannot compress encrypted envelope\");\n }\n if (c.type === \"elided\") {\n throw EnvelopeError.general(\"Cannot compress elided envelope\");\n }\n\n // Compress the entire envelope\n const cbor = this.taggedCbor();\n\n const decompressedData = cborData(cbor);\n\n const compressed = Compressed.fromDecompressedData(decompressedData, this.digest());\n\n // Create a compressed envelope case\n return Envelope.fromCase({ type: \"compressed\", value: compressed });\n };\n\n /// Implementation of decompress()\n Envelope.prototype.decompress = function (this: Envelope): Envelope {\n const c = this.case();\n\n if (c.type !== \"compressed\") {\n throw EnvelopeError.general(\"Envelope is not compressed\");\n }\n\n const compressed = c.value;\n const digest = compressed.digestOpt();\n\n if (digest === undefined) {\n throw EnvelopeError.general(\"Missing digest in compressed envelope\");\n }\n\n // Verify the digest matches\n if (!digest.equals(this.digest())) {\n throw EnvelopeError.general(\"Invalid digest in compressed envelope\");\n }\n\n // Decompress the data\n const decompressedData = compressed.decompress();\n\n // Parse back to envelope\n\n const cbor = decodeCbor(decompressedData);\n const envelope = Envelope.fromTaggedCbor(cbor);\n\n // Verify the decompressed envelope has the correct digest\n if (!envelope.digest().equals(digest)) {\n throw EnvelopeError.general(\"Invalid digest after decompression\");\n }\n\n return envelope;\n };\n\n /// Implementation of compressSubject()\n Envelope.prototype.compressSubject = function (this: Envelope): Envelope {\n if (this.subject().isCompressed()) {\n return this;\n }\n\n const subject = this.subject().compress();\n return this.replaceSubject(subject);\n };\n\n /// Implementation of decompressSubject()\n Envelope.prototype.decompressSubject = function (this: Envelope): Envelope {\n if (this.subject().isCompressed()) {\n const subject = this.subject().decompress();\n return this.replaceSubject(subject);\n }\n\n return this;\n };\n\n /// Implementation of isCompressed()\n Envelope.prototype.isCompressed = function (this: Envelope): boolean {\n return this.case().type === \"compressed\";\n };\n}\n\n// Registration is handled by the main index.ts to avoid circular dependency issues.\n// The registerCompressExtension() function is called explicitly after all modules are loaded.\n","import { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { type Digest } from \"../base/digest\";\nimport { cborData, decodeCbor } from \"@bcts/dcbor\";\nimport {\n aeadChaCha20Poly1305EncryptWithAad,\n aeadChaCha20Poly1305DecryptWithAad,\n SYMMETRIC_NONCE_SIZE,\n} from \"@bcts/crypto\";\nimport { SecureRandomNumberGenerator, rngRandomData } from \"@bcts/rand\";\n\n/**\n * Re-export SymmetricKey from @bcts/components for type compatibility.\n *\n * The @bcts/components SymmetricKey class is the canonical implementation with:\n * - Full CBOR support (tagged/untagged)\n * - UR support\n * - Complete factory methods\n *\n * This re-export ensures type compatibility between @bcts/envelope\n * and @bcts/components when used together.\n */\nexport { SymmetricKey } from \"@bcts/components\";\nimport type { SymmetricKey } from \"@bcts/components\";\n\n/// Extension for encrypting and decrypting envelopes using symmetric encryption.\n///\n/// This module extends Gordian Envelope with functions for symmetric encryption\n/// and decryption using the IETF-ChaCha20-Poly1305 construct. It enables\n/// privacy-enhancing operations by allowing envelope elements to be encrypted\n/// without changing the envelope's digest, similar to elision.\n///\n/// The encryption process preserves the envelope's digest tree structure, which\n/// means signatures, proofs, and other cryptographic artifacts remain valid\n/// even when parts of the envelope are encrypted.\n\n/**\n * Encrypts plaintext with a symmetric key using the given digest as AAD.\n * This is an envelope-specific helper function that returns an envelope EncryptedMessage.\n */\nfunction encryptWithDigest(\n key: SymmetricKey,\n plaintext: Uint8Array,\n digest: Digest,\n): EncryptedMessage {\n const rng = new SecureRandomNumberGenerator();\n const nonce = rngRandomData(rng, SYMMETRIC_NONCE_SIZE);\n const aad = digest.data();\n const [ciphertext, authTag] = aeadChaCha20Poly1305EncryptWithAad(\n plaintext,\n key.data(),\n nonce,\n aad,\n );\n return new EncryptedMessage(ciphertext, nonce, authTag, digest);\n}\n\n/**\n * Decrypts an envelope EncryptedMessage with a symmetric key.\n * This is an envelope-specific helper function.\n */\nfunction decryptWithDigest(key: SymmetricKey, message: EncryptedMessage): Uint8Array {\n const digest = message.aadDigest();\n if (digest === undefined) {\n throw EnvelopeError.general(\"Missing digest in encrypted message\");\n }\n const aad = digest.data();\n try {\n return aeadChaCha20Poly1305DecryptWithAad(\n message.ciphertext(),\n key.data(),\n message.nonce(),\n aad,\n message.authTag(),\n );\n } catch (_error) {\n throw EnvelopeError.general(\"Decryption failed: invalid key or corrupted data\");\n }\n}\n\n/// Represents an encrypted message with nonce, auth tag, and optional AAD digest\n/// Matches bc-components-rust/src/symmetric/encrypted_message.rs\nexport class EncryptedMessage {\n private readonly _ciphertext: Uint8Array;\n private readonly _nonce: Uint8Array;\n private readonly _authTag: Uint8Array;\n private readonly _aadDigest?: Digest;\n\n constructor(ciphertext: Uint8Array, nonce: Uint8Array, authTag: Uint8Array, aadDigest?: Digest) {\n this._ciphertext = ciphertext;\n this._nonce = nonce;\n this._authTag = authTag;\n if (aadDigest !== undefined) {\n this._aadDigest = aadDigest;\n }\n }\n\n /// Returns the ciphertext\n ciphertext(): Uint8Array {\n return this._ciphertext;\n }\n\n /// Returns the nonce\n nonce(): Uint8Array {\n return this._nonce;\n }\n\n /// Returns the authentication tag\n authTag(): Uint8Array {\n return this._authTag;\n }\n\n /// Returns the optional AAD digest\n aadDigest(): Digest | undefined {\n return this._aadDigest;\n }\n\n /// Returns the digest of this encrypted message (the AAD digest)\n digest(): Digest {\n if (this._aadDigest === undefined) {\n throw new Error(\"Encrypted message missing AAD digest\");\n }\n return this._aadDigest;\n }\n}\n\n/// Register encryption extension methods on Envelope prototype\n/// This function is exported and called during module initialization\n/// to ensure Envelope is fully defined before attaching methods.\nexport function registerEncryptExtension(): void {\n if (Envelope?.prototype === undefined) {\n return;\n }\n\n // Skip if already registered\n if (typeof Envelope.prototype.encryptSubject === \"function\") {\n return;\n }\n\n Envelope.prototype.encryptSubject = function (this: Envelope, key: SymmetricKey): Envelope {\n const c = this.case();\n\n // Can't encrypt if already encrypted or elided\n if (c.type === \"encrypted\") {\n throw EnvelopeError.general(\"Envelope is already encrypted\");\n }\n if (c.type === \"elided\") {\n throw EnvelopeError.general(\"Cannot encrypt elided envelope\");\n }\n\n // For node case, encrypt just the subject\n if (c.type === \"node\") {\n if (c.subject.isEncrypted()) {\n throw EnvelopeError.general(\"Subject is already encrypted\");\n }\n\n // Get the subject's CBOR data\n const subjectCbor = c.subject.taggedCbor();\n const encodedCbor = cborData(subjectCbor);\n const subjectDigest = c.subject.digest();\n\n // Encrypt the subject\n const encryptedMessage = encryptWithDigest(key, encodedCbor, subjectDigest);\n\n // Create encrypted envelope\n const encryptedSubject = Envelope.fromCase({\n type: \"encrypted\",\n message: encryptedMessage,\n });\n\n // Rebuild the node with encrypted subject and same assertions\n return Envelope.newWithAssertions(encryptedSubject, c.assertions);\n }\n\n // For other cases, encrypt the entire envelope\n const cbor = this.taggedCbor();\n const encodedCbor = cborData(cbor);\n const digest = this.digest();\n\n const encryptedMessage = encryptWithDigest(key, encodedCbor, digest);\n\n return Envelope.fromCase({\n type: \"encrypted\",\n message: encryptedMessage,\n });\n };\n\n /// Implementation of decryptSubject()\n Envelope.prototype.decryptSubject = function (this: Envelope, key: SymmetricKey): Envelope {\n const subjectCase = this.subject().case();\n\n if (subjectCase.type !== \"encrypted\") {\n throw EnvelopeError.general(\"Subject is not encrypted\");\n }\n\n const message = subjectCase.message;\n const subjectDigest = message.aadDigest();\n\n if (subjectDigest === undefined) {\n throw EnvelopeError.general(\"Missing digest in encrypted message\");\n }\n\n // Decrypt the subject\n const decryptedData = decryptWithDigest(key, message);\n\n // Parse back to envelope\n const cbor = decodeCbor(decryptedData);\n const resultSubject = Envelope.fromTaggedCbor(cbor);\n\n // Verify digest\n if (!resultSubject.digest().equals(subjectDigest)) {\n throw EnvelopeError.general(\"Invalid digest after decryption\");\n }\n\n const c = this.case();\n\n // If this is a node, rebuild with decrypted subject\n if (c.type === \"node\") {\n const result = Envelope.newWithAssertions(resultSubject, c.assertions);\n if (!result.digest().equals(c.digest)) {\n throw EnvelopeError.general(\"Invalid envelope digest after decryption\");\n }\n return result;\n }\n\n // Otherwise just return the decrypted subject\n return resultSubject;\n };\n\n /// Implementation of encrypt() - convenience method\n Envelope.prototype.encrypt = function (this: Envelope, key: SymmetricKey): Envelope {\n return this.wrap().encryptSubject(key);\n };\n\n /// Implementation of decrypt() - convenience method\n Envelope.prototype.decrypt = function (this: Envelope, key: SymmetricKey): Envelope {\n const decrypted = this.decryptSubject(key);\n return decrypted.unwrap();\n };\n\n /// Implementation of isEncrypted()\n Envelope.prototype.isEncrypted = function (this: Envelope): boolean {\n return this.case().type === \"encrypted\";\n };\n}\n\n/// Encrypts an entire envelope as a unit, matching Rust's\n/// ObscureAction::Encrypt behavior in elide_set_with_action.\n/// Unlike encryptSubject which only encrypts a node's subject,\n/// this encrypts the entire envelope's tagged CBOR.\nexport function encryptWholeEnvelope(envelope: Envelope, key: SymmetricKey): Envelope {\n const c = envelope.case();\n if (c.type === \"encrypted\") {\n throw EnvelopeError.general(\"Envelope is already encrypted\");\n }\n if (c.type === \"elided\") {\n throw EnvelopeError.general(\"Cannot encrypt elided envelope\");\n }\n const cbor = envelope.taggedCbor();\n const encodedCbor = cborData(cbor);\n const digest = envelope.digest();\n const encryptedMessage = encryptWithDigest(key, encodedCbor, digest);\n return Envelope.fromCase({ type: \"encrypted\", message: encryptedMessage });\n}\n\n// Registration is handled by the main index.ts to avoid circular dependency issues.\n// The registerEncryptExtension() function is called explicitly after all modules are loaded.\n","import { Digest, type DigestProvider } from \"./digest\";\nimport { Assertion } from \"./assertion\";\nimport { EnvelopeError } from \"./error\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { KnownValue } from \"@bcts/known-values\";\nimport type { Cbor, CborMap } from \"@bcts/dcbor\";\nimport {\n cbor,\n cborData,\n toTaggedValue,\n TAG_ENCODED_CBOR,\n MajorType,\n asByteString,\n asCborArray,\n asCborMap,\n asTaggedValue,\n tryExpectedTaggedValue,\n} from \"@bcts/dcbor\";\nimport { ENVELOPE, LEAF, ENCRYPTED, COMPRESSED } from \"@bcts/components\";\n\n// Type imports for extension method declarations\n// These are imported as types only to avoid circular dependencies at runtime\nimport type { ObscureAction, ObscureType } from \"./elide\";\nimport type { Visitor } from \"./walk\";\nimport type {\n SymmetricKey,\n SealedMessage,\n Signer,\n Verifier,\n Signature,\n SignatureMetadata,\n SigningOptions,\n} from \"../extension\";\nimport type { UR } from \"@bcts/uniform-resources\";\nimport type { TreeFormatOptions } from \"../format/tree\";\nimport type { EnvelopeFormatOpts } from \"../format/notation\";\nimport type { MermaidFormatOpts } from \"../format/mermaid\";\nimport type { FormatContext } from \"../format/format-context\";\nimport type { KeyDerivationMethod, Encrypter, Decrypter, Nonce, SSKRSpec } from \"@bcts/components\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\n/// Import tag values from the tags registry\n/// These match the Rust reference implementation in bc-tags-rust\nconst TAG_ENVELOPE = ENVELOPE.value;\nconst TAG_LEAF = LEAF.value;\nconst TAG_ENCRYPTED = ENCRYPTED.value;\nconst TAG_COMPRESSED = COMPRESSED.value;\n\n/// The core structural variants of a Gordian Envelope.\n///\n/// Each variant represents a different structural form that an\n/// envelope can take, as defined in the Gordian Envelope IETF Internet Draft.\n/// The different cases provide different capabilities and serve different\n/// purposes in the envelope ecosystem.\n///\n/// The `EnvelopeCase` is the internal representation of an envelope's\n/// structure. While each case has unique properties, they all maintain a digest\n/// that ensures the integrity of the envelope.\n///\n/// It is advised to use the other Envelope APIs for most uses. Please see the\n/// queries module for more information on how to interact with envelopes.\nexport type EnvelopeCase =\n | {\n type: \"node\";\n /// The subject of the node\n subject: Envelope;\n /// The assertions attached to the subject\n assertions: Envelope[];\n /// The digest of the node\n digest: Digest;\n }\n | {\n type: \"leaf\";\n /// The CBOR value contained in the leaf\n cbor: Cbor;\n /// The digest of the leaf\n digest: Digest;\n }\n | {\n type: \"wrapped\";\n /// The envelope being wrapped\n envelope: Envelope;\n /// The digest of the wrapped envelope\n digest: Digest;\n }\n | {\n type: \"assertion\";\n /// The assertion\n assertion: Assertion;\n }\n | {\n type: \"elided\";\n /// The digest of the elided content\n digest: Digest;\n }\n | {\n type: \"knownValue\";\n /// The known value instance\n value: KnownValue;\n /// The digest of the known value\n digest: Digest;\n }\n | {\n type: \"encrypted\";\n /// The encrypted message\n message: EncryptedMessage;\n }\n | {\n type: \"compressed\";\n /// The compressed data\n value: Compressed;\n };\n\n// Import types from extension modules (will be available at runtime)\nimport { Compressed } from \"../extension/compress\";\nimport { EncryptedMessage } from \"../extension/encrypt\";\n\n/// A flexible container for structured data with built-in integrity\n/// verification.\n///\n/// Gordian Envelope is the primary data structure of this library. It provides a\n/// way to encapsulate and organize data with cryptographic integrity, privacy\n/// features, and selective disclosure capabilities.\n///\n/// Key characteristics of envelopes:\n///\n/// - **Immutability**: Envelopes are immutable. Operations that appear to\n/// \"modify\" an envelope actually create a new envelope. This immutability is\n/// fundamental to maintaining the integrity of the envelope's digest tree.\n///\n/// - **Efficient Cloning**: Envelopes use shallow copying for efficient O(1)\n/// cloning. Since they're immutable, clones share the same underlying data.\n///\n/// - **Semantic Structure**: Envelopes can represent various semantic\n/// relationships through subjects, predicates, and objects (similar to RDF\n/// triples).\n///\n/// - **Digest Tree**: Each envelope maintains a Merkle-like digest tree that\n/// ensures the integrity of its contents and enables verification of\n/// individual parts.\n///\n/// - **Privacy Features**: Envelopes support selective disclosure through\n/// elision, encryption, and compression of specific parts, while maintaining\n/// the overall integrity of the structure.\n///\n/// - **Deterministic Representation**: Envelopes use deterministic CBOR\n/// encoding to ensure consistent serialization across platforms.\n///\n/// The Gordian Envelope specification is defined in an IETF Internet Draft, and\n/// this implementation closely follows that specification.\n///\n/// @example\n/// ```typescript\n/// // Create an envelope representing a person\n/// const person = Envelope.new(\"person\")\n/// .addAssertion(\"name\", \"Alice\")\n/// .addAssertion(\"age\", 30)\n/// .addAssertion(\"email\", \"alice@example.com\");\n///\n/// // Create a partially redacted version by eliding the email\n/// const redacted = person.elideRemovingTarget(\n/// person.assertionWithPredicate(\"email\")\n/// );\n///\n/// // The digest of both envelopes remains the same\n/// assert(person.digest().equals(redacted.digest()));\n/// ```\nexport class Envelope implements DigestProvider {\n private readonly _case: EnvelopeCase;\n\n /// Private constructor. Use static factory methods to create envelopes.\n ///\n /// @param envelopeCase - The envelope case variant\n private constructor(envelopeCase: EnvelopeCase) {\n this._case = envelopeCase;\n }\n\n /// Returns a reference to the underlying envelope case.\n ///\n /// The `EnvelopeCase` enum represents the specific structural variant of\n /// this envelope. This method provides access to that underlying\n /// variant for operations that need to differentiate between the\n /// different envelope types.\n ///\n /// @returns The `EnvelopeCase` that defines this envelope's structure.\n case(): EnvelopeCase {\n return this._case;\n }\n\n /// Creates an envelope with a subject, which can be any value that\n /// can be encoded as an envelope.\n ///\n /// @param subject - The subject value\n /// @returns A new envelope containing the subject\n ///\n /// @example\n /// ```typescript\n /// const envelope = Envelope.new(\"Hello, world!\");\n /// const numberEnvelope = Envelope.new(42);\n /// const binaryEnvelope = Envelope.new(new Uint8Array([1, 2, 3]));\n /// ```\n static new(subject: EnvelopeEncodableValue): Envelope {\n // Convert the subject to an envelope\n if (subject instanceof Envelope) {\n return subject;\n }\n\n // Handle KnownValue specially to create knownValue envelopes\n if (subject instanceof KnownValue) {\n return Envelope.newWithKnownValue(subject);\n }\n\n // Handle primitives and create leaf envelopes\n return Envelope.newLeaf(subject);\n }\n\n /// Creates an envelope with a subject, or null if subject is undefined.\n ///\n /// @param subject - The optional subject value\n /// @returns A new envelope or null envelope\n static newOrNull(subject: EnvelopeEncodableValue | undefined): Envelope {\n if (subject === undefined || subject === null) {\n return Envelope.null();\n }\n return Envelope.new(subject);\n }\n\n /// Creates an envelope with a subject, or undefined if subject is undefined.\n ///\n /// @param subject - The optional subject value\n /// @returns A new envelope or undefined\n static newOrNone(subject: EnvelopeEncodableValue | undefined): Envelope | undefined {\n if (subject === undefined || subject === null) {\n return undefined;\n }\n return Envelope.new(subject);\n }\n\n /// Creates an envelope from an EnvelopeCase.\n ///\n /// This is an internal method used by extensions to create envelopes\n /// from custom case types like compressed or encrypted.\n ///\n /// @param envelopeCase - The envelope case to wrap\n /// @returns A new envelope with the given case\n static fromCase(envelopeCase: EnvelopeCase): Envelope {\n return new Envelope(envelopeCase);\n }\n\n /// Creates an assertion envelope with a predicate and object.\n ///\n /// @param predicate - The predicate of the assertion\n /// @param object - The object of the assertion\n /// @returns A new assertion envelope\n ///\n /// @example\n /// ```typescript\n /// const assertion = Envelope.newAssertion(\"name\", \"Alice\");\n /// ```\n static newAssertion(predicate: EnvelopeEncodableValue, object: EnvelopeEncodableValue): Envelope {\n const predicateEnv = predicate instanceof Envelope ? predicate : Envelope.new(predicate);\n const objectEnv = object instanceof Envelope ? object : Envelope.new(object);\n return Envelope.newWithAssertion(new Assertion(predicateEnv, objectEnv));\n }\n\n /// Creates a null envelope (containing CBOR null).\n ///\n /// @returns A null envelope\n static null(): Envelope {\n return Envelope.newLeaf(null);\n }\n\n //\n // Internal constructors\n //\n\n /// Creates an envelope with a subject and unchecked assertions.\n ///\n /// The assertions are sorted by digest and the envelope's digest is calculated.\n ///\n /// @param subject - The subject envelope\n /// @param uncheckedAssertions - The assertions to attach\n /// @returns A new node envelope\n static newWithUncheckedAssertions(subject: Envelope, uncheckedAssertions: Envelope[]): Envelope {\n if (uncheckedAssertions.length === 0) {\n throw new Error(\"Assertions array cannot be empty\");\n }\n\n // Sort assertions by digest\n const sortedAssertions = [...uncheckedAssertions].sort((a, b) => {\n const aHex = a.digest().hex();\n const bHex = b.digest().hex();\n return aHex.localeCompare(bHex);\n });\n\n // Calculate digest from subject and all assertions\n const digests = [subject.digest(), ...sortedAssertions.map((a) => a.digest())];\n const digest = Digest.fromDigests(digests);\n\n return new Envelope({\n type: \"node\",\n subject,\n assertions: sortedAssertions,\n digest,\n });\n }\n\n /// Creates an envelope with a subject and validated assertions.\n ///\n /// All assertions must be assertion or obscured envelopes.\n ///\n /// @param subject - The subject envelope\n /// @param assertions - The assertions to attach\n /// @returns A new node envelope\n /// @throws {EnvelopeError} If any assertion is not valid\n static newWithAssertions(subject: Envelope, assertions: Envelope[]): Envelope {\n // Validate that all assertions are assertion or obscured envelopes\n for (const assertion of assertions) {\n if (!assertion.isSubjectAssertion() && !assertion.isSubjectObscured()) {\n throw EnvelopeError.invalidFormat();\n }\n }\n\n return Envelope.newWithUncheckedAssertions(subject, assertions);\n }\n\n /// Creates an envelope with an assertion as its subject.\n ///\n /// @param assertion - The assertion\n /// @returns A new assertion envelope\n static newWithAssertion(assertion: Assertion): Envelope {\n return new Envelope({\n type: \"assertion\",\n assertion,\n });\n }\n\n /// Creates an envelope with a known value.\n ///\n /// @param value - The known value (can be a KnownValue instance or a number/bigint)\n /// @returns A new known value envelope\n static newWithKnownValue(value: KnownValue | number | bigint): Envelope {\n const knownValue = value instanceof KnownValue ? value : new KnownValue(value);\n // Calculate digest from CBOR encoding of the known value\n const digest = Digest.fromImage(knownValue.toCborData());\n return new Envelope({\n type: \"knownValue\",\n value: knownValue,\n digest,\n });\n }\n\n /// Creates an envelope with encrypted content.\n ///\n /// @param encryptedMessage - The encrypted message\n /// @returns A new encrypted envelope\n /// @throws {EnvelopeError} If the encrypted message doesn't have a digest\n static newWithEncrypted(encryptedMessage: EncryptedMessage): Envelope {\n // TODO: Validate that encrypted message has digest\n // if (!encryptedMessage.hasDigest()) {\n // throw EnvelopeError.missingDigest();\n // }\n return new Envelope({\n type: \"encrypted\",\n message: encryptedMessage,\n });\n }\n\n /// Creates an envelope with compressed content.\n ///\n /// @param compressed - The compressed data\n /// @returns A new compressed envelope\n /// @throws {EnvelopeError} If the compressed data doesn't have a digest\n static newWithCompressed(compressed: Compressed): Envelope {\n // TODO: Validate that compressed has digest\n // if (!compressed.hasDigest()) {\n // throw EnvelopeError.missingDigest();\n // }\n return new Envelope({\n type: \"compressed\",\n value: compressed,\n });\n }\n\n /// Creates an elided envelope containing only a digest.\n ///\n /// @param digest - The digest of the elided content\n /// @returns A new elided envelope\n static newElided(digest: Digest): Envelope {\n return new Envelope({\n type: \"elided\",\n digest,\n });\n }\n\n /// Creates a leaf envelope containing a CBOR value.\n ///\n /// @param value - The value to encode as CBOR\n /// @returns A new leaf envelope\n static newLeaf(value: unknown): Envelope {\n // Convert value to CBOR\n const cbor = Envelope.valueToCbor(value);\n\n // Calculate digest from CBOR bytes\n const cborBytes = Envelope.cborToBytes(cbor);\n const digest = Digest.fromImage(cborBytes);\n\n return new Envelope({\n type: \"leaf\",\n cbor,\n digest,\n });\n }\n\n /// Creates a wrapped envelope.\n ///\n /// @param envelope - The envelope to wrap\n /// @returns A new wrapped envelope\n static newWrapped(envelope: Envelope): Envelope {\n const digest = Digest.fromDigests([envelope.digest()]);\n return new Envelope({\n type: \"wrapped\",\n envelope,\n digest,\n });\n }\n\n /// Returns the digest of this envelope.\n ///\n /// Implementation of DigestProvider interface.\n ///\n /// @returns The envelope's digest\n digest(): Digest {\n const c = this._case;\n switch (c.type) {\n case \"node\":\n case \"leaf\":\n case \"wrapped\":\n case \"elided\":\n case \"knownValue\":\n return c.digest;\n case \"assertion\":\n return c.assertion.digest();\n case \"encrypted\": {\n // Get digest from encrypted message (AAD)\n const digest = c.message.aadDigest();\n if (digest === undefined) {\n throw new Error(\"Encrypted envelope missing digest\");\n }\n return digest;\n }\n case \"compressed\": {\n // Get digest from compressed value\n const digest = c.value.digestOpt();\n if (digest === undefined) {\n throw new Error(\"Compressed envelope missing digest\");\n }\n return digest;\n }\n }\n }\n\n /// Returns the subject of this envelope.\n ///\n /// For different envelope cases:\n /// - Node: Returns the subject envelope\n /// - Other cases: Returns the envelope itself\n ///\n /// @returns The subject envelope\n subject(): Envelope {\n const c = this._case;\n switch (c.type) {\n case \"node\":\n return c.subject;\n case \"leaf\":\n case \"wrapped\":\n case \"assertion\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n return this;\n }\n }\n\n /// Checks if the envelope's subject is an assertion.\n ///\n /// @returns `true` if the subject is an assertion, `false` otherwise\n isSubjectAssertion(): boolean {\n if (this._case.type === \"assertion\") return true;\n if (this._case.type === \"node\") return this._case.subject.isSubjectAssertion();\n return false;\n }\n\n /// Checks if the envelope's subject is obscured (elided, encrypted, or compressed).\n ///\n /// @returns `true` if the subject is obscured, `false` otherwise\n isSubjectObscured(): boolean {\n const t = this._case.type;\n return t === \"elided\" || t === \"encrypted\" || t === \"compressed\";\n }\n\n //\n // CBOR conversion helpers\n //\n\n /// Converts a value to CBOR.\n ///\n /// @param value - The value to convert\n /// @returns A CBOR representation\n private static valueToCbor(value: unknown): Cbor {\n // Import cbor function at runtime to avoid circular dependencies\n\n return cbor(value as Parameters<typeof cbor>[0]);\n }\n\n /// Converts CBOR to bytes.\n ///\n /// @param cbor - The CBOR value\n /// @returns Byte representation\n private static cborToBytes(cbor: Cbor): Uint8Array {\n // Import cborData function at runtime to avoid circular dependencies\n\n return cborData(cbor);\n }\n\n /// Returns the untagged CBOR representation of this envelope.\n ///\n /// @returns The untagged CBOR\n untaggedCbor(): Cbor {\n const c = this._case;\n switch (c.type) {\n case \"node\": {\n // Array with subject followed by assertions\n const result = [c.subject.untaggedCbor()];\n for (const assertion of c.assertions) {\n result.push(assertion.untaggedCbor());\n }\n return Envelope.valueToCbor(result);\n }\n case \"leaf\":\n // Tagged with TAG_LEAF (204)\n return toTaggedValue(TAG_LEAF, c.cbor);\n case \"wrapped\":\n // Wrapped envelopes are tagged with TAG_ENVELOPE\n return c.envelope.taggedCbor();\n case \"assertion\":\n // Assertions convert to CBOR maps\n return c.assertion.toCbor();\n case \"elided\":\n // Elided is just the digest bytes\n return Envelope.valueToCbor(c.digest.data());\n case \"knownValue\":\n // Known values are encoded as untagged unsigned integers\n // This matches Rust: value.untagged_cbor()\n return c.value.untaggedCbor();\n case \"encrypted\": {\n // Encrypted is tagged with TAG_ENCRYPTED (40002)\n // Contains: [ciphertext, nonce, auth, optional_aad_digest]\n // Per BCR-2023-004 and BCR-2022-001\n const message = c.message;\n const digest = message.aadDigest();\n const arr =\n digest !== undefined\n ? [message.ciphertext(), message.nonce(), message.authTag(), digest.data()]\n : [message.ciphertext(), message.nonce(), message.authTag()];\n return toTaggedValue(TAG_ENCRYPTED, Envelope.valueToCbor(arr));\n }\n case \"compressed\": {\n // Compressed is tagged with TAG_COMPRESSED (40003)\n // and contains an array: [compressed_data, optional_digest]\n const digest = c.value.digestOpt();\n const data = c.value.compressedData();\n const arr = digest !== undefined ? [data, digest.data()] : [data];\n return toTaggedValue(TAG_COMPRESSED, Envelope.valueToCbor(arr));\n }\n }\n }\n\n /// Returns the tagged CBOR representation of this envelope.\n ///\n /// All envelopes are tagged with TAG_ENVELOPE (200).\n ///\n /// @returns The tagged CBOR\n taggedCbor(): Cbor {\n return toTaggedValue(TAG_ENVELOPE, this.untaggedCbor());\n }\n\n /// Creates an envelope from untagged CBOR.\n ///\n /// @param cbor - The untagged CBOR value\n /// @returns A new envelope\n static fromUntaggedCbor(cbor: Cbor): Envelope {\n // Check if it's a tagged value\n const tagged = asTaggedValue(cbor);\n if (tagged !== undefined) {\n const [tag, item] = tagged;\n switch (tag.value) {\n case TAG_LEAF:\n case TAG_ENCODED_CBOR:\n // Leaf envelope\n return Envelope.newLeaf(item);\n case TAG_ENVELOPE: {\n // Wrapped envelope\n const envelope = Envelope.fromUntaggedCbor(item);\n return Envelope.newWrapped(envelope);\n }\n case TAG_COMPRESSED: {\n // Compressed envelope: array with [compressed_data, optional_digest]\n const arr = asCborArray(item);\n if (arr === undefined || arr.length < 1 || arr.length > 2) {\n throw EnvelopeError.cbor(\"compressed envelope must have 1 or 2 elements\");\n }\n // We've already checked arr.length >= 1 above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const compressedData = asByteString(arr.get(0)!);\n if (compressedData === undefined) {\n throw EnvelopeError.cbor(\"compressed data must be byte string\");\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const digestBytes = arr.length === 2 ? asByteString(arr.get(1)!) : undefined;\n if (arr.length === 2 && digestBytes === undefined) {\n throw EnvelopeError.cbor(\"digest must be byte string\");\n }\n const digest = digestBytes !== undefined ? Digest.fromData(digestBytes) : undefined;\n\n // Import Compressed class at runtime to avoid circular dependency\n\n const compressed = new Compressed(compressedData, digest);\n return Envelope.fromCase({ type: \"compressed\", value: compressed });\n }\n case TAG_ENCRYPTED: {\n // Encrypted envelope: array with [ciphertext, nonce, auth, optional_aad_digest]\n // Per BCR-2023-004 and BCR-2022-001\n const arr = asCborArray(item);\n if (arr === undefined || arr.length < 3 || arr.length > 4) {\n throw EnvelopeError.cbor(\"encrypted envelope must have 3 or 4 elements\");\n }\n // We've already checked arr.length >= 3 above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const ciphertext = asByteString(arr.get(0)!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const nonce = asByteString(arr.get(1)!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const authTag = asByteString(arr.get(2)!);\n if (ciphertext === undefined || nonce === undefined || authTag === undefined) {\n throw EnvelopeError.cbor(\"ciphertext, nonce, and auth must be byte strings\");\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const digestBytes = arr.length === 4 ? asByteString(arr.get(3)!) : undefined;\n if (arr.length === 4 && digestBytes === undefined) {\n throw EnvelopeError.cbor(\"aad digest must be byte string\");\n }\n const digest = digestBytes !== undefined ? Digest.fromData(digestBytes) : undefined;\n\n const message = new EncryptedMessage(ciphertext, nonce, authTag, digest);\n return Envelope.fromCase({ type: \"encrypted\", message });\n }\n default:\n throw EnvelopeError.cbor(`unknown envelope tag: ${tag.value}`);\n }\n }\n\n // Check if it's a byte string (elided)\n const bytes = asByteString(cbor);\n if (bytes !== undefined) {\n if (bytes.length !== 32) {\n throw EnvelopeError.cbor(\"elided digest must be 32 bytes\");\n }\n return Envelope.newElided(Digest.fromData(bytes));\n }\n\n // Check if it's an array (node)\n const array = asCborArray(cbor);\n if (array !== undefined) {\n if (array.length < 2) {\n throw EnvelopeError.cbor(\"node must have at least two elements\");\n }\n const subjectCbor = array.get(0);\n if (subjectCbor === undefined) {\n throw EnvelopeError.cbor(\"node subject is missing\");\n }\n const subject = Envelope.fromUntaggedCbor(subjectCbor);\n const assertions: Envelope[] = [];\n for (let i = 1; i < array.length; i++) {\n const assertionCbor = array.get(i);\n if (assertionCbor === undefined) {\n throw EnvelopeError.cbor(`node assertion at index ${i} is missing`);\n }\n assertions.push(Envelope.fromUntaggedCbor(assertionCbor));\n }\n return Envelope.newWithAssertions(subject, assertions);\n }\n\n // Check if it's a map (assertion)\n const map = asCborMap(cbor);\n if (map !== undefined) {\n const assertion = Assertion.fromCborMap(map);\n return Envelope.newWithAssertion(assertion);\n }\n\n // Handle known values (unsigned integers)\n if (cbor.type === MajorType.Unsigned) {\n const knownValue = new KnownValue(cbor.value as number | bigint);\n return Envelope.newWithKnownValue(knownValue);\n }\n\n throw EnvelopeError.cbor(\"invalid envelope format\");\n }\n\n /// Creates an envelope from tagged CBOR.\n ///\n /// @param cbor - The tagged CBOR value (should have TAG_ENVELOPE)\n /// @returns A new envelope\n static fromTaggedCbor(cbor: Cbor): Envelope {\n try {\n const untagged = tryExpectedTaggedValue(cbor, TAG_ENVELOPE);\n return Envelope.fromUntaggedCbor(untagged);\n } catch (error) {\n throw EnvelopeError.cbor(\n `expected TAG_ENVELOPE (${TAG_ENVELOPE})`,\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /// Adds an assertion to this envelope.\n ///\n /// @param predicate - The assertion predicate\n /// @param object - The assertion object\n /// @returns A new envelope with the assertion added\n ///\n /// @example\n /// ```typescript\n /// const person = Envelope.new(\"Alice\")\n /// .addAssertion(\"age\", 30)\n /// .addAssertion(\"city\", \"Boston\");\n /// ```\n addAssertion(predicate: EnvelopeEncodableValue, object: EnvelopeEncodableValue): Envelope {\n const assertion = Envelope.newAssertion(predicate, object);\n return this.addAssertionEnvelope(assertion);\n }\n\n /// Adds an assertion envelope to this envelope.\n ///\n /// @param assertion - The assertion envelope\n /// @returns A new envelope with the assertion added\n addAssertionEnvelope(assertion: Envelope): Envelope {\n const c = this._case;\n\n // If this is already a node, add to existing assertions\n if (c.type === \"node\") {\n return Envelope.newWithAssertions(c.subject, [...c.assertions, assertion]);\n }\n\n // Otherwise, create a new node with this envelope as subject\n return Envelope.newWithAssertions(this, [assertion]);\n }\n\n /// Creates a string representation of this envelope.\n ///\n /// @returns A string representation\n toString(): string {\n return `Envelope(${this._case.type})`;\n }\n\n /// Creates a shallow copy of this envelope.\n ///\n /// Since envelopes are immutable, this returns the same instance.\n ///\n /// @returns This envelope\n clone(): Envelope {\n return this;\n }\n\n //\n // Format methods (implemented via prototype extension in format module)\n //\n\n /// Returns a tree-formatted string representation of the envelope.\n ///\n /// The tree format displays the hierarchical structure of the envelope,\n /// showing subjects, assertions, and their relationships.\n ///\n /// @param options - Optional formatting options\n /// @returns A tree-formatted string\n declare treeFormat: (options?: TreeFormatOptions) => string;\n\n /// Returns a short identifier for this envelope based on its digest.\n ///\n /// @param format - Format for the digest ('short', 'full', or 'ur')\n /// @returns A digest identifier string\n declare shortId: (format?: \"short\" | \"full\" | \"ur\") => string;\n\n /// Returns a summary string for this envelope.\n ///\n /// @param maxLength - Maximum length of the summary\n /// @returns A summary string\n declare summary: (maxLength?: number) => string;\n\n /// Returns a hex representation of the envelope's CBOR encoding.\n ///\n /// @returns A hex string\n declare hex: () => string;\n\n /// Returns the CBOR-encoded bytes of the envelope.\n ///\n /// @returns The CBOR bytes\n declare cborBytes: () => Uint8Array;\n\n /// Returns a CBOR diagnostic notation string for the envelope.\n ///\n /// @returns A diagnostic string\n declare diagnostic: () => string;\n\n //\n // Extension methods (implemented via prototype extension in extension modules)\n // These declarations ensure TypeScript recognizes the methods when consuming the package\n //\n\n // From assertions.ts\n declare addAssertionEnvelopes: (assertions: Envelope[]) => Envelope;\n declare addOptionalAssertionEnvelope: (assertion: Envelope | undefined) => Envelope;\n declare addOptionalAssertion: (\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue | undefined,\n ) => Envelope;\n declare addNonemptyStringAssertion: (predicate: EnvelopeEncodableValue, str: string) => Envelope;\n declare addAssertions: (envelopes: Envelope[]) => Envelope;\n declare addAssertionIf: (\n condition: boolean,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n ) => Envelope;\n declare addAssertionEnvelopeIf: (condition: boolean, assertionEnvelope: Envelope) => Envelope;\n declare removeAssertion: (target: Envelope) => Envelope;\n declare replaceAssertion: (assertion: Envelope, newAssertion: Envelope) => Envelope;\n declare replaceSubject: (subject: Envelope) => Envelope;\n // From salt.ts - assertion methods with optional salting\n declare addAssertionSalted: (\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n salted: boolean,\n ) => Envelope;\n declare addAssertionEnvelopeSalted: (assertionEnvelope: Envelope, salted: boolean) => Envelope;\n declare addOptionalAssertionEnvelopeSalted: (\n assertionEnvelope: Envelope | undefined,\n salted: boolean,\n ) => Envelope;\n\n // From elide.ts\n declare elide: () => Envelope;\n declare elideRemovingSetWithAction: (target: Set<Digest>, action: ObscureAction) => Envelope;\n declare elideRemovingSet: (target: Set<Digest>) => Envelope;\n declare elideRemovingArrayWithAction: (\n target: DigestProvider[],\n action: ObscureAction,\n ) => Envelope;\n declare elideRemovingArray: (target: DigestProvider[]) => Envelope;\n declare elideRemovingTargetWithAction: (\n target: DigestProvider,\n action: ObscureAction,\n ) => Envelope;\n declare elideRemovingTarget: (target: DigestProvider) => Envelope;\n declare elideRevealingSetWithAction: (target: Set<Digest>, action: ObscureAction) => Envelope;\n declare elideRevealingSet: (target: Set<Digest>) => Envelope;\n declare elideRevealingArrayWithAction: (\n target: DigestProvider[],\n action: ObscureAction,\n ) => Envelope;\n declare elideRevealingArray: (target: DigestProvider[]) => Envelope;\n declare elideRevealingTargetWithAction: (\n target: DigestProvider,\n action: ObscureAction,\n ) => Envelope;\n declare elideRevealingTarget: (target: DigestProvider) => Envelope;\n declare unelide: (envelope: Envelope) => Envelope;\n declare nodesMatching: (\n targetDigests: Set<Digest> | undefined,\n obscureTypes: ObscureType[],\n ) => Set<Digest>;\n declare walkUnelide: (envelopes: Envelope[]) => Envelope;\n declare walkReplace: (target: Set<Digest>, replacement: Envelope) => Envelope;\n declare isEquivalentTo: (other: Envelope) => boolean;\n declare isIdenticalTo: (other: Envelope) => boolean;\n\n // From leaf.ts\n declare tryLeaf: () => Cbor;\n declare extractString: () => string;\n declare extractNumber: () => number;\n declare extractBoolean: () => boolean;\n declare extractBytes: () => Uint8Array;\n declare extractNull: () => null;\n\n // Generic typed extraction methods from envelope-decodable.ts\n declare extractSubject: <T>(decoder: (cbor: Cbor) => T) => T;\n declare tryObjectForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T;\n declare tryOptionalObjectForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T | undefined;\n declare extractObjectForPredicateWithDefault: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n defaultValue: T,\n ) => T;\n declare extractObjectsForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T[];\n declare tryObjectsForPredicate: <T>(\n predicate: EnvelopeEncodableValue,\n decoder: (cbor: Cbor) => T,\n ) => T[];\n\n // From queries.ts\n declare isFalse: () => boolean;\n declare isTrue: () => boolean;\n declare isBool: () => boolean;\n declare isNumber: () => boolean;\n declare isSubjectNumber: () => boolean;\n declare isNaN: () => boolean;\n declare isSubjectNaN: () => boolean;\n declare isNull: () => boolean;\n declare tryByteString: () => Uint8Array;\n declare asByteString: () => Uint8Array | undefined;\n declare asArray: () => readonly Cbor[] | undefined;\n declare asMap: () => CborMap | undefined;\n declare asText: () => string | undefined;\n declare asLeaf: () => Cbor | undefined;\n declare asKnownValue: () => KnownValue | undefined;\n declare tryKnownValue: () => KnownValue;\n declare isKnownValue: () => boolean;\n declare isSubjectUnit: () => boolean;\n declare checkSubjectUnit: () => Envelope;\n declare hasAssertions: () => boolean;\n declare asAssertion: () => Envelope | undefined;\n declare tryAssertion: () => Envelope;\n declare asPredicate: () => Envelope | undefined;\n declare tryPredicate: () => Envelope;\n declare asObject: () => Envelope | undefined;\n declare tryObject: () => Envelope;\n declare isAssertion: () => boolean;\n declare isElided: () => boolean;\n declare isLeaf: () => boolean;\n declare isNode: () => boolean;\n declare isWrapped: () => boolean;\n declare isInternal: () => boolean;\n declare isObscured: () => boolean;\n declare assertions: () => Envelope[];\n declare assertionsWithPredicate: (predicate: EnvelopeEncodableValue) => Envelope[];\n declare assertionWithPredicate: (predicate: EnvelopeEncodableValue) => Envelope;\n declare optionalAssertionWithPredicate: (\n predicate: EnvelopeEncodableValue,\n ) => Envelope | undefined;\n declare objectForPredicate: (predicate: EnvelopeEncodableValue) => Envelope;\n declare optionalObjectForPredicate: (predicate: EnvelopeEncodableValue) => Envelope | undefined;\n declare objectsForPredicate: (predicate: EnvelopeEncodableValue) => Envelope[];\n declare elementsCount: () => number;\n declare isSubjectEncrypted: () => boolean;\n declare isSubjectCompressed: () => boolean;\n declare isSubjectElided: () => boolean;\n declare setPosition: (position: number) => Envelope;\n declare position: () => number;\n declare removePosition: () => Envelope;\n\n // From walk.ts\n declare walk: <State>(hideNodes: boolean, state: State, visit: Visitor<State>) => void;\n\n // Digest-related methods\n declare digests: (levelLimit: number) => Set<Digest>;\n declare shallowDigests: () => Set<Digest>;\n declare deepDigests: () => Set<Digest>;\n\n // Alias methods for Rust API compatibility\n declare object: () => Envelope;\n declare predicate: () => Envelope;\n\n // Additional elision method\n declare elideSetWithAction: (target: Set<Digest>, action: ObscureAction) => Envelope;\n\n // From ur.ts - UR (Uniform Resource) support\n declare urString: () => string;\n declare ur: () => UR;\n declare taggedCborData: () => Uint8Array;\n declare static fromUrString: (urString: string) => Envelope;\n declare static fromURString: (urString: string) => Envelope;\n declare static fromUR: (ur: UR) => Envelope;\n\n // From wrap.ts\n declare wrap: () => Envelope;\n declare tryUnwrap: () => Envelope;\n declare unwrap: () => Envelope;\n\n // From attachment.ts\n declare addAttachment: (\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n ) => Envelope;\n declare attachmentPayload: () => Envelope;\n declare attachmentVendor: () => string;\n declare attachmentConformsTo: () => string | undefined;\n declare attachments: () => Envelope[];\n declare attachmentsWithVendorAndConformsTo: (vendor?: string, conformsTo?: string) => Envelope[];\n declare attachmentWithVendorAndConformsTo: (vendor?: string, conformsTo?: string) => Envelope;\n declare validateAttachment: () => void;\n\n // From edge.ts (BCR-2026-003)\n declare addEdgeEnvelope: (edge: Envelope) => Envelope;\n declare edges: () => Envelope[];\n declare validateEdge: () => void;\n declare edgeIsA: () => Envelope;\n declare edgeSource: () => Envelope;\n declare edgeTarget: () => Envelope;\n declare edgeSubject: () => Envelope;\n declare edgesMatching: (\n isA?: Envelope,\n source?: Envelope,\n target?: Envelope,\n subject?: Envelope,\n ) => Envelope[];\n\n // From compress.ts\n declare compress: () => Envelope;\n declare decompress: () => Envelope;\n declare compressSubject: () => Envelope;\n declare decompressSubject: () => Envelope;\n declare isCompressed: () => boolean;\n\n // From encrypt.ts\n declare encryptSubject: (key: SymmetricKey) => Envelope;\n declare decryptSubject: (key: SymmetricKey) => Envelope;\n declare encrypt: (key: SymmetricKey) => Envelope;\n declare decrypt: (key: SymmetricKey) => Envelope;\n declare isEncrypted: () => boolean;\n\n // From proof.ts\n declare proofContainsSet: (target: Set<Digest>) => Envelope | undefined;\n declare proofContainsTarget: (target: Envelope) => Envelope | undefined;\n declare confirmContainsSet: (target: Set<Digest>, proof: Envelope) => boolean;\n declare confirmContainsTarget: (target: Envelope, proof: Envelope) => boolean;\n\n // From recipient.ts - uses Encrypter/Decrypter interfaces for PQ support\n declare encryptSubjectToRecipient: (recipient: Encrypter) => Envelope;\n declare encryptSubjectToRecipients: (recipients: Encrypter[]) => Envelope;\n declare addRecipient: (\n recipient: Encrypter,\n contentKey: SymmetricKey,\n testNonce?: Nonce,\n ) => Envelope;\n declare decryptSubjectToRecipient: (recipient: Decrypter) => Envelope;\n declare decryptToRecipient: (recipient: Decrypter) => Envelope;\n declare encryptToRecipients: (recipients: Encrypter[]) => Envelope;\n declare recipients: () => SealedMessage[];\n\n // From seal.ts\n declare encryptToRecipient: (recipient: Encrypter) => Envelope;\n declare seal: (sender: Signer, recipient: Encrypter) => Envelope;\n declare unseal: (senderPublicKey: Verifier, recipient: Decrypter) => Envelope;\n\n // From salt.ts\n declare addSalt: () => Envelope;\n declare addSaltWithLength: (count: number) => Envelope;\n declare addSaltWithLen: (count: number) => Envelope;\n declare addSaltBytes: (saltBytes: Uint8Array) => Envelope;\n declare addSaltInRange: (min: number, max: number) => Envelope;\n\n // From signature.ts — matches bc-envelope-rust/src/extension/signature/signature_impl.rs\n declare addSignature: (signer: Signer) => Envelope;\n declare addSignatureOpt: (\n signer: Signer,\n options?: SigningOptions,\n metadata?: SignatureMetadata,\n ) => Envelope;\n declare addSignatureWithMetadata: (signer: Signer, metadata?: SignatureMetadata) => Envelope;\n declare addSignatures: (signers: Signer[]) => Envelope;\n declare addSignaturesOpt: (\n signersWithOptions: {\n signer: Signer;\n options?: SigningOptions;\n metadata?: SignatureMetadata;\n }[],\n ) => Envelope;\n declare addSignaturesWithMetadata: (\n signersWithMetadata: { signer: Signer; metadata?: SignatureMetadata }[],\n ) => Envelope;\n declare makeSignedAssertion: (signature: Signature, note?: string) => Envelope;\n declare isVerifiedSignature: (signature: Signature, verifier: Verifier) => boolean;\n declare verifySignature: (signature: Signature, verifier: Verifier) => Envelope;\n declare hasSignatureFrom: (verifier: Verifier) => boolean;\n declare hasSignatureFromReturningMetadata: (verifier: Verifier) => Envelope | undefined;\n declare verifySignatureFrom: (verifier: Verifier) => Envelope;\n declare verifySignatureFromReturningMetadata: (verifier: Verifier) => Envelope;\n declare hasSignaturesFrom: (verifiers: Verifier[]) => boolean;\n declare hasSignaturesFromThreshold: (verifiers: Verifier[], threshold?: number) => boolean;\n declare verifySignaturesFrom: (verifiers: Verifier[]) => Envelope;\n declare verifySignaturesFromThreshold: (verifiers: Verifier[], threshold?: number) => Envelope;\n declare signatures: () => Envelope[];\n declare sign: (signer: Signer) => Envelope;\n declare signOpt: (signer: Signer, options?: SigningOptions) => Envelope;\n declare signWithMetadata: (signer: Signer, metadata?: SignatureMetadata) => Envelope;\n declare verify: (verifier: Verifier) => Envelope;\n declare verifyReturningMetadata: (verifier: Verifier) => {\n envelope: Envelope;\n metadata: Envelope;\n };\n\n // From types.ts\n declare addType: (object: EnvelopeEncodableValue) => Envelope;\n declare types: () => Envelope[];\n declare getType: () => Envelope;\n declare hasType: (t: EnvelopeEncodableValue) => boolean;\n declare checkType: (t: EnvelopeEncodableValue) => void;\n\n // Static methods from extensions\n declare static newAttachment: (\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n ) => Envelope;\n\n // Static methods from leaf.ts\n declare static unit: () => Envelope;\n\n // From format/notation.ts\n declare format: () => string;\n declare formatOpt: (opts: EnvelopeFormatOpts) => string;\n declare formatFlat: () => string;\n\n // From format/mermaid.ts\n declare mermaidFormat: () => string;\n declare mermaidFormatOpt: (opts: MermaidFormatOpts) => string;\n\n // From format/envelope-summary.ts\n declare summaryWithContext: (maxLength: number, context: FormatContext) => string;\n\n // From secret.ts\n declare lockSubject: (method: KeyDerivationMethod, secret: Uint8Array) => Envelope;\n declare unlockSubject: (secret: Uint8Array) => Envelope;\n declare isLockedWithPassword: () => boolean;\n declare isLockedWithSshAgent: () => boolean;\n declare addSecret: (\n method: KeyDerivationMethod,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n ) => Envelope;\n declare lock: (method: KeyDerivationMethod, secret: Uint8Array) => Envelope;\n declare unlock: (secret: Uint8Array) => Envelope;\n\n // From extension/sskr.ts\n declare sskrSplit: (spec: SSKRSpec, contentKey: SymmetricKey) => Envelope[][];\n declare sskrSplitFlattened: (spec: SSKRSpec, contentKey: SymmetricKey) => Envelope[];\n declare sskrSplitUsing: (\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n rng: RandomNumberGenerator,\n ) => Envelope[][];\n declare static sskrJoin: (envelopes: Envelope[]) => Envelope;\n\n // CBOR methods\n declare toCbor: () => unknown;\n declare expectLeaf: () => unknown;\n declare checkTypeValue: (type: unknown) => void;\n}\n","import type { CborTaggedEncodable } from \"@bcts/dcbor\";\nimport type { KnownValue } from \"@bcts/known-values\";\nimport type { Envelope } from \"./envelope\";\n\n/// A trait for types that can be encoded as a Gordian Envelope.\n///\n/// This interface defines the contract for converting a value into an envelope.\n/// Types implementing this interface can be used directly with envelope\n/// construction functions without explicit conversion.\n///\n/// There are numerous built-in implementations for common types including:\n/// - Primitive types (numbers, strings, booleans)\n/// - CBOR values\n/// - Cryptographic types (digests, keys, etc.)\n/// - Assertions\n/// - Other envelopes\n///\n/// @example\n/// ```typescript\n/// // String implements EnvelopeEncodable\n/// const e1 = Envelope.new(\"Hello\");\n///\n/// // Numbers implement EnvelopeEncodable\n/// const e2 = Envelope.new(42);\n///\n/// // Using in envelope construction\n/// const envelope = Envelope.new(\"subject\")\n/// .addAssertion(\"name\", \"Alice\") // Uses EnvelopeEncodable for both predicate and object\n/// .addAssertion(\"age\", 30); // Uses EnvelopeEncodable for the numeric object\n/// ```\nexport interface EnvelopeEncodable {\n /// Converts this value into a Gordian Envelope.\n ///\n /// This is the core method of the interface, converting the implementing type\n /// into an envelope representation. Most implementations will convert the\n /// value to a leaf envelope containing the value.\n ///\n /// @returns A new envelope containing the value.\n intoEnvelope(): Envelope;\n}\n\n/// Type guard to check if a value implements EnvelopeEncodable.\n///\n/// @param value - The value to check\n/// @returns `true` if the value implements EnvelopeEncodable, `false` otherwise\nexport function isEnvelopeEncodable(value: unknown): value is EnvelopeEncodable {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"intoEnvelope\" in value &&\n typeof (value as EnvelopeEncodable).intoEnvelope === \"function\"\n );\n}\n\n/// Helper type for values that can be encoded as envelopes.\n///\n/// This includes:\n/// - Types that directly implement EnvelopeEncodable\n/// - Primitive types (string, number, boolean)\n/// - Uint8Array (for binary data)\n/// - null and undefined\n///\n/// The Envelope class will handle conversion of these types automatically.\nexport type EnvelopeEncodableValue =\n | EnvelopeEncodable\n | string\n | number\n | boolean\n | bigint\n | Uint8Array\n | null\n | undefined\n | Envelope\n | KnownValue\n | CborTaggedEncodable;\n","import type { Cbor } from \"@bcts/dcbor\";\nimport {\n type CborTagged,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n tagsForValues,\n cborData,\n decodeCbor,\n} from \"@bcts/dcbor\";\nimport { ENVELOPE } from \"@bcts/components\";\nimport { Envelope } from \"./envelope\";\n\nconst TAG_ENVELOPE = ENVELOPE.value;\n\n/// Support for CBOR encoding and decoding of `Envelope`.\n///\n/// All envelopes are tagged with the `envelope` tag (200). Within that tag,\n/// each of the envelope cases has a unique CBOR signature:\n///\n/// * `.node` contains a CBOR array, the first element of which is the subject,\n/// followed by one or more assertions.\n/// * `.leaf` is tagged #6.24 (TAG_ENCODED_CBOR) or #6.204 (TAG_LEAF), which\n/// are the IANA tag for embedded CBOR.\n/// * `.wrapped` is tagged with the `envelope` tag.\n/// * `.assertion` is a single-element map `{predicate: object}`.\n/// * `.knownValue` is an unsigned 64-bit integer.\n/// * `.encrypted` is tagged with the `crypto-msg` tag.\n/// * `.elided` is a byte string of length 32 (the digest).\n/// * `.compressed` is tagged with the `compressed` tag.\n///\n/// This module provides implementations of the CBOR encoding/decoding traits\n/// for the Envelope type, matching the Rust bc-envelope implementation.\n\n/// Implements CborTagged interface for Envelope.\n///\n/// Returns the tags that should be used for CBOR encoding.\nexport class EnvelopeCBORTagged implements CborTagged {\n cborTags(): ReturnType<typeof tagsForValues> {\n return tagsForValues([TAG_ENVELOPE]);\n }\n\n static cborTags(): number[] {\n return tagsForValues([TAG_ENVELOPE]).map((tag) => Number(tag.value));\n }\n}\n\n/// Implements CborTaggedEncodable for Envelope.\n///\n/// Provides the untagged CBOR representation of an envelope.\nexport class EnvelopeCBORTaggedEncodable implements CborTaggedEncodable {\n constructor(private readonly envelope: Envelope) {}\n\n cborTags(): ReturnType<typeof tagsForValues> {\n return tagsForValues([TAG_ENVELOPE]);\n }\n\n untaggedCbor(): Cbor {\n return this.envelope.untaggedCbor();\n }\n\n taggedCbor(): Cbor {\n return this.envelope.taggedCbor();\n }\n}\n\n/// Implements CborTaggedDecodable for Envelope.\n///\n/// Provides the ability to decode an envelope from untagged CBOR.\nexport class EnvelopeCBORTaggedDecodable<T = Envelope> implements CborTaggedDecodable<T> {\n cborTags(): ReturnType<typeof tagsForValues> {\n return tagsForValues([TAG_ENVELOPE]);\n }\n\n static fromUntaggedCbor(cbor: Cbor): Envelope {\n return Envelope.fromUntaggedCbor(cbor);\n }\n\n static fromTaggedCbor(cbor: Cbor): Envelope {\n return Envelope.fromTaggedCbor(cbor);\n }\n\n fromUntaggedCbor(cbor: Cbor): T {\n return Envelope.fromUntaggedCbor(cbor) as T;\n }\n\n fromTaggedCbor(cbor: Cbor): T {\n return Envelope.fromTaggedCbor(cbor) as T;\n }\n}\n\n/// Convenience function to convert an Envelope to CBOR.\n///\n/// @param envelope - The envelope to convert\n/// @returns The CBOR representation (tagged)\nexport function envelopeToCbor(envelope: Envelope): Cbor {\n return envelope.taggedCbor();\n}\n\n/// Convenience function to create an Envelope from CBOR.\n///\n/// @param cbor - The CBOR value (expected to be tagged with TAG_ENVELOPE)\n/// @returns A new Envelope\nexport function envelopeFromCbor(cbor: Cbor): Envelope {\n return Envelope.fromTaggedCbor(cbor);\n}\n\n/// Convenience function to encode an Envelope to CBOR bytes.\n///\n/// @param envelope - The envelope to encode\n/// @returns The CBOR bytes\nexport function envelopeToBytes(envelope: Envelope): Uint8Array {\n return cborData(envelope.taggedCbor());\n}\n\n/// Convenience function to decode an Envelope from CBOR bytes.\n///\n/// @param bytes - The CBOR bytes\n/// @returns A new Envelope\nexport function envelopeFromBytes(bytes: Uint8Array): Envelope {\n const cbor = decodeCbor(bytes);\n return Envelope.fromTaggedCbor(cbor);\n}\n","import type { Cbor } from \"@bcts/dcbor\";\nimport { tryIntoText, tryIntoBool, tryIntoByteString, isNull, decodeCbor } from \"@bcts/dcbor\";\nimport { Envelope } from \"./envelope\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { EnvelopeError, ErrorCode } from \"./error\";\n\n/// Provides functions for extracting typed values from envelopes.\n///\n/// This module defines conversion functions that parallel Rust's `TryFrom<Envelope>`\n/// implementations. These allow extracting specific types from envelope leaf values.\n///\n/// In the Rust version, a macro (`impl_envelope_decodable!`) is used to generate\n/// these implementations for many types. In TypeScript, we provide explicit\n/// conversion functions instead.\n\n/// Extracts a string value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The string value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractString(envelope: Envelope): string {\n const cbor = envelope.tryLeaf();\n try {\n return tryIntoText(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"envelope does not contain a string\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n\n/// Extracts a number value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The number value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractNumber(envelope: Envelope): number {\n const cbor = envelope.tryLeaf();\n\n // Handle unsigned, negative, and simple (float) types\n if (\"type\" in cbor) {\n switch (cbor.type) {\n case 0: // MajorType.Unsigned\n return typeof cbor.value === \"bigint\" ? Number(cbor.value) : cbor.value;\n case 1: {\n // MajorType.Negative\n // Negative values are stored as magnitude, convert back\n const magnitude = typeof cbor.value === \"bigint\" ? Number(cbor.value) : cbor.value;\n return -magnitude - 1;\n }\n case 7: // MajorType.Simple\n if (\n typeof cbor.value === \"object\" &&\n cbor.value !== null &&\n \"type\" in cbor.value &&\n cbor.value.type === \"Float\"\n ) {\n return cbor.value.value;\n }\n break;\n case 2: // MajorType.ByteString\n case 3: // MajorType.TextString\n case 4: // MajorType.Array\n case 5: // MajorType.Map\n case 6: // MajorType.Tag\n // These CBOR types don't represent numbers\n break;\n }\n }\n\n throw EnvelopeError.cbor(\"envelope does not contain a number\");\n}\n\n/// Extracts a boolean value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The boolean value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractBoolean(envelope: Envelope): boolean {\n const cbor = envelope.tryLeaf();\n try {\n return tryIntoBool(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"envelope does not contain a boolean\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n\n/// Extracts a byte array value from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @returns The byte array value\n/// @throws {EnvelopeError} If the envelope is not a leaf or cannot be converted\nexport function extractBytes(envelope: Envelope): Uint8Array {\n const cbor = envelope.tryLeaf();\n try {\n return tryIntoByteString(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"envelope does not contain bytes\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n\n/// Extracts null from an envelope.\n///\n/// @param envelope - The envelope to extract from\n/// @throws {EnvelopeError} If the envelope is not a leaf containing null\nexport function extractNull(envelope: Envelope): null {\n const cbor = envelope.tryLeaf();\n if (isNull(cbor)) {\n return null;\n }\n throw EnvelopeError.cbor(\"envelope does not contain null\");\n}\n\n/// Static methods for creating envelopes from CBOR data.\n///\n/// These are convenience methods that mirror the Rust implementation.\nexport class EnvelopeDecoder {\n /// Creates an envelope from a CBOR value.\n ///\n /// @param cbor - The CBOR value to convert into an envelope\n /// @returns A new envelope created from the CBOR data\n /// @throws {EnvelopeError} If the CBOR does not represent a valid envelope\n static tryFromCbor(cbor: Cbor): Envelope {\n try {\n return Envelope.fromTaggedCbor(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\"invalid envelope CBOR\", error instanceof Error ? error : undefined);\n }\n }\n\n /// Creates an envelope from raw CBOR binary data.\n ///\n /// @param data - The raw CBOR binary data to convert into an envelope\n /// @returns A new envelope created from the CBOR data\n /// @throws {EnvelopeError} If the data is not valid CBOR or does not\n /// represent a valid envelope structure\n static tryFromCborData(data: Uint8Array): Envelope {\n try {\n const cbor = decodeCbor(data);\n return EnvelopeDecoder.tryFromCbor(cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"invalid envelope CBOR data\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n}\n\n/// Add the tryLeaf method to Envelope prototype.\n///\n/// This extracts the leaf CBOR value from an envelope.\nEnvelope.prototype.tryLeaf = function (this: Envelope): Cbor {\n const c = this.case();\n if (c.type !== \"leaf\") {\n throw EnvelopeError.notLeaf();\n }\n return c.cbor;\n};\n\n/// Add extraction convenience methods to Envelope prototype\nEnvelope.prototype.extractString = function (this: Envelope): string {\n return extractString(this);\n};\n\nEnvelope.prototype.extractNumber = function (this: Envelope): number {\n return extractNumber(this);\n};\n\nEnvelope.prototype.extractBoolean = function (this: Envelope): boolean {\n return extractBoolean(this);\n};\n\nEnvelope.prototype.extractBytes = function (this: Envelope): Uint8Array {\n return extractBytes(this);\n};\n\nEnvelope.prototype.extractNull = function (this: Envelope): null {\n return extractNull(this);\n};\n\n// ============================================================================\n// Generic Typed Extraction Methods\n// ============================================================================\n\n/// Type for CBOR decoder functions\nexport type CborDecoder<T> = (cbor: Cbor) => T;\n\n/// Extracts the subject of an envelope as type T using a decoder function.\n///\n/// This is the TypeScript equivalent of Rust's `TryFrom<Envelope>` trait bound.\n/// Since TypeScript doesn't have trait bounds on generics, we pass a decoder\n/// function explicitly.\n///\n/// Handles all envelope case types:\n/// - leaf: decodes the CBOR value\n/// - knownValue: converts to tagged CBOR then decodes\n/// - wrapped: recurses into the inner envelope\n/// - node: recurses on the subject\n///\n/// @example\n/// ```typescript\n/// const envelope = Envelope.new(myEncryptedKey.taggedCbor());\n/// const extracted = envelope.extractSubject(EncryptedKey.fromTaggedCbor);\n/// ```\n///\n/// @param decoder - Function to decode CBOR to type T\n/// @returns The decoded value of type T\n/// @throws {EnvelopeError} If the envelope case is unsupported or decoding fails\nexport function extractSubject<T>(envelope: Envelope, decoder: CborDecoder<T>): T {\n const subject = envelope.subject();\n const c = subject.case();\n\n switch (c.type) {\n case \"leaf\":\n try {\n return decoder(c.cbor);\n } catch (error) {\n throw EnvelopeError.cbor(\n \"failed to decode subject\",\n error instanceof Error ? error : undefined,\n );\n }\n case \"knownValue\":\n try {\n return decoder(c.value.taggedCbor());\n } catch (error) {\n throw EnvelopeError.cbor(\n \"failed to decode subject\",\n error instanceof Error ? error : undefined,\n );\n }\n case \"wrapped\":\n return extractSubject(c.envelope, decoder);\n case \"node\":\n return extractSubject(c.subject, decoder);\n case \"assertion\":\n try {\n return decoder(c.assertion.toCbor());\n } catch {\n throw EnvelopeError.invalidFormat();\n }\n case \"elided\":\n try {\n return decoder(c.digest.taggedCbor());\n } catch {\n throw EnvelopeError.invalidFormat();\n }\n case \"encrypted\":\n throw EnvelopeError.invalidFormat();\n case \"compressed\":\n throw EnvelopeError.invalidFormat();\n }\n}\n\n/// Add extractSubject method to Envelope prototype\nEnvelope.prototype.extractSubject = function <T>(this: Envelope, decoder: CborDecoder<T>): T {\n return extractSubject(this, decoder);\n};\n\n/// Extracts the object for a predicate as type T using a decoder function.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns The decoded value of type T\n/// @throws {EnvelopeError} If predicate not found or decoding fails\nexport function tryObjectForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T {\n const obj = envelope.objectForPredicate(predicate);\n return extractSubject(obj, decoder);\n}\n\n/// Add tryObjectForPredicate method to Envelope prototype\nEnvelope.prototype.tryObjectForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T {\n return tryObjectForPredicate(this, predicate, decoder);\n};\n\n/// Extracts the optional object for a predicate as type T using a decoder function.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns The decoded value of type T, or undefined if predicate not found\n/// @throws {EnvelopeError} If decoding fails (but not if predicate not found)\nexport function tryOptionalObjectForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T | undefined {\n const obj = envelope.optionalObjectForPredicate(predicate);\n if (obj === undefined) {\n return undefined;\n }\n return extractSubject(obj, decoder);\n}\n\n/// Add tryOptionalObjectForPredicate method to Envelope prototype\nEnvelope.prototype.tryOptionalObjectForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T | undefined {\n return tryOptionalObjectForPredicate(this, predicate, decoder);\n};\n\n/// Extracts the object for a predicate as type T, with a default value if not found.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @param defaultValue - Value to return if predicate not found\n/// @returns The decoded value of type T, or the default value\n/// @throws {EnvelopeError} If decoding fails (but not if predicate not found)\nexport function extractObjectForPredicateWithDefault<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n defaultValue: T,\n): T {\n const result = tryOptionalObjectForPredicate(envelope, predicate, decoder);\n return result ?? defaultValue;\n}\n\n/// Add extractObjectForPredicateWithDefault method to Envelope prototype\nEnvelope.prototype.extractObjectForPredicateWithDefault = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n defaultValue: T,\n): T {\n return extractObjectForPredicateWithDefault(this, predicate, decoder, defaultValue);\n};\n\n/// Extracts all objects for a predicate as type T using a decoder function.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns Array of decoded values of type T\n/// @throws {EnvelopeError} If any decoding fails\nexport function extractObjectsForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n const objects = envelope.objectsForPredicate(predicate);\n return objects.map((obj) => extractSubject(obj, decoder));\n}\n\n/// Add extractObjectsForPredicate method to Envelope prototype\nEnvelope.prototype.extractObjectsForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n return extractObjectsForPredicate(this, predicate, decoder);\n};\n\n/// Extracts all objects for a predicate as type T, returning empty array if none found.\n///\n/// @param envelope - The envelope to query\n/// @param predicate - The predicate to match\n/// @param decoder - Function to decode CBOR to type T\n/// @returns Array of decoded values of type T (empty if no matches)\n/// @throws {EnvelopeError} If any decoding fails\nexport function tryObjectsForPredicate<T>(\n envelope: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n try {\n return extractObjectsForPredicate(envelope, predicate, decoder);\n } catch (error) {\n // If it's a nonexistent predicate error, return empty array\n if (error instanceof EnvelopeError && error.code === ErrorCode.NONEXISTENT_PREDICATE) {\n return [];\n }\n throw error;\n }\n}\n\n/// Add tryObjectsForPredicate method to Envelope prototype\nEnvelope.prototype.tryObjectsForPredicate = function <T>(\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n decoder: CborDecoder<T>,\n): T[] {\n return tryObjectsForPredicate(this, predicate, decoder);\n};\n","import { type Digest, type DigestProvider } from \"./digest\";\nimport { Envelope } from \"./envelope\";\nimport { Assertion } from \"./assertion\";\nimport { EnvelopeError } from \"./error\";\n\n/// Types of obscuration that can be applied to envelope elements.\n///\n/// This enum identifies the different ways an envelope element can be obscured.\nexport enum ObscureType {\n /// The element has been elided, showing only its digest.\n Elided = \"elided\",\n\n /// The element has been encrypted using symmetric encryption.\n /// TODO: Implement when encrypt feature is added\n Encrypted = \"encrypted\",\n\n /// The element has been compressed to reduce its size.\n /// TODO: Implement when compress feature is added\n Compressed = \"compressed\",\n}\n\n/// Actions that can be performed on parts of an envelope to obscure them.\n///\n/// Gordian Envelope supports several ways to obscure parts of an envelope while\n/// maintaining its semantic integrity and digest tree.\nexport type ObscureAction =\n | { type: \"elide\" }\n | { type: \"encrypt\"; key: unknown }\n | { type: \"compress\" };\n\n/// Helper to create elide action\nexport function elideAction(): ObscureAction {\n return { type: \"elide\" };\n}\n\n/// Late-binding handler for the encrypt obscure action.\n/// Registered by extension/encrypt.ts to avoid circular dependencies.\nlet _obscureEncryptHandler: ((envelope: Envelope, key: unknown) => Envelope) | undefined;\n\n/// Registers the handler for the encrypt obscure action.\n/// Called by registerEncryptExtension() during module initialization.\nexport function registerObscureEncryptHandler(\n handler: (envelope: Envelope, key: unknown) => Envelope,\n): void {\n _obscureEncryptHandler = handler;\n}\n\n/// Implementation of elide()\nEnvelope.prototype.elide = function (this: Envelope): Envelope {\n const c = this.case();\n if (c.type === \"elided\") {\n return this;\n }\n return Envelope.newElided(this.digest());\n};\n\n/// Core elision logic\nfunction elideSetWithAction(\n envelope: Envelope,\n target: Set<Digest>,\n isRevealing: boolean,\n action: ObscureAction,\n): Envelope {\n const selfDigest = envelope.digest();\n const targetContainsSelf = Array.from(target).some((d) => d.equals(selfDigest));\n\n // Target Matches isRevealing elide\n // false false false\n // false true true\n // true false true\n // true true false\n\n if (targetContainsSelf !== isRevealing) {\n // Should obscure this envelope\n if (action.type === \"elide\") {\n return envelope.elide();\n } else if (action.type === \"encrypt\") {\n if (_obscureEncryptHandler === undefined) {\n throw new Error(\"Encrypt action handler not registered\");\n }\n return _obscureEncryptHandler(envelope, action.key);\n } else if (action.type === \"compress\") {\n return envelope.compress();\n }\n }\n\n const c = envelope.case();\n\n // Recursively process structure\n if (c.type === \"assertion\") {\n const predicate = elideSetWithAction(c.assertion.predicate(), target, isRevealing, action);\n const object = elideSetWithAction(c.assertion.object(), target, isRevealing, action);\n const elidedAssertion = new Assertion(predicate, object);\n return Envelope.newWithAssertion(elidedAssertion);\n } else if (c.type === \"node\") {\n const elidedSubject = elideSetWithAction(c.subject, target, isRevealing, action);\n const elidedAssertions = c.assertions.map((a) =>\n elideSetWithAction(a, target, isRevealing, action),\n );\n return Envelope.newWithUncheckedAssertions(elidedSubject, elidedAssertions);\n } else if (c.type === \"wrapped\") {\n const elidedEnvelope = elideSetWithAction(c.envelope, target, isRevealing, action);\n return Envelope.newWrapped(elidedEnvelope);\n }\n\n return envelope;\n}\n\n/// Implementation of elideRemovingSetWithAction\nEnvelope.prototype.elideRemovingSetWithAction = function (\n this: Envelope,\n target: Set<Digest>,\n action: ObscureAction,\n): Envelope {\n return elideSetWithAction(this, target, false, action);\n};\n\n/// Implementation of elideSetWithAction (for revealing mode)\nEnvelope.prototype.elideSetWithAction = function (\n this: Envelope,\n target: Set<Digest>,\n action: ObscureAction,\n): Envelope {\n return elideSetWithAction(this, target, true, action);\n};\n\n/// Implementation of elideRemovingSet\nEnvelope.prototype.elideRemovingSet = function (this: Envelope, target: Set<Digest>): Envelope {\n return elideSetWithAction(this, target, false, elideAction());\n};\n\n/// Implementation of elideRemovingArrayWithAction\nEnvelope.prototype.elideRemovingArrayWithAction = function (\n this: Envelope,\n target: DigestProvider[],\n action: ObscureAction,\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, false, action);\n};\n\n/// Implementation of elideRemovingArray\nEnvelope.prototype.elideRemovingArray = function (\n this: Envelope,\n target: DigestProvider[],\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, false, elideAction());\n};\n\n/// Implementation of elideRemovingTargetWithAction\nEnvelope.prototype.elideRemovingTargetWithAction = function (\n this: Envelope,\n target: DigestProvider,\n action: ObscureAction,\n): Envelope {\n return this.elideRemovingArrayWithAction([target], action);\n};\n\n/// Implementation of elideRemovingTarget\nEnvelope.prototype.elideRemovingTarget = function (\n this: Envelope,\n target: DigestProvider,\n): Envelope {\n return this.elideRemovingArray([target]);\n};\n\n/// Implementation of elideRevealingSetWithAction\nEnvelope.prototype.elideRevealingSetWithAction = function (\n this: Envelope,\n target: Set<Digest>,\n action: ObscureAction,\n): Envelope {\n return elideSetWithAction(this, target, true, action);\n};\n\n/// Implementation of elideRevealingSet\nEnvelope.prototype.elideRevealingSet = function (this: Envelope, target: Set<Digest>): Envelope {\n return elideSetWithAction(this, target, true, elideAction());\n};\n\n/// Implementation of elideRevealingArrayWithAction\nEnvelope.prototype.elideRevealingArrayWithAction = function (\n this: Envelope,\n target: DigestProvider[],\n action: ObscureAction,\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, true, action);\n};\n\n/// Implementation of elideRevealingArray\nEnvelope.prototype.elideRevealingArray = function (\n this: Envelope,\n target: DigestProvider[],\n): Envelope {\n const targetSet = new Set(target.map((p) => p.digest()));\n return elideSetWithAction(this, targetSet, true, elideAction());\n};\n\n/// Implementation of elideRevealingTargetWithAction\nEnvelope.prototype.elideRevealingTargetWithAction = function (\n this: Envelope,\n target: DigestProvider,\n action: ObscureAction,\n): Envelope {\n return this.elideRevealingArrayWithAction([target], action);\n};\n\n/// Implementation of elideRevealingTarget\nEnvelope.prototype.elideRevealingTarget = function (\n this: Envelope,\n target: DigestProvider,\n): Envelope {\n return this.elideRevealingArray([target]);\n};\n\n/// Implementation of unelide\nEnvelope.prototype.unelide = function (this: Envelope, envelope: Envelope): Envelope {\n if (this.digest().equals(envelope.digest())) {\n return envelope;\n }\n throw EnvelopeError.invalidDigest();\n};\n\n/// Implementation of nodesMatching\nEnvelope.prototype.nodesMatching = function (\n this: Envelope,\n targetDigests: Set<Digest> | undefined,\n obscureTypes: ObscureType[],\n): Set<Digest> {\n const result = new Set<Digest>();\n\n const visitor = (envelope: Envelope): void => {\n // Check if this node matches the target digests\n const digestMatches =\n targetDigests === undefined ||\n Array.from(targetDigests).some((d) => d.equals(envelope.digest()));\n\n if (!digestMatches) {\n return;\n }\n\n // If no obscure types specified, include all nodes\n if (obscureTypes.length === 0) {\n result.add(envelope.digest());\n return;\n }\n\n // Check if this node matches any of the specified obscure types\n const c = envelope.case();\n const typeMatches = obscureTypes.some((obscureType) => {\n if (obscureType === ObscureType.Elided && c.type === \"elided\") {\n return true;\n }\n if (obscureType === ObscureType.Encrypted && c.type === \"encrypted\") {\n return true;\n }\n if (obscureType === ObscureType.Compressed && c.type === \"compressed\") {\n return true;\n }\n return false;\n });\n\n if (typeMatches) {\n result.add(envelope.digest());\n }\n };\n\n // Walk the envelope tree\n walkEnvelope(this, visitor);\n\n return result;\n};\n\n/// Helper to walk envelope tree\nfunction walkEnvelope(envelope: Envelope, visitor: (e: Envelope) => void): void {\n visitor(envelope);\n\n const c = envelope.case();\n if (c.type === \"node\") {\n walkEnvelope(c.subject, visitor);\n for (const assertion of c.assertions) {\n walkEnvelope(assertion, visitor);\n }\n } else if (c.type === \"assertion\") {\n walkEnvelope(c.assertion.predicate(), visitor);\n walkEnvelope(c.assertion.object(), visitor);\n } else if (c.type === \"wrapped\") {\n walkEnvelope(c.envelope, visitor);\n }\n}\n\n/// Implementation of walkUnelide\nEnvelope.prototype.walkUnelide = function (this: Envelope, envelopes: Envelope[]): Envelope {\n // Build a lookup map of digest -> envelope\n const envelopeMap = new Map<string, Envelope>();\n for (const env of envelopes) {\n envelopeMap.set(env.digest().hex(), env);\n }\n\n return walkUnelideWithMap(this, envelopeMap);\n};\n\n/// Helper for walkUnelide with map\nfunction walkUnelideWithMap(envelope: Envelope, envelopeMap: Map<string, Envelope>): Envelope {\n const c = envelope.case();\n\n if (c.type === \"elided\") {\n // Try to find a matching envelope to restore\n const replacement = envelopeMap.get(envelope.digest().hex());\n return replacement ?? envelope;\n }\n\n if (c.type === \"node\") {\n const newSubject = walkUnelideWithMap(c.subject, envelopeMap);\n const newAssertions = c.assertions.map((a) => walkUnelideWithMap(a, envelopeMap));\n\n if (\n newSubject.isIdenticalTo(c.subject) &&\n newAssertions.every((a, i) => a.isIdenticalTo(c.assertions[i]))\n ) {\n return envelope;\n }\n\n return Envelope.newWithUncheckedAssertions(newSubject, newAssertions);\n }\n\n if (c.type === \"wrapped\") {\n const newEnvelope = walkUnelideWithMap(c.envelope, envelopeMap);\n if (newEnvelope.isIdenticalTo(c.envelope)) {\n return envelope;\n }\n return Envelope.newWrapped(newEnvelope);\n }\n\n if (c.type === \"assertion\") {\n const newPredicate = walkUnelideWithMap(c.assertion.predicate(), envelopeMap);\n const newObject = walkUnelideWithMap(c.assertion.object(), envelopeMap);\n\n if (\n newPredicate.isIdenticalTo(c.assertion.predicate()) &&\n newObject.isIdenticalTo(c.assertion.object())\n ) {\n return envelope;\n }\n\n return Envelope.newAssertion(newPredicate, newObject);\n }\n\n return envelope;\n}\n\n/// Implementation of walkReplace\nEnvelope.prototype.walkReplace = function (\n this: Envelope,\n target: Set<Digest>,\n replacement: Envelope,\n): Envelope {\n // Check if this node matches the target\n if (Array.from(target).some((d) => d.equals(this.digest()))) {\n return replacement;\n }\n\n const c = this.case();\n\n if (c.type === \"node\") {\n const newSubject = c.subject.walkReplace(target, replacement);\n const newAssertions = c.assertions.map((a) => a.walkReplace(target, replacement));\n\n if (\n newSubject.isIdenticalTo(c.subject) &&\n newAssertions.every((a, i) => a.isIdenticalTo(c.assertions[i]))\n ) {\n return this;\n }\n\n // Validate that all assertions are either assertions or obscured\n return Envelope.newWithAssertions(newSubject, newAssertions);\n }\n\n if (c.type === \"wrapped\") {\n const newEnvelope = c.envelope.walkReplace(target, replacement);\n if (newEnvelope.isIdenticalTo(c.envelope)) {\n return this;\n }\n return Envelope.newWrapped(newEnvelope);\n }\n\n if (c.type === \"assertion\") {\n const newPredicate = c.assertion.predicate().walkReplace(target, replacement);\n const newObject = c.assertion.object().walkReplace(target, replacement);\n\n if (\n newPredicate.isIdenticalTo(c.assertion.predicate()) &&\n newObject.isIdenticalTo(c.assertion.object())\n ) {\n return this;\n }\n\n return Envelope.newAssertion(newPredicate, newObject);\n }\n\n return this;\n};\n\n/// Implementation of isEquivalentTo\n///\n/// Two envelopes are equivalent if they have the same digest (semantic equivalence).\n/// This is a weaker comparison than `isIdenticalTo` which also checks the case type.\n///\n/// Equivalent to Rust's `is_equivalent_to()` in `src/base/digest.rs`.\nEnvelope.prototype.isEquivalentTo = function (this: Envelope, other: Envelope): boolean {\n return this.digest().equals(other.digest());\n};\n\n/// Implementation of isIdenticalTo\nEnvelope.prototype.isIdenticalTo = function (this: Envelope, other: Envelope): boolean {\n // Two envelopes are identical if they have the same digest\n // and the same case type (to handle wrapped vs unwrapped with same content)\n return this.digest().equals(other.digest()) && this.case().type === other.case().type;\n};\n","import { Envelope } from \"./envelope\";\nimport type { Digest } from \"./digest\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\n\n/// Functions for traversing and manipulating the envelope hierarchy.\n///\n/// This module provides functionality for traversing the hierarchical structure\n/// of envelopes, allowing for operations such as inspection, transformation,\n/// and extraction of specific elements. It implements a visitor pattern that\n/// enables executing arbitrary code on each element of an envelope in a\n/// structured way.\n///\n/// The traversal can be performed in two modes:\n/// - Structure-based traversal: Visits every element in the envelope hierarchy\n/// - Tree-based traversal: Skips node elements and focuses on the semantic\n/// content\n\n/// The type of incoming edge provided to the visitor.\n///\n/// This enum identifies how an envelope element is connected to its parent in\n/// the hierarchy during traversal. It helps the visitor function understand the\n/// semantic relationship between elements.\nexport enum EdgeType {\n /// No incoming edge (root)\n None = \"none\",\n /// Element is the subject of a node\n Subject = \"subject\",\n /// Element is an assertion on a node\n Assertion = \"assertion\",\n /// Element is the predicate of an assertion\n Predicate = \"predicate\",\n /// Element is the object of an assertion\n Object = \"object\",\n /// Element is the content wrapped by another envelope\n Content = \"content\",\n}\n\n/// Returns a short text label for the edge type, or undefined if no label is\n/// needed.\n///\n/// This is primarily used for tree formatting to identify relationships\n/// between elements.\n///\n/// @param edgeType - The edge type\n/// @returns A short label or undefined\nexport function edgeLabel(edgeType: EdgeType): string | undefined {\n switch (edgeType) {\n case EdgeType.Subject:\n return \"subj\";\n case EdgeType.Content:\n return \"cont\";\n case EdgeType.Predicate:\n return \"pred\";\n case EdgeType.Object:\n return \"obj\";\n case EdgeType.None:\n case EdgeType.Assertion:\n return undefined;\n default:\n return undefined;\n }\n}\n\n/// A visitor function that is called for each element in the envelope.\n///\n/// The visitor function takes the following parameters:\n/// - `envelope`: The current envelope element being visited\n/// - `level`: The depth level in the hierarchy (0 for root)\n/// - `incomingEdge`: The type of edge connecting this element to its parent\n/// - `state`: Optional context passed down from the parent's visitor call\n///\n/// The visitor returns a tuple of:\n/// - The state that will be passed to child elements\n/// - A boolean indicating whether to stop traversal (true = stop)\n///\n/// This enables accumulating state or passing context during traversal.\nexport type Visitor<State> = (\n envelope: Envelope,\n level: number,\n incomingEdge: EdgeType,\n state: State,\n) => [State, boolean];\n\n/// Implementation of walk()\nEnvelope.prototype.walk = function <State>(\n this: Envelope,\n hideNodes: boolean,\n state: State,\n visit: Visitor<State>,\n): void {\n if (hideNodes) {\n walkTree(this, 0, EdgeType.None, state, visit);\n } else {\n walkStructure(this, 0, EdgeType.None, state, visit);\n }\n};\n\n/// Recursive implementation of structure-based traversal.\n///\n/// This internal function performs the actual recursive traversal of the\n/// envelope structure, visiting every element and maintaining the\n/// correct level and edge relationships.\nfunction walkStructure<State>(\n envelope: Envelope,\n level: number,\n incomingEdge: EdgeType,\n state: State,\n visit: Visitor<State>,\n): void {\n // Visit this envelope\n const [newState, stop] = visit(envelope, level, incomingEdge, state);\n if (stop) {\n return;\n }\n\n const nextLevel = level + 1;\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\":\n // Visit subject\n walkStructure(c.subject, nextLevel, EdgeType.Subject, newState, visit);\n // Visit all assertions\n for (const assertion of c.assertions) {\n walkStructure(assertion, nextLevel, EdgeType.Assertion, newState, visit);\n }\n break;\n\n case \"wrapped\":\n // Visit wrapped envelope\n walkStructure(c.envelope, nextLevel, EdgeType.Content, newState, visit);\n break;\n\n case \"assertion\":\n // Visit predicate and object\n walkStructure(c.assertion.predicate(), nextLevel, EdgeType.Predicate, newState, visit);\n walkStructure(c.assertion.object(), nextLevel, EdgeType.Object, newState, visit);\n break;\n\n case \"leaf\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n // Leaf nodes and other types have no children\n break;\n }\n}\n\n/// Recursive implementation of tree-based traversal.\n///\n/// This internal function performs the actual recursive traversal of the\n/// envelope's semantic tree, skipping node containers and focusing on\n/// the semantic content elements. It maintains the correct level and\n/// edge relationships while skipping structural elements.\nfunction walkTree<State>(\n envelope: Envelope,\n level: number,\n incomingEdge: EdgeType,\n state: State,\n visit: Visitor<State>,\n): State {\n let currentState = state;\n let subjectLevel = level;\n\n // Skip visiting if this is a node\n if (!envelope.isNode()) {\n const [newState, stop] = visit(envelope, level, incomingEdge, currentState);\n if (stop) {\n return newState;\n }\n currentState = newState;\n subjectLevel = level + 1;\n }\n\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\": {\n // Visit subject\n const assertionState = walkTree(\n c.subject,\n subjectLevel,\n EdgeType.Subject,\n currentState,\n visit,\n );\n // Visit all assertions\n const assertionLevel = subjectLevel + 1;\n for (const assertion of c.assertions) {\n walkTree(assertion, assertionLevel, EdgeType.Assertion, assertionState, visit);\n }\n break;\n }\n\n case \"wrapped\":\n // Visit wrapped envelope\n walkTree(c.envelope, subjectLevel, EdgeType.Content, currentState, visit);\n break;\n\n case \"assertion\":\n // Visit predicate and object\n walkTree(c.assertion.predicate(), subjectLevel, EdgeType.Predicate, currentState, visit);\n walkTree(c.assertion.object(), subjectLevel, EdgeType.Object, currentState, visit);\n break;\n\n case \"leaf\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n // Leaf nodes and other types have no children\n break;\n }\n\n return currentState;\n}\n\n// ============================================================================\n// Digest collection methods\n// ============================================================================\n\n/// Implementation of digests()\n/// Returns the set of digests in the envelope, down to the specified level.\nEnvelope.prototype.digests = function (this: Envelope, levelLimit: number): Set<Digest> {\n const result = new Set<Digest>();\n\n const visitor = (\n envelope: Envelope,\n level: number,\n _incomingEdge: EdgeType,\n _state: undefined,\n ): [undefined, boolean] => {\n if (level < levelLimit) {\n result.add(envelope.digest());\n result.add(envelope.subject().digest());\n }\n return [undefined, false]; // Continue walking\n };\n\n this.walk(false, undefined, visitor);\n return result;\n};\n\n/// Implementation of deepDigests()\n/// Returns all digests in the envelope at all levels.\nEnvelope.prototype.deepDigests = function (this: Envelope): Set<Digest> {\n return this.digests(Number.MAX_SAFE_INTEGER);\n};\n\n/// Implementation of shallowDigests()\n/// Returns the digests in the envelope down to its second level.\nEnvelope.prototype.shallowDigests = function (this: Envelope): Set<Digest> {\n return this.digests(2);\n};\n\n// ============================================================================\n// Alias methods for Rust API compatibility\n// ============================================================================\n\n/// Implementation of object() - alias for tryObject()\nEnvelope.prototype.object = function (this: Envelope): Envelope {\n return this.tryObject();\n};\n\n/// Implementation of predicate() - alias for tryPredicate()\nEnvelope.prototype.predicate = function (this: Envelope): Envelope {\n return this.tryPredicate();\n};\n\n// ============================================================================\n// CBOR helper methods\n// ============================================================================\n\n/// Implementation of toCbor() - alias for taggedCbor()\nEnvelope.prototype.toCbor = function (this: Envelope): unknown {\n return this.taggedCbor();\n};\n\n/// Implementation of expectLeaf() - returns the leaf CBOR value or throws\nEnvelope.prototype.expectLeaf = function (this: Envelope): unknown {\n return this.tryLeaf();\n};\n\n/// Implementation of checkTypeValue() - validates the envelope has a specific type\nEnvelope.prototype.checkTypeValue = function (this: Envelope, type: unknown): void {\n this.checkType(type as EnvelopeEncodableValue);\n};\n","import { Envelope } from \"./envelope\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { EnvelopeError } from \"./error\";\n\n/// Support for adding assertions.\n///\n/// Assertions are predicate-object pairs that make statements about an\n/// envelope's subject. This implementation provides methods for adding various\n/// types of assertions to envelopes.\n///\n/// These methods extend the Envelope class to provide a rich API for\n/// working with assertions, matching the Rust bc-envelope implementation.\n\n/// Implementation of addAssertionEnvelopes\nEnvelope.prototype.addAssertionEnvelopes = function (\n this: Envelope,\n assertions: Envelope[],\n): Envelope {\n return assertions.reduce((result, assertion) => result.addAssertionEnvelope(assertion), this);\n};\n\n/// Implementation of addOptionalAssertionEnvelope\nEnvelope.prototype.addOptionalAssertionEnvelope = function (\n this: Envelope,\n assertion: Envelope | undefined,\n): Envelope {\n if (assertion === undefined) {\n return this;\n }\n\n // Validate that the assertion is a valid assertion or obscured envelope\n if (!assertion.isSubjectAssertion() && !assertion.isSubjectObscured()) {\n throw EnvelopeError.invalidFormat();\n }\n\n const c = this.case();\n\n // Check if this is already a node\n if (c.type === \"node\") {\n // Check for duplicate assertions\n const isDuplicate = c.assertions.some((a) => a.digest().equals(assertion.digest()));\n if (isDuplicate) {\n return this;\n }\n\n // Add the new assertion\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, assertion]);\n }\n\n // Otherwise, create a new node with this envelope as subject\n return Envelope.newWithUncheckedAssertions(this.subject(), [assertion]);\n};\n\n/// Implementation of addOptionalAssertion\nEnvelope.prototype.addOptionalAssertion = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue | undefined,\n): Envelope {\n if (object === undefined || object === null) {\n return this;\n }\n return this.addAssertion(predicate, object);\n};\n\n/// Implementation of addNonemptyStringAssertion\nEnvelope.prototype.addNonemptyStringAssertion = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n str: string,\n): Envelope {\n if (str.length === 0) {\n return this;\n }\n return this.addAssertion(predicate, str);\n};\n\n/// Implementation of addAssertions\nEnvelope.prototype.addAssertions = function (this: Envelope, envelopes: Envelope[]): Envelope {\n return envelopes.reduce((result, envelope) => result.addAssertionEnvelope(envelope), this);\n};\n\n/// Implementation of addAssertionIf\nEnvelope.prototype.addAssertionIf = function (\n this: Envelope,\n condition: boolean,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n): Envelope {\n if (condition) {\n return this.addAssertion(predicate, object);\n }\n return this;\n};\n\n/// Implementation of addAssertionEnvelopeIf\nEnvelope.prototype.addAssertionEnvelopeIf = function (\n this: Envelope,\n condition: boolean,\n assertionEnvelope: Envelope,\n): Envelope {\n if (condition) {\n return this.addAssertionEnvelope(assertionEnvelope);\n }\n return this;\n};\n\n/// Implementation of removeAssertion\nEnvelope.prototype.removeAssertion = function (this: Envelope, target: Envelope): Envelope {\n const assertions = this.assertions();\n const targetDigest = target.digest();\n\n const index = assertions.findIndex((a) => a.digest().equals(targetDigest));\n\n if (index === -1) {\n // Assertion not found, return unchanged\n return this;\n }\n\n // Remove the assertion\n const newAssertions = [...assertions.slice(0, index), ...assertions.slice(index + 1)];\n\n if (newAssertions.length === 0) {\n // No assertions left, return just the subject\n return this.subject();\n }\n\n // Return envelope with remaining assertions\n return Envelope.newWithUncheckedAssertions(this.subject(), newAssertions);\n};\n\n/// Implementation of replaceAssertion\nEnvelope.prototype.replaceAssertion = function (\n this: Envelope,\n assertion: Envelope,\n newAssertion: Envelope,\n): Envelope {\n return this.removeAssertion(assertion).addAssertionEnvelope(newAssertion);\n};\n\n/// Implementation of replaceSubject\nEnvelope.prototype.replaceSubject = function (this: Envelope, subject: Envelope): Envelope {\n return this.assertions().reduce((e, a) => e.addAssertionEnvelope(a), subject);\n};\n\n/// Implementation of assertions\nEnvelope.prototype.assertions = function (this: Envelope): Envelope[] {\n const c = this.case();\n if (c.type === \"node\") {\n return c.assertions;\n }\n return [];\n};\n\n// Note: addAssertionSalted, addAssertionEnvelopeSalted, and addOptionalAssertionEnvelopeSalted\n// are implemented in extension/salt.ts to keep all salt-related functionality together.\n","import type { Cbor } from \"@bcts/dcbor\";\nimport { isNumber, isNaN, asArray, asMap, asText } from \"@bcts/dcbor\";\nimport type { KnownValue } from \"@bcts/known-values\";\nimport { UNIT } from \"@bcts/known-values\";\nimport { Envelope } from \"./envelope\";\nimport { EnvelopeError } from \"./error\";\n\n/// Provides methods for working with envelope leaf nodes,\n/// which are dCBOR values of any kind.\n///\n/// This module extends the Envelope class with convenience methods for\n/// working with leaf values, including type checking and extraction.\n\n// Note: Static methods Envelope.false() and Envelope.true() are implemented below\n// but cannot be declared in TypeScript module augmentation due to reserved keywords.\n\n/// Implementation of static false()\n(Envelope as unknown as { false: () => Envelope }).false = function (): Envelope {\n return Envelope.newLeaf(false);\n};\n\n/// Implementation of static true()\n(Envelope as unknown as { true: () => Envelope }).true = function (): Envelope {\n return Envelope.newLeaf(true);\n};\n\n/// Implementation of isFalse()\nEnvelope.prototype.isFalse = function (this: Envelope): boolean {\n try {\n return this.extractBoolean() === false;\n } catch {\n return false;\n }\n};\n\n/// Implementation of isTrue()\nEnvelope.prototype.isTrue = function (this: Envelope): boolean {\n try {\n return this.extractBoolean() === true;\n } catch {\n return false;\n }\n};\n\n/// Implementation of isBool()\nEnvelope.prototype.isBool = function (this: Envelope): boolean {\n try {\n const value = this.extractBoolean();\n return typeof value === \"boolean\";\n } catch {\n return false;\n }\n};\n\n/// Implementation of isNumber()\nEnvelope.prototype.isNumber = function (this: Envelope): boolean {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return false;\n }\n\n return isNumber(leaf);\n};\n\n/// Implementation of isSubjectNumber()\nEnvelope.prototype.isSubjectNumber = function (this: Envelope): boolean {\n return this.subject().isNumber();\n};\n\n/// Implementation of isNaN()\nEnvelope.prototype.isNaN = function (this: Envelope): boolean {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return false;\n }\n\n // Check for NaN in CBOR simple types\n if (\"type\" in leaf && leaf.type === 7) {\n return isNaN(leaf as unknown as Parameters<typeof isNaN>[0]);\n }\n return false;\n};\n\n/// Implementation of isSubjectNaN()\nEnvelope.prototype.isSubjectNaN = function (this: Envelope): boolean {\n return this.subject().isNaN();\n};\n\n/// Implementation of isNull()\nEnvelope.prototype.isNull = function (this: Envelope): boolean {\n try {\n this.extractNull();\n return true;\n } catch (_error) {\n return false;\n }\n};\n\n/// Implementation of tryByteString()\nEnvelope.prototype.tryByteString = function (this: Envelope): Uint8Array {\n return this.extractBytes();\n};\n\n/// Implementation of asByteString()\nEnvelope.prototype.asByteString = function (this: Envelope): Uint8Array | undefined {\n try {\n return this.extractBytes();\n } catch {\n return undefined;\n }\n};\n\n/// Implementation of asArray()\nEnvelope.prototype.asArray = function (this: Envelope): readonly Cbor[] | undefined {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return undefined;\n }\n\n return asArray(leaf);\n};\n\n/// Implementation of asMap()\nEnvelope.prototype.asMap = function (this: Envelope) {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return undefined;\n }\n\n return asMap(leaf);\n};\n\n/// Implementation of asText()\nEnvelope.prototype.asText = function (this: Envelope): string | undefined {\n const leaf = this.asLeaf();\n if (leaf === undefined) {\n return undefined;\n }\n\n return asText(leaf);\n};\n\n/// Implementation of asLeaf()\nEnvelope.prototype.asLeaf = function (this: Envelope): Cbor | undefined {\n const c = this.case();\n if (c.type === \"leaf\") {\n return c.cbor;\n }\n return undefined;\n};\n\n// ============================================================================\n// Known Value Methods\n// ============================================================================\n\n/// Implementation of static unit()\n/// Unit envelopes have the known value ''. They represent a position\n/// where no meaningful data *can* exist. In this sense they make a\n/// semantically stronger assertion than `null`, which represents a\n/// position where no meaningful data currently exists, but could exist in\n/// the future.\n(Envelope as unknown as { unit: () => Envelope }).unit = function (): Envelope {\n return Envelope.new(UNIT);\n};\n\n/// Implementation of asKnownValue()\nEnvelope.prototype.asKnownValue = function (this: Envelope): KnownValue | undefined {\n const c = this.case();\n if (c.type === \"knownValue\") {\n return c.value;\n }\n return undefined;\n};\n\n/// Implementation of tryKnownValue()\nEnvelope.prototype.tryKnownValue = function (this: Envelope): KnownValue {\n const kv = this.asKnownValue();\n if (kv === undefined) {\n throw EnvelopeError.notKnownValue();\n }\n return kv;\n};\n\n/// Implementation of isKnownValue()\nEnvelope.prototype.isKnownValue = function (this: Envelope): boolean {\n return this.case().type === \"knownValue\";\n};\n\n/// Implementation of isSubjectUnit()\nEnvelope.prototype.isSubjectUnit = function (this: Envelope): boolean {\n const kv = this.subject().asKnownValue();\n if (kv === undefined) {\n return false;\n }\n return kv.equals(UNIT);\n};\n\n/// Implementation of checkSubjectUnit()\nEnvelope.prototype.checkSubjectUnit = function (this: Envelope): Envelope {\n if (this.isSubjectUnit()) {\n return this;\n }\n throw EnvelopeError.subjectNotUnit();\n};\n","// Cbor type available if needed later\nimport { Envelope } from \"./envelope\";\nimport type { EnvelopeEncodableValue } from \"./envelope-encodable\";\nimport { EnvelopeError } from \"./error\";\nimport { POSITION } from \"@bcts/known-values\";\n\n/// Provides methods for querying envelope structure and extracting data.\n///\n/// The `queries` module contains methods for:\n///\n/// 1. **Structural queries**: Methods for examining the envelope's structure\n/// (`subject()`, `assertions()`)\n/// 2. **Type queries**: Methods for determining the envelope's type\n/// (`isLeaf()`, `isNode()`, etc.)\n/// 3. **Content extraction**: Methods for extracting typed content from\n/// envelopes (`extractSubject()`, `extractObjectForPredicate()`)\n/// 4. **Assertion queries**: Methods for finding assertions with specific\n/// predicates (`assertionWithPredicate()`)\n///\n/// These methods enable traversal and inspection of envelope hierarchies,\n/// allowing for flexible manipulation and access to envelope data structures.\n\n/// Implementation of hasAssertions()\nEnvelope.prototype.hasAssertions = function (this: Envelope): boolean {\n const c = this.case();\n return c.type === \"node\" && c.assertions.length > 0;\n};\n\n/// Implementation of asAssertion()\nEnvelope.prototype.asAssertion = function (this: Envelope): Envelope | undefined {\n const c = this.case();\n return c.type === \"assertion\" ? this : undefined;\n};\n\n/// Implementation of tryAssertion()\nEnvelope.prototype.tryAssertion = function (this: Envelope): Envelope {\n const result = this.asAssertion();\n if (result === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return result;\n};\n\n/// Implementation of asPredicate()\nEnvelope.prototype.asPredicate = function (this: Envelope): Envelope | undefined {\n // Refer to subject in case the assertion is a node and therefore has\n // its own assertions\n const subj = this.subject();\n const c = subj.case();\n if (c.type === \"assertion\") {\n return c.assertion.predicate();\n }\n return undefined;\n};\n\n/// Implementation of tryPredicate()\nEnvelope.prototype.tryPredicate = function (this: Envelope): Envelope {\n const result = this.asPredicate();\n if (result === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return result;\n};\n\n/// Implementation of asObject()\nEnvelope.prototype.asObject = function (this: Envelope): Envelope | undefined {\n // Refer to subject in case the assertion is a node and therefore has\n // its own assertions\n const subj = this.subject();\n const c = subj.case();\n if (c.type === \"assertion\") {\n return c.assertion.object();\n }\n return undefined;\n};\n\n/// Implementation of tryObject()\nEnvelope.prototype.tryObject = function (this: Envelope): Envelope {\n const result = this.asObject();\n if (result === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return result;\n};\n\n/// Implementation of isAssertion()\nEnvelope.prototype.isAssertion = function (this: Envelope): boolean {\n return this.case().type === \"assertion\";\n};\n\n/// Implementation of isElided()\nEnvelope.prototype.isElided = function (this: Envelope): boolean {\n return this.case().type === \"elided\";\n};\n\n/// Implementation of isLeaf()\nEnvelope.prototype.isLeaf = function (this: Envelope): boolean {\n return this.case().type === \"leaf\";\n};\n\n/// Implementation of isNode()\nEnvelope.prototype.isNode = function (this: Envelope): boolean {\n return this.case().type === \"node\";\n};\n\n/// Implementation of isWrapped()\nEnvelope.prototype.isWrapped = function (this: Envelope): boolean {\n return this.case().type === \"wrapped\";\n};\n\n/// Implementation of isInternal()\nEnvelope.prototype.isInternal = function (this: Envelope): boolean {\n const type = this.case().type;\n return type === \"node\" || type === \"wrapped\" || type === \"assertion\";\n};\n\n/// Implementation of isObscured()\nEnvelope.prototype.isObscured = function (this: Envelope): boolean {\n const type = this.case().type;\n return type === \"elided\" || type === \"encrypted\" || type === \"compressed\";\n};\n\n/// Implementation of assertionsWithPredicate()\nEnvelope.prototype.assertionsWithPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope[] {\n const predicateEnv = Envelope.new(predicate);\n const predicateDigest = predicateEnv.digest();\n\n return this.assertions().filter((assertion) => {\n const pred = assertion.subject().asPredicate();\n return pred?.digest().equals(predicateDigest) === true;\n });\n};\n\n/// Implementation of assertionWithPredicate()\nEnvelope.prototype.assertionWithPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope {\n const matches = this.assertionsWithPredicate(predicate);\n\n if (matches.length === 0) {\n throw EnvelopeError.nonexistentPredicate();\n }\n if (matches.length > 1) {\n throw EnvelopeError.ambiguousPredicate();\n }\n\n return matches[0];\n};\n\n/// Implementation of optionalAssertionWithPredicate()\nEnvelope.prototype.optionalAssertionWithPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope | undefined {\n const matches = this.assertionsWithPredicate(predicate);\n\n if (matches.length === 0) {\n return undefined;\n }\n if (matches.length > 1) {\n throw EnvelopeError.ambiguousPredicate();\n }\n\n return matches[0];\n};\n\n/// Implementation of objectForPredicate()\nEnvelope.prototype.objectForPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope {\n const assertion = this.assertionWithPredicate(predicate);\n const obj = assertion.asObject();\n if (obj === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return obj;\n};\n\n/// Implementation of optionalObjectForPredicate()\nEnvelope.prototype.optionalObjectForPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope | undefined {\n const matches = this.assertionsWithPredicate(predicate);\n\n if (matches.length === 0) {\n return undefined;\n }\n if (matches.length > 1) {\n throw EnvelopeError.ambiguousPredicate();\n }\n\n const obj = matches[0].subject().asObject();\n return obj;\n};\n\n/// Implementation of objectsForPredicate()\nEnvelope.prototype.objectsForPredicate = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n): Envelope[] {\n return this.assertionsWithPredicate(predicate).map((assertion) => {\n const obj = assertion.asObject();\n if (obj === undefined) {\n throw EnvelopeError.notAssertion();\n }\n return obj;\n });\n};\n\n/// Implementation of elementsCount()\nEnvelope.prototype.elementsCount = function (this: Envelope): number {\n let count = 1; // Count this envelope\n\n const c = this.case();\n switch (c.type) {\n case \"node\":\n count += c.subject.elementsCount();\n for (const assertion of c.assertions) {\n count += assertion.elementsCount();\n }\n break;\n case \"assertion\":\n count += c.assertion.predicate().elementsCount();\n count += c.assertion.object().elementsCount();\n break;\n case \"wrapped\":\n count += c.envelope.elementsCount();\n break;\n case \"leaf\":\n case \"elided\":\n case \"knownValue\":\n case \"encrypted\":\n case \"compressed\":\n // These cases don't contribute additional elements\n break;\n }\n\n return count;\n};\n\n// ============================================================================\n// Subject State Queries\n// ============================================================================\n\n/// Implementation of isSubjectEncrypted()\nEnvelope.prototype.isSubjectEncrypted = function (this: Envelope): boolean {\n const c = this.case();\n if (c.type === \"encrypted\") {\n return true;\n }\n if (c.type === \"node\") {\n return c.subject.isSubjectEncrypted();\n }\n return false;\n};\n\n/// Implementation of isSubjectCompressed()\nEnvelope.prototype.isSubjectCompressed = function (this: Envelope): boolean {\n const c = this.case();\n if (c.type === \"compressed\") {\n return true;\n }\n if (c.type === \"node\") {\n return c.subject.isSubjectCompressed();\n }\n return false;\n};\n\n/// Implementation of isSubjectElided()\nEnvelope.prototype.isSubjectElided = function (this: Envelope): boolean {\n const c = this.case();\n if (c.type === \"elided\") {\n return true;\n }\n if (c.type === \"node\") {\n return c.subject.isSubjectElided();\n }\n return false;\n};\n\n// ============================================================================\n// Position Management\n// ============================================================================\n\n/// Implementation of setPosition()\nEnvelope.prototype.setPosition = function (this: Envelope, position: number): Envelope {\n // Find all POSITION assertions\n const positionAssertions = this.assertionsWithPredicate(POSITION);\n\n // If there is more than one POSITION assertion, throw an error\n if (positionAssertions.length > 1) {\n throw EnvelopeError.invalidFormat();\n }\n\n // If there is a single POSITION assertion, remove it and add the new position\n // Otherwise, just add the new position to this envelope\n const baseEnvelope =\n positionAssertions.length === 1 ? this.removeAssertion(positionAssertions[0]) : this;\n\n // Add a new POSITION assertion with the given position\n return baseEnvelope.addAssertion(POSITION, position);\n};\n\n/// Implementation of position()\nEnvelope.prototype.position = function (this: Envelope): number {\n // Find the POSITION assertion in the envelope\n const positionEnvelope = this.objectForPredicate(POSITION);\n\n // Extract the position value\n const positionValue = positionEnvelope.extractNumber();\n return positionValue;\n};\n\n/// Implementation of removePosition()\nEnvelope.prototype.removePosition = function (this: Envelope): Envelope {\n // Find all POSITION assertions\n const positionAssertions = this.assertionsWithPredicate(POSITION);\n\n // If there is more than one POSITION assertion, throw an error\n if (positionAssertions.length > 1) {\n throw EnvelopeError.invalidFormat();\n }\n\n // If there is a single POSITION assertion, remove it\n if (positionAssertions.length === 1) {\n return this.removeAssertion(positionAssertions[0]);\n }\n\n // No POSITION assertion, return unchanged\n return this;\n};\n","import { Envelope } from \"./envelope\";\nimport { EnvelopeError } from \"./error\";\n\n/// Support for wrapping and unwrapping envelopes.\n///\n/// Wrapping allows treating an envelope (including its assertions) as a single\n/// unit, making it possible to add assertions about the envelope as a whole.\n\n/// Implementation of wrap()\nEnvelope.prototype.wrap = function (this: Envelope): Envelope {\n return Envelope.newWrapped(this);\n};\n\n/// Implementation of tryUnwrap()\nEnvelope.prototype.tryUnwrap = function (this: Envelope): Envelope {\n const c = this.subject().case();\n if (c.type === \"wrapped\") {\n return c.envelope;\n }\n throw EnvelopeError.notWrapped();\n};\n\n/// Implementation of unwrap() - alias for tryUnwrap()\nEnvelope.prototype.unwrap = function (this: Envelope): Envelope {\n return this.tryUnwrap();\n};\n","/// UR (Uniform Resource) support for Gordian Envelope.\n///\n/// This module adds urString() and fromUrString() methods to the Envelope class,\n/// enabling serialization to and from UR format as specified in BCR-2020-005.\n\nimport { UR } from \"@bcts/uniform-resources\";\nimport { Envelope } from \"./envelope\";\n\n// ============================================================================\n// Envelope Prototype Extensions for UR Support\n// ============================================================================\n\n/// Implementation of urString\nEnvelope.prototype.urString = function (this: Envelope): string {\n // Use untaggedCbor() per Rust implementation - the UR type \"envelope\" implies the tag\n const ur = UR.new(\"envelope\", this.untaggedCbor());\n return ur.string();\n};\n\n/// Implementation of ur\nEnvelope.prototype.ur = function (this: Envelope): UR {\n // Use untaggedCbor() per Rust implementation - the UR type \"envelope\" implies the tag\n return UR.new(\"envelope\", this.untaggedCbor());\n};\n\n/// Implementation of taggedCborData (alias for cborBytes)\nEnvelope.prototype.taggedCborData = function (this: Envelope): Uint8Array {\n return this.cborBytes();\n};\n\n/// Implementation of fromUrString\nEnvelope.fromUrString = function (urString: string): Envelope {\n const ur = UR.fromURString(urString);\n return Envelope.fromUR(ur);\n};\n\n/// Implementation of fromURString (alias)\nEnvelope.fromURString = Envelope.fromUrString;\n\n/// Implementation of fromUR\nEnvelope.fromUR = function (ur: UR): Envelope {\n ur.checkType(\"envelope\");\n // Use fromUntaggedCbor() per Rust implementation - the UR type \"envelope\" implies the tag\n return Envelope.fromUntaggedCbor(ur.cbor());\n};\n","import { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\nimport { IS_A } from \"@bcts/known-values\";\n\n/// Type system for Gordian Envelopes.\n///\n/// This module provides functionality for adding, querying, and verifying types\n/// within envelopes. In Gordian Envelope, types are implemented using the\n/// special `'isA'` KnownValue predicate (value 1), which is semantically\n/// equivalent to the RDF `rdf:type` concept.\n///\n/// Type information enables:\n/// - Semantic classification of envelopes\n/// - Type verification before processing content\n/// - Conversion between domain objects and envelopes\n/// - Schema validation\n///\n/// ## Type Representation\n///\n/// Types are represented as assertions with the `'isA'` predicate and an object\n/// that specifies the type. The type object is typically a string or an envelope.\n///\n/// ## Usage Patterns\n///\n/// The type system is commonly used in two ways:\n///\n/// 1. **Type Tagging**: Adding type information to envelopes to indicate their\n/// semantic meaning\n///\n/// ```typescript\n/// // Create an envelope representing a person\n/// const person = Envelope.new(\"Alice\")\n/// .addType(\"Person\")\n/// .addAssertion(\"age\", 30);\n/// ```\n///\n/// 2. **Type Checking**: Verifying that an envelope has the expected type\n/// before processing\n///\n/// ```typescript\n/// function processPerson(envelope: Envelope): void {\n/// // Verify this is a person before processing\n/// envelope.checkType(\"Person\");\n///\n/// // Now we can safely extract person-specific information\n/// const name = envelope.subject().extractString();\n/// const age = envelope.objectForPredicate(\"age\").extractNumber();\n///\n/// console.log(`${name} is ${age} years old`);\n/// }\n/// ```\n\n/// Implementation of addType()\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.addType = function (this: Envelope, object: EnvelopeEncodableValue): Envelope {\n return this.addAssertion(IS_A, object);\n };\n\n /// Implementation of types()\n Envelope.prototype.types = function (this: Envelope): Envelope[] {\n return this.objectsForPredicate(IS_A);\n };\n\n /// Implementation of getType()\n Envelope.prototype.getType = function (this: Envelope): Envelope {\n const t = this.types();\n if (t.length === 0) {\n throw EnvelopeError.invalidType();\n }\n if (t.length === 1) {\n return t[0];\n }\n throw EnvelopeError.ambiguousType();\n };\n\n /// Implementation of hasType()\n Envelope.prototype.hasType = function (this: Envelope, t: EnvelopeEncodableValue): boolean {\n const e = Envelope.new(t);\n return this.types().some((x) => x.digest().equals(e.digest()));\n };\n\n /// Implementation of checkType()\n Envelope.prototype.checkType = function (this: Envelope, t: EnvelopeEncodableValue): void {\n if (!this.hasType(t)) {\n throw EnvelopeError.invalidType();\n }\n };\n}\n","import { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport type { EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport {\n SecureRandomNumberGenerator,\n rngRandomData,\n rngNextInClosedRangeI32,\n type RandomNumberGenerator,\n} from \"@bcts/rand\";\nimport { SALT as SALT_KV } from \"@bcts/known-values\";\nimport { Salt as SaltComponent } from \"@bcts/components\";\n\n/// Extension for adding salt to envelopes to prevent correlation.\n///\n/// This module provides functionality for decorrelating envelopes by adding\n/// random salt. Salt is added as an assertion with the predicate 'salt' and\n/// a random value. When an envelope is elided, this salt ensures that the\n/// digest of the elided envelope cannot be correlated with other elided\n/// envelopes containing the same information.\n///\n/// Decorrelation is an important privacy feature that prevents third parties\n/// from determining whether two elided envelopes originally contained the same\n/// information by comparing their digests.\n///\n/// Based on bc-envelope-rust/src/extension/salt.rs and bc-components-rust/src/salt.rs\n///\n/// @example\n/// ```typescript\n/// // Create a simple envelope\n/// const envelope = Envelope.new(\"Hello\");\n///\n/// // Create a decorrelated version by adding salt\n/// const salted = envelope.addSalt();\n///\n/// // The salted envelope has a different digest than the original\n/// console.log(envelope.digest().equals(salted.digest())); // false\n/// ```\n\n// ============================================================================\n// Envelope Prototype Extensions for Salted Assertions\n// ============================================================================\n\n/// The standard predicate for salt assertions (KnownValue matching Rust)\nexport const SALT = SALT_KV;\n\n/// Minimum salt size in bytes (64 bits)\nconst MIN_SALT_SIZE = 8;\n\n/// Creates a new SecureRandomNumberGenerator instance\nfunction createSecureRng(): RandomNumberGenerator {\n return new SecureRandomNumberGenerator();\n}\n\n/// Generates random bytes using the rand package\nfunction generateRandomBytes(length: number, rng?: RandomNumberGenerator): Uint8Array {\n const actualRng = rng ?? createSecureRng();\n return rngRandomData(actualRng, length);\n}\n\n/// Calculates salt size proportional to envelope size\n/// This matches the Rust implementation in bc-components-rust/src/salt.rs\nfunction calculateProportionalSaltSize(envelopeSize: number, rng?: RandomNumberGenerator): number {\n const actualRng = rng ?? createSecureRng();\n const count = envelopeSize;\n const minSize = Math.max(8, Math.ceil(count * 0.05));\n const maxSize = Math.max(minSize + 8, Math.ceil(count * 0.25));\n return rngNextInClosedRangeI32(actualRng, minSize, maxSize);\n}\n\n/// Implementation of addSalt()\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.addSalt = function (this: Envelope): Envelope {\n const rng = createSecureRng();\n const envelopeSize = this.cborBytes().length;\n const saltSize = calculateProportionalSaltSize(envelopeSize, rng);\n const saltBytes = generateRandomBytes(saltSize, rng);\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Implementation of addSaltWithLength()\n Envelope.prototype.addSaltWithLength = function (this: Envelope, count: number): Envelope {\n if (count < MIN_SALT_SIZE) {\n throw EnvelopeError.general(`Salt must be at least ${MIN_SALT_SIZE} bytes, got ${count}`);\n }\n const saltBytes = generateRandomBytes(count);\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Alias for addSaltWithLength (Rust API compatibility)\n Envelope.prototype.addSaltWithLen = Envelope.prototype.addSaltWithLength;\n\n /// Implementation of addSaltBytes()\n Envelope.prototype.addSaltBytes = function (this: Envelope, saltBytes: Uint8Array): Envelope {\n if (saltBytes.length < MIN_SALT_SIZE) {\n throw EnvelopeError.general(\n `Salt must be at least ${MIN_SALT_SIZE} bytes, got ${saltBytes.length}`,\n );\n }\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Implementation of addSaltInRange()\n Envelope.prototype.addSaltInRange = function (\n this: Envelope,\n min: number,\n max: number,\n ): Envelope {\n if (min < MIN_SALT_SIZE) {\n throw EnvelopeError.general(\n `Minimum salt size must be at least ${MIN_SALT_SIZE} bytes, got ${min}`,\n );\n }\n if (max < min) {\n throw EnvelopeError.general(\n `Maximum salt size must be at least minimum, got min=${min} max=${max}`,\n );\n }\n const rng = createSecureRng();\n const saltSize = rngNextInClosedRangeI32(rng, min, max);\n const saltBytes = generateRandomBytes(saltSize, rng);\n return this.addAssertion(SALT, SaltComponent.fromData(saltBytes));\n };\n\n /// Implementation of addAssertionSalted()\n Envelope.prototype.addAssertionSalted = function (\n this: Envelope,\n predicate: EnvelopeEncodableValue,\n object: EnvelopeEncodableValue,\n salted: boolean,\n ): Envelope {\n // Create the assertion envelope\n const assertion = Envelope.newAssertion(predicate, object);\n\n // If not salted, use the normal addAssertionEnvelope\n if (!salted) {\n return this.addAssertionEnvelope(assertion);\n }\n\n // Add salt to the assertion envelope (this creates a node with assertion as subject)\n const saltedAssertion = assertion.addSalt();\n\n // When salted, we need to use newWithUncheckedAssertions because the salted\n // assertion is a node (not pure assertion type) and would fail normal validation\n const c = this.case();\n if (c.type === \"node\") {\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);\n }\n return Envelope.newWithUncheckedAssertions(this, [saltedAssertion]);\n };\n\n /// Implementation of addAssertionEnvelopeSalted()\n Envelope.prototype.addAssertionEnvelopeSalted = function (\n this: Envelope,\n assertionEnvelope: Envelope,\n salted: boolean,\n ): Envelope {\n // If not salted, use the normal addAssertionEnvelope\n if (!salted) {\n return this.addAssertionEnvelope(assertionEnvelope);\n }\n\n // Add salt to the assertion envelope (this creates a node with assertion as subject)\n const saltedAssertion = assertionEnvelope.addSalt();\n\n // When salted, we need to use newWithUncheckedAssertions because the salted\n // assertion is a node (not pure assertion type) and would fail normal validation\n const c = this.case();\n if (c.type === \"node\") {\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);\n }\n return Envelope.newWithUncheckedAssertions(this, [saltedAssertion]);\n };\n\n /// Implementation of addOptionalAssertionEnvelopeSalted()\n Envelope.prototype.addOptionalAssertionEnvelopeSalted = function (\n this: Envelope,\n assertionEnvelope: Envelope | undefined,\n salted: boolean,\n ): Envelope {\n if (assertionEnvelope === undefined) {\n return this;\n }\n\n // If not salted, use the normal addOptionalAssertionEnvelope\n if (!salted) {\n return this.addOptionalAssertionEnvelope(assertionEnvelope);\n }\n\n // Add salt to the assertion envelope (this creates a node with assertion as subject)\n const saltedAssertion = assertionEnvelope.addSalt();\n\n // When salted, we need to use newWithUncheckedAssertions because the salted\n // assertion is a node (not pure assertion type) and would fail normal validation\n const c = this.case();\n if (c.type === \"node\") {\n // Check for duplicate assertions\n const isDuplicate = c.assertions.some((a) => a.digest().equals(saltedAssertion.digest()));\n if (isDuplicate) {\n return this;\n }\n return Envelope.newWithUncheckedAssertions(c.subject, [...c.assertions, saltedAssertion]);\n }\n return Envelope.newWithUncheckedAssertions(this.subject(), [saltedAssertion]);\n };\n}\n","/**\n * Signature Extension for Gordian Envelope\n *\n * Provides functionality for digitally signing Envelopes and verifying signatures,\n * with optional metadata support.\n *\n * The signature extension allows:\n * - Signing envelope subjects to validate their authenticity\n * - Adding metadata to signatures (e.g., signer identity, date, purpose)\n * - Verification of signatures, both with and without metadata\n * - Support for multiple signatures on a single envelope\n *\n * Ported from bc-envelope-rust/src/extension/signature/\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport type { EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SIGNED as SIGNED_KV, NOTE as NOTE_KV } from \"@bcts/known-values\";\n\n/**\n * Re-export signing types from @bcts/components for type compatibility.\n */\nexport {\n Signature,\n SigningPrivateKey,\n SigningPublicKey,\n type Signer,\n type Verifier,\n type SigningOptions,\n} from \"@bcts/components\";\nimport { Signature, type Signer, type Verifier, type SigningOptions } from \"@bcts/components\";\n\n/**\n * Known value for the 'signed' predicate.\n * This is the standard predicate used for signature assertions.\n */\nexport const SIGNED = SIGNED_KV;\n\n/**\n * Known value for the 'note' predicate.\n * Used for adding notes/comments to signatures.\n */\nexport const NOTE = NOTE_KV;\n\n/**\n * Metadata associated with a signature in a Gordian Envelope.\n *\n * `SignatureMetadata` provides a way to attach additional information to\n * signatures, such as the signer's identity, the signing date, or the purpose\n * of the signature. When used with the signature extension, this metadata is\n * included in a structured way that is also signed, ensuring the metadata\n * cannot be tampered with without invalidating the signature.\n *\n * Ported from bc-envelope-rust/src/extension/signature/signature_metadata.rs\n */\nexport class SignatureMetadata {\n private readonly _assertions: [EnvelopeEncodableValue, unknown][] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n private constructor() {}\n\n /**\n * Creates a new empty SignatureMetadata.\n */\n static new(): SignatureMetadata {\n return new SignatureMetadata();\n }\n\n /**\n * Adds an assertion to the metadata.\n *\n * @param predicate - The predicate for the assertion (accepts KnownValue, string, etc.)\n * @param object - The object for the assertion\n * @returns A new SignatureMetadata with the assertion added\n */\n withAssertion(predicate: EnvelopeEncodableValue, object: unknown): SignatureMetadata {\n const metadata = new SignatureMetadata();\n metadata._assertions.push(...this._assertions);\n metadata._assertions.push([predicate, object]);\n return metadata;\n }\n\n /**\n * Returns all assertions in this metadata.\n */\n assertions(): readonly [EnvelopeEncodableValue, unknown][] {\n return this._assertions;\n }\n\n /**\n * Returns whether this metadata contains any assertions.\n */\n hasAssertions(): boolean {\n return this._assertions.length > 0;\n }\n}\n\n// ============================================================================\n// Note: Type declarations for signature methods are in ../base/envelope.ts\n// to ensure they are included in bundled type definitions.\n// ============================================================================\n\n// ============================================================================\n// Envelope Extension Methods for Signatures\n// ============================================================================\n\n/// Creates a signature for the envelope's subject and returns a new\n/// envelope with a `'signed': Signature` assertion.\n///\n/// Matches Rust: add_signature_opt()\nEnvelope.prototype.addSignatureOpt = function (\n this: Envelope,\n signer: Signer,\n options?: SigningOptions,\n metadata?: SignatureMetadata,\n): Envelope {\n const digest = this.subject().digest();\n let signatureEnvelope = Envelope.new(signer.signWithOptions(digest.data(), options));\n\n if (metadata?.hasAssertions() === true) {\n // Add metadata assertions to the signature envelope\n for (const [predicate, object] of metadata.assertions()) {\n signatureEnvelope = signatureEnvelope.addAssertion(\n predicate,\n object as EnvelopeEncodableValue,\n );\n }\n\n // Wrap the signature envelope (cryptographic binding)\n signatureEnvelope = signatureEnvelope.wrap();\n\n // Sign the wrapped structure with the same key\n const outerSignature = Envelope.new(\n signer.signWithOptions(signatureEnvelope.digest().data(), options),\n );\n\n // Add the outer signature assertion\n signatureEnvelope = signatureEnvelope.addAssertion(SIGNED, outerSignature);\n }\n\n return this.addAssertion(SIGNED, signatureEnvelope);\n};\n\n/// Creates a signature without options or metadata.\n///\n/// Matches Rust: add_signature()\nEnvelope.prototype.addSignature = function (this: Envelope, signer: Signer): Envelope {\n return this.addSignatureOpt(signer, undefined, undefined);\n};\n\n/// Creates a signature with optional metadata but no options.\n///\n/// Convenience method matching the common use case.\nEnvelope.prototype.addSignatureWithMetadata = function (\n this: Envelope,\n signer: Signer,\n metadata?: SignatureMetadata,\n): Envelope {\n return this.addSignatureOpt(signer, undefined, metadata);\n};\n\n/// Creates several signatures for the envelope's subject.\n///\n/// Matches Rust: add_signatures()\nEnvelope.prototype.addSignatures = function (this: Envelope, signers: Signer[]): Envelope {\n return signers.reduce<Envelope>((envelope, signer) => envelope.addSignature(signer), this);\n};\n\n/// Creates several signatures with individual options and metadata.\n///\n/// Matches Rust: add_signatures_opt()\nEnvelope.prototype.addSignaturesOpt = function (\n this: Envelope,\n signersWithOptions: { signer: Signer; options?: SigningOptions; metadata?: SignatureMetadata }[],\n): Envelope {\n return signersWithOptions.reduce<Envelope>(\n (envelope, { signer, options, metadata }) =>\n envelope.addSignatureOpt(signer, options, metadata),\n this,\n );\n};\n\n/// Creates several signatures with metadata (no options).\nEnvelope.prototype.addSignaturesWithMetadata = function (\n this: Envelope,\n signersWithMetadata: { signer: Signer; metadata?: SignatureMetadata }[],\n): Envelope {\n return signersWithMetadata.reduce<Envelope>(\n (envelope, { signer, metadata }) => envelope.addSignatureWithMetadata(signer, metadata),\n this,\n );\n};\n\n/// Convenience constructor for a `'signed': Signature` assertion envelope.\n///\n/// Matches Rust: make_signed_assertion()\nEnvelope.prototype.makeSignedAssertion = function (\n this: Envelope,\n signature: Signature,\n note?: string,\n): Envelope {\n let envelope = Envelope.newAssertion(SIGNED, signature as unknown as EnvelopeEncodableValue);\n if (note !== undefined) {\n envelope = envelope.addAssertion(NOTE, note);\n }\n return envelope;\n};\n\n/// Returns whether the given signature is valid.\n///\n/// Matches Rust: is_verified_signature()\nEnvelope.prototype.isVerifiedSignature = function (\n this: Envelope,\n signature: Signature,\n verifier: Verifier,\n): boolean {\n return verifier.verify(signature, this.subject().digest().data());\n};\n\n/// Checks whether the given signature is valid for the given public key.\n///\n/// Matches Rust: verify_signature()\nEnvelope.prototype.verifySignature = function (\n this: Envelope,\n signature: Signature,\n verifier: Verifier,\n): Envelope {\n if (!verifier.verify(signature, this.subject().digest().data())) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n// ============================================================================\n// Internal: Core signature verification with metadata support\n// ============================================================================\n\n/// Returns the signature metadata envelope if the given verifier has signed\n/// this envelope, or undefined if no matching signature is found.\n///\n/// Handles both simple signatures and wrapped (double-signed) signatures\n/// with metadata.\n///\n/// Matches Rust: has_some_signature_from_key_returning_metadata()\nEnvelope.prototype.hasSignatureFromReturningMetadata = function (\n this: Envelope,\n verifier: Verifier,\n): Envelope | undefined {\n // Valid signature objects are either:\n // - `Signature` objects, or\n // - `Signature` objects with additional metadata assertions, wrapped\n // and then signed by the same key.\n const signatureObjects = this.objectsForPredicate(SIGNED);\n\n for (const signatureObject of signatureObjects) {\n const signatureObjectSubject = signatureObject.subject();\n\n if (signatureObjectSubject.isWrapped()) {\n // Wrapped case: signature with metadata\n // The structure is:\n // {Signature ['note': \"...\"]} ['signed': OuterSignature]\n\n // Step 1: Verify outer signature if present\n let outerSigFound = false;\n try {\n const outerSignatureObject = signatureObject.objectForPredicate(SIGNED);\n outerSigFound = true;\n const outerSignature = outerSignatureObject.extractSubject((cbor) =>\n Signature.fromTaggedCbor(cbor),\n );\n if (!verifier.verify(outerSignature, signatureObjectSubject.digest().data())) {\n continue; // Outer signature doesn't match key, try next\n }\n } catch (_e) {\n if (outerSigFound) {\n // Found 'signed' assertion but couldn't extract Signature\n throw EnvelopeError.invalidOuterSignatureType();\n }\n // No 'signed' assertion on the signature object — skip outer check\n // (object_for_predicate failed with NONEXISTENT_PREDICATE)\n }\n\n // Step 2: Unwrap and verify inner signature\n const signatureMetadataEnvelope = signatureObjectSubject.tryUnwrap();\n try {\n const innerSignature = signatureMetadataEnvelope.extractSubject((cbor) =>\n Signature.fromTaggedCbor(cbor),\n );\n if (!verifier.verify(innerSignature, this.subject().digest().data())) {\n throw EnvelopeError.unverifiedInnerSignature();\n }\n return signatureMetadataEnvelope;\n } catch (e) {\n if (e instanceof EnvelopeError) throw e;\n throw EnvelopeError.invalidInnerSignatureType();\n }\n } else {\n // Simple case: no metadata\n try {\n const signature = signatureObject.extractSubject((cbor) => Signature.fromTaggedCbor(cbor));\n if (verifier.verify(signature, this.subject().digest().data())) {\n return signatureObject;\n }\n } catch {\n throw EnvelopeError.invalidSignatureType();\n }\n }\n }\n\n return undefined;\n};\n\n/// Returns whether the envelope's subject has a valid signature from the\n/// given public key.\n///\n/// Matches Rust: has_signature_from()\nEnvelope.prototype.hasSignatureFrom = function (this: Envelope, verifier: Verifier): boolean {\n return this.hasSignatureFromReturningMetadata(verifier) !== undefined;\n};\n\n/// Returns whether the envelope's subject has a valid signature from all\n/// the given public keys.\n///\n/// Matches Rust: has_signatures_from()\nEnvelope.prototype.hasSignaturesFrom = function (this: Envelope, verifiers: Verifier[]): boolean {\n return verifiers.every((verifier) => this.hasSignatureFrom(verifier));\n};\n\n/// Returns whether the envelope's subject has some threshold of signatures.\n///\n/// Matches Rust: has_signatures_from_threshold()\nEnvelope.prototype.hasSignaturesFromThreshold = function (\n this: Envelope,\n verifiers: Verifier[],\n threshold?: number,\n): boolean {\n const t = threshold ?? verifiers.length;\n let count = 0;\n for (const verifier of verifiers) {\n if (this.hasSignatureFrom(verifier)) {\n count++;\n if (count >= t) {\n return true;\n }\n }\n }\n return false;\n};\n\n/// Checks whether the envelope's subject has a valid signature from the\n/// given public key.\n///\n/// Matches Rust: verify_signature_from()\nEnvelope.prototype.verifySignatureFrom = function (this: Envelope, verifier: Verifier): Envelope {\n if (!this.hasSignatureFrom(verifier)) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n/// Verifies signature and returns the metadata envelope.\n///\n/// Matches Rust: verify_signature_from_returning_metadata()\nEnvelope.prototype.verifySignatureFromReturningMetadata = function (\n this: Envelope,\n verifier: Verifier,\n): Envelope {\n const metadata = this.hasSignatureFromReturningMetadata(verifier);\n if (metadata === undefined) {\n throw EnvelopeError.unverifiedSignature();\n }\n return metadata;\n};\n\n/// Checks whether the envelope's subject has a set of signatures.\n///\n/// Matches Rust: verify_signatures_from()\nEnvelope.prototype.verifySignaturesFrom = function (\n this: Envelope,\n verifiers: Verifier[],\n): Envelope {\n if (!this.hasSignaturesFrom(verifiers)) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n/// Checks whether the envelope's subject has some threshold of signatures.\n///\n/// Matches Rust: verify_signatures_from_threshold()\nEnvelope.prototype.verifySignaturesFromThreshold = function (\n this: Envelope,\n verifiers: Verifier[],\n threshold?: number,\n): Envelope {\n const t = threshold ?? verifiers.length;\n if (!this.hasSignaturesFromThreshold(verifiers, t)) {\n throw EnvelopeError.unverifiedSignature();\n }\n return this;\n};\n\n/// Returns all signature assertion objects.\n///\n/// Matches Rust: objects_for_predicate(SIGNED) via signatures()\nEnvelope.prototype.signatures = function (this: Envelope): Envelope[] {\n return this.objectsForPredicate(SIGNED);\n};\n\n// ============================================================================\n// Convenience methods for signing and verifying entire envelopes.\n//\n// These wrap the envelope before signing, ensuring all assertions are\n// included in the signature.\n// ============================================================================\n\n/// Signs the entire envelope by wrapping it first.\n///\n/// Matches Rust: sign()\nEnvelope.prototype.sign = function (this: Envelope, signer: Signer): Envelope {\n return this.signOpt(signer, undefined);\n};\n\n/// Signs the entire envelope with options but no metadata.\n///\n/// Matches Rust: sign_opt()\nEnvelope.prototype.signOpt = function (\n this: Envelope,\n signer: Signer,\n options?: SigningOptions,\n): Envelope {\n return this.wrap().addSignatureOpt(signer, options, undefined);\n};\n\n/// Signs the entire envelope with optional metadata.\nEnvelope.prototype.signWithMetadata = function (\n this: Envelope,\n signer: Signer,\n metadata?: SignatureMetadata,\n): Envelope {\n return this.wrap().addSignatureOpt(signer, undefined, metadata);\n};\n\n/// Verifies that the envelope has a valid signature from the specified\n/// verifier, and unwraps it.\n///\n/// Matches Rust: verify()\nEnvelope.prototype.verify = function (this: Envelope, verifier: Verifier): Envelope {\n return this.verifySignatureFrom(verifier).tryUnwrap();\n};\n\n/// Verifies the envelope's signature and returns both the unwrapped\n/// envelope and signature metadata.\n///\n/// Matches Rust: verify_returning_metadata()\nEnvelope.prototype.verifyReturningMetadata = function (\n this: Envelope,\n verifier: Verifier,\n): { envelope: Envelope; metadata: Envelope } {\n const metadata = this.verifySignatureFromReturningMetadata(verifier);\n return { envelope: this.tryUnwrap(), metadata };\n};\n","/**\n * Attachment Extension for Gordian Envelope\n *\n * Provides functionality for attaching vendor-specific metadata to envelopes.\n * Attachments enable flexible, extensible data storage without modifying\n * the core data model, facilitating interoperability and future compatibility.\n *\n * Each attachment has:\n * - A payload (arbitrary data)\n * - A required vendor identifier (typically a reverse domain name)\n * - An optional conformsTo URI that indicates the format of the attachment\n *\n * See BCR-2023-006: https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2023-006-envelope-attachment.md\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport { type Digest } from \"../base/digest\";\nimport { EnvelopeError } from \"../base/error\";\nimport type { EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport {\n ATTACHMENT as ATTACHMENT_KV,\n VENDOR as VENDOR_KV,\n CONFORMS_TO as CONFORMS_TO_KV,\n} from \"@bcts/known-values\";\n\n/**\n * Known value for the 'attachment' predicate.\n */\nexport const ATTACHMENT = ATTACHMENT_KV;\n\n/**\n * Known value for the 'vendor' predicate.\n */\nexport const VENDOR = VENDOR_KV;\n\n/**\n * Known value for the 'conformsTo' predicate.\n */\nexport const CONFORMS_TO = CONFORMS_TO_KV;\n\n/**\n * A container for vendor-specific metadata attachments.\n *\n * Attachments provides a flexible mechanism for attaching arbitrary metadata\n * to envelopes without modifying their core structure.\n */\nexport class Attachments {\n private readonly _envelopes = new Map<string, Envelope>();\n\n /**\n * Creates a new empty attachments container.\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n constructor() {}\n\n /**\n * Adds a new attachment with the specified payload and metadata.\n *\n * @param payload - The data to attach\n * @param vendor - A string identifying the entity that defined the attachment format\n * @param conformsTo - Optional URI identifying the structure the payload conforms to\n */\n add(payload: EnvelopeEncodableValue, vendor: string, conformsTo?: string): void {\n const attachment = Envelope.newAttachment(payload, vendor, conformsTo);\n this._envelopes.set(attachment.digest().hex(), attachment);\n }\n\n /**\n * Adds a pre-constructed attachment envelope directly.\n *\n * @param envelope - The attachment envelope to add\n */\n addEnvelope(envelope: Envelope): void {\n this._envelopes.set(envelope.digest().hex(), envelope);\n }\n\n /**\n * Retrieves an attachment by its digest.\n *\n * @param digest - The unique digest of the attachment to retrieve\n * @returns The envelope if found, or undefined\n */\n get(digest: Digest): Envelope | undefined {\n return this._envelopes.get(digest.hex());\n }\n\n /**\n * Removes an attachment by its digest.\n *\n * @param digest - The unique digest of the attachment to remove\n * @returns The removed envelope if found, or undefined\n */\n remove(digest: Digest): Envelope | undefined {\n const envelope = this._envelopes.get(digest.hex());\n this._envelopes.delete(digest.hex());\n return envelope;\n }\n\n /**\n * Removes all attachments from the container.\n */\n clear(): void {\n this._envelopes.clear();\n }\n\n /**\n * Returns whether the container has any attachments.\n */\n isEmpty(): boolean {\n return this._envelopes.size === 0;\n }\n\n /**\n * Returns the number of attachments in the container.\n */\n len(): number {\n return this._envelopes.size;\n }\n\n /**\n * Returns an iterator over all attachment envelopes.\n */\n iter(): IterableIterator<[string, Envelope]> {\n return this._envelopes.entries();\n }\n\n /**\n * Check equality with another Attachments container.\n */\n equals(other: Attachments): boolean {\n if (this._envelopes.size !== other._envelopes.size) return false;\n for (const [key] of this._envelopes) {\n if (!other._envelopes.has(key)) return false;\n }\n return true;\n }\n\n /**\n * Adds all attachments from this container to an envelope.\n *\n * @param envelope - The envelope to add attachments to\n * @returns A new envelope with all attachments added as assertions\n */\n addToEnvelope(envelope: Envelope): Envelope {\n let result = envelope;\n for (const attachment of this._envelopes.values()) {\n result = result.addAssertion(ATTACHMENT, attachment);\n }\n return result;\n }\n\n /**\n * Creates an Attachments container from an envelope's attachment assertions.\n *\n * @param envelope - The envelope to extract attachments from\n * @returns A new Attachments container with the envelope's attachments\n */\n static fromEnvelope(envelope: Envelope): Attachments {\n const attachments = new Attachments();\n const attachmentEnvelopes = envelope.attachments();\n\n for (const attachment of attachmentEnvelopes) {\n attachments._envelopes.set(attachment.digest().hex(), attachment);\n }\n\n return attachments;\n }\n}\n\n// Implementation\n\n/**\n * Creates a new attachment envelope.\n */\nEnvelope.newAttachment = function (\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n): Envelope {\n // Create the payload envelope wrapped with vendor assertion\n let attachmentObj = Envelope.new(payload).wrap().addAssertion(VENDOR, vendor);\n\n // Add optional conformsTo\n if (conformsTo !== undefined) {\n attachmentObj = attachmentObj.addAssertion(CONFORMS_TO, conformsTo);\n }\n\n // Create an assertion with 'attachment' as predicate and the wrapped payload as object\n // This returns an assertion envelope\n const attachmentPredicate = Envelope.new(ATTACHMENT);\n return attachmentPredicate.addAssertion(ATTACHMENT, attachmentObj).assertions()[0];\n};\n\n/**\n * Adds an attachment to an envelope.\n */\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.addAttachment = function (\n this: Envelope,\n payload: EnvelopeEncodableValue,\n vendor: string,\n conformsTo?: string,\n ): Envelope {\n let attachmentObj = Envelope.new(payload).wrap().addAssertion(VENDOR, vendor);\n\n if (conformsTo !== undefined) {\n attachmentObj = attachmentObj.addAssertion(CONFORMS_TO, conformsTo);\n }\n\n return this.addAssertion(ATTACHMENT, attachmentObj);\n };\n\n /**\n * Returns the payload of an attachment envelope.\n */\n Envelope.prototype.attachmentPayload = function (this: Envelope): Envelope {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.general(\"Envelope is not an attachment assertion\");\n }\n\n const obj = c.assertion.object();\n return obj.unwrap();\n };\n\n /**\n * Returns the vendor of an attachment envelope.\n */\n Envelope.prototype.attachmentVendor = function (this: Envelope): string {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.general(\"Envelope is not an attachment assertion\");\n }\n\n const obj = c.assertion.object();\n const vendorEnv = obj.objectForPredicate(VENDOR);\n const vendor = vendorEnv.asText();\n\n if (vendor === undefined || vendor === \"\") {\n throw EnvelopeError.general(\"Attachment has no vendor\");\n }\n\n return vendor;\n };\n\n /**\n * Returns the conformsTo of an attachment envelope.\n */\n Envelope.prototype.attachmentConformsTo = function (this: Envelope): string | undefined {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.general(\"Envelope is not an attachment assertion\");\n }\n\n const obj = c.assertion.object();\n const conformsToEnv = obj.optionalObjectForPredicate(CONFORMS_TO);\n\n if (conformsToEnv === undefined) {\n return undefined;\n }\n\n return conformsToEnv.asText();\n };\n\n /**\n * Returns all attachment assertions.\n */\n Envelope.prototype.attachments = function (this: Envelope): Envelope[] {\n return this.assertionsWithPredicate(ATTACHMENT).map((a) => {\n const c = a.case();\n if (c.type === \"assertion\") {\n return c.assertion.object();\n }\n throw EnvelopeError.general(\"Invalid attachment assertion\");\n });\n };\n\n /**\n * Returns attachments matching vendor and/or conformsTo.\n */\n Envelope.prototype.attachmentsWithVendorAndConformsTo = function (\n this: Envelope,\n vendor?: string,\n conformsTo?: string,\n ): Envelope[] {\n const allAttachments = this.attachments();\n\n return allAttachments.filter((attachment) => {\n try {\n // The attachment is already a wrapped envelope with vendor/conformsTo assertions\n // Check vendor if specified\n if (vendor !== undefined) {\n const vendorEnv = attachment.objectForPredicate(VENDOR);\n const attachmentVendor = vendorEnv.asText();\n if (attachmentVendor !== vendor) {\n return false;\n }\n }\n\n // Check conformsTo if specified\n if (conformsTo !== undefined) {\n const conformsToEnv = attachment.optionalObjectForPredicate(CONFORMS_TO);\n if (conformsToEnv === undefined) {\n return false;\n }\n const conformsToText = conformsToEnv.asText();\n if (conformsToText !== conformsTo) {\n return false;\n }\n }\n\n return true;\n } catch {\n return false;\n }\n });\n };\n\n /**\n * Validates that this envelope is a valid attachment.\n *\n * An attachment is valid if:\n * 1. The envelope is an assertion with 'attachment' as predicate\n * 2. The object contains a wrapped payload with vendor assertion\n * 3. Reconstructing the attachment yields an equivalent envelope\n *\n * @throws EnvelopeError if the envelope is not a valid attachment\n */\n Envelope.prototype.validateAttachment = function (this: Envelope): void {\n const c = this.case();\n if (c.type !== \"assertion\") {\n throw EnvelopeError.invalidAttachment(\"Envelope is not an assertion\");\n }\n\n // Verify predicate is 'attachment' (using digest comparison for KnownValue predicates)\n const predicate = c.assertion.predicate();\n const expectedPredicate = Envelope.new(ATTACHMENT);\n if (!predicate.digest().equals(expectedPredicate.digest())) {\n throw EnvelopeError.invalidAttachment(\"Assertion predicate is not 'attachment'\");\n }\n\n // Extract components\n const payload = this.attachmentPayload();\n const vendor = this.attachmentVendor();\n const conformsTo = this.attachmentConformsTo();\n\n // Reconstruct the attachment\n const reconstructed = Envelope.newAttachment(payload, vendor, conformsTo);\n\n // Check equivalence (same digest = semantically equivalent)\n if (!this.digest().equals(reconstructed.digest())) {\n throw EnvelopeError.invalidAttachment(\"Attachment structure is invalid\");\n }\n };\n\n /**\n * Finds a single attachment matching the given vendor and conformsTo.\n *\n * Unlike `attachmentsWithVendorAndConformsTo` which returns an array,\n * this method requires exactly one attachment to match.\n *\n * @param vendor - Optional vendor identifier to match\n * @param conformsTo - Optional conformsTo URI to match\n * @returns The matching attachment envelope\n * @throws EnvelopeError if not exactly one attachment matches\n */\n Envelope.prototype.attachmentWithVendorAndConformsTo = function (\n this: Envelope,\n vendor?: string,\n conformsTo?: string,\n ): Envelope {\n const matches = this.attachmentsWithVendorAndConformsTo(vendor, conformsTo);\n\n if (matches.length === 0) {\n throw EnvelopeError.general(\"No matching attachment found\");\n }\n if (matches.length > 1) {\n throw EnvelopeError.general(`Expected exactly one attachment, found ${matches.length}`);\n }\n\n return matches[0];\n };\n}\n","/**\n * Edge Extension for Gordian Envelope (BCR-2026-003)\n *\n * Provides functionality for creating and managing edge envelopes that\n * represent verifiable relationships between entities. An edge envelope\n * contains three required assertions:\n * - `'isA'`: The type of relationship\n * - `'source'`: The source entity\n * - `'target'`: The target entity\n *\n * Edges may optionally be wrapped and signed. When accessing edge properties,\n * the implementation handles both wrapped (signed) and unwrapped edges\n * transparently.\n *\n * Equivalent to Rust's `src/extension/edge/` module.\n *\n * @module edge\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport { type Digest } from \"../base/digest\";\nimport { EnvelopeError } from \"../base/error\";\nimport { EDGE, IS_A, IS_A_RAW, SOURCE, SOURCE_RAW, TARGET, TARGET_RAW } from \"@bcts/known-values\";\n\n// -------------------------------------------------------------------\n// Edges Container\n// -------------------------------------------------------------------\n\n/**\n * A container for edge envelopes on a document.\n *\n * `Edges` stores pre-constructed edge envelopes keyed by their digest,\n * mirroring the `Attachments` container but for edges as defined in\n * BCR-2026-003.\n *\n * Equivalent to Rust's `Edges` struct in `src/extension/edge/edges.rs`.\n */\nexport class Edges {\n private readonly _envelopes: Map<string, Envelope>;\n\n /**\n * Creates a new empty edges container.\n */\n constructor() {\n this._envelopes = new Map();\n }\n\n /**\n * Adds a pre-constructed edge envelope.\n *\n * @param edgeEnvelope - The edge envelope to add\n */\n add(edgeEnvelope: Envelope): void {\n const digest = edgeEnvelope.digest();\n this._envelopes.set(digest.hex(), edgeEnvelope);\n }\n\n /**\n * Retrieves an edge by its digest.\n *\n * @param digest - The digest of the edge to retrieve\n * @returns The edge envelope if found, or undefined\n */\n get(digest: Digest): Envelope | undefined {\n return this._envelopes.get(digest.hex());\n }\n\n /**\n * Removes an edge by its digest.\n *\n * @param digest - The digest of the edge to remove\n * @returns The removed edge envelope if found, or undefined\n */\n remove(digest: Digest): Envelope | undefined {\n const key = digest.hex();\n const envelope = this._envelopes.get(key);\n this._envelopes.delete(key);\n return envelope;\n }\n\n /**\n * Removes all edges from the container.\n */\n clear(): void {\n this._envelopes.clear();\n }\n\n /**\n * Returns whether the container has no edges.\n */\n isEmpty(): boolean {\n return this._envelopes.size === 0;\n }\n\n /**\n * Returns the number of edges in the container.\n */\n len(): number {\n return this._envelopes.size;\n }\n\n /**\n * Returns an iterator over all edge envelopes.\n */\n iter(): IterableIterator<[string, Envelope]> {\n return this._envelopes.entries();\n }\n\n /**\n * Check equality with another Edges container.\n */\n equals(other: Edges): boolean {\n if (this._envelopes.size !== other._envelopes.size) return false;\n for (const [key] of this._envelopes) {\n if (!other._envelopes.has(key)) return false;\n }\n return true;\n }\n\n /**\n * Adds all edges as `'edge'` assertion envelopes to the given envelope.\n *\n * @param envelope - The envelope to add edges to\n * @returns A new envelope with all edges added as assertions\n */\n addToEnvelope(envelope: Envelope): Envelope {\n let result = envelope;\n for (const edgeEnvelope of this._envelopes.values()) {\n result = result.addAssertion(EDGE, edgeEnvelope);\n }\n return result;\n }\n\n /**\n * Extracts edges from an envelope's `'edge'` assertions.\n *\n * Equivalent to Rust's `Edges::try_from_envelope()`.\n *\n * @param envelope - The envelope to extract edges from\n * @returns A new Edges container with the envelope's edges\n */\n static fromEnvelope(envelope: Envelope): Edges {\n const edgeEnvelopes = envelope.edges();\n const edges = new Edges();\n for (const edge of edgeEnvelopes) {\n edges._envelopes.set(edge.digest().hex(), edge);\n }\n return edges;\n }\n}\n\n// -------------------------------------------------------------------\n// Edgeable Interface\n// -------------------------------------------------------------------\n\n/**\n * A trait for types that can have edges.\n *\n * `Edgeable` provides a consistent interface for working with edges.\n * Types implementing this interface can store and retrieve edge envelopes\n * representing verifiable claims as defined in BCR-2026-003.\n *\n * Equivalent to Rust's `Edgeable` trait in `src/extension/edge/edges.rs`.\n */\nexport interface Edgeable {\n /** Returns a reference to the edges container. */\n edges(): Edges;\n /** Returns a mutable reference to the edges container. */\n edgesMut(): Edges;\n /** Adds a pre-constructed edge envelope. */\n addEdge(edgeEnvelope: Envelope): void;\n /** Retrieves an edge by its digest. */\n getEdge(digest: Digest): Envelope | undefined;\n /** Removes an edge by its digest. */\n removeEdge(digest: Digest): Envelope | undefined;\n /** Removes all edges. */\n clearEdges(): void;\n /** Returns whether the object has any edges. */\n hasEdges(): boolean;\n}\n\n// -------------------------------------------------------------------\n// Envelope Prototype Methods\n// -------------------------------------------------------------------\n\n/**\n * Returns a new envelope with an added `'edge': <edge>` assertion.\n *\n * Equivalent to Rust's `Envelope::add_edge_envelope()`.\n */\nEnvelope.prototype.addEdgeEnvelope = function (this: Envelope, edge: Envelope): Envelope {\n return this.addAssertion(EDGE, edge);\n};\n\n/**\n * Returns all edge object envelopes (assertions with predicate `'edge'`).\n *\n * Equivalent to Rust's `Envelope::edges()`.\n */\nEnvelope.prototype.edges = function (this: Envelope): Envelope[] {\n return this.objectsForPredicate(EDGE);\n};\n\n/**\n * Validates an edge envelope's structure per BCR-2026-003.\n *\n * An edge may be wrapped (signed) or unwrapped. The inner envelope\n * must have exactly three assertion predicates: `'isA'`, `'source'`,\n * and `'target'`. No other assertions are permitted on the edge subject.\n *\n * Equivalent to Rust's `Envelope::validate_edge()`.\n *\n * @throws {EnvelopeError} If the edge structure is invalid\n */\nEnvelope.prototype.validateEdge = function (this: Envelope): void {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n\n let seenIsA = false;\n let seenSource = false;\n let seenTarget = false;\n\n for (const assertion of inner.assertions()) {\n const predicateEnv = assertion.tryPredicate();\n const kv = predicateEnv.asKnownValue();\n if (kv === undefined) {\n throw EnvelopeError.edgeUnexpectedAssertion();\n }\n const raw = kv.valueBigInt();\n switch (raw) {\n case IS_A_RAW:\n if (seenIsA) {\n throw EnvelopeError.edgeDuplicateIsA();\n }\n seenIsA = true;\n break;\n case SOURCE_RAW:\n if (seenSource) {\n throw EnvelopeError.edgeDuplicateSource();\n }\n seenSource = true;\n break;\n case TARGET_RAW:\n if (seenTarget) {\n throw EnvelopeError.edgeDuplicateTarget();\n }\n seenTarget = true;\n break;\n default:\n throw EnvelopeError.edgeUnexpectedAssertion();\n }\n }\n\n if (!seenIsA) {\n throw EnvelopeError.edgeMissingIsA();\n }\n if (!seenSource) {\n throw EnvelopeError.edgeMissingSource();\n }\n if (!seenTarget) {\n throw EnvelopeError.edgeMissingTarget();\n }\n};\n\n/**\n * Extracts the `'isA'` assertion object from an edge envelope.\n *\n * Equivalent to Rust's `Envelope::edge_is_a()`.\n */\nEnvelope.prototype.edgeIsA = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.objectForPredicate(IS_A);\n};\n\n/**\n * Extracts the `'source'` assertion object from an edge envelope.\n *\n * Equivalent to Rust's `Envelope::edge_source()`.\n */\nEnvelope.prototype.edgeSource = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.objectForPredicate(SOURCE);\n};\n\n/**\n * Extracts the `'target'` assertion object from an edge envelope.\n *\n * Equivalent to Rust's `Envelope::edge_target()`.\n */\nEnvelope.prototype.edgeTarget = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.objectForPredicate(TARGET);\n};\n\n/**\n * Extracts the edge's subject identifier (the inner envelope's subject).\n *\n * Equivalent to Rust's `Envelope::edge_subject()`.\n */\nEnvelope.prototype.edgeSubject = function (this: Envelope): Envelope {\n const inner = this.subject().isWrapped() ? this.subject().tryUnwrap() : this;\n return inner.subject();\n};\n\n/**\n * Filters edges by optional criteria.\n *\n * Each parameter is optional. When provided, only edges matching\n * all specified criteria are returned.\n *\n * Equivalent to Rust's `Envelope::edges_matching()`.\n *\n * @param isA - Optional `'isA'` envelope to match\n * @param source - Optional `'source'` envelope to match\n * @param target - Optional `'target'` envelope to match\n * @param subject - Optional subject envelope to match\n * @returns Array of matching edge envelopes\n */\nEnvelope.prototype.edgesMatching = function (\n this: Envelope,\n isA?: Envelope,\n source?: Envelope,\n target?: Envelope,\n subject?: Envelope,\n): Envelope[] {\n const allEdges = this.edges();\n const matching: Envelope[] = [];\n\n for (const edge of allEdges) {\n if (isA !== undefined) {\n try {\n const edgeIsA = edge.edgeIsA();\n if (!edgeIsA.isEquivalentTo(isA)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n if (source !== undefined) {\n try {\n const edgeSource = edge.edgeSource();\n if (!edgeSource.isEquivalentTo(source)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n if (target !== undefined) {\n try {\n const edgeTarget = edge.edgeTarget();\n if (!edgeTarget.isEquivalentTo(target)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n if (subject !== undefined) {\n try {\n const edgeSubject = edge.edgeSubject();\n if (!edgeSubject.isEquivalentTo(subject)) {\n continue;\n }\n } catch {\n continue;\n }\n }\n\n matching.push(edge);\n }\n\n return matching;\n};\n","/**\n * Public key encryption extension for Gordian Envelope.\n *\n * This module implements public key encryption for Gordian Envelope, allowing\n * encrypted content to be selectively shared with one or more recipients. Each\n * recipient needs their own public/private key pair, and only recipients with\n * the corresponding private key can decrypt the envelope's content.\n *\n * The recipient extension builds on the basic envelope encryption capabilities\n * by adding:\n *\n * - **Multiple Recipients** - A single envelope can be encrypted to multiple\n * recipients\n * - **Content Key Distribution** - Uses public key cryptography to securely\n * distribute the symmetric key that encrypts the actual content\n * - **Privacy** - Recipients can decrypt the envelope independently without\n * revealing their identity or access to other recipients\n *\n * ## How It Works\n *\n * The envelope's subject is encrypted using a random symmetric key (the\n * \"content key\"), and then this content key is encrypted to each recipient's\n * public key using a `SealedMessage`. Each encrypted content key is attached\n * to the envelope with a `hasRecipient` assertion.\n *\n * When recipients want to decrypt the envelope, they use their private key to\n * decrypt the content key from the appropriate `SealedMessage`, and then use\n * that content key to decrypt the envelope's subject.\n *\n * Ported from bc-envelope-rust/src/extension/recipient.rs\n */\n\nimport { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SymmetricKey } from \"./encrypt\";\nimport {\n type Encrypter,\n type Decrypter,\n type Nonce,\n SealedMessage as ComponentsSealedMessage,\n isEncrypter,\n} from \"@bcts/components\";\nimport { HAS_RECIPIENT as HAS_RECIPIENT_KV } from \"@bcts/known-values\";\n\n/**\n * Predicate constant for recipient assertions.\n * This is the known value 'hasRecipient' used to identify recipient assertions.\n */\nexport const HAS_RECIPIENT = HAS_RECIPIENT_KV;\n\n/**\n * Re-export the SealedMessage from @bcts/components for compatibility.\n * This is the proper implementation that supports both X25519 and MLKEM.\n */\nexport { SealedMessage as ComponentsSealedMessage } from \"@bcts/components\";\n\n/**\n * Re-export Encrypter and Decrypter types for convenience.\n */\nexport type { Encrypter, Decrypter } from \"@bcts/components\";\n\n/**\n * Legacy PublicKeyBase class for backwards compatibility.\n * New code should use Encrypter interface directly.\n *\n * @deprecated Use Encrypter interface from @bcts/components instead\n */\nexport { EncapsulationPublicKey as PublicKeyBase } from \"@bcts/components\";\n\n/**\n * Legacy PrivateKeyBase class for backwards compatibility.\n * New code should use Decrypter interface or PrivateKeys from @bcts/components instead.\n *\n * Note: This now exports PrivateKeys (which includes both signing and encapsulation keys)\n * instead of just EncapsulationPrivateKey to match the expected API with .publicKeys() method.\n *\n * @deprecated Use Decrypter interface or PrivateKeys from @bcts/components instead\n */\nexport { PrivateKeys as PrivateKeyBase } from \"@bcts/components\";\n\n/**\n * SealedMessage wrapping the sealed content key for a recipient.\n * This is the proper implementation from @bcts/components that supports\n * both X25519 and MLKEM encryption schemes.\n */\nexport class SealedMessage {\n private readonly _inner: ComponentsSealedMessage;\n\n constructor(sealedMessage: ComponentsSealedMessage) {\n this._inner = sealedMessage;\n }\n\n /**\n * Creates a sealed message by encrypting a symmetric key to a recipient.\n * Uses the Encrypter interface which supports both X25519 and MLKEM.\n *\n * @param contentKey - The symmetric key to encrypt\n * @param recipient - The recipient's public key (implements Encrypter)\n * @param testNonce - Optional nonce for deterministic testing\n * @returns A sealed message containing the encrypted content key\n */\n static seal(contentKey: SymmetricKey, recipient: Encrypter, testNonce?: Nonce): SealedMessage {\n // Get the encapsulation public key from the Encrypter\n const encapsulationPublicKey = recipient.encapsulationPublicKey();\n\n // Use the SealedMessage.newOpt from components which properly handles\n // both X25519 and MLKEM encapsulation\n const inner = ComponentsSealedMessage.newOpt(\n contentKey.data(),\n encapsulationPublicKey,\n new Uint8Array(0), // No AAD\n testNonce,\n );\n\n return new SealedMessage(inner);\n }\n\n /**\n * Decrypts this sealed message using recipient's private key.\n *\n * @param recipient - The recipient's private key (implements Decrypter)\n * @returns The decrypted content key data\n */\n decrypt(recipient: Decrypter): Uint8Array {\n const encapsulationPrivateKey = recipient.encapsulationPrivateKey();\n return this._inner.decrypt(encapsulationPrivateKey);\n }\n\n /**\n * Returns the underlying SealedMessage from components.\n */\n inner(): ComponentsSealedMessage {\n return this._inner;\n }\n\n /**\n * Returns the CBOR-encoded data of this sealed message.\n */\n data(): Uint8Array {\n return this._inner.taggedCborData();\n }\n\n /**\n * Creates a SealedMessage from CBOR-encoded data.\n */\n static fromData(data: Uint8Array): SealedMessage {\n const inner = ComponentsSealedMessage.fromTaggedCborData(data);\n return new SealedMessage(inner);\n }\n}\n\n// ============================================================================\n// Envelope Extension Methods\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n /**\n * Adds a recipient assertion to this envelope.\n *\n * This method adds a `hasRecipient` assertion containing a `SealedMessage`\n * that holds the content key encrypted to the recipient's public key.\n *\n * @param recipient - The recipient's public key (implements Encrypter)\n * @param contentKey - The symmetric key used to encrypt the envelope's subject\n * @param testNonce - Optional nonce for deterministic testing\n * @returns A new envelope with the recipient assertion added\n */\n Envelope.prototype.addRecipient = function (\n this: Envelope,\n recipient: Encrypter,\n contentKey: SymmetricKey,\n testNonce?: Nonce,\n ): Envelope {\n const sealedMessage = SealedMessage.seal(contentKey, recipient, testNonce);\n // Store the sealed message as CBOR data in the assertion\n return this.addAssertion(HAS_RECIPIENT, sealedMessage.inner());\n };\n\n /**\n * Encrypts the envelope's subject and adds a recipient assertion.\n *\n * This is a convenience method that:\n * 1. Generates a random content key\n * 2. Encrypts the subject with the content key\n * 3. Adds a recipient assertion with the sealed content key\n *\n * @param recipient - The recipient's public key (implements Encrypter)\n * @returns A new envelope with encrypted subject and recipient assertion\n */\n Envelope.prototype.encryptSubjectToRecipient = function (\n this: Envelope,\n recipient: Encrypter,\n ): Envelope {\n // Validate that recipient implements Encrypter\n if (!isEncrypter(recipient)) {\n throw EnvelopeError.general(\n \"Recipient must implement Encrypter interface. \" +\n \"Use PublicKeys or EncapsulationPublicKey from @bcts/components.\",\n );\n }\n\n // Generate a random content key\n const contentKey = SymmetricKey.new();\n\n // Encrypt the subject with the content key\n const encrypted = this.encryptSubject(contentKey);\n\n // Add the recipient\n return encrypted.addRecipient(recipient, contentKey);\n };\n\n /**\n * Encrypts the envelope's subject and adds recipient assertions for multiple recipients.\n *\n * @param recipients - Array of recipient public keys (each implements Encrypter)\n * @returns A new envelope with encrypted subject and recipient assertions\n */\n Envelope.prototype.encryptSubjectToRecipients = function (\n this: Envelope,\n recipients: Encrypter[],\n ): Envelope {\n if (recipients.length === 0) {\n throw EnvelopeError.general(\"Must provide at least one recipient\");\n }\n\n // Generate a random content key\n const contentKey = SymmetricKey.new();\n\n // Encrypt the subject with the content key\n let result = this.encryptSubject(contentKey);\n\n // Add each recipient\n for (const recipient of recipients) {\n if (!isEncrypter(recipient)) {\n throw EnvelopeError.general(\n \"All recipients must implement Encrypter interface. \" +\n \"Use PublicKeys or EncapsulationPublicKey from @bcts/components.\",\n );\n }\n result = result.addRecipient(recipient, contentKey);\n }\n\n return result;\n };\n\n /**\n * Returns all SealedMessages from the envelope's `hasRecipient` assertions.\n *\n * @returns Array of SealedMessage objects\n */\n Envelope.prototype.recipients = function (this: Envelope): SealedMessage[] {\n const recipientAssertions = this.assertions().filter((assertion) => {\n try {\n const predicate = assertion.subject().asPredicate();\n if (predicate === undefined) return false;\n // Check if it's the hasRecipient known value\n const knownValue = predicate.asKnownValue();\n if (knownValue !== undefined) {\n return knownValue.equals(HAS_RECIPIENT);\n }\n // Also check string form for backwards compatibility\n const text = predicate.asText();\n return text === \"hasRecipient\";\n } catch {\n return false;\n }\n });\n\n return recipientAssertions.map((assertion) => {\n // Get the object from the assertion case\n const assertionCase = assertion.case();\n if (assertionCase.type !== \"assertion\") {\n throw EnvelopeError.general(\"Invalid recipient assertion structure\");\n }\n\n const obj = assertionCase.assertion.object();\n\n // Try to decode as SealedMessage from components\n try {\n // The object should be a leaf envelope containing a SealedMessage\n // Get the underlying CBOR from the leaf envelope\n const leafCbor = obj.asLeaf();\n if (leafCbor !== undefined) {\n // Convert the CBOR to bytes and decode as SealedMessage\n const cborData = leafCbor.toData();\n const inner = ComponentsSealedMessage.fromTaggedCborData(cborData);\n return new SealedMessage(inner);\n }\n\n // Try extracting from the full envelope CBOR as fallback\n const cborData = obj.taggedCborData();\n const inner = ComponentsSealedMessage.fromTaggedCborData(cborData);\n return new SealedMessage(inner);\n } catch {\n // Try legacy format: raw bytes\n try {\n const sealedData = obj.asByteString();\n if (sealedData !== undefined) {\n return SealedMessage.fromData(sealedData);\n }\n } catch {\n // Fall through to error\n }\n throw EnvelopeError.general(\"Invalid recipient sealed message format\");\n }\n });\n };\n\n /**\n * Decrypts the envelope's subject using the recipient's private key.\n *\n * This method:\n * 1. Finds all `hasRecipient` assertions\n * 2. Tries to decrypt each sealed message until one succeeds\n * 3. Uses the recovered content key to decrypt the subject\n *\n * @param recipient - The recipient's private key (implements Decrypter)\n * @returns A new envelope with decrypted subject\n */\n Envelope.prototype.decryptSubjectToRecipient = function (\n this: Envelope,\n recipient: Decrypter,\n ): Envelope {\n // Check that the subject is encrypted\n const subjectCase = this.subject().case();\n if (subjectCase.type !== \"encrypted\") {\n throw EnvelopeError.general(\"Subject is not encrypted\");\n }\n\n // Get all sealed messages from recipient assertions\n const sealedMessages = this.recipients();\n\n if (sealedMessages.length === 0) {\n throw EnvelopeError.general(\"No recipients found\");\n }\n\n // Try each sealed message until one decrypts successfully\n let contentKeyData: Uint8Array | null = null;\n\n for (const sealedMessage of sealedMessages) {\n try {\n contentKeyData = sealedMessage.decrypt(recipient);\n break; // Success!\n } catch {\n // Not for us, try next one\n continue;\n }\n }\n\n if (contentKeyData === null) {\n throw EnvelopeError.general(\"Not a valid recipient\");\n }\n\n // Create SymmetricKey from the decrypted content key\n const contentKey = SymmetricKey.from(contentKeyData);\n\n // Decrypt the subject using the content key\n return this.decryptSubject(contentKey);\n };\n\n /**\n * Decrypts an envelope that was encrypted to a recipient and unwraps it.\n *\n * This is a convenience method that:\n * 1. Decrypts the subject using the recipient's private key\n * 2. Unwraps the resulting envelope\n *\n * @param recipient - The recipient's private key (implements Decrypter)\n * @returns The unwrapped, decrypted envelope\n */\n Envelope.prototype.decryptToRecipient = function (\n this: Envelope,\n recipient: Decrypter,\n ): Envelope {\n const decrypted = this.decryptSubjectToRecipient(recipient);\n return decrypted.unwrap();\n };\n\n /**\n * Wraps and encrypts an envelope to multiple recipients.\n *\n * @param recipients - Array of recipient public keys (each implements Encrypter)\n * @returns A wrapped and encrypted envelope\n */\n Envelope.prototype.encryptToRecipients = function (\n this: Envelope,\n recipients: Encrypter[],\n ): Envelope {\n return this.wrap().encryptSubjectToRecipients(recipients);\n };\n}\n\n// Import side-effect to register prototype extensions\nexport {};\n","import { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\n\n/// Extension for envelope expressions.\n///\n/// This module implements the Gordian Envelope expression syntax as specified\n/// in BCR-2023-012. Expressions enable encoding of machine-evaluatable\n/// expressions using envelopes, providing a foundation for distributed\n/// function calls and computation.\n///\n/// ## Expression Structure\n///\n/// An expression consists of:\n/// - A function identifier (the subject)\n/// - Zero or more parameters (as assertions)\n/// - Optional metadata (non-parameter assertions)\n///\n/// ## CBOR Tags\n///\n/// - Function: #6.40006\n/// - Parameter: #6.40007\n/// - Placeholder: #6.40008\n/// - Replacement: #6.40009\n///\n/// @example\n/// ```typescript\n/// // Create a simple addition expression: add(lhs: 2, rhs: 3)\n/// const expr = new Function('add')\n/// .withParameter('lhs', 2)\n/// .withParameter('rhs', 3);\n///\n/// const envelope = expr.envelope();\n/// ```\n\n/// CBOR tag for function identifiers\nexport const CBOR_TAG_FUNCTION = 40006;\n\n/// CBOR tag for parameter identifiers\nexport const CBOR_TAG_PARAMETER = 40007;\n\n/// CBOR tag for placeholder identifiers\nexport const CBOR_TAG_PLACEHOLDER = 40008;\n\n/// CBOR tag for replacement identifiers\nexport const CBOR_TAG_REPLACEMENT = 40009;\n\n/// Well-known function identifiers (numeric)\nexport const FUNCTION_IDS = {\n ADD: 1, // addition\n SUB: 2, // subtraction\n MUL: 3, // multiplication\n DIV: 4, // division\n NEG: 5, // unary negation\n LT: 6, // less than\n LE: 7, // less than or equal\n GT: 8, // greater than\n GE: 9, // greater than or equal\n EQ: 10, // equal to\n NE: 11, // not equal to\n AND: 12, // logical and\n OR: 13, // logical or\n XOR: 14, // logical xor\n NOT: 15, // logical not\n} as const;\n\n/// Well-known parameter identifiers (numeric)\nexport const PARAMETER_IDS = {\n BLANK: 1, // blank/implicit parameter (_)\n LHS: 2, // left-hand side\n RHS: 3, // right-hand side\n} as const;\n\n/// Type for function identifier (number or string)\nexport type FunctionID = number | string;\n\n/// Type for parameter identifier (number or string)\nexport type ParameterID = number | string;\n\n//------------------------------------------------------------------------------\n// Function class - matches Rust's Function enum\n//------------------------------------------------------------------------------\n\n/// Type tag for function variant\ntype FunctionVariant = \"known\" | \"named\";\n\n/// Represents a function identifier in an expression.\n///\n/// In Gordian Envelope, a function appears as the subject of an expression\n/// envelope, with its parameters as assertions on that envelope.\n///\n/// Functions can be identified in two ways:\n/// 1. By a numeric ID (for well-known functions) - Known variant\n/// 2. By a string name (for application-specific functions) - Named variant\n///\n/// When encoded in CBOR, functions are tagged with #6.40006.\nexport class Function implements EnvelopeEncodable {\n private readonly _variant: FunctionVariant;\n private readonly _value: number; // Only used for 'known' variant\n private readonly _name: string | undefined;\n\n private constructor(variant: FunctionVariant, value: number, name?: string) {\n this._variant = variant;\n this._value = value;\n this._name = name;\n }\n\n /// Creates a new known function with a numeric ID and optional name.\n static newKnown(value: number, name?: string): Function {\n return new Function(\"known\", value, name);\n }\n\n /// Creates a new named function identified by a string.\n static newNamed(name: string): Function {\n return new Function(\"named\", 0, name);\n }\n\n /// Creates a function from a numeric ID (convenience method).\n static fromNumeric(id: number): Function {\n return Function.newKnown(id);\n }\n\n /// Creates a function from a string name (convenience method).\n static fromString(name: string): Function {\n return Function.newNamed(name);\n }\n\n /// Returns true if this is a known (numeric) function.\n isKnown(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a named (string) function.\n isNamed(): boolean {\n return this._variant === \"named\";\n }\n\n /// Returns the numeric value for known functions.\n value(): number | undefined {\n return this._variant === \"known\" ? this._value : undefined;\n }\n\n /// Returns the function identifier (number for known, string for named).\n id(): FunctionID {\n if (this._variant === \"known\") {\n return this._value;\n }\n // For named variant, name is always set during construction\n if (this._name === undefined) {\n throw new Error(\"Invalid named function: missing name\");\n }\n return this._name;\n }\n\n /// Returns the display name of the function.\n ///\n /// For known functions with a name, returns the name.\n /// For known functions without a name, returns the numeric ID as a string.\n /// For named functions, returns the name enclosed in quotes.\n name(): string {\n if (this._variant === \"known\") {\n return this._name ?? this._value.toString();\n } else {\n return `\"${this._name}\"`;\n }\n }\n\n /// Returns the raw name for named functions, or undefined for known functions.\n namedName(): string | undefined {\n return this._variant === \"named\" ? this._name : undefined;\n }\n\n /// Returns the assigned name if present (for known functions only).\n assignedName(): string | undefined {\n return this._variant === \"known\" ? this._name : undefined;\n }\n\n /// Returns true if this is a numeric function ID (legacy compatibility).\n isNumeric(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a string function ID (legacy compatibility).\n isString(): boolean {\n return this._variant === \"named\";\n }\n\n /// Creates an expression envelope with this function as the subject.\n envelope(): Envelope {\n const functionStr = this._variant === \"known\" ? `«${this._value}»` : `«\"${this._name}\"»`;\n return Envelope.new(functionStr);\n }\n\n /// Converts this function into an envelope (EnvelopeEncodable implementation).\n intoEnvelope(): Envelope {\n return this.envelope();\n }\n\n /// Creates an expression with a parameter.\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Expression {\n const expr = new Expression(this);\n return expr.withParameter(param, value);\n }\n\n /// Checks equality based on value (for known) or name (for named).\n equals(other: Function): boolean {\n if (this._variant !== other._variant) return false;\n if (this._variant === \"known\") {\n return this._value === other._value;\n } else {\n return this._name === other._name;\n }\n }\n\n /// Returns a hash code for this function.\n hashCode(): number {\n if (this._variant === \"known\") {\n return this._value;\n } else {\n // Simple string hash\n let hash = 0;\n for (let i = 0; i < (this._name?.length ?? 0); i++) {\n hash = (hash * 31 + (this._name?.charCodeAt(i) ?? 0)) | 0;\n }\n return hash;\n }\n }\n\n /// Returns a string representation for display.\n toString(): string {\n return this._variant === \"known\" ? `«${this._value}»` : `«\"${this._name}\"»`;\n }\n}\n\n//------------------------------------------------------------------------------\n// FunctionsStore class - matches Rust's FunctionsStore\n//------------------------------------------------------------------------------\n\n/// A store that maps functions to their assigned names.\n///\n/// FunctionsStore maintains a registry of functions and their human-readable\n/// names, which is useful for displaying and debugging expression functions.\nexport class FunctionsStore {\n private readonly _dict = new Map<number | string, Function>();\n\n /// Creates a new FunctionsStore with the given functions.\n constructor(functions: Iterable<Function> = []) {\n for (const func of functions) {\n this.insert(func);\n }\n }\n\n /// Inserts a function into the store.\n insert(func: Function): void {\n if (func.isKnown()) {\n const value = func.value();\n if (value !== undefined) {\n this._dict.set(value, func);\n }\n } else {\n const name = func.namedName();\n if (name !== undefined) {\n this._dict.set(name, func);\n }\n }\n }\n\n /// Returns the assigned name for a function, if it exists in the store.\n assignedName(func: Function): string | undefined {\n let key: number | string | undefined;\n if (func.isKnown()) {\n key = func.value();\n } else {\n key = func.namedName();\n }\n if (key === undefined) return undefined;\n const stored = this._dict.get(key);\n return stored?.assignedName();\n }\n\n /// Returns the name for a function, either from this store or from the function itself.\n name(func: Function): string {\n const assigned = this.assignedName(func);\n return assigned ?? func.name();\n }\n\n /// Static method that returns the name of a function, using an optional store.\n static nameForFunction(func: Function, store?: FunctionsStore): string {\n if (store !== undefined) {\n const assigned = store.assignedName(func);\n if (assigned !== undefined && assigned !== \"\") return assigned;\n }\n return func.name();\n }\n}\n\n//------------------------------------------------------------------------------\n// Parameter class - matches Rust's Parameter enum\n//------------------------------------------------------------------------------\n\n/// Type tag for parameter variant\ntype ParameterVariant = \"known\" | \"named\";\n\n/// Represents a parameter identifier in an expression.\n///\n/// In Gordian Envelope, a parameter appears as a predicate in an assertion on\n/// an expression envelope. The parameter identifies the name of the argument,\n/// and the object of the assertion is the argument value.\n///\n/// Parameters can be identified in two ways:\n/// 1. By a numeric ID (for well-known parameters) - Known variant\n/// 2. By a string name (for application-specific parameters) - Named variant\n///\n/// When encoded in CBOR, parameters are tagged with #6.40007.\nexport class Parameter implements EnvelopeEncodable {\n private readonly _variant: ParameterVariant;\n private readonly _value: number; // Only used for 'known' variant, or 0 for 'named'\n private readonly _name: string | undefined;\n private readonly _paramValue: Envelope | undefined; // The parameter's value envelope\n\n private constructor(\n variant: ParameterVariant,\n value: number,\n name?: string,\n paramValue?: Envelope,\n ) {\n this._variant = variant;\n this._value = value;\n this._name = name;\n this._paramValue = paramValue;\n }\n\n /// Creates a new known parameter with a numeric ID and optional name.\n static newKnown(value: number, name?: string): Parameter {\n return new Parameter(\"known\", value, name);\n }\n\n /// Creates a new named parameter identified by a string.\n static newNamed(name: string): Parameter {\n return new Parameter(\"named\", 0, name);\n }\n\n /// Creates a parameter with a value envelope (internal use).\n static withValue(id: ParameterID, value: Envelope): Parameter {\n if (typeof id === \"number\") {\n return new Parameter(\"known\", id, undefined, value);\n } else {\n return new Parameter(\"named\", 0, id, value);\n }\n }\n\n /// Returns true if this is a known (numeric) parameter.\n isKnown(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a named (string) parameter.\n isNamed(): boolean {\n return this._variant === \"named\";\n }\n\n /// Returns the numeric value for known parameters.\n value(): number | undefined {\n return this._variant === \"known\" ? this._value : undefined;\n }\n\n /// Returns the parameter identifier (number for known, string for named).\n id(): ParameterID {\n if (this._variant === \"known\") {\n return this._value;\n }\n // For named variant, name is always set during construction\n if (this._name === undefined) {\n throw new Error(\"Invalid named parameter: missing name\");\n }\n return this._name;\n }\n\n /// Returns the display name of the parameter.\n ///\n /// For known parameters with a name, returns the name.\n /// For known parameters without a name, returns the numeric ID as a string.\n /// For named parameters, returns the name enclosed in quotes.\n name(): string {\n if (this._variant === \"known\") {\n return this._name ?? this._value.toString();\n } else {\n return `\"${this._name}\"`;\n }\n }\n\n /// Returns the raw name for named parameters, or undefined for known parameters.\n namedName(): string | undefined {\n return this._variant === \"named\" ? this._name : undefined;\n }\n\n /// Returns the assigned name if present (for known parameters only).\n assignedName(): string | undefined {\n return this._variant === \"known\" ? this._name : undefined;\n }\n\n /// Returns the parameter value as an envelope, if set.\n paramValue(): Envelope | undefined {\n return this._paramValue;\n }\n\n /// Returns true if this is a numeric parameter ID (legacy compatibility).\n isNumeric(): boolean {\n return this._variant === \"known\";\n }\n\n /// Returns true if this is a string parameter ID (legacy compatibility).\n isString(): boolean {\n return this._variant === \"named\";\n }\n\n /// Creates a parameter envelope.\n envelope(): Envelope {\n const paramStr = this._variant === \"known\" ? `❰${this._value}❱` : `❰\"${this._name}\"❱`;\n if (this._paramValue !== undefined) {\n return Envelope.newAssertion(paramStr, this._paramValue);\n }\n return Envelope.new(paramStr);\n }\n\n /// Converts this parameter into an envelope (EnvelopeEncodable implementation).\n intoEnvelope(): Envelope {\n return this.envelope();\n }\n\n /// Checks equality based on value (for known) or name (for named).\n equals(other: Parameter): boolean {\n if (this._variant !== other._variant) return false;\n if (this._variant === \"known\") {\n return this._value === other._value;\n } else {\n return this._name === other._name;\n }\n }\n\n /// Returns a hash code for this parameter.\n hashCode(): number {\n if (this._variant === \"known\") {\n return this._value;\n } else {\n let hash = 0;\n for (let i = 0; i < (this._name?.length ?? 0); i++) {\n hash = (hash * 31 + (this._name?.charCodeAt(i) ?? 0)) | 0;\n }\n return hash;\n }\n }\n\n /// Returns a string representation for display.\n toString(): string {\n const idStr = this._variant === \"known\" ? `❰${this._value}❱` : `❰\"${this._name}\"❱`;\n if (this._paramValue !== undefined) {\n return `${idStr}: ${this._paramValue.asText()}`;\n }\n return idStr;\n }\n\n // Convenience static methods for standard parameters\n static blank(value: EnvelopeEncodableValue): Parameter {\n return Parameter.withValue(PARAMETER_IDS.BLANK, Envelope.new(value));\n }\n\n static lhs(value: EnvelopeEncodableValue): Parameter {\n return Parameter.withValue(PARAMETER_IDS.LHS, Envelope.new(value));\n }\n\n static rhs(value: EnvelopeEncodableValue): Parameter {\n return Parameter.withValue(PARAMETER_IDS.RHS, Envelope.new(value));\n }\n}\n\n//------------------------------------------------------------------------------\n// ParametersStore class - matches Rust's ParametersStore\n//------------------------------------------------------------------------------\n\n/// A store that maps parameters to their assigned names.\n///\n/// ParametersStore maintains a registry of parameters and their human-readable\n/// names, which is useful for displaying and debugging expression parameters.\nexport class ParametersStore {\n private readonly _dict = new Map<number | string, Parameter>();\n\n /// Creates a new ParametersStore with the given parameters.\n constructor(parameters: Iterable<Parameter> = []) {\n for (const param of parameters) {\n this.insert(param);\n }\n }\n\n /// Inserts a parameter into the store.\n insert(param: Parameter): void {\n if (param.isKnown()) {\n const value = param.value();\n if (value !== undefined) {\n this._dict.set(value, param);\n }\n } else {\n const name = param.namedName();\n if (name !== undefined) {\n this._dict.set(name, param);\n }\n }\n }\n\n /// Returns the assigned name for a parameter, if it exists in the store.\n assignedName(param: Parameter): string | undefined {\n let key: number | string | undefined;\n if (param.isKnown()) {\n key = param.value();\n } else {\n key = param.namedName();\n }\n if (key === undefined) return undefined;\n const stored = this._dict.get(key);\n return stored?.assignedName();\n }\n\n /// Returns the name for a parameter, either from this store or from the parameter itself.\n name(param: Parameter): string {\n const assigned = this.assignedName(param);\n return assigned ?? param.name();\n }\n\n /// Static method that returns the name of a parameter, using an optional store.\n static nameForParameter(param: Parameter, store?: ParametersStore): string {\n if (store !== undefined) {\n const assigned = store.assignedName(param);\n if (assigned !== undefined && assigned !== \"\") return assigned;\n }\n return param.name();\n }\n}\n\n//------------------------------------------------------------------------------\n// Well-known function constants (matching Rust's function_constant! macro)\n//------------------------------------------------------------------------------\n\n/// Standard arithmetic and logical functions\nexport const ADD = Function.newKnown(FUNCTION_IDS.ADD, \"add\");\nexport const SUB = Function.newKnown(FUNCTION_IDS.SUB, \"sub\");\nexport const MUL = Function.newKnown(FUNCTION_IDS.MUL, \"mul\");\nexport const DIV = Function.newKnown(FUNCTION_IDS.DIV, \"div\");\nexport const NEG = Function.newKnown(FUNCTION_IDS.NEG, \"neg\");\nexport const LT = Function.newKnown(FUNCTION_IDS.LT, \"lt\");\nexport const LE = Function.newKnown(FUNCTION_IDS.LE, \"le\");\nexport const GT = Function.newKnown(FUNCTION_IDS.GT, \"gt\");\nexport const GE = Function.newKnown(FUNCTION_IDS.GE, \"ge\");\nexport const EQ = Function.newKnown(FUNCTION_IDS.EQ, \"eq\");\nexport const NE = Function.newKnown(FUNCTION_IDS.NE, \"ne\");\nexport const AND = Function.newKnown(FUNCTION_IDS.AND, \"and\");\nexport const OR = Function.newKnown(FUNCTION_IDS.OR, \"or\");\nexport const XOR = Function.newKnown(FUNCTION_IDS.XOR, \"xor\");\nexport const NOT = Function.newKnown(FUNCTION_IDS.NOT, \"not\");\n\n/// Raw value constants (matching Rust's _VALUE suffix constants)\nexport const ADD_VALUE = FUNCTION_IDS.ADD;\nexport const SUB_VALUE = FUNCTION_IDS.SUB;\nexport const MUL_VALUE = FUNCTION_IDS.MUL;\nexport const DIV_VALUE = FUNCTION_IDS.DIV;\nexport const NEG_VALUE = FUNCTION_IDS.NEG;\nexport const LT_VALUE = FUNCTION_IDS.LT;\nexport const LE_VALUE = FUNCTION_IDS.LE;\nexport const GT_VALUE = FUNCTION_IDS.GT;\nexport const GE_VALUE = FUNCTION_IDS.GE;\nexport const EQ_VALUE = FUNCTION_IDS.EQ;\nexport const NE_VALUE = FUNCTION_IDS.NE;\nexport const AND_VALUE = FUNCTION_IDS.AND;\nexport const OR_VALUE = FUNCTION_IDS.OR;\nexport const XOR_VALUE = FUNCTION_IDS.XOR;\nexport const NOT_VALUE = FUNCTION_IDS.NOT;\n\n//------------------------------------------------------------------------------\n// Well-known parameter constants (matching Rust's parameter_constant! macro)\n//------------------------------------------------------------------------------\n\n/// Standard parameters\nexport const BLANK = Parameter.newKnown(PARAMETER_IDS.BLANK, \"_\");\nexport const LHS = Parameter.newKnown(PARAMETER_IDS.LHS, \"lhs\");\nexport const RHS = Parameter.newKnown(PARAMETER_IDS.RHS, \"rhs\");\n\n/// Raw value constants\nexport const BLANK_VALUE = PARAMETER_IDS.BLANK;\nexport const LHS_VALUE = PARAMETER_IDS.LHS;\nexport const RHS_VALUE = PARAMETER_IDS.RHS;\n\n//------------------------------------------------------------------------------\n// Global stores (matching Rust's GLOBAL_FUNCTIONS and GLOBAL_PARAMETERS)\n//------------------------------------------------------------------------------\n\n/// Lazy initialization helper for global stores\nexport class LazyStore<T> {\n private _store: T | undefined;\n private readonly _initializer: () => T;\n\n constructor(initializer: () => T) {\n this._initializer = initializer;\n }\n\n get(): T {\n this._store ??= this._initializer();\n return this._store;\n }\n}\n\n/// The global shared store of known functions.\nexport const GLOBAL_FUNCTIONS = new LazyStore(\n () => new FunctionsStore([ADD, SUB, MUL, DIV, NEG, LT, LE, GT, GE, EQ, NE, AND, OR, XOR, NOT]),\n);\n\n/// The global shared store of known parameters.\nexport const GLOBAL_PARAMETERS = new LazyStore(() => new ParametersStore([BLANK, LHS, RHS]));\n\n//------------------------------------------------------------------------------\n// Expression class\n//------------------------------------------------------------------------------\n\n/// Represents a complete expression with function and parameters.\nexport class Expression implements EnvelopeEncodable {\n private readonly _function: Function;\n private readonly _parameters = new Map<string, Parameter>();\n private _envelope: Envelope | null = null;\n\n constructor(func: Function) {\n this._function = func;\n }\n\n /// Returns the function.\n function(): Function {\n return this._function;\n }\n\n /// Returns all parameters.\n parameters(): Parameter[] {\n return Array.from(this._parameters.values());\n }\n\n /// Adds a parameter to the expression.\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Expression {\n const key = typeof param === \"number\" ? param.toString() : param;\n this._parameters.set(key, Parameter.withValue(param, Envelope.new(value)));\n this._envelope = null; // Invalidate cached envelope\n return this;\n }\n\n /// Adds multiple parameters at once.\n withParameters(params: Record<string, EnvelopeEncodableValue>): Expression {\n for (const [key, value] of Object.entries(params)) {\n this.withParameter(key, value);\n }\n return this;\n }\n\n /// Gets a parameter value by ID.\n getParameter(param: ParameterID): Envelope | undefined {\n const key = typeof param === \"number\" ? param.toString() : param;\n return this._parameters.get(key)?.paramValue();\n }\n\n /// Checks if a parameter exists.\n hasParameter(param: ParameterID): boolean {\n const key = typeof param === \"number\" ? param.toString() : param;\n return this._parameters.has(key);\n }\n\n /// Converts the expression to an envelope.\n envelope(): Envelope {\n if (this._envelope !== null) {\n return this._envelope;\n }\n\n // Start with function envelope\n let env = this._function.envelope();\n\n // Add all parameters as assertions\n for (const param of this._parameters.values()) {\n const paramEnv = param.envelope();\n // The paramEnv is itself an assertion envelope - extract predicate and object directly\n const paramCase = paramEnv.case();\n if (paramCase.type === \"assertion\") {\n const predicate = paramCase.assertion.predicate();\n const object = paramCase.assertion.object();\n const predText = predicate.asText();\n if (predText !== undefined) {\n env = env.addAssertion(predText, object);\n }\n }\n }\n\n this._envelope = env;\n return env;\n }\n\n /// Converts this expression into an envelope (EnvelopeEncodable implementation).\n intoEnvelope(): Envelope {\n return this.envelope();\n }\n\n /// Creates an expression from an envelope.\n static fromEnvelope(envelope: Envelope): Expression {\n // Extract function from subject\n const subject = envelope.subject();\n const subjectText = subject.asText();\n if (subjectText === undefined) {\n throw EnvelopeError.general(\"Not a valid function envelope\");\n }\n\n // Parse function identifier\n let func: Function;\n if (subjectText.startsWith(\"«\") && subjectText.endsWith(\"»\")) {\n const inner = subjectText.slice(1, -1);\n if (inner.startsWith('\"') && inner.endsWith('\"')) {\n func = Function.newNamed(inner.slice(1, -1));\n } else {\n func = Function.newKnown(parseInt(inner, 10));\n }\n } else {\n throw EnvelopeError.general(\"Not a valid function envelope\");\n }\n\n const expr = new Expression(func);\n\n // Extract parameters from assertions\n for (const assertion of envelope.assertions()) {\n try {\n const pred = assertion.subject().asPredicate();\n const obj = assertion.asObject();\n\n if (pred !== undefined && obj !== undefined) {\n const predText = pred.asText();\n if (predText !== undefined && predText.startsWith(\"❰\") && predText.endsWith(\"❱\")) {\n const inner = predText.slice(1, -1);\n let paramId: ParameterID;\n if (inner.startsWith('\"') && inner.endsWith('\"')) {\n paramId = inner.slice(1, -1);\n } else {\n paramId = parseInt(inner, 10);\n }\n expr.withParameter(paramId, obj);\n }\n }\n } catch {\n // Skip non-parameter assertions\n continue;\n }\n }\n\n return expr;\n }\n\n /// Returns a string representation for display.\n toString(): string {\n const params = Array.from(this._parameters.values())\n .map((p) => p.toString())\n .join(\", \");\n return `${this._function.toString()} [${params}]`;\n }\n}\n\n//------------------------------------------------------------------------------\n// Helper functions for creating common expressions\n//------------------------------------------------------------------------------\n\n/// Creates an addition expression: lhs + rhs\nexport function add(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(ADD)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a subtraction expression: lhs - rhs\nexport function sub(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(SUB)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a multiplication expression: lhs * rhs\nexport function mul(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(MUL)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a division expression: lhs / rhs\nexport function div(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(DIV)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a negation expression: -value\nexport function neg(value: EnvelopeEncodableValue): Expression {\n return new Expression(NEG).withParameter(PARAMETER_IDS.BLANK, value);\n}\n\n/// Creates a less-than expression: lhs < rhs\nexport function lt(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(LT)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a less-than-or-equal expression: lhs <= rhs\nexport function le(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(LE)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a greater-than expression: lhs > rhs\nexport function gt(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(GT)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a greater-than-or-equal expression: lhs >= rhs\nexport function ge(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(GE)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates an equality expression: lhs == rhs\nexport function eq(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(EQ)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a not-equal expression: lhs != rhs\nexport function ne(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(NE)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical AND expression: lhs && rhs\nexport function and(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(AND)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical OR expression: lhs || rhs\nexport function or(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(OR)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical XOR expression: lhs ^ rhs\nexport function xor(lhs: EnvelopeEncodableValue, rhs: EnvelopeEncodableValue): Expression {\n return new Expression(XOR)\n .withParameter(PARAMETER_IDS.LHS, lhs)\n .withParameter(PARAMETER_IDS.RHS, rhs);\n}\n\n/// Creates a logical NOT expression: !value\nexport function not(value: EnvelopeEncodableValue): Expression {\n return new Expression(NOT).withParameter(PARAMETER_IDS.BLANK, value);\n}\n","import { Envelope } from \"../base/envelope\";\nimport { type Digest } from \"../base/digest\";\n\n/// Extension for envelope inclusion proofs.\n///\n/// Inclusion proofs allow a holder of an envelope to prove that specific\n/// elements exist within the envelope without revealing the entire contents.\n/// This is particularly useful for selective disclosure of information in\n/// privacy-preserving scenarios.\n///\n/// ## How Inclusion Proofs Work\n///\n/// The inclusion proof mechanism leverages the Merkle-like digest tree\n/// structure of envelopes:\n/// - The holder creates a minimal structure containing only the digests\n/// necessary to validate the proof\n/// - A verifier with a trusted root digest can confirm that the specific\n/// elements exist in the original envelope\n/// - All other content can remain elided, preserving privacy\n///\n/// For enhanced privacy, elements can be salted to prevent correlation attacks.\n///\n/// @example\n/// ```typescript\n/// // Create an envelope with multiple assertions\n/// const aliceFriends = Envelope.new('Alice')\n/// .addAssertion('knows', 'Bob')\n/// .addAssertion('knows', 'Carol')\n/// .addAssertion('knows', 'Dan');\n///\n/// // Create a representation of just the root digest\n/// const aliceFriendsRoot = aliceFriends.elideRevealingSet(new Set());\n///\n/// // Create the target we want to prove exists\n/// const knowsBobAssertion = Envelope.newAssertion('knows', 'Bob');\n///\n/// // Generate a proof that Alice knows Bob\n/// const aliceKnowsBobProof = aliceFriends.proofContainsTarget(knowsBobAssertion);\n///\n/// // A third party can verify the proof against the trusted root\n/// if (aliceKnowsBobProof) {\n/// const isValid = aliceFriendsRoot.confirmContainsTarget(\n/// knowsBobAssertion,\n/// aliceKnowsBobProof\n/// );\n/// console.log('Proof is valid:', isValid);\n/// }\n/// ```\n\n/// Implementation of proof methods on Envelope prototype\n// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\nif (Envelope?.prototype) {\n Envelope.prototype.proofContainsSet = function (target: Set<Digest>): Envelope | undefined {\n const revealSet = revealSetOfSet(this, target);\n\n // Check if all targets can be revealed\n if (!isSubset(target, revealSet)) {\n return undefined;\n }\n\n // Create a proof by revealing only what's necessary, then eliding the targets\n const revealed = this.elideRevealingSet(revealSet);\n return revealed.elideRemovingSet(target);\n };\n\n Envelope.prototype.proofContainsTarget = function (target: Envelope): Envelope | undefined {\n const targetSet = new Set<Digest>([target.digest()]);\n return this.proofContainsSet(targetSet);\n };\n\n Envelope.prototype.confirmContainsSet = function (target: Set<Digest>, proof: Envelope): boolean {\n // Verify the proof has the same digest as this envelope\n if (this.digest().hex() !== proof.digest().hex()) {\n return false;\n }\n\n // Verify the proof contains all target elements\n return containsAll(proof, target);\n };\n\n Envelope.prototype.confirmContainsTarget = function (target: Envelope, proof: Envelope): boolean {\n const targetSet = new Set<Digest>([target.digest()]);\n return this.confirmContainsSet(targetSet, proof);\n };\n}\n\n/// Internal helper functions\n\n/// Builds a set of all digests needed to reveal the target set.\n///\n/// This collects all digests in the path from the envelope's root to each\n/// target element.\nfunction revealSetOfSet(envelope: Envelope, target: Set<Digest>): Set<Digest> {\n const result = new Set<Digest>();\n revealSets(envelope, target, new Set<Digest>(), result);\n return result;\n}\n\n/// Recursively traverses the envelope to collect all digests needed to\n/// reveal the target set.\n///\n/// Builds the set of digests forming the path from the root to each target element.\nfunction revealSets(\n envelope: Envelope,\n target: Set<Digest>,\n current: Set<Digest>,\n result: Set<Digest>,\n): void {\n // Add current envelope's digest to the path\n const newCurrent = new Set(current);\n newCurrent.add(envelope.digest());\n\n // If this is a target, add the entire path to the result\n if (containsDigest(target, envelope.digest())) {\n for (const digest of newCurrent) {\n result.add(digest);\n }\n }\n\n // Traverse the envelope structure\n const envelopeCase = envelope.case();\n\n if (envelopeCase.type === \"node\") {\n // Traverse subject\n revealSets(envelopeCase.subject, target, newCurrent, result);\n\n // Traverse all assertions\n for (const assertion of envelopeCase.assertions) {\n revealSets(assertion, target, newCurrent, result);\n }\n } else if (envelopeCase.type === \"wrapped\") {\n // Traverse wrapped envelope\n revealSets(envelopeCase.envelope, target, newCurrent, result);\n } else if (envelopeCase.type === \"assertion\") {\n // Traverse predicate and object\n const predicate = envelopeCase.assertion.predicate();\n const object = envelopeCase.assertion.object();\n revealSets(predicate, target, newCurrent, result);\n revealSets(object, target, newCurrent, result);\n }\n // For leaf envelopes (elided, encrypted, compressed, leaf), no further traversal needed\n}\n\n/// Checks if this envelope contains all elements in the target set.\n///\n/// Used during proof verification to confirm all target elements exist in the proof.\nfunction containsAll(envelope: Envelope, target: Set<Digest>): boolean {\n const targetCopy = new Set(target);\n removeAllFound(envelope, targetCopy);\n return targetCopy.size === 0;\n}\n\n/// Recursively traverses the envelope and removes found target elements from the set.\n///\n/// Used during proof verification to confirm all target elements are present.\nfunction removeAllFound(envelope: Envelope, target: Set<Digest>): void {\n // Check if this envelope's digest is in the target set\n if (containsDigest(target, envelope.digest())) {\n removeDigest(target, envelope.digest());\n }\n\n // Early exit if all targets found\n if (target.size === 0) {\n return;\n }\n\n // Traverse the envelope structure\n const envelopeCase = envelope.case();\n\n if (envelopeCase.type === \"node\") {\n // Traverse subject\n removeAllFound(envelopeCase.subject, target);\n\n // Traverse all assertions\n for (const assertion of envelopeCase.assertions) {\n removeAllFound(assertion, target);\n if (target.size === 0) break;\n }\n } else if (envelopeCase.type === \"wrapped\") {\n // Traverse wrapped envelope\n removeAllFound(envelopeCase.envelope, target);\n } else if (envelopeCase.type === \"assertion\") {\n // Traverse predicate and object\n const predicate = envelopeCase.assertion.predicate();\n const object = envelopeCase.assertion.object();\n removeAllFound(predicate, target);\n if (target.size > 0) {\n removeAllFound(object, target);\n }\n }\n // For leaf envelopes (elided, encrypted, compressed, leaf), no further traversal needed\n}\n\n/// Helper function to check if a set contains a digest (by hex comparison)\nfunction containsDigest(set: Set<Digest>, digest: Digest): boolean {\n const hexToFind = digest.hex();\n for (const d of set) {\n if (d.hex() === hexToFind) {\n return true;\n }\n }\n return false;\n}\n\n/// Helper function to remove a digest from a set (by hex comparison)\nfunction removeDigest(set: Set<Digest>, digest: Digest): void {\n const hexToFind = digest.hex();\n for (const d of set) {\n if (d.hex() === hexToFind) {\n set.delete(d);\n return;\n }\n }\n}\n\n/// Helper function to check if one set is a subset of another (by hex comparison)\nfunction isSubset(subset: Set<Digest>, superset: Set<Digest>): boolean {\n for (const digest of subset) {\n if (!containsDigest(superset, digest)) {\n return false;\n }\n }\n return true;\n}\n\n/// Register proof extension on Envelope prototype.\n/// This function is exported to allow explicit registration.\nexport function registerProofExtension(): void {\n // Methods are already registered above when this module loads\n}\n","/// Secret-based envelope locking and unlocking.\n///\n/// This module provides functionality for encrypting envelope subjects using\n/// password-based or key-based derivation methods, allowing envelopes to be\n/// locked with secrets and later unlocked.\n///\n/// The implementation uses `EncryptedKey` from bc-components for key\n/// derivation and encryption.\n\nimport {\n SymmetricKey as ComponentsSymmetricKey,\n EncryptedKey,\n type KeyDerivationMethod,\n} from \"@bcts/components\";\nimport { HAS_SECRET } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SymmetricKey } from \"./encrypt\";\n\n// ============================================================================\n// Envelope Prototype Extensions for Secret Locking\n// ============================================================================\n\n/// Implementation of lockSubject\nEnvelope.prototype.lockSubject = function (\n this: Envelope,\n method: KeyDerivationMethod,\n secret: Uint8Array,\n): Envelope {\n // Generate a new content key using local SymmetricKey\n const contentKey = SymmetricKey.new();\n\n // Convert to components SymmetricKey for EncryptedKey.lock\n const componentsKey = ComponentsSymmetricKey.fromData(contentKey.data());\n\n // Lock the content key using the specified derivation method\n const encryptedKey = EncryptedKey.lock(method, secret, componentsKey);\n\n // Encrypt the subject and add the hasSecret assertion\n const encrypted = this.encryptSubject(contentKey);\n return encrypted.addAssertion(HAS_SECRET, encryptedKey);\n};\n\n/// Implementation of unlockSubject\nEnvelope.prototype.unlockSubject = function (this: Envelope, secret: Uint8Array): Envelope {\n // Find all hasSecret assertions\n const assertions = this.assertionsWithPredicate(HAS_SECRET);\n\n // Try each one until we find one that unlocks\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n // Skip obscured (elided/encrypted/compressed) assertions\n if (obj.isObscured()) continue;\n\n try {\n // Try to extract the EncryptedKey\n const encryptedKey = obj.extractSubject((cbor) => EncryptedKey.fromTaggedCbor(cbor));\n\n // Try to unlock with the provided secret (returns ComponentsSymmetricKey)\n const componentsKey = encryptedKey.unlock(secret);\n\n // Convert to local SymmetricKey for decryptSubject\n const contentKey = SymmetricKey.from(componentsKey.data());\n\n // If successful, decrypt the subject\n return this.decryptSubject(contentKey);\n } catch {\n // This assertion didn't work, try the next one\n continue;\n }\n }\n\n // No matching secret found\n throw EnvelopeError.unknownSecret();\n};\n\n/// Implementation of isLockedWithPassword\nEnvelope.prototype.isLockedWithPassword = function (this: Envelope): boolean {\n const assertions = this.assertionsWithPredicate(HAS_SECRET);\n\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n try {\n const encryptedKey = obj.extractSubject((cbor) => EncryptedKey.fromTaggedCbor(cbor));\n if (encryptedKey.isPasswordBased()) {\n return true;\n }\n } catch {\n continue;\n }\n }\n\n return false;\n};\n\n/// Implementation of isLockedWithSshAgent\nEnvelope.prototype.isLockedWithSshAgent = function (this: Envelope): boolean {\n const assertions = this.assertionsWithPredicate(HAS_SECRET);\n\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n try {\n const encryptedKey = obj.extractSubject((cbor) => EncryptedKey.fromTaggedCbor(cbor));\n if (encryptedKey.isSshAgent()) {\n return true;\n }\n } catch {\n continue;\n }\n }\n\n return false;\n};\n\n/// Implementation of addSecret\nEnvelope.prototype.addSecret = function (\n this: Envelope,\n method: KeyDerivationMethod,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n): Envelope {\n // Convert to components SymmetricKey for EncryptedKey.lock\n const componentsKey = ComponentsSymmetricKey.fromData(contentKey.data());\n\n // Lock the content key using the specified derivation method\n const encryptedKey = EncryptedKey.lock(method, secret, componentsKey);\n\n // Add a hasSecret assertion with the EncryptedKey\n return this.addAssertion(HAS_SECRET, encryptedKey);\n};\n\n/// Implementation of lock\nEnvelope.prototype.lock = function (\n this: Envelope,\n method: KeyDerivationMethod,\n secret: Uint8Array,\n): Envelope {\n return this.wrap().lockSubject(method, secret);\n};\n\n/// Implementation of unlock\nEnvelope.prototype.unlock = function (this: Envelope, secret: Uint8Array): Envelope {\n return this.unlockSubject(secret).tryUnwrap();\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the secret extension\nexport const registerSecretExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","/// SSKR-based envelope splitting and joining.\n///\n/// This module provides functionality for splitting encrypted envelopes\n/// using SSKR (Sharded Secret Key Reconstruction), which is an implementation\n/// of Shamir's Secret Sharing. SSKR allows splitting a secret (the symmetric\n/// encryption key) into multiple shares, with a threshold required for\n/// reconstruction.\n///\n/// SSKR provides social recovery for encrypted envelopes by allowing the owner\n/// to distribute shares to trusted individuals or storage locations, with a\n/// specified threshold required to reconstruct the original envelope.\n\nimport {\n SSKRShareCbor,\n SSKRSecret,\n SSKRSpec,\n SSKRGroupSpec,\n sskrGenerateShares,\n sskrCombineShares,\n sskrGenerateUsing,\n} from \"@bcts/components\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SSKR_SHARE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { EnvelopeError } from \"../base/error\";\nimport { SymmetricKey } from \"./encrypt\";\n\n// Re-export useful types\nexport { SSKRSpec, SSKRGroupSpec, SSKRShareCbor, SSKRSecret };\n\n// ============================================================================\n// Envelope Prototype Extensions for SSKR\n// ============================================================================\n\n/// Helper function to add an SSKR share assertion to the envelope\nconst addSskrShare = (envelope: Envelope, share: SSKRShareCbor): Envelope => {\n return envelope.addAssertion(SSKR_SHARE, share);\n};\n\n/// Implementation of sskrSplit\nEnvelope.prototype.sskrSplit = function (\n this: Envelope,\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n): Envelope[][] {\n // Convert symmetric key to SSKR secret\n const masterSecret = SSKRSecret.new(contentKey.data());\n\n // Generate SSKR shares with CBOR wrappers\n const shareGroups: SSKRShareCbor[][] = sskrGenerateShares(spec, masterSecret);\n\n // Create envelope copies with SSKR share assertions\n const result: Envelope[][] = [];\n for (const group of shareGroups) {\n const groupResult: Envelope[] = [];\n for (const share of group) {\n const shareEnvelope = addSskrShare(this, share);\n groupResult.push(shareEnvelope);\n }\n result.push(groupResult);\n }\n\n return result;\n};\n\n/// Implementation of sskrSplitFlattened\nEnvelope.prototype.sskrSplitFlattened = function (\n this: Envelope,\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n): Envelope[] {\n return this.sskrSplit(spec, contentKey).flat();\n};\n\n/// Implementation of sskrSplitUsing (with custom RNG)\nEnvelope.prototype.sskrSplitUsing = function (\n this: Envelope,\n spec: SSKRSpec,\n contentKey: SymmetricKey,\n rng: RandomNumberGenerator,\n): Envelope[][] {\n // Convert symmetric key to SSKR secret\n const masterSecret = SSKRSecret.new(contentKey.data());\n\n // Generate SSKR shares using custom RNG\n const shareGroups = sskrGenerateUsing(spec, masterSecret, rng);\n\n // Convert raw bytes to SSKRShareCbor and create envelope copies\n const result: Envelope[][] = [];\n for (const group of shareGroups) {\n const groupResult: Envelope[] = [];\n for (const shareData of group) {\n const share = SSKRShareCbor.fromData(shareData);\n const shareEnvelope = addSskrShare(this, share);\n groupResult.push(shareEnvelope);\n }\n result.push(groupResult);\n }\n\n return result;\n};\n\n/// Helper function to extract SSKR shares from envelopes, grouped by identifier\nconst extractSskrSharesGrouped = (envelopes: Envelope[]): Map<number, SSKRShareCbor[]> => {\n const result = new Map<number, SSKRShareCbor[]>();\n\n for (const envelope of envelopes) {\n const assertions = envelope.assertionsWithPredicate(SSKR_SHARE);\n\n for (const assertion of assertions) {\n const obj = assertion.asObject();\n if (obj === undefined) continue;\n\n // Skip obscured (elided/encrypted/compressed) assertions\n if (obj.isObscured()) continue;\n\n try {\n // Try to extract the SSKRShareCbor\n const share = obj.extractSubject((cbor) => SSKRShareCbor.fromTaggedCbor(cbor));\n const identifier = share.identifier();\n\n const existing = result.get(identifier);\n if (existing !== undefined) {\n existing.push(share);\n } else {\n result.set(identifier, [share]);\n }\n } catch {\n // This assertion didn't contain a valid SSKR share, skip it\n continue;\n }\n }\n }\n\n return result;\n};\n\n/// Implementation of sskrJoin (static method)\n(Envelope as unknown as { sskrJoin: (envelopes: Envelope[]) => Envelope }).sskrJoin = function (\n envelopes: Envelope[],\n): Envelope {\n if (envelopes.length === 0) {\n throw EnvelopeError.invalidShares();\n }\n\n // Extract and group shares by identifier\n const groupedShares = extractSskrSharesGrouped(envelopes);\n\n // Try each group of shares (shares with same identifier)\n for (const shares of groupedShares.values()) {\n try {\n // Try to combine the shares\n const secret: SSKRSecret = sskrCombineShares(shares);\n\n // Convert secret back to symmetric key (local SymmetricKey uses `from`)\n const contentKey = SymmetricKey.from(secret.getData());\n\n // Try to decrypt the envelope subject\n const decrypted = envelopes[0].decryptSubject(contentKey);\n\n // Return the decrypted subject\n return decrypted.subject();\n } catch {\n // This group of shares didn't work, try the next one\n continue;\n }\n }\n\n // No valid combination found\n throw EnvelopeError.invalidShares();\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the SSKR extension\nexport const registerSskrExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","/**\n * Request type for distributed function calls.\n *\n * Ported from bc-envelope-rust/src/extension/expressions/request.rs\n *\n * A Request represents a message requesting execution of a function with\n * parameters. Requests are part of the expression system that enables\n * distributed function calls and communication between systems.\n *\n * Each request:\n * - Contains a body (an Expression) that represents the function to be executed\n * - Has a unique identifier (ARID) for tracking and correlation\n * - May include optional metadata like a note and timestamp\n *\n * Requests are designed to be paired with Response objects that contain the\n * results of executing the requested function.\n *\n * When serialized to an envelope, requests are tagged with REQUEST tag.\n */\n\nimport { ARID } from \"@bcts/components\";\nimport { REQUEST as TAG_REQUEST } from \"@bcts/tags\";\nimport { toTaggedValue } from \"@bcts/dcbor\";\nimport { BODY, NOTE, DATE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\nimport { Expression, Function, type ParameterID } from \"./expression\";\n\n/**\n * Interface that defines the behavior of a request.\n *\n * This interface extends expression behavior to add methods specific to requests,\n * including metadata management and access to request properties.\n */\nexport interface RequestBehavior {\n /**\n * Adds a parameter to the request.\n */\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Request;\n\n /**\n * Adds a note to the request.\n */\n withNote(note: string): Request;\n\n /**\n * Adds a date to the request.\n */\n withDate(date: Date): Request;\n\n /**\n * Returns the body of the request (the expression to be evaluated).\n */\n body(): Expression;\n\n /**\n * Returns the unique identifier (ARID) of the request.\n */\n id(): ARID;\n\n /**\n * Returns the note attached to the request, or an empty string if none exists.\n */\n note(): string;\n\n /**\n * Returns the date attached to the request, if any.\n */\n date(): Date | undefined;\n\n /**\n * Returns the function of the request.\n */\n function(): Function;\n\n /**\n * Returns the expression envelope of the request.\n */\n expressionEnvelope(): Envelope;\n\n /**\n * Converts the request to an envelope.\n */\n toEnvelope(): Envelope;\n}\n\n/**\n * A Request represents a message requesting execution of a function with parameters.\n *\n * @example\n * ```typescript\n * import { Request, ARID } from '@bcts/envelope';\n *\n * // Create a random request ID\n * const requestId = ARID.new();\n *\n * // Create a request to execute a function with parameters\n * const request = Request.new(\"getBalance\", requestId)\n * .withParameter(\"account\", \"alice\")\n * .withParameter(\"currency\", \"USD\")\n * .withNote(\"Monthly balance check\");\n *\n * // Convert to an envelope\n * const envelope = request.toEnvelope();\n * ```\n */\nexport class Request implements RequestBehavior, EnvelopeEncodable {\n private readonly _body: Expression;\n private readonly _id: ARID;\n private _note: string;\n private _date: Date | undefined;\n\n private constructor(body: Expression, id: ARID, note = \"\", date?: Date) {\n this._body = body;\n this._id = id;\n this._note = note;\n this._date = date;\n }\n\n /**\n * Creates a new request with the specified expression body and ID.\n */\n static newWithBody(body: Expression, id: ARID): Request {\n return new Request(body, id);\n }\n\n /**\n * Creates a new request with a function and ID.\n *\n * This is a convenience method that creates an expression from the\n * function and then creates a request with that expression.\n */\n static new(func: Function | string | number, id: ARID): Request {\n const f =\n typeof func === \"string\"\n ? Function.newNamed(func)\n : typeof func === \"number\"\n ? Function.newKnown(func)\n : func;\n return Request.newWithBody(new Expression(f), id);\n }\n\n /**\n * Returns a human-readable summary of the request.\n */\n summary(): string {\n return `id: ${this._id.shortDescription()}, body: ${this._body.envelope().formatFlat()}`;\n }\n\n // RequestBehavior implementation\n\n withParameter(param: ParameterID, value: EnvelopeEncodableValue): Request {\n this._body.withParameter(param, value);\n return this;\n }\n\n withNote(note: string): Request {\n this._note = note;\n return this;\n }\n\n withDate(date: Date): Request {\n this._date = date;\n return this;\n }\n\n body(): Expression {\n return this._body;\n }\n\n id(): ARID {\n return this._id;\n }\n\n note(): string {\n return this._note;\n }\n\n date(): Date | undefined {\n return this._date;\n }\n\n function(): Function {\n return this._body.function();\n }\n\n expressionEnvelope(): Envelope {\n return this._body.envelope();\n }\n\n /**\n * Converts the request to an envelope.\n *\n * The envelope's subject is the request's ID tagged with TAG_REQUEST,\n * and assertions include the request's body, note (if not empty), and date (if present).\n */\n toEnvelope(): Envelope {\n // Create the tagged ARID as the subject\n const taggedArid = toTaggedValue(TAG_REQUEST, this._id.untaggedCbor());\n\n let envelope = Envelope.newLeaf(taggedArid).addAssertion(BODY, this._body.envelope());\n\n if (this._note !== \"\") {\n envelope = envelope.addAssertion(NOTE, this._note);\n }\n\n if (this._date !== undefined) {\n envelope = envelope.addAssertion(DATE, this._date.toISOString());\n }\n\n return envelope;\n }\n\n /**\n * Converts this request into an envelope (EnvelopeEncodable implementation).\n */\n intoEnvelope(): Envelope {\n return this.toEnvelope();\n }\n\n /**\n * Creates a request from an envelope.\n */\n static fromEnvelope(envelope: Envelope, expectedFunction?: Function): Request {\n // Extract the body\n const bodyEnvelope = envelope.objectForPredicate(BODY);\n if (bodyEnvelope === undefined) {\n throw EnvelopeError.general(\"Request envelope missing body\");\n }\n\n // Parse the expression from the body\n const body = Expression.fromEnvelope(bodyEnvelope);\n\n // Validate function if expected\n if (expectedFunction !== undefined && !body.function().equals(expectedFunction)) {\n throw EnvelopeError.general(\"Request function mismatch\");\n }\n\n // Extract the ARID from the subject\n const subject = envelope.subject();\n const leaf = subject.asLeaf();\n if (leaf === undefined) {\n throw EnvelopeError.general(\"Request envelope has invalid subject\");\n }\n\n // The subject is TAG_REQUEST(ARID_bytes)\n // First expect the REQUEST tag, then extract the ARID from the content\n const aridCbor = leaf.expectTag(TAG_REQUEST);\n const aridBytes = aridCbor.toByteString();\n const id = ARID.fromData(aridBytes);\n\n // Extract optional note\n let note = \"\";\n try {\n const noteObj = envelope.objectForPredicate(NOTE);\n if (noteObj !== undefined) {\n note = noteObj.asText() ?? \"\";\n }\n } catch {\n // Note is optional\n }\n\n // Extract optional date\n let date: Date | undefined;\n try {\n const dateObj = envelope.objectForPredicate(DATE);\n if (dateObj !== undefined) {\n const dateStr = dateObj.asText();\n if (dateStr !== undefined) {\n date = new Date(dateStr);\n }\n }\n } catch {\n // Date is optional\n }\n\n return new Request(body, id, note, date);\n }\n\n /**\n * Returns a string representation of the request.\n */\n toString(): string {\n return `Request(${this.summary()})`;\n }\n\n /**\n * Checks equality with another request.\n */\n equals(other: Request): boolean {\n return (\n this._id.equals(other._id) &&\n this._note === other._note &&\n this._date?.getTime() === other._date?.getTime()\n );\n }\n}\n","/**\n * Response type for distributed function calls.\n *\n * Ported from bc-envelope-rust/src/extension/expressions/response.rs\n *\n * A Response represents a reply to a Request containing either a\n * successful result or an error.\n *\n * Responses are part of the expression system that enables distributed\n * function calls. Each response contains:\n * - A reference to the original request's ID (ARID) for correlation\n * - Either a successful result or an error message\n *\n * When serialized to an envelope, responses are tagged with RESPONSE tag.\n */\n\nimport { ARID } from \"@bcts/components\";\nimport { RESPONSE as TAG_RESPONSE } from \"@bcts/tags\";\nimport { toTaggedValue } from \"@bcts/dcbor\";\nimport { RESULT, ERROR, OK_VALUE, UNKNOWN_VALUE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\n\n/**\n * Type representing a successful response: (ARID, result envelope)\n */\ninterface SuccessResult {\n ok: true;\n id: ARID;\n result: Envelope;\n}\n\n/**\n * Type representing a failed response: (optional ARID, error envelope)\n */\ninterface FailureResult {\n ok: false;\n id: ARID | undefined;\n error: Envelope;\n}\n\n/**\n * Internal result type for Response\n */\ntype ResponseResult = SuccessResult | FailureResult;\n\n/**\n * Interface that defines the behavior of a response.\n */\nexport interface ResponseBehavior {\n /**\n * Sets the result value for a successful response.\n * @throws Error if called on a failure response.\n */\n withResult(result: EnvelopeEncodableValue): Response;\n\n /**\n * Sets the error value for a failure response.\n * @throws Error if called on a successful response.\n */\n withError(error: EnvelopeEncodableValue): Response;\n\n /**\n * Returns true if this is a successful response.\n */\n isOk(): boolean;\n\n /**\n * Returns true if this is a failure response.\n */\n isErr(): boolean;\n\n /**\n * Returns the ID of the request this response corresponds to, if known.\n */\n id(): ARID | undefined;\n\n /**\n * Returns the result envelope if this is a successful response.\n * @throws Error if this is a failure response.\n */\n result(): Envelope;\n\n /**\n * Returns the error envelope if this is a failure response.\n * @throws Error if this is a successful response.\n */\n error(): Envelope;\n\n /**\n * Converts the response to an envelope.\n */\n toEnvelope(): Envelope;\n}\n\n/**\n * A Response represents a reply to a Request containing either a\n * successful result or an error.\n *\n * @example\n * ```typescript\n * import { Response, ARID } from '@bcts/envelope';\n *\n * // Create a request ID (normally this would come from the original request)\n * const requestId = ARID.new();\n *\n * // Create a successful response\n * const successResponse = Response.newSuccess(requestId)\n * .withResult(\"Transaction completed\");\n *\n * // Create an error response\n * const errorResponse = Response.newFailure(requestId)\n * .withError(\"Insufficient funds\");\n *\n * // Convert to envelopes\n * const successEnvelope = successResponse.toEnvelope();\n * const errorEnvelope = errorResponse.toEnvelope();\n * ```\n */\nexport class Response implements ResponseBehavior, EnvelopeEncodable {\n private _result: ResponseResult;\n\n private constructor(result: ResponseResult) {\n this._result = result;\n }\n\n /**\n * Creates a new successful response with the specified request ID.\n *\n * By default, the result will be the 'OK' known value. Use `withResult`\n * to set a specific result value.\n */\n static newSuccess(id: ARID): Response {\n return new Response({\n ok: true,\n id,\n result: Response.ok(),\n });\n }\n\n /**\n * Creates a new failure response with the specified request ID.\n *\n * By default, the error will be the 'Unknown' known value. Use\n * `withError` to set a specific error message.\n */\n static newFailure(id: ARID): Response {\n return new Response({\n ok: false,\n id,\n error: Response.unknown(),\n });\n }\n\n /**\n * Creates a new early failure response without a request ID.\n *\n * An early failure occurs when the error happens before the request\n * has been fully processed, so the request ID is not known.\n */\n static newEarlyFailure(): Response {\n return new Response({\n ok: false,\n id: undefined,\n error: Response.unknown(),\n });\n }\n\n /**\n * Creates an envelope containing the 'Unknown' known value.\n */\n static unknown(): Envelope {\n return Envelope.new(UNKNOWN_VALUE);\n }\n\n /**\n * Creates an envelope containing the 'OK' known value.\n */\n static ok(): Envelope {\n return Envelope.new(OK_VALUE);\n }\n\n /**\n * Returns a human-readable summary of the response.\n */\n summary(): string {\n if (this._result.ok) {\n return `id: ${this._result.id.shortDescription()}, result: ${this._result.result.formatFlat()}`;\n } else {\n const idStr =\n this._result.id !== undefined ? this._result.id.shortDescription() : \"'Unknown'\";\n return `id: ${idStr}, error: ${this._result.error.formatFlat()}`;\n }\n }\n\n // ResponseBehavior implementation\n\n withResult(result: EnvelopeEncodableValue): Response {\n if (!this._result.ok) {\n throw new Error(\"Cannot set result on a failed response\");\n }\n this._result = {\n ok: true,\n id: this._result.id,\n result: Envelope.new(result),\n };\n return this;\n }\n\n withOptionalResult(result: EnvelopeEncodableValue | undefined): Response {\n if (result !== undefined) {\n return this.withResult(result);\n }\n return this.withResult(null);\n }\n\n withError(error: EnvelopeEncodableValue): Response {\n if (this._result.ok) {\n throw new Error(\"Cannot set error on a successful response\");\n }\n this._result = {\n ok: false,\n id: this._result.id,\n error: Envelope.new(error),\n };\n return this;\n }\n\n withOptionalError(error: EnvelopeEncodableValue | undefined): Response {\n if (error !== undefined) {\n return this.withError(error);\n }\n return this;\n }\n\n isOk(): boolean {\n return this._result.ok;\n }\n\n isErr(): boolean {\n return !this._result.ok;\n }\n\n id(): ARID | undefined {\n return this._result.id;\n }\n\n expectId(): ARID {\n const id = this.id();\n if (id === undefined) {\n throw new Error(\"Expected an ID\");\n }\n return id;\n }\n\n result(): Envelope {\n if (!this._result.ok) {\n throw EnvelopeError.general(\"Cannot get result from failed response\");\n }\n return this._result.result;\n }\n\n error(): Envelope {\n if (this._result.ok) {\n throw EnvelopeError.general(\"Cannot get error from successful response\");\n }\n return this._result.error;\n }\n\n /**\n * Extracts a typed result value from a successful response.\n */\n extractResult<T>(decoder: (cbor: unknown) => T): T {\n return this.result().extractSubject(decoder);\n }\n\n /**\n * Extracts a typed error value from a failure response.\n */\n extractError<T>(decoder: (cbor: unknown) => T): T {\n return this.error().extractSubject(decoder);\n }\n\n /**\n * Converts the response to an envelope.\n *\n * Successful responses have the request ID as the subject and a 'result'\n * assertion. Failure responses have the request ID (or 'Unknown' if not known)\n * as the subject and an 'error' assertion.\n */\n toEnvelope(): Envelope {\n if (this._result.ok) {\n const taggedArid = toTaggedValue(TAG_RESPONSE, this._result.id.untaggedCbor());\n return Envelope.newLeaf(taggedArid).addAssertion(RESULT, this._result.result);\n } else {\n let subject: Envelope;\n if (this._result.id !== undefined) {\n const taggedArid = toTaggedValue(TAG_RESPONSE, this._result.id.untaggedCbor());\n subject = Envelope.newLeaf(taggedArid);\n } else {\n const taggedUnknown = toTaggedValue(TAG_RESPONSE, UNKNOWN_VALUE.untaggedCbor());\n subject = Envelope.newLeaf(taggedUnknown);\n }\n return subject.addAssertion(ERROR, this._result.error);\n }\n }\n\n /**\n * Converts this response into an envelope (EnvelopeEncodable implementation).\n */\n intoEnvelope(): Envelope {\n return this.toEnvelope();\n }\n\n /**\n * Creates a response from an envelope.\n */\n static fromEnvelope(envelope: Envelope): Response {\n // Check for result or error assertion\n let hasResult = false;\n let hasError = false;\n\n try {\n const resultObj = envelope.objectForPredicate(RESULT);\n hasResult = resultObj !== undefined;\n } catch {\n // No result\n }\n\n try {\n const errorObj = envelope.objectForPredicate(ERROR);\n hasError = errorObj !== undefined;\n } catch {\n // No error\n }\n\n // Must have exactly one of result or error\n if (hasResult === hasError) {\n throw EnvelopeError.invalidResponse();\n }\n\n // Extract ARID from tagged subject\n // Subject is TAG_RESPONSE(ARID_bytes) or TAG_RESPONSE(UNKNOWN_VALUE)\n const subject = envelope.subject();\n const leaf = subject.asLeaf();\n if (leaf === undefined) {\n throw EnvelopeError.general(\"Response envelope has invalid subject\");\n }\n\n // Expect the RESPONSE tag\n const content = leaf.expectTag(TAG_RESPONSE);\n\n // Try to extract ARID from byte string; if it's a KnownValue, ID is undefined\n let id: ARID | undefined;\n const bytes = content.asByteString();\n if (bytes !== undefined) {\n id = ARID.fromData(bytes);\n }\n // If bytes is undefined, the content is UNKNOWN_VALUE, so id remains undefined\n\n if (hasResult) {\n const resultEnvelope = envelope.objectForPredicate(RESULT);\n if (id === undefined) {\n throw EnvelopeError.general(\"Successful response must have an ID\");\n }\n return new Response({\n ok: true,\n id,\n result: resultEnvelope ?? Response.ok(),\n });\n } else {\n const errorEnvelope = envelope.objectForPredicate(ERROR);\n return new Response({\n ok: false,\n id,\n error: errorEnvelope ?? Response.unknown(),\n });\n }\n }\n\n /**\n * Returns a string representation of the response.\n */\n toString(): string {\n return `Response(${this.summary()})`;\n }\n\n /**\n * Checks equality with another response.\n */\n equals(other: Response): boolean {\n if (this._result.ok !== other._result.ok) return false;\n\n if (this._result.ok && other._result.ok) {\n return this._result.id.equals(other._result.id);\n }\n\n if (!this._result.ok && !other._result.ok) {\n if (this._result.id === undefined && other._result.id === undefined) {\n return true;\n }\n if (this._result.id !== undefined && other._result.id !== undefined) {\n return this._result.id.equals(other._result.id);\n }\n return false;\n }\n\n return false;\n }\n}\n","/**\n * Event type for notifications and messages.\n *\n * Ported from bc-envelope-rust/src/extension/expressions/event.rs\n *\n * An Event represents a notification or message that doesn't expect a\n * response.\n *\n * Unlike Request and Response which form a pair, an Event is a\n * standalone message that can be used for broadcasting information, logging,\n * or publishing notifications. Events are used when the sender does not expect\n * or require a response from the recipients.\n *\n * Each event contains:\n * - Content of a generic type that holds the event payload\n * - A unique identifier (ARID) for tracking and correlation\n * - Optional metadata like a note and timestamp\n *\n * When serialized to an envelope, events are tagged with EVENT tag.\n */\n\nimport { ARID } from \"@bcts/components\";\nimport { EVENT as TAG_EVENT } from \"@bcts/tags\";\nimport { toTaggedValue } from \"@bcts/dcbor\";\nimport { CONTENT, NOTE, DATE } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport { type EnvelopeEncodable, type EnvelopeEncodableValue } from \"../base/envelope-encodable\";\nimport { EnvelopeError } from \"../base/error\";\n\n/**\n * Interface that defines the behavior of an event.\n */\nexport interface EventBehavior<T extends EnvelopeEncodableValue> {\n /**\n * Adds a note to the event.\n */\n withNote(note: string): Event<T>;\n\n /**\n * Adds a date to the event.\n */\n withDate(date: Date): Event<T>;\n\n /**\n * Returns the content of the event.\n */\n content(): T;\n\n /**\n * Returns the unique identifier (ARID) of the event.\n */\n id(): ARID;\n\n /**\n * Returns the note attached to the event, or an empty string if none exists.\n */\n note(): string;\n\n /**\n * Returns the date attached to the event, if any.\n */\n date(): Date | undefined;\n\n /**\n * Converts the event to an envelope.\n */\n toEnvelope(): Envelope;\n}\n\n/**\n * An Event represents a notification or message that doesn't expect a response.\n *\n * @example\n * ```typescript\n * import { Event, ARID } from '@bcts/envelope';\n *\n * // Create a status update event\n * const eventId = ARID.new();\n * const timestamp = new Date(\"2024-08-15T13:45:30Z\");\n *\n * const statusEvent = Event.new(\"System online\", eventId)\n * .withNote(\"Regular status update\")\n * .withDate(timestamp);\n *\n * // Convert to an envelope for transmission\n * const envelope = statusEvent.toEnvelope();\n * ```\n *\n * @typeParam T - The type of content this event carries\n */\nexport class Event<T extends EnvelopeEncodableValue>\n implements EventBehavior<T>, EnvelopeEncodable\n{\n private readonly _content: T;\n private readonly _id: ARID;\n private _note: string;\n private _date: Date | undefined;\n\n private constructor(content: T, id: ARID, note = \"\", date?: Date) {\n this._content = content;\n this._id = id;\n this._note = note;\n this._date = date;\n }\n\n /**\n * Creates a new event with the specified content and ID.\n */\n static new<T extends EnvelopeEncodableValue>(content: T, id: ARID): Event<T> {\n return new Event(content, id);\n }\n\n /**\n * Returns a human-readable summary of the event.\n */\n summary(): string {\n const contentEnvelope = Envelope.new(this._content);\n return `id: ${this._id.shortDescription()}, content: ${contentEnvelope.formatFlat()}`;\n }\n\n // EventBehavior implementation\n\n withNote(note: string): Event<T> {\n this._note = note;\n return this;\n }\n\n withDate(date: Date): Event<T> {\n this._date = date;\n return this;\n }\n\n content(): T {\n return this._content;\n }\n\n id(): ARID {\n return this._id;\n }\n\n note(): string {\n return this._note;\n }\n\n date(): Date | undefined {\n return this._date;\n }\n\n /**\n * Converts the event to an envelope.\n *\n * The envelope's subject is the event's ID tagged with TAG_EVENT,\n * and assertions include the event's content, note (if not empty), and date\n * (if present).\n */\n toEnvelope(): Envelope {\n const taggedArid = toTaggedValue(TAG_EVENT, this._id.untaggedCbor());\n const contentEnvelope = Envelope.new(this._content);\n\n let envelope = Envelope.newLeaf(taggedArid).addAssertion(CONTENT, contentEnvelope);\n\n if (this._note !== \"\") {\n envelope = envelope.addAssertion(NOTE, this._note);\n }\n\n if (this._date !== undefined) {\n envelope = envelope.addAssertion(DATE, this._date.toISOString());\n }\n\n return envelope;\n }\n\n /**\n * Converts this event into an envelope (EnvelopeEncodable implementation).\n */\n intoEnvelope(): Envelope {\n return this.toEnvelope();\n }\n\n /**\n * Creates an event from an envelope.\n *\n * @typeParam T - The type to extract the content as\n */\n static fromEnvelope<T extends EnvelopeEncodableValue>(\n envelope: Envelope,\n contentExtractor: (env: Envelope) => T,\n ): Event<T> {\n // Extract content\n const contentEnvelope = envelope.objectForPredicate(CONTENT);\n if (contentEnvelope === undefined) {\n throw EnvelopeError.general(\"Event envelope missing content\");\n }\n const content = contentExtractor(contentEnvelope);\n\n // Extract the ARID from the subject\n // Subject is TAG_EVENT(ARID_bytes)\n const subject = envelope.subject();\n const leaf = subject.asLeaf();\n if (leaf === undefined) {\n throw EnvelopeError.general(\"Event envelope has invalid subject\");\n }\n\n // Expect the EVENT tag and extract the ARID\n const aridCbor = leaf.expectTag(TAG_EVENT);\n const aridBytes = aridCbor.toByteString();\n const id = ARID.fromData(aridBytes);\n\n // Extract optional note\n let note = \"\";\n try {\n const noteObj = envelope.objectForPredicate(NOTE);\n if (noteObj !== undefined) {\n note = noteObj.asText() ?? \"\";\n }\n } catch {\n // Note is optional\n }\n\n // Extract optional date\n let date: Date | undefined;\n try {\n const dateObj = envelope.objectForPredicate(DATE);\n if (dateObj !== undefined) {\n const dateStr = dateObj.asText();\n if (dateStr !== undefined) {\n date = new Date(dateStr);\n }\n }\n } catch {\n // Date is optional\n }\n\n return new Event(content, id, note, date);\n }\n\n /**\n * Creates a string event from an envelope.\n */\n static stringFromEnvelope(envelope: Envelope): Event<string> {\n return Event.fromEnvelope<string>(envelope, (env) => env.asText() ?? \"\");\n }\n\n /**\n * Returns a string representation of the event.\n */\n toString(): string {\n return `Event(${this.summary()})`;\n }\n\n /**\n * Checks equality with another event.\n */\n equals(other: Event<T>): boolean {\n return (\n this._id.equals(other._id) &&\n this._note === other._note &&\n this._date?.getTime() === other._date?.getTime()\n );\n }\n}\n","import { Envelope } from \"../base/envelope\";\nimport { type EdgeType, edgeLabel } from \"../base/walk\";\n\n// ============================================================================\n// DigestDisplayFormat - Enum for digest display formatting\n// ============================================================================\n\n/**\n * Specifies the format for displaying envelope digests in tree output.\n *\n * Ported from bc-envelope-rust/src/format/tree/format/digest.rs\n */\nexport enum DigestDisplayFormat {\n /**\n * Short format: first 7 hex characters of the digest.\n * This is the default format.\n */\n Short = \"short\",\n\n /**\n * Full format: complete 64 hex character digest.\n */\n Full = \"full\",\n\n /**\n * UR format: digest encoded as a UR string.\n */\n UR = \"ur\",\n}\n\n/// Tree formatting for Gordian Envelopes.\n///\n/// This module provides functionality for creating textual tree\n/// representations of envelopes, which is useful for debugging and visualizing\n/// the hierarchical structure of complex envelopes.\n///\n/// The tree format displays each component of an envelope (subject and\n/// assertions) as nodes in a tree, making it easy to understand the\n/// hierarchical structure of nested envelopes. Each node includes:\n///\n/// - The first 8 characters of the element's digest (for easy reference)\n/// - The type of the element (NODE, ASSERTION, ELIDED, etc.)\n/// - The content of the element (for leaf nodes)\n\n/// Options for tree formatting\nexport interface TreeFormatOptions {\n /// If true, hides NODE identifiers and only shows semantic content\n hideNodes?: boolean;\n /// Set of digest strings to highlight in the tree\n highlightDigests?: Set<string>;\n /// Format for displaying digests: \"short\" (7 hex chars), \"full\" (64 hex chars), or \"ur\" (UR string)\n digestDisplay?: DigestDisplayFormat | \"short\" | \"full\" | \"ur\";\n}\n\n/// Represents an element in the tree representation\ninterface TreeElement {\n /// Indentation level\n level: number;\n /// The envelope element\n envelope: Envelope;\n /// Type of incoming edge\n incomingEdge: EdgeType;\n /// Whether to show the digest ID\n showId: boolean;\n /// Whether this element is highlighted\n isHighlighted: boolean;\n}\n\n// Note: Method declarations are in the base Envelope class.\n// This module provides the prototype implementations.\n\n/// Implementation of shortId()\nEnvelope.prototype.shortId = function (\n this: Envelope,\n format: \"short\" | \"full\" | \"ur\" = \"short\",\n): string {\n const digest = this.digest();\n if (format === \"full\") {\n return digest.hex();\n }\n if (format === \"ur\") {\n return digest.urString();\n }\n return digest.short();\n};\n\n/// Implementation of summary()\nEnvelope.prototype.summary = function (this: Envelope, maxLength = 40): string {\n const c = this.case();\n\n switch (c.type) {\n case \"node\":\n return \"NODE\";\n case \"leaf\": {\n // Try to extract a readable value\n try {\n const text = this.asText();\n if (text !== undefined) {\n const truncated = text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;\n return JSON.stringify(truncated);\n }\n } catch {\n // Fall through\n }\n\n try {\n const num = this.extractNumber();\n return String(num);\n } catch {\n // Fall through\n }\n\n try {\n const bool = this.extractBoolean();\n return String(bool);\n } catch {\n // Fall through\n }\n\n if (this.isNull()) {\n return \"null\";\n }\n\n // Fallback: show byte string\n const bytes = this.asByteString();\n if (bytes !== undefined && bytes.length <= 16) {\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `h'${hex}'`;\n }\n\n return \"LEAF\";\n }\n case \"wrapped\":\n return \"WRAPPED\";\n case \"assertion\":\n return \"ASSERTION\";\n case \"elided\":\n return \"ELIDED\";\n case \"encrypted\":\n return \"ENCRYPTED\";\n case \"compressed\":\n return \"COMPRESSED\";\n case \"knownValue\":\n return \"KNOWN_VALUE\";\n default:\n return \"UNKNOWN\";\n }\n};\n\n/// Implementation of treeFormat()\nEnvelope.prototype.treeFormat = function (this: Envelope, options: TreeFormatOptions = {}): string {\n const hideNodes = options.hideNodes ?? false;\n const highlightDigests = options.highlightDigests ?? new Set<string>();\n const digestDisplay = options.digestDisplay ?? \"short\";\n\n const elements: TreeElement[] = [];\n\n // Walk the envelope and collect elements\n this.walk(hideNodes, undefined, (envelope, level, incomingEdge, _state) => {\n const digestStr = envelope.digest().short();\n const isHighlighted = highlightDigests.has(digestStr);\n\n elements.push({\n level,\n envelope,\n incomingEdge,\n showId: !hideNodes,\n isHighlighted,\n });\n\n return [undefined, false];\n });\n\n // Format each element as a line\n const lines = elements.map((elem) => {\n const parts: string[] = [];\n\n if (elem.isHighlighted) {\n parts.push(\"*\");\n }\n\n if (elem.showId) {\n parts.push(elem.envelope.shortId(digestDisplay));\n }\n\n const label = edgeLabel(elem.incomingEdge);\n if (label !== undefined && label !== \"\") {\n parts.push(label);\n }\n\n parts.push(elem.envelope.summary(40));\n\n const line = parts.join(\" \");\n const indent = \" \".repeat(elem.level * 4);\n return indent + line;\n });\n\n return lines.join(\"\\n\");\n};\n","/// Format context for Gordian Envelopes with annotations.\n///\n/// The FormatContext provides information about CBOR tags, known values,\n/// functions, and parameters that are used to annotate the output of envelope\n/// formatting functions. This context enables human-readable output when\n/// converting envelopes to string representations like diagnostic notation.\n\nimport {\n type TagsStore,\n type TagsStoreTrait,\n type Tag,\n type CborNumber,\n type CborSummarizer,\n TagsStore as TagsStoreClass,\n getGlobalTagsStore,\n toTaggedValue,\n} from \"@bcts/dcbor\";\nimport {\n type KnownValuesStore,\n KnownValuesStore as KnownValuesStoreClass,\n KnownValue,\n KNOWN_VALUES,\n TAG_KNOWN_VALUE,\n} from \"@bcts/known-values\";\nimport {\n registerTags as registerBcTags,\n DIGEST as TAG_DIGEST,\n ARID as TAG_ARID,\n URI as TAG_URI,\n UUID as TAG_UUID,\n NONCE as TAG_NONCE,\n SALT as TAG_SALT,\n SEED as TAG_SEED,\n SIGNATURE as TAG_SIGNATURE,\n SEALED_MESSAGE as TAG_SEALED_MESSAGE,\n ENCRYPTED_KEY as TAG_ENCRYPTED_KEY,\n PRIVATE_KEY_BASE as TAG_PRIVATE_KEY_BASE,\n PRIVATE_KEYS as TAG_PRIVATE_KEYS,\n PUBLIC_KEYS as TAG_PUBLIC_KEYS,\n SIGNING_PRIVATE_KEY as TAG_SIGNING_PRIVATE_KEY,\n SIGNING_PUBLIC_KEY as TAG_SIGNING_PUBLIC_KEY,\n SSKR_SHARE as TAG_SSKR_SHARE,\n XID as TAG_XID,\n} from \"@bcts/tags\";\nimport {\n Digest,\n ARID,\n URI,\n UUID,\n Nonce,\n Salt,\n Seed,\n Signature,\n SignatureScheme,\n SealedMessage,\n EncapsulationScheme,\n EncryptedKey,\n PrivateKeyBase,\n PrivateKeys,\n PublicKeys,\n SigningPrivateKey,\n SigningPublicKey,\n SSKRShareCbor,\n XID,\n} from \"@bcts/components\";\n\n// ============================================================================\n// FormatContextOpt - Option type for format context\n// ============================================================================\n\n/// Option type for format context, similar to Rust's FormatContextOpt<'a>.\nexport type FormatContextOpt =\n | { type: \"none\" }\n | { type: \"global\" }\n | { type: \"custom\"; context: FormatContext };\n\n/// Create a FormatContextOpt with no context\nexport const formatContextNone = (): FormatContextOpt => ({ type: \"none\" });\n\n/// Create a FormatContextOpt with global context\nexport const formatContextGlobal = (): FormatContextOpt => ({ type: \"global\" });\n\n/// Create a FormatContextOpt with custom context\nexport const formatContextCustom = (context: FormatContext): FormatContextOpt => ({\n type: \"custom\",\n context,\n});\n\n// ============================================================================\n// FormatContext - Main formatting context class\n// ============================================================================\n\n/// Context object for formatting Gordian Envelopes with annotations.\n///\n/// The FormatContext provides information about CBOR tags, known values,\n/// functions, and parameters that are used to annotate the output of envelope\n/// formatting functions.\nexport class FormatContext implements TagsStoreTrait {\n private readonly _tags: TagsStore;\n private readonly _knownValues: KnownValuesStore;\n\n constructor(tags?: TagsStore, knownValues?: KnownValuesStore) {\n this._tags = tags ?? new TagsStoreClass();\n this._knownValues = knownValues ?? new KnownValuesStoreClass();\n }\n\n /// Returns a reference to the CBOR tags registry.\n tags(): TagsStore {\n return this._tags;\n }\n\n /// Returns a reference to the known values registry.\n knownValues(): KnownValuesStore {\n return this._knownValues;\n }\n\n // Implement TagsStoreTrait by delegating to internal tags store\n assignedNameForTag(tag: Tag): string | undefined {\n return this._tags.assignedNameForTag(tag);\n }\n\n nameForTag(tag: Tag): string {\n return this._tags.nameForTag(tag);\n }\n\n tagForValue(value: CborNumber): Tag | undefined {\n return this._tags.tagForValue(value);\n }\n\n tagForName(name: string): Tag | undefined {\n return this._tags.tagForName(name);\n }\n\n nameForValue(value: CborNumber): string {\n return this._tags.nameForValue(value);\n }\n\n summarizer(tag: CborNumber): CborSummarizer | undefined {\n return this._tags.summarizer(tag);\n }\n\n /// Register a tag with a name\n registerTag(value: number | bigint, name: string): void {\n this._tags.insert({ value: BigInt(value), name });\n }\n\n /// Create a clone of this context\n clone(): FormatContext {\n // Note: This creates a shallow copy - tags and knownValues are shared\n // For a full deep copy, we would need to clone the stores\n return new FormatContext(this._tags, this._knownValues);\n }\n}\n\n// ============================================================================\n// Global Format Context\n// ============================================================================\n\n/// Global singleton instance of FormatContext for application-wide use.\nlet _globalFormatContextInstance: FormatContext | undefined;\nlet isInitialized = false;\n\n/// Get the global format context instance, initializing it if necessary.\nexport const getGlobalFormatContext = (): FormatContext => {\n if (!isInitialized) {\n // Register all known tags (dcbor + BC component tags) in the global tags store\n registerBcTags();\n\n // Get the global stores\n const tags = getGlobalTagsStore();\n const knownValues = KNOWN_VALUES.get();\n\n _globalFormatContextInstance = new FormatContext(tags, knownValues);\n isInitialized = true;\n\n // Set up known value summarizer\n setupKnownValueSummarizer(_globalFormatContextInstance);\n\n // Set up component tag summarizers\n setupComponentSummarizers(_globalFormatContextInstance);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Safe: initialized in the if block above\n return _globalFormatContextInstance!;\n};\n\n/// Execute a function with access to the global format context.\nexport const withFormatContext = <T>(action: (context: FormatContext) => T): T => {\n return action(getGlobalFormatContext());\n};\n\n/// Execute a function with mutable access to the global format context.\nexport const withFormatContextMut = <T>(action: (context: FormatContext) => T): T => {\n return action(getGlobalFormatContext());\n};\n\n// ============================================================================\n// Tag Registration\n// ============================================================================\n\n/// Set up the known value summarizer in a format context\nconst setupKnownValueSummarizer = (context: FormatContext): void => {\n const knownValues = context.knownValues();\n const tags = context.tags();\n\n // Known value summarizer - formats known values with single quotes\n const summarizer: CborSummarizer = (cbor, _flat) => {\n try {\n // Try to extract the known value from the CBOR\n const kv = KnownValue.fromUntaggedCbor(cbor);\n const name = knownValues.name(kv);\n return { ok: true, value: `'${name}'` };\n } catch {\n return { ok: true, value: \"'<unknown>'\" };\n }\n };\n\n tags.setSummarizer(BigInt(TAG_KNOWN_VALUE), summarizer);\n};\n\n/// Registers standard tags and summarizers in a format context.\nexport const registerTagsIn = (context: FormatContext): void => {\n // Register all known tags (dcbor + BC component tags)\n registerBcTags();\n\n // Set up known value summarizer\n setupKnownValueSummarizer(context);\n\n // Set up component tag summarizers\n setupComponentSummarizers(context);\n};\n\n/// Registers standard tags in the global format context.\nexport const registerTags = (): void => {\n withFormatContextMut((context) => {\n registerTagsIn(context);\n });\n};\n\n// ============================================================================\n// Component Tag Summarizers\n// ============================================================================\n\n/// Helper to create an error result for summarizers\nconst summarizerError = (e: unknown): { ok: false; error: { type: \"Custom\"; message: string } } => {\n const message = e instanceof Error ? e.message : String(e);\n return { ok: false as const, error: { type: \"Custom\" as const, message } };\n};\n\n/// Set up component tag summarizers matching Rust bc-components-rust/src/tags_registry.rs\nconst setupComponentSummarizers = (context: FormatContext): void => {\n const tags = context.tags();\n\n // Digest: \"Digest(shortDesc)\"\n tags.setSummarizer(TAG_DIGEST.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_DIGEST.value, cbor);\n const digest = Digest.fromTaggedCbor(tagged);\n return { ok: true, value: `Digest(${digest.shortDescription()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // ARID: \"ARID(shortDesc)\"\n tags.setSummarizer(TAG_ARID.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_ARID.value, cbor);\n const arid = ARID.fromTaggedCbor(tagged);\n return { ok: true, value: `ARID(${arid.shortDescription()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // URI: \"URI(uri)\"\n tags.setSummarizer(TAG_URI.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_URI.value, cbor);\n const uri = URI.fromTaggedCbor(tagged);\n return { ok: true, value: `URI(${uri.toString()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // UUID: \"UUID(uuid)\"\n tags.setSummarizer(TAG_UUID.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_UUID.value, cbor);\n const uuid = UUID.fromTaggedCbor(tagged);\n return { ok: true, value: `UUID(${uuid.toString()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Nonce: \"Nonce\"\n tags.setSummarizer(TAG_NONCE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_NONCE.value, cbor);\n Nonce.fromTaggedCbor(tagged);\n return { ok: true, value: \"Nonce\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Salt: \"Salt\"\n tags.setSummarizer(TAG_SALT.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SALT.value, cbor);\n Salt.fromTaggedCbor(tagged);\n return { ok: true, value: \"Salt\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Seed: \"Seed\"\n tags.setSummarizer(TAG_SEED.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SEED.value, cbor);\n Seed.fromTaggedCbor(tagged);\n return { ok: true, value: \"Seed\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // Signature: \"Signature\" for Ed25519/Schnorr (defaults), \"Signature(scheme)\" otherwise\n tags.setSummarizer(TAG_SIGNATURE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SIGNATURE.value, cbor);\n const sig = Signature.fromTaggedCbor(tagged);\n const scheme = sig.scheme();\n // Match Rust: default scheme shows just \"Signature\"\n if (scheme === SignatureScheme.Ed25519 || scheme === SignatureScheme.Schnorr) {\n return { ok: true, value: \"Signature\" };\n }\n return { ok: true, value: `Signature(${sig.signatureType()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SealedMessage: \"SealedMessage\" for X25519 (default), \"SealedMessage(scheme)\" otherwise\n tags.setSummarizer(TAG_SEALED_MESSAGE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SEALED_MESSAGE.value, cbor);\n const msg = SealedMessage.fromTaggedCbor(tagged);\n const scheme = msg.encapsulationScheme();\n if (scheme === EncapsulationScheme.X25519) {\n return { ok: true, value: \"SealedMessage\" };\n }\n return { ok: true, value: `SealedMessage(${scheme})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // EncryptedKey: toString()\n tags.setSummarizer(TAG_ENCRYPTED_KEY.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_ENCRYPTED_KEY.value, cbor);\n const ek = EncryptedKey.fromTaggedCbor(tagged);\n return { ok: true, value: ek.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // PrivateKeyBase: toString()\n tags.setSummarizer(TAG_PRIVATE_KEY_BASE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_PRIVATE_KEY_BASE.value, cbor);\n const pkb = PrivateKeyBase.fromTaggedCbor(tagged);\n return { ok: true, value: pkb.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // PrivateKeys: toString()\n tags.setSummarizer(TAG_PRIVATE_KEYS.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_PRIVATE_KEYS.value, cbor);\n const pk = PrivateKeys.fromTaggedCbor(tagged);\n return { ok: true, value: pk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // PublicKeys: toString()\n tags.setSummarizer(TAG_PUBLIC_KEYS.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_PUBLIC_KEYS.value, cbor);\n const pk = PublicKeys.fromTaggedCbor(tagged);\n return { ok: true, value: pk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SigningPrivateKey: toString()\n tags.setSummarizer(TAG_SIGNING_PRIVATE_KEY.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SIGNING_PRIVATE_KEY.value, cbor);\n const spk = SigningPrivateKey.fromTaggedCbor(tagged);\n return { ok: true, value: spk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SigningPublicKey: toString()\n tags.setSummarizer(TAG_SIGNING_PUBLIC_KEY.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SIGNING_PUBLIC_KEY.value, cbor);\n const spk = SigningPublicKey.fromTaggedCbor(tagged);\n return { ok: true, value: spk.toString() };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // SSKRShare: \"SSKRShare\"\n tags.setSummarizer(TAG_SSKR_SHARE.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_SSKR_SHARE.value, cbor);\n SSKRShareCbor.fromTaggedCbor(tagged);\n return { ok: true, value: \"SSKRShare\" };\n } catch (e) {\n return summarizerError(e);\n }\n });\n\n // XID: \"XID(shortDesc)\"\n tags.setSummarizer(TAG_XID.value, (cbor, _flat) => {\n try {\n const tagged = toTaggedValue(TAG_XID.value, cbor);\n const xid = XID.fromTaggedCbor(tagged);\n return { ok: true, value: `XID(${xid.shortDescription()})` };\n } catch (e) {\n return summarizerError(e);\n }\n });\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\n/// Alias function for getGlobalFormatContext\nexport const globalFormatContext = getGlobalFormatContext;\n\n/// Object-style access to global format context\nexport const GLOBAL_FORMAT_CONTEXT = {\n get: getGlobalFormatContext,\n};\n","/// Envelope summary functionality for generating short text representations.\n///\n/// This module provides the EnvelopeSummary interface and implementations\n/// for generating concise text summaries of CBOR values and envelopes.\n\nimport type { Cbor } from \"@bcts/dcbor\";\nimport {\n isUnsigned,\n isNegative,\n isBytes,\n isText,\n isSimple,\n isArray,\n isMap,\n isTagged,\n asText,\n diagnosticOpt,\n type DiagFormatOpts,\n} from \"@bcts/dcbor\";\nimport { Envelope } from \"../base/envelope\";\nimport {\n type FormatContext,\n type FormatContextOpt,\n getGlobalFormatContext,\n} from \"./format-context\";\n\n// ============================================================================\n// EnvelopeSummary Interface\n// ============================================================================\n\n/// Interface for types that can produce envelope summary strings.\nexport interface EnvelopeSummary {\n envelopeSummary(maxLength: number, context: FormatContextOpt): string;\n}\n\n// ============================================================================\n// CBOR Summary Implementation\n// ============================================================================\n\n/// Helper to flank a string with prefix and suffix\nconst flankedBy = (s: string, prefix: string, suffix: string): string => {\n return `${prefix}${s}${suffix}`;\n};\n\n/// Generate an envelope summary for a CBOR value.\nexport const cborEnvelopeSummary = (\n cbor: Cbor,\n maxLength: number,\n context: FormatContextOpt,\n): string => {\n // Handle unsigned integers\n if (isUnsigned(cbor)) {\n return String(cbor);\n }\n\n // Handle negative integers\n if (isNegative(cbor)) {\n // In CBOR, negative integers are stored as -(n+1), so we need to compute the actual value\n const n = cbor.value;\n return typeof n === \"bigint\" ? String(-1n - n) : String(-1 - n);\n }\n\n // Handle byte strings\n if (isBytes(cbor)) {\n const bytes = cbor.value;\n return `Bytes(${bytes.length})`;\n }\n\n // Handle text strings\n if (isText(cbor)) {\n let text = asText(cbor) ?? \"\";\n if (text.length > maxLength) {\n text = `${text.substring(0, maxLength)}…`;\n }\n // Replace newlines with escaped version\n text = text.replace(/\\n/g, \"\\\\n\");\n return flankedBy(text, '\"', '\"');\n }\n\n // Handle simple values (bool, null, undefined, float)\n if (isSimple(cbor)) {\n const value = cbor as unknown;\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return \"NaN\";\n if (!Number.isFinite(value)) return value > 0 ? \"Infinity\" : \"-Infinity\";\n return String(value);\n }\n // Fallback for other simple values - use diagnostic notation\n return diagnosticOpt(cbor, { summarize: true });\n }\n\n // Handle arrays, maps, and tagged values - use diagnostic notation\n if (isArray(cbor) || isMap(cbor) || isTagged(cbor)) {\n const opts: DiagFormatOpts = { summarize: true };\n\n // Get appropriate tags store based on context\n if (context.type === \"custom\") {\n return diagnosticOpt(cbor, { ...opts, tags: context.context.tags() });\n } else if (context.type === \"global\") {\n const ctx = getGlobalFormatContext();\n return diagnosticOpt(cbor, { ...opts, tags: ctx.tags() });\n } else {\n return diagnosticOpt(cbor, opts);\n }\n }\n\n // Fallback\n return String(cbor);\n};\n\n// ============================================================================\n// Envelope Summary Method Extension\n// ============================================================================\n\n/// Implementation of summaryWithContext\nEnvelope.prototype.summaryWithContext = function (\n this: Envelope,\n maxLength: number,\n context: FormatContext,\n): string {\n const c = this.case();\n\n switch (c.type) {\n case \"node\":\n return \"NODE\";\n\n case \"leaf\":\n return cborEnvelopeSummary(c.cbor, maxLength, {\n type: \"custom\",\n context,\n });\n\n case \"wrapped\":\n return \"WRAPPED\";\n\n case \"assertion\":\n return \"ASSERTION\";\n\n case \"elided\":\n return \"ELIDED\";\n\n case \"knownValue\": {\n const knownValues = context.knownValues();\n const name = knownValues.name(c.value);\n return flankedBy(name, \"'\", \"'\");\n }\n\n case \"encrypted\":\n return \"ENCRYPTED\";\n\n case \"compressed\":\n return \"COMPRESSED\";\n\n default:\n return \"UNKNOWN\";\n }\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { cborEnvelopeSummary as envelopeSummary };\n","/// Envelope notation formatting.\n///\n/// This module provides functionality for formatting envelopes in human-readable\n/// envelope notation, which shows the semantic structure of an envelope.\n///\n/// # Examples\n///\n/// ```typescript\n/// const envelope = Envelope.new(\"Alice\")\n/// .addAssertion(\"knows\", \"Bob\")\n/// .addAssertion(\"knows\", \"Carol\");\n///\n/// // Format the envelope as human-readable envelope notation\n/// const formatted = envelope.format();\n/// // Will output: \"Alice\" [ \"knows\": \"Bob\", \"knows\": \"Carol\" ]\n/// ```\n\nimport type { Cbor } from \"@bcts/dcbor\";\nimport { isTagged, tagValue } from \"@bcts/dcbor\";\nimport { IS_A } from \"@bcts/known-values\";\nimport { Envelope } from \"../base/envelope\";\nimport type { Assertion } from \"../base/assertion\";\nimport {\n type FormatContextOpt,\n getGlobalFormatContext,\n formatContextGlobal,\n} from \"./format-context\";\nimport { cborEnvelopeSummary } from \"./envelope-summary\";\n\n// ============================================================================\n// EnvelopeFormatOpts - Options for envelope formatting\n// ============================================================================\n\n/// Options for envelope notation formatting.\nexport interface EnvelopeFormatOpts {\n /// If true, format as a single line without indentation\n flat: boolean;\n /// The format context to use\n context: FormatContextOpt;\n}\n\n/// Create default format options\nexport const defaultFormatOpts = (): EnvelopeFormatOpts => ({\n flat: false,\n context: formatContextGlobal(),\n});\n\n/// Create format options with flat formatting\nexport const flatFormatOpts = (): EnvelopeFormatOpts => ({\n flat: true,\n context: formatContextGlobal(),\n});\n\n// ============================================================================\n// EnvelopeFormatItem - Format item types\n// ============================================================================\n\n/// Type returned by EnvelopeFormat implementations.\nexport type EnvelopeFormatItem =\n | { type: \"begin\"; value: string }\n | { type: \"end\"; value: string }\n | { type: \"item\"; value: string }\n | { type: \"separator\" }\n | { type: \"list\"; items: EnvelopeFormatItem[] };\n\n/// Create a Begin item\nexport const formatBegin = (value: string): EnvelopeFormatItem => ({\n type: \"begin\",\n value,\n});\n\n/// Create an End item\nexport const formatEnd = (value: string): EnvelopeFormatItem => ({\n type: \"end\",\n value,\n});\n\n/// Create an Item\nexport const formatItem = (value: string): EnvelopeFormatItem => ({\n type: \"item\",\n value,\n});\n\n/// Create a Separator\nexport const formatSeparator = (): EnvelopeFormatItem => ({ type: \"separator\" });\n\n/// Create a List\nexport const formatList = (items: EnvelopeFormatItem[]): EnvelopeFormatItem => ({\n type: \"list\",\n items,\n});\n\n// ============================================================================\n// EnvelopeFormatItem Utilities\n// ============================================================================\n\n/// Flatten a format item into a flat array\nconst flatten = (item: EnvelopeFormatItem): EnvelopeFormatItem[] => {\n if (item.type === \"list\") {\n return item.items.flatMap(flatten);\n }\n return [item];\n};\n\n/// Nicen the format items by combining adjacent End/Begin pairs\nconst nicen = (items: EnvelopeFormatItem[]): EnvelopeFormatItem[] => {\n const input = [...items];\n const result: EnvelopeFormatItem[] = [];\n\n while (input.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Array length checked above\n const current = input.shift()!;\n if (input.length === 0) {\n result.push(current);\n break;\n }\n\n if (current.type === \"end\" && input[0]?.type === \"begin\") {\n const endString = current.value;\n const beginString = input[0].value;\n result.push(formatEnd(`${endString} ${beginString}`));\n result.push(formatBegin(\"\"));\n input.shift();\n } else {\n result.push(current);\n }\n }\n\n return result;\n};\n\n/// Create indentation string\nconst indent = (level: number): string => \" \".repeat(level * 4);\n\n/// Add space at end if needed\nconst addSpaceAtEndIfNeeded = (s: string): string => {\n if (s.length === 0) return \" \";\n if (s.endsWith(\" \")) return s;\n return `${s} `;\n};\n\n/// Format items in flat mode (single line)\nconst formatFlat = (item: EnvelopeFormatItem): string => {\n let line = \"\";\n const items = flatten(item);\n\n for (const i of items) {\n switch (i.type) {\n case \"begin\":\n if (!line.endsWith(\" \")) line += \" \";\n line += `${i.value} `;\n break;\n case \"end\":\n if (!line.endsWith(\" \")) line += \" \";\n line += `${i.value} `;\n break;\n case \"item\":\n line += i.value;\n break;\n case \"separator\":\n line = `${line.trimEnd()}, `;\n break;\n case \"list\":\n for (const subItem of i.items) {\n line += formatFlat(subItem);\n }\n break;\n }\n }\n\n return line;\n};\n\n/// Format items in hierarchical mode (with indentation)\nconst formatHierarchical = (item: EnvelopeFormatItem): string => {\n const lines: string[] = [];\n let level = 0;\n let currentLine = \"\";\n const items = nicen(flatten(item));\n\n for (const i of items) {\n switch (i.type) {\n case \"begin\": {\n const delimiter = i.value;\n if (delimiter.length > 0) {\n const c =\n currentLine.length === 0\n ? delimiter\n : `${addSpaceAtEndIfNeeded(currentLine)}${delimiter}`;\n lines.push(`${indent(level)}${c}\\n`);\n }\n level += 1;\n currentLine = \"\";\n break;\n }\n case \"end\": {\n const delimiter = i.value;\n if (currentLine.length > 0) {\n lines.push(`${indent(level)}${currentLine}\\n`);\n currentLine = \"\";\n }\n level -= 1;\n lines.push(`${indent(level)}${delimiter}\\n`);\n break;\n }\n case \"item\":\n currentLine += i.value;\n break;\n case \"separator\":\n if (currentLine.length > 0) {\n lines.push(`${indent(level)}${currentLine}\\n`);\n currentLine = \"\";\n }\n break;\n case \"list\":\n lines.push(\"<list>\");\n break;\n }\n }\n\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n\n return lines.join(\"\");\n};\n\n/// Format a format item according to options\nconst formatFormatItem = (item: EnvelopeFormatItem, opts: EnvelopeFormatOpts): string => {\n if (opts.flat) {\n return formatFlat(item);\n }\n return formatHierarchical(item);\n};\n\n// ============================================================================\n// EnvelopeFormat Interface and Implementations\n// ============================================================================\n\n/// Format a CBOR value as an envelope format item\nexport const formatCbor = (cbor: Cbor, opts: EnvelopeFormatOpts): EnvelopeFormatItem => {\n // Check if this is a tagged envelope\n if (isTagged(cbor)) {\n const tag = tagValue(cbor);\n // Envelope tag is 200\n if (tag === 200n || tag === 200) {\n try {\n const envelope = Envelope.fromTaggedCbor(cbor);\n return formatEnvelope(envelope, opts);\n } catch {\n return formatItem(\"<error>\");\n }\n }\n }\n\n // For non-envelope CBOR, use summary\n const summary = cborEnvelopeSummary(cbor, Number.MAX_SAFE_INTEGER, opts.context);\n return formatItem(summary);\n};\n\n/// Format an Assertion as an envelope format item\nexport const formatAssertion = (\n assertion: Assertion,\n opts: EnvelopeFormatOpts,\n): EnvelopeFormatItem => {\n return formatList([\n formatEnvelope(assertion.predicate(), opts),\n formatItem(\": \"),\n formatEnvelope(assertion.object(), opts),\n ]);\n};\n\n/// Format an Envelope as an envelope format item\nexport const formatEnvelope = (\n envelope: Envelope,\n opts: EnvelopeFormatOpts,\n): EnvelopeFormatItem => {\n const c = envelope.case();\n\n switch (c.type) {\n case \"leaf\":\n return formatCbor(c.cbor, opts);\n\n case \"wrapped\":\n return formatList([formatBegin(\"{\"), formatEnvelope(c.envelope, opts), formatEnd(\"}\")]);\n\n case \"assertion\":\n return formatAssertion(c.assertion, opts);\n\n case \"knownValue\": {\n // Get the name from context\n let name: string;\n if (opts.context.type === \"custom\") {\n const knownValues = opts.context.context.knownValues();\n const assignedName = knownValues.assignedName(c.value);\n name = assignedName ?? c.value.name();\n } else if (opts.context.type === \"global\") {\n const ctx = getGlobalFormatContext();\n const knownValues = ctx.knownValues();\n const assignedName = knownValues.assignedName(c.value);\n name = assignedName ?? c.value.name();\n } else {\n name = c.value.name();\n }\n return formatItem(`'${name}'`);\n }\n\n case \"encrypted\":\n return formatItem(\"ENCRYPTED\");\n\n case \"compressed\":\n return formatItem(\"COMPRESSED\");\n\n case \"elided\":\n return formatItem(\"ELIDED\");\n\n case \"node\": {\n const items: EnvelopeFormatItem[] = [];\n const subjectItem = formatEnvelope(c.subject, opts);\n\n let elidedCount = 0;\n let encryptedCount = 0;\n let compressedCount = 0;\n const typeAssertionItems: EnvelopeFormatItem[][] = [];\n const assertionItems: EnvelopeFormatItem[][] = [];\n\n for (const assertion of c.assertions) {\n const assertionCase = assertion.case();\n\n switch (assertionCase.type) {\n case \"elided\":\n elidedCount += 1;\n break;\n case \"encrypted\":\n encryptedCount += 1;\n break;\n case \"compressed\":\n compressedCount += 1;\n break;\n case \"node\":\n case \"leaf\":\n case \"wrapped\":\n case \"assertion\":\n case \"knownValue\": {\n const item = [formatEnvelope(assertion, opts)];\n\n // Check if this is a type assertion (isA predicate)\n let isTypeAssertion = false;\n const predicate = assertion.asPredicate();\n if (predicate?.subject().asKnownValue()?.equals(IS_A) === true) {\n isTypeAssertion = true;\n }\n\n if (isTypeAssertion) {\n typeAssertionItems.push(item);\n } else {\n assertionItems.push(item);\n }\n break;\n }\n }\n }\n\n // Sort assertion items\n typeAssertionItems.sort((a, b) => compareFormatItems(a[0], b[0]));\n assertionItems.sort((a, b) => compareFormatItems(a[0], b[0]));\n\n // Add type assertions first\n const allAssertionItems = [...typeAssertionItems, ...assertionItems];\n\n // Add compressed count\n if (compressedCount > 1) {\n allAssertionItems.push([formatItem(`COMPRESSED (${compressedCount})`)]);\n } else if (compressedCount > 0) {\n allAssertionItems.push([formatItem(\"COMPRESSED\")]);\n }\n\n // Add elided count\n if (elidedCount > 1) {\n allAssertionItems.push([formatItem(`ELIDED (${elidedCount})`)]);\n } else if (elidedCount > 0) {\n allAssertionItems.push([formatItem(\"ELIDED\")]);\n }\n\n // Add encrypted count\n if (encryptedCount > 1) {\n allAssertionItems.push([formatItem(`ENCRYPTED (${encryptedCount})`)]);\n } else if (encryptedCount > 0) {\n allAssertionItems.push([formatItem(\"ENCRYPTED\")]);\n }\n\n // Intersperse with separators\n const joinedAssertionItems: EnvelopeFormatItem[] = [];\n for (let i = 0; i < allAssertionItems.length; i++) {\n if (i > 0) {\n joinedAssertionItems.push(formatSeparator());\n }\n joinedAssertionItems.push(...allAssertionItems[i]);\n }\n\n // Check if subject needs braces (if it's an assertion)\n const needsBraces = c.subject.isSubjectAssertion();\n\n if (needsBraces) {\n items.push(formatBegin(\"{\"));\n }\n items.push(subjectItem);\n if (needsBraces) {\n items.push(formatEnd(\"}\"));\n }\n items.push(formatBegin(\"[\"));\n items.push(...joinedAssertionItems);\n items.push(formatEnd(\"]\"));\n\n return formatList(items);\n }\n }\n};\n\n/// Compare format items for sorting\nconst compareFormatItems = (a: EnvelopeFormatItem, b: EnvelopeFormatItem): number => {\n const getIndex = (item: EnvelopeFormatItem): number => {\n switch (item.type) {\n case \"begin\":\n return 1;\n case \"end\":\n return 2;\n case \"item\":\n return 3;\n case \"separator\":\n return 4;\n case \"list\":\n return 5;\n }\n };\n\n const aIndex = getIndex(a);\n const bIndex = getIndex(b);\n\n if (aIndex !== bIndex) {\n return aIndex - bIndex;\n }\n\n // Same type, compare values\n if (a.type === \"item\" && b.type === \"item\") {\n return a.value.localeCompare(b.value);\n }\n if (a.type === \"begin\" && b.type === \"begin\") {\n return a.value.localeCompare(b.value);\n }\n if (a.type === \"end\" && b.type === \"end\") {\n return a.value.localeCompare(b.value);\n }\n\n return 0;\n};\n\n// ============================================================================\n// Envelope Prototype Extensions\n// ============================================================================\n\n/// Implementation of formatOpt\nEnvelope.prototype.formatOpt = function (this: Envelope, opts: EnvelopeFormatOpts): string {\n const item = formatEnvelope(this, opts);\n return formatFormatItem(item, opts).trim();\n};\n\n/// Implementation of format\nEnvelope.prototype.format = function (this: Envelope): string {\n return this.formatOpt(defaultFormatOpts());\n};\n\n/// Implementation of formatFlat\nEnvelope.prototype.formatFlat = function (this: Envelope): string {\n return this.formatOpt(flatFormatOpts());\n};\n\n// All exports are done inline above with 'export const' and 'export interface'\n","/// Mermaid diagram formatting for Gordian Envelopes.\n///\n/// This module provides functionality for creating Mermaid flowchart diagrams\n/// of envelopes, which is useful for visualizing the hierarchical structure\n/// of complex envelopes in documentation and debugging.\n///\n/// The Mermaid format displays each component of an envelope as nodes in a\n/// flowchart graph, with edges showing relationships between components.\n\nimport { Envelope } from \"../base/envelope\";\nimport { EdgeType, edgeLabel } from \"../base/walk\";\nimport type { Digest } from \"../base/digest\";\nimport { withFormatContext } from \"./format-context\";\n\n// ============================================================================\n// Mermaid Types\n// ============================================================================\n\n/// The orientation of the Mermaid flowchart.\nexport enum MermaidOrientation {\n LeftToRight = \"LR\",\n TopToBottom = \"TB\",\n RightToLeft = \"RL\",\n BottomToTop = \"BT\",\n}\n\n/// The theme for the Mermaid flowchart.\nexport enum MermaidTheme {\n Default = \"default\",\n Neutral = \"neutral\",\n Dark = \"dark\",\n Forest = \"forest\",\n Base = \"base\",\n}\n\n/// Options for Mermaid diagram formatting.\nexport interface MermaidFormatOpts {\n /// Whether to hide NODE identifiers in the diagram (default: false)\n hideNodes?: boolean;\n /// Whether to use monochrome colors (default: false)\n monochrome?: boolean;\n /// The theme for the diagram (default: Default)\n theme?: MermaidTheme;\n /// The orientation of the diagram (default: LeftToRight)\n orientation?: MermaidOrientation;\n /// Set of digests to highlight in the diagram\n highlightingTarget?: Set<Digest>;\n}\n\n/// Default options for Mermaid formatting\nexport const defaultMermaidOpts = (): MermaidFormatOpts => ({\n hideNodes: false,\n monochrome: false,\n theme: MermaidTheme.Default,\n orientation: MermaidOrientation.LeftToRight,\n highlightingTarget: new Set(),\n});\n\n// ============================================================================\n// Internal Types\n// ============================================================================\n\n/// Represents an element in the Mermaid diagram\ninterface MermaidElement {\n id: number;\n level: number;\n envelope: Envelope;\n incomingEdge: EdgeType;\n showId: boolean;\n isHighlighted: boolean;\n parent: MermaidElement | undefined;\n}\n\n// ============================================================================\n// Envelope Prototype Extensions\n// ============================================================================\n\n/// Implementation of mermaidFormat\nEnvelope.prototype.mermaidFormat = function (this: Envelope): string {\n return this.mermaidFormatOpt(defaultMermaidOpts());\n};\n\n/// Implementation of mermaidFormatOpt\nEnvelope.prototype.mermaidFormatOpt = function (this: Envelope, opts: MermaidFormatOpts): string {\n const hideNodes = opts.hideNodes ?? false;\n const monochrome = opts.monochrome ?? false;\n const theme = opts.theme ?? MermaidTheme.Default;\n const orientation = opts.orientation ?? MermaidOrientation.LeftToRight;\n const highlightingTarget = opts.highlightingTarget ?? new Set<Digest>();\n\n const elements: MermaidElement[] = [];\n let nextId = 0;\n\n // Build a stack to track parent elements during traversal\n const parentStack: MermaidElement[] = [];\n\n // Walk the envelope and collect elements\n this.walk(hideNodes, undefined, (envelope, level, incomingEdge, _state) => {\n const id = nextId++;\n\n // Find the parent (last element at level - 1)\n let parent: MermaidElement | undefined;\n while (parentStack.length > 0 && parentStack[parentStack.length - 1].level >= level) {\n parentStack.pop();\n }\n if (parentStack.length > 0) {\n parent = parentStack[parentStack.length - 1];\n }\n\n const isHighlighted = containsDigest(highlightingTarget, envelope.digest());\n\n const elem: MermaidElement = {\n id,\n level,\n envelope,\n incomingEdge,\n showId: !hideNodes,\n isHighlighted,\n parent,\n };\n\n elements.push(elem);\n parentStack.push(elem);\n\n return [undefined, false];\n });\n\n // Track which element IDs have been formatted\n const formattedIds = new Set<number>();\n\n // Build output lines\n const lines: string[] = [\n `%%{ init: { 'theme': '${theme}', 'flowchart': { 'curve': 'basis' } } }%%`,\n `graph ${orientation}`,\n ];\n\n const nodeStyles: string[] = [];\n const linkStyles: string[] = [];\n let linkIndex = 0;\n\n for (const element of elements) {\n const indent = \" \".repeat(element.level);\n\n let content: string;\n if (element.parent !== undefined) {\n // Format as edge\n const thisLinkStyles: string[] = [];\n\n if (!monochrome) {\n const strokeColor = linkStrokeColor(element.incomingEdge);\n if (strokeColor !== undefined) {\n thisLinkStyles.push(`stroke:${strokeColor}`);\n }\n }\n\n if (element.isHighlighted && element.parent.isHighlighted) {\n thisLinkStyles.push(\"stroke-width:4px\");\n } else {\n thisLinkStyles.push(\"stroke-width:2px\");\n }\n\n if (thisLinkStyles.length > 0) {\n linkStyles.push(`linkStyle ${linkIndex} ${thisLinkStyles.join(\",\")}`);\n }\n linkIndex++;\n\n content = formatEdge(element, formattedIds);\n } else {\n // Format as node (root)\n content = formatNode(element, formattedIds);\n }\n\n // Node styles\n const thisNodeStyles: string[] = [];\n if (!monochrome) {\n const strokeColor = nodeColor(element.envelope);\n thisNodeStyles.push(`stroke:${strokeColor}`);\n }\n\n if (element.isHighlighted) {\n thisNodeStyles.push(\"stroke-width:6px\");\n } else {\n thisNodeStyles.push(\"stroke-width:4px\");\n }\n\n if (thisNodeStyles.length > 0) {\n nodeStyles.push(`style ${element.id} ${thisNodeStyles.join(\",\")}`);\n }\n\n lines.push(`${indent}${content}`);\n }\n\n // Add styles\n for (const style of nodeStyles) {\n lines.push(style);\n }\n for (const style of linkStyles) {\n lines.push(style);\n }\n\n return lines.join(\"\\n\");\n};\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/// Check if a set of Digests contains a specific digest\nconst containsDigest = (set: Set<Digest>, digest: Digest): boolean => {\n for (const d of set) {\n if (d.equals(digest)) {\n return true;\n }\n }\n return false;\n};\n\n/// Format a node element\nconst formatNode = (element: MermaidElement, formattedIds: Set<number>): string => {\n if (!formattedIds.has(element.id)) {\n formattedIds.add(element.id);\n\n const lines: string[] = [];\n\n // Get summary\n const summary = withFormatContext((ctx) => {\n return element.envelope.summaryWithContext(20, ctx).replace(/\"/g, \""\");\n });\n lines.push(summary);\n\n // Add digest if showing IDs\n if (element.showId) {\n const id = element.envelope.digest().short();\n lines.push(id);\n }\n\n const content = lines.join(\"<br>\");\n const [frameL, frameR] = mermaidFrame(element.envelope);\n return `${element.id}${frameL}\"${content}\"${frameR}`;\n } else {\n return `${element.id}`;\n }\n};\n\n/// Format an edge element\nconst formatEdge = (element: MermaidElement, formattedIds: Set<number>): string => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Parent is always defined for edge elements\n const parent = element.parent!;\n const label = edgeLabel(element.incomingEdge);\n const arrow = label !== undefined ? `-- ${label} -->` : \"-->\";\n\n return `${formatNode(parent, formattedIds)} ${arrow} ${formatNode(element, formattedIds)}`;\n};\n\n/// Get the Mermaid frame characters for an envelope type\nconst mermaidFrame = (envelope: Envelope): [string, string] => {\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\":\n return [\"((\", \"))\"];\n case \"leaf\":\n return [\"[\", \"]\"];\n case \"wrapped\":\n return [\"[/\", \"\\\\]\"];\n case \"assertion\":\n return [\"([\", \"])\"];\n case \"elided\":\n return [\"{{\", \"}}\"];\n case \"knownValue\":\n return [\"[/\", \"/]\"];\n case \"encrypted\":\n return [\">\", \"]\"];\n case \"compressed\":\n return [\"[[\", \"]]\"];\n default:\n return [\"[\", \"]\"];\n }\n};\n\n/// Get the node color for an envelope type\nconst nodeColor = (envelope: Envelope): string => {\n const c = envelope.case();\n\n switch (c.type) {\n case \"node\":\n return \"red\";\n case \"leaf\":\n return \"teal\";\n case \"wrapped\":\n return \"blue\";\n case \"assertion\":\n return \"green\";\n case \"elided\":\n return \"gray\";\n case \"knownValue\":\n return \"goldenrod\";\n case \"encrypted\":\n return \"coral\";\n case \"compressed\":\n return \"purple\";\n default:\n return \"gray\";\n }\n};\n\n/// Get the link stroke color for an edge type\nconst linkStrokeColor = (edgeType: EdgeType): string | undefined => {\n switch (edgeType) {\n case EdgeType.Subject:\n return \"red\";\n case EdgeType.Content:\n return \"blue\";\n case EdgeType.Predicate:\n return \"cyan\";\n case EdgeType.Object:\n return \"magenta\";\n case EdgeType.None:\n case EdgeType.Assertion:\n return undefined;\n }\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the mermaid format extension\nexport const registerMermaidExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","import { Envelope } from \"../base/envelope\";\nimport { cborData } from \"@bcts/dcbor\";\n\n/// Hex formatting for Gordian Envelopes.\n///\n/// This module provides methods for converting envelopes to hexadecimal\n/// representations of their CBOR encoding, useful for debugging and\n/// low-level inspection.\n\n// Note: Method declarations are in the base Envelope class.\n// This module provides the prototype implementations.\n\n/// Implementation of hex()\nEnvelope.prototype.hex = function (this: Envelope): string {\n const bytes = this.cborBytes();\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n};\n\n/// Implementation of cborBytes()\nEnvelope.prototype.cborBytes = function (this: Envelope): Uint8Array {\n const cbor = this.taggedCbor();\n return cborData(cbor);\n};\n","import { Envelope } from \"../base/envelope\";\n\n// Type for CBOR values that can appear in diagnostic notation\ntype CborValue =\n | string\n | number\n | boolean\n | null\n | Uint8Array\n | CborValue[]\n | Map<CborValue, CborValue>\n | { tag: number; value: CborValue }\n | { type: number; value: unknown };\n\n/// Diagnostic notation formatting for Gordian Envelopes.\n///\n/// This module provides methods for converting envelopes to CBOR diagnostic\n/// notation, a human-readable text format defined in RFC 8949 §8.\n///\n/// See [RFC-8949 §8](https://www.rfc-editor.org/rfc/rfc8949.html#name-diagnostic-notation)\n/// for information on CBOR diagnostic notation.\n\n// Note: Method declarations are in the base Envelope class.\n// This module provides the prototype implementations.\n\n/// Converts a CBOR value to diagnostic notation\nfunction cborToDiagnostic(cbor: CborValue, indent = 0): string {\n // Handle tagged values (CBOR tags)\n if (typeof cbor === \"object\" && cbor !== null && \"tag\" in cbor && \"value\" in cbor) {\n const tagged = cbor as { tag: number; value: CborValue };\n return `${tagged.tag}(${cborToDiagnostic(tagged.value, indent)})`;\n }\n\n // Handle arrays\n if (Array.isArray(cbor)) {\n if (cbor.length === 0) {\n return \"[]\";\n }\n const items = cbor.map((item) => cborToDiagnostic(item, indent + 2));\n return `[${items.join(\", \")}]`;\n }\n\n // Handle Maps\n if (cbor instanceof Map) {\n if (cbor.size === 0) {\n return \"{}\";\n }\n const entries: string[] = [];\n for (const [key, value] of cbor) {\n const keyStr = cborToDiagnostic(key, indent + 2);\n const valueStr = cborToDiagnostic(value, indent + 2);\n entries.push(`${keyStr}: ${valueStr}`);\n }\n return `{${entries.join(\", \")}}`;\n }\n\n // Handle Uint8Array (byte strings)\n if (cbor instanceof Uint8Array) {\n const hex = Array.from(cbor)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `h'${hex}'`;\n }\n\n // Handle strings\n if (typeof cbor === \"string\") {\n return JSON.stringify(cbor);\n }\n\n // Handle CBOR objects with type information\n if (typeof cbor === \"object\" && cbor !== null && \"type\" in cbor) {\n const typed = cbor as { type: number; value: unknown };\n switch (typed.type) {\n case 0: // Unsigned\n return String(typed.value);\n case 1: // Negative\n return String(-1 - Number(typed.value));\n case 7: {\n // Simple\n const simpleValue = typed.value;\n if (simpleValue !== null && typeof simpleValue === \"object\" && \"type\" in simpleValue) {\n const floatValue = simpleValue as { type: string; value: unknown };\n if (floatValue.type === \"Float\") {\n return String(floatValue.value);\n }\n }\n if (simpleValue === 20) return \"false\";\n if (simpleValue === 21) return \"true\";\n if (simpleValue === 22) return \"null\";\n if (simpleValue === 23) return \"undefined\";\n return `simple(${String(simpleValue)})`;\n }\n }\n }\n\n // Fallback for primitives\n if (typeof cbor === \"boolean\") return String(cbor);\n if (typeof cbor === \"number\") return String(cbor);\n if (typeof cbor === \"bigint\") return String(cbor);\n if (cbor === null) return \"null\";\n if (cbor === undefined) return \"undefined\";\n\n // Unknown type - try JSON stringify\n try {\n return JSON.stringify(cbor);\n } catch {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return String(cbor);\n }\n}\n\n/// Implementation of diagnostic()\nEnvelope.prototype.diagnostic = function (this: Envelope): string {\n const cbor = this.taggedCbor();\n return cborToDiagnostic(cbor);\n};\n","/// Envelope Sealing and Unsealing\n///\n/// This module provides convenience functions for combining signing and\n/// encryption operations in a single step, creating secure, authenticated\n/// envelopes.\n///\n/// ## Sealing\n///\n/// Sealing an envelope:\n/// 1. Signs the envelope with the sender's private key\n/// 2. Encrypts the signed envelope to the recipient's public key\n///\n/// This creates a secure container where:\n/// - The recipient can verify who sent the envelope (authentication)\n/// - Only the intended recipient can decrypt the content (confidentiality)\n/// - The signature ensures the content hasn't been modified (integrity)\n///\n/// ## Unsealing\n///\n/// Unsealing performs these operations in reverse:\n/// 1. Decrypts the envelope using the recipient's private key\n/// 2. Verifies the signature using the sender's public key\n\nimport { Envelope } from \"./base/envelope\";\nimport type { Signer, Verifier } from \"./extension/signature\";\nimport type { Encrypter, Decrypter } from \"@bcts/components\";\n\n// ============================================================================\n// Envelope Prototype Extensions for Sealing\n// ============================================================================\n\n/// Implementation of encryptToRecipient\nEnvelope.prototype.encryptToRecipient = function (this: Envelope, recipient: Encrypter): Envelope {\n return this.wrap().encryptSubjectToRecipient(recipient);\n};\n\n/// Implementation of seal\nEnvelope.prototype.seal = function (\n this: Envelope,\n sender: Signer,\n recipient: Encrypter,\n): Envelope {\n return this.addSignature(sender).encryptToRecipient(recipient);\n};\n\n/// Implementation of unseal\nEnvelope.prototype.unseal = function (\n this: Envelope,\n senderPublicKey: Verifier,\n recipient: Decrypter,\n): Envelope {\n return this.decryptToRecipient(recipient).verifySignatureFrom(senderPublicKey);\n};\n\n// ============================================================================\n// Module Registration\n// ============================================================================\n\n/// Register the seal extension\nexport const registerSealExtension = (): void => {\n // Extension methods are already added to prototype above\n};\n","/**\n * String utility functions used throughout the envelope library.\n *\n * Provides helper methods for string formatting and manipulation.\n */\n\n/**\n * Flanks a string with specified left and right delimiters.\n *\n * @param str - The string to flank\n * @param left - The left delimiter\n * @param right - The right delimiter\n * @returns The flanked string\n *\n * @example\n * ```typescript\n * flanked('hello', '\"', '\"') // Returns: \"hello\"\n * flanked('name', \"'\", \"'\") // Returns: 'name'\n * flanked('item', '[', ']') // Returns: [item]\n * ```\n */\nexport function flanked(str: string, left: string, right: string): string {\n return `${left}${str}${right}`;\n}\n\n/**\n * Extension methods for String objects to support fluent API style.\n */\ndeclare global {\n interface String {\n /**\n * Flanks this string with specified left and right delimiters.\n *\n * @param left - The left delimiter\n * @param right - The right delimiter\n * @returns The flanked string\n */\n flankedBy(left: string, right: string): string;\n }\n}\n\n// Extend String prototype with flankedBy method\nString.prototype.flankedBy = function (this: string, left: string, right: string): string {\n return flanked(this, left, right);\n};\n\n// Export the extension for side-effects\nexport {};\n","/// Gordian Envelope TypeScript Library\n///\n/// A TypeScript implementation of Blockchain Commons' Gordian Envelope\n/// specification for structured, privacy-focused data containers.\n///\n/// This is a 1:1 port of the Rust bc-envelope library, maintaining the same\n/// API structure and functionality.\n///\n/// @module bc-envelope\n\n// Re-export everything from the base module\nexport * from \"./base\";\n\n// Re-export everything from the extension module\nexport * from \"./extension\";\n\n// Import registration functions and call them to ensure proper initialization order\nimport { registerEncryptExtension, encryptWholeEnvelope } from \"./extension/encrypt\";\nimport { registerCompressExtension } from \"./extension/compress\";\nimport { registerProofExtension } from \"./extension/proof\";\nimport { registerSecretExtension } from \"./extension/secret\";\nimport { registerSskrExtension } from \"./extension/sskr\";\nimport { registerObscureEncryptHandler } from \"./base/elide\";\nimport type { SymmetricKey } from \"@bcts/components\";\nregisterEncryptExtension();\nregisterCompressExtension();\nregisterProofExtension();\nregisterSecretExtension();\nregisterSskrExtension();\n// Wire up obscure action handlers after all extensions are registered\nregisterObscureEncryptHandler((env, key) => encryptWholeEnvelope(env, key as SymmetricKey));\n\n// Re-export everything from the format module\n// Import for side effects (registers prototype extensions like treeFormat)\nimport \"./format\";\nexport * from \"./format\";\n\n// Import edge module for side effects (registers prototype extensions)\nimport \"./extension/edge\";\n\n// Import seal module for side effects (registers prototype extensions)\nimport \"./seal\";\nexport { registerSealExtension } from \"./seal\";\n\n// Re-export everything from the utils module\nexport * from \"./utils\";\n\n// Version information\nexport const VERSION = \"0.37.0\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,wBAAO,UAAU,QAAQ,WAAgC;AAEvD,QAAO,KAAK,KAAK,CAAC,MAAM,GAAG,EAAE;;;;;AChE/B,IAAY,gDAAL;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;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