@bcts/gstp 1.0.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1280 @@
1
+ import { t as __exportAll } from "./chunk-15K8U1wQ.mjs";
2
+ import { ARID } from "@bcts/components";
3
+ import { Envelope, Event, Request, Response } from "@bcts/envelope";
4
+ import { ID, RECIPIENT_CONTINUATION, SENDER, SENDER_CONTINUATION, VALID_UNTIL } from "@bcts/known-values";
5
+ import { XIDDocument } from "@bcts/xid";
6
+
7
+ //#region src/error.ts
8
+ /**
9
+ * GSTP Error Types
10
+ *
11
+ * Error types returned when operating on GSTP messages.
12
+ * Ported from gstp-rust/src/error.rs
13
+ */
14
+ /**
15
+ * Error codes for GSTP operations.
16
+ */
17
+ let GstpErrorCode = /* @__PURE__ */ function(GstpErrorCode$1) {
18
+ /** Sender must have an encryption key. */
19
+ GstpErrorCode$1["SENDER_MISSING_ENCRYPTION_KEY"] = "SENDER_MISSING_ENCRYPTION_KEY";
20
+ /** Recipient must have an encryption key. */
21
+ GstpErrorCode$1["RECIPIENT_MISSING_ENCRYPTION_KEY"] = "RECIPIENT_MISSING_ENCRYPTION_KEY";
22
+ /** Sender must have a verification key. */
23
+ GstpErrorCode$1["SENDER_MISSING_VERIFICATION_KEY"] = "SENDER_MISSING_VERIFICATION_KEY";
24
+ /** Continuation has expired. */
25
+ GstpErrorCode$1["CONTINUATION_EXPIRED"] = "CONTINUATION_EXPIRED";
26
+ /** Continuation ID is invalid. */
27
+ GstpErrorCode$1["CONTINUATION_ID_INVALID"] = "CONTINUATION_ID_INVALID";
28
+ /** Peer continuation must be encrypted. */
29
+ GstpErrorCode$1["PEER_CONTINUATION_NOT_ENCRYPTED"] = "PEER_CONTINUATION_NOT_ENCRYPTED";
30
+ /** Requests must contain a peer continuation. */
31
+ GstpErrorCode$1["MISSING_PEER_CONTINUATION"] = "MISSING_PEER_CONTINUATION";
32
+ /** Error from envelope operations. */
33
+ GstpErrorCode$1["ENVELOPE"] = "ENVELOPE";
34
+ /** Error from XID operations. */
35
+ GstpErrorCode$1["XID"] = "XID";
36
+ return GstpErrorCode$1;
37
+ }({});
38
+ /**
39
+ * Error class for GSTP operations.
40
+ *
41
+ * Provides specific error types that can occur during GSTP message
42
+ * creation, sealing, and parsing operations.
43
+ */
44
+ var GstpError = class GstpError extends Error {
45
+ code;
46
+ constructor(code, message, cause) {
47
+ super(message);
48
+ this.name = "GstpError";
49
+ this.code = code;
50
+ if (cause !== void 0) this.cause = cause;
51
+ if ("captureStackTrace" in Error) Error.captureStackTrace(this, GstpError);
52
+ }
53
+ /**
54
+ * Returned when the sender is missing an encryption key.
55
+ */
56
+ static senderMissingEncryptionKey() {
57
+ return new GstpError(GstpErrorCode.SENDER_MISSING_ENCRYPTION_KEY, "sender must have an encryption key");
58
+ }
59
+ /**
60
+ * Returned when the recipient is missing an encryption key.
61
+ */
62
+ static recipientMissingEncryptionKey() {
63
+ return new GstpError(GstpErrorCode.RECIPIENT_MISSING_ENCRYPTION_KEY, "recipient must have an encryption key");
64
+ }
65
+ /**
66
+ * Returned when the sender is missing a verification key.
67
+ */
68
+ static senderMissingVerificationKey() {
69
+ return new GstpError(GstpErrorCode.SENDER_MISSING_VERIFICATION_KEY, "sender must have a verification key");
70
+ }
71
+ /**
72
+ * Returned when the continuation has expired.
73
+ */
74
+ static continuationExpired() {
75
+ return new GstpError(GstpErrorCode.CONTINUATION_EXPIRED, "continuation expired");
76
+ }
77
+ /**
78
+ * Returned when the continuation ID is invalid.
79
+ */
80
+ static continuationIdInvalid() {
81
+ return new GstpError(GstpErrorCode.CONTINUATION_ID_INVALID, "continuation ID invalid");
82
+ }
83
+ /**
84
+ * Returned when the peer continuation is not encrypted.
85
+ */
86
+ static peerContinuationNotEncrypted() {
87
+ return new GstpError(GstpErrorCode.PEER_CONTINUATION_NOT_ENCRYPTED, "peer continuation must be encrypted");
88
+ }
89
+ /**
90
+ * Returned when a request is missing the peer continuation.
91
+ */
92
+ static missingPeerContinuation() {
93
+ return new GstpError(GstpErrorCode.MISSING_PEER_CONTINUATION, "requests must contain a peer continuation");
94
+ }
95
+ /**
96
+ * Envelope error wrapper.
97
+ */
98
+ static envelope(cause) {
99
+ return new GstpError(GstpErrorCode.ENVELOPE, "envelope error", cause);
100
+ }
101
+ /**
102
+ * XID error wrapper.
103
+ */
104
+ static xid(cause) {
105
+ return new GstpError(GstpErrorCode.XID, "XID error", cause);
106
+ }
107
+ };
108
+
109
+ //#endregion
110
+ //#region src/continuation.ts
111
+ /**
112
+ * Continuation - Encrypted State Continuations (ESC)
113
+ *
114
+ * Continuations embed encrypted state data directly into messages,
115
+ * eliminating the need for local state storage and enhancing security
116
+ * for devices with limited storage or requiring distributed state management.
117
+ *
118
+ * Ported from gstp-rust/src/continuation.rs
119
+ */
120
+ /**
121
+ * Represents an encrypted state continuation.
122
+ *
123
+ * Continuations provide a way to maintain state across message exchanges
124
+ * without requiring local storage. The state is encrypted and embedded
125
+ * directly in the message envelope.
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * import { Continuation } from '@bcts/gstp';
130
+ *
131
+ * // Create a continuation with state
132
+ * const continuation = new Continuation("session state data")
133
+ * .withValidId(requestId)
134
+ * .withValidUntil(new Date(Date.now() + 60000)); // Valid for 60 seconds
135
+ *
136
+ * // Convert to envelope (optionally encrypted)
137
+ * const envelope = continuation.toEnvelope(recipientPublicKey);
138
+ * ```
139
+ */
140
+ var Continuation = class Continuation {
141
+ _state;
142
+ _validId;
143
+ _validUntil;
144
+ /**
145
+ * Creates a new Continuation with the given state.
146
+ *
147
+ * The state can be any value that implements EnvelopeEncodable.
148
+ *
149
+ * @param state - The state to embed in the continuation
150
+ * @param validId - Optional ID for validation
151
+ * @param validUntil - Optional expiration date
152
+ */
153
+ constructor(state, validId, validUntil) {
154
+ this._state = Envelope.new(state);
155
+ this._validId = validId;
156
+ this._validUntil = validUntil;
157
+ }
158
+ /**
159
+ * Creates a new continuation with a specific valid ID.
160
+ *
161
+ * @param validId - The ID to use for validation
162
+ * @returns A new Continuation instance with the valid ID set
163
+ */
164
+ withValidId(validId) {
165
+ return new Continuation(this._state, validId, this._validUntil);
166
+ }
167
+ /**
168
+ * Creates a new continuation with an optional valid ID.
169
+ *
170
+ * @param validId - The ID to use for validation, or undefined
171
+ * @returns A new Continuation instance with the valid ID set
172
+ */
173
+ withOptionalValidId(validId) {
174
+ return new Continuation(this._state, validId, this._validUntil);
175
+ }
176
+ /**
177
+ * Creates a new continuation with a specific valid until date.
178
+ *
179
+ * @param validUntil - The date until which the continuation is valid
180
+ * @returns A new Continuation instance with the valid until date set
181
+ */
182
+ withValidUntil(validUntil) {
183
+ return new Continuation(this._state, this._validId, validUntil);
184
+ }
185
+ /**
186
+ * Creates a new continuation with an optional valid until date.
187
+ *
188
+ * @param validUntil - The date until which the continuation is valid, or undefined
189
+ * @returns A new Continuation instance with the valid until date set
190
+ */
191
+ withOptionalValidUntil(validUntil) {
192
+ return new Continuation(this._state, this._validId, validUntil);
193
+ }
194
+ /**
195
+ * Creates a new continuation with a validity duration from now.
196
+ *
197
+ * @param durationMs - The duration in milliseconds for which the continuation is valid
198
+ * @returns A new Continuation instance with the valid until date set
199
+ */
200
+ withValidDuration(durationMs) {
201
+ const validUntil = new Date(Date.now() + durationMs);
202
+ return new Continuation(this._state, this._validId, validUntil);
203
+ }
204
+ /**
205
+ * Returns the state envelope of the continuation.
206
+ */
207
+ state() {
208
+ return this._state;
209
+ }
210
+ /**
211
+ * Returns the valid ID of the continuation, if set.
212
+ */
213
+ id() {
214
+ return this._validId;
215
+ }
216
+ /**
217
+ * Returns the valid until date of the continuation, if set.
218
+ */
219
+ validUntil() {
220
+ return this._validUntil;
221
+ }
222
+ /**
223
+ * Checks if the continuation is valid at the given time.
224
+ *
225
+ * If no valid_until is set, always returns true.
226
+ * If no time is provided, always returns true.
227
+ *
228
+ * @param now - The time to check against, or undefined to skip time validation
229
+ * @returns true if the continuation is valid at the given time
230
+ */
231
+ isValidDate(now) {
232
+ if (this._validUntil === void 0) return true;
233
+ if (now === void 0) return true;
234
+ return now.getTime() <= this._validUntil.getTime();
235
+ }
236
+ /**
237
+ * Checks if the continuation has the expected ID.
238
+ *
239
+ * If no valid_id is set, always returns true.
240
+ * If no ID is provided for checking, always returns true.
241
+ *
242
+ * @param id - The ID to check against, or undefined to skip ID validation
243
+ * @returns true if the continuation has the expected ID
244
+ */
245
+ isValidId(id) {
246
+ if (this._validId === void 0) return true;
247
+ if (id === void 0) return true;
248
+ return this._validId.equals(id);
249
+ }
250
+ /**
251
+ * Checks if the continuation is valid (both date and ID).
252
+ *
253
+ * @param now - The time to check against, or undefined to skip time validation
254
+ * @param id - The ID to check against, or undefined to skip ID validation
255
+ * @returns true if the continuation is valid
256
+ */
257
+ isValid(now, id) {
258
+ return this.isValidDate(now) && this.isValidId(id);
259
+ }
260
+ /**
261
+ * Converts the continuation to an envelope.
262
+ *
263
+ * If a recipient is provided, the envelope is encrypted to that recipient.
264
+ *
265
+ * @param recipient - Optional recipient to encrypt the envelope to
266
+ * @returns The continuation as an envelope
267
+ */
268
+ toEnvelope(recipient) {
269
+ let envelope = this._state;
270
+ if (this._validId !== void 0) envelope = envelope.addAssertion(ID, this._validId);
271
+ if (this._validUntil !== void 0) envelope = envelope.addAssertion(VALID_UNTIL, this._validUntil.toISOString());
272
+ if (recipient !== void 0) envelope = envelope.encryptToRecipients([recipient]);
273
+ return envelope;
274
+ }
275
+ /**
276
+ * Parses a continuation from an envelope.
277
+ *
278
+ * @param encryptedEnvelope - The envelope to parse
279
+ * @param expectedId - Optional ID to validate against
280
+ * @param now - Optional time to validate against
281
+ * @param recipient - Optional private keys to decrypt with
282
+ * @returns The parsed continuation
283
+ * @throws GstpError if validation fails or parsing fails
284
+ */
285
+ static tryFromEnvelope(encryptedEnvelope, expectedId, now, recipient) {
286
+ let envelope = encryptedEnvelope;
287
+ if (recipient !== void 0) try {
288
+ envelope = encryptedEnvelope.decryptToRecipient(recipient);
289
+ } catch (e) {
290
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
291
+ }
292
+ const state = envelope.subject();
293
+ let validId;
294
+ try {
295
+ const idObj = envelope.objectForPredicate(ID);
296
+ if (idObj !== void 0) {
297
+ const leafCbor = idObj.asLeaf();
298
+ if (leafCbor !== void 0) validId = ARID.fromTaggedCborData(leafCbor.toData());
299
+ }
300
+ } catch {}
301
+ let validUntil;
302
+ try {
303
+ const validUntilObj = envelope.objectForPredicate(VALID_UNTIL);
304
+ if (validUntilObj !== void 0) {
305
+ const dateStr = validUntilObj.asText();
306
+ if (dateStr !== void 0) validUntil = new Date(dateStr);
307
+ }
308
+ } catch {}
309
+ const continuation = new Continuation(state, validId, validUntil);
310
+ if (!continuation.isValidDate(now)) throw GstpError.continuationExpired();
311
+ if (!continuation.isValidId(expectedId)) throw GstpError.continuationIdInvalid();
312
+ return continuation;
313
+ }
314
+ /**
315
+ * Checks equality with another continuation.
316
+ *
317
+ * Two continuations are equal if they have the same state, ID, and valid_until.
318
+ *
319
+ * @param other - The continuation to compare with
320
+ * @returns true if the continuations are equal
321
+ */
322
+ equals(other) {
323
+ if (!this._state.digest().equals(other._state.digest())) return false;
324
+ if (this._validId === void 0 && other._validId === void 0) {} else if (this._validId !== void 0 && other._validId !== void 0) {
325
+ if (!this._validId.equals(other._validId)) return false;
326
+ } else return false;
327
+ if (this._validUntil === void 0 && other._validUntil === void 0) {} else if (this._validUntil !== void 0 && other._validUntil !== void 0) {
328
+ if (this._validUntil.getTime() !== other._validUntil.getTime()) return false;
329
+ } else return false;
330
+ return true;
331
+ }
332
+ /**
333
+ * Returns a string representation of the continuation.
334
+ */
335
+ toString() {
336
+ const parts = [`Continuation(state: ${this._state.formatFlat()}`];
337
+ if (this._validId !== void 0) parts.push(`id: ${this._validId.shortDescription()}`);
338
+ if (this._validUntil !== void 0) parts.push(`validUntil: ${this._validUntil.toISOString()}`);
339
+ return `${parts.join(", ")})`;
340
+ }
341
+ };
342
+
343
+ //#endregion
344
+ //#region src/sealed-request.ts
345
+ /**
346
+ * A sealed request that combines a Request with sender information and
347
+ * state continuations for secure communication.
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * import { SealedRequest, ARID } from '@bcts/gstp';
352
+ * import { XIDDocument } from '@bcts/xid';
353
+ *
354
+ * // Create sender XID document
355
+ * const sender = XIDDocument.new();
356
+ * const requestId = ARID.new();
357
+ *
358
+ * // Create a sealed request
359
+ * const request = SealedRequest.new("getBalance", requestId, sender)
360
+ * .withParameter("account", "alice")
361
+ * .withState("session-state-data")
362
+ * .withNote("Balance check");
363
+ *
364
+ * // Convert to sealed envelope
365
+ * const envelope = request.toEnvelope(
366
+ * new Date(Date.now() + 60000), // Valid for 60 seconds
367
+ * senderPrivateKey,
368
+ * recipientXIDDocument
369
+ * );
370
+ * ```
371
+ */
372
+ var SealedRequest = class SealedRequest {
373
+ _request;
374
+ _sender;
375
+ _state;
376
+ _peerContinuation;
377
+ constructor(request, sender, state, peerContinuation) {
378
+ this._request = request;
379
+ this._sender = sender;
380
+ this._state = state;
381
+ this._peerContinuation = peerContinuation;
382
+ }
383
+ /**
384
+ * Creates a new sealed request with the given function, ID, and sender.
385
+ *
386
+ * @param func - The function to call (string name or Function object)
387
+ * @param id - The request ID
388
+ * @param sender - The sender's XID document
389
+ */
390
+ static new(func, id, sender) {
391
+ return new SealedRequest(Request.new(func, id), sender);
392
+ }
393
+ /**
394
+ * Creates a new sealed request with an expression body.
395
+ *
396
+ * @param body - The expression body
397
+ * @param id - The request ID
398
+ * @param sender - The sender's XID document
399
+ */
400
+ static newWithBody(body, id, sender) {
401
+ return new SealedRequest(Request.newWithBody(body, id), sender);
402
+ }
403
+ /**
404
+ * Adds a parameter to the request.
405
+ */
406
+ withParameter(parameter, value) {
407
+ this._request = this._request.withParameter(parameter, value);
408
+ return this;
409
+ }
410
+ /**
411
+ * Adds an optional parameter to the request.
412
+ */
413
+ withOptionalParameter(parameter, value) {
414
+ if (value !== void 0) this._request = this._request.withParameter(parameter, value);
415
+ return this;
416
+ }
417
+ /**
418
+ * Returns the function of the request.
419
+ */
420
+ function() {
421
+ return this._request.function();
422
+ }
423
+ /**
424
+ * Returns the expression envelope of the request.
425
+ */
426
+ expressionEnvelope() {
427
+ return this._request.expressionEnvelope();
428
+ }
429
+ /**
430
+ * Returns the object for a parameter.
431
+ */
432
+ objectForParameter(param) {
433
+ return this._request.body().getParameter(param);
434
+ }
435
+ /**
436
+ * Returns all objects for a parameter.
437
+ */
438
+ objectsForParameter(param) {
439
+ const obj = this._request.body().getParameter(param);
440
+ return obj !== void 0 ? [obj] : [];
441
+ }
442
+ /**
443
+ * Extracts an object for a parameter as a specific type.
444
+ */
445
+ extractObjectForParameter(param) {
446
+ const envelope = this.objectForParameter(param);
447
+ if (envelope === void 0) throw GstpError.envelope(/* @__PURE__ */ new Error(`Parameter not found: ${param}`));
448
+ return envelope.extractSubject((cbor) => {
449
+ if (cbor.isInteger()) return cbor.toInteger();
450
+ if (cbor.isText()) return cbor.toText();
451
+ if (cbor.isBool()) return cbor.toBool();
452
+ if (cbor.isNumber()) return cbor.toNumber();
453
+ if (cbor.isByteString()) return cbor.toByteString();
454
+ return cbor;
455
+ });
456
+ }
457
+ /**
458
+ * Extracts an optional object for a parameter.
459
+ */
460
+ extractOptionalObjectForParameter(param) {
461
+ const envelope = this.objectForParameter(param);
462
+ if (envelope === void 0) return;
463
+ return envelope.extractSubject((cbor) => {
464
+ if (cbor.isInteger()) return cbor.toInteger();
465
+ if (cbor.isText()) return cbor.toText();
466
+ if (cbor.isBool()) return cbor.toBool();
467
+ if (cbor.isNumber()) return cbor.toNumber();
468
+ if (cbor.isByteString()) return cbor.toByteString();
469
+ return cbor;
470
+ });
471
+ }
472
+ /**
473
+ * Extracts all objects for a parameter as a specific type.
474
+ */
475
+ extractObjectsForParameter(param) {
476
+ return this.objectsForParameter(param).map((env) => env.extractSubject((cbor) => cbor));
477
+ }
478
+ /**
479
+ * Adds a note to the request.
480
+ */
481
+ withNote(note) {
482
+ this._request = this._request.withNote(note);
483
+ return this;
484
+ }
485
+ /**
486
+ * Adds a date to the request.
487
+ */
488
+ withDate(date) {
489
+ this._request = this._request.withDate(date);
490
+ return this;
491
+ }
492
+ /**
493
+ * Returns the body of the request.
494
+ */
495
+ body() {
496
+ return this._request.body();
497
+ }
498
+ /**
499
+ * Returns the ID of the request.
500
+ */
501
+ id() {
502
+ return this._request.id();
503
+ }
504
+ /**
505
+ * Returns the note of the request.
506
+ */
507
+ note() {
508
+ return this._request.note();
509
+ }
510
+ /**
511
+ * Returns the date of the request.
512
+ */
513
+ date() {
514
+ return this._request.date();
515
+ }
516
+ /**
517
+ * Adds state to the request that the receiver must return in the response.
518
+ */
519
+ withState(state) {
520
+ this._state = Envelope.new(state);
521
+ return this;
522
+ }
523
+ /**
524
+ * Adds optional state to the request.
525
+ */
526
+ withOptionalState(state) {
527
+ this._state = state !== void 0 ? Envelope.new(state) : void 0;
528
+ return this;
529
+ }
530
+ /**
531
+ * Adds a continuation previously received from the recipient.
532
+ */
533
+ withPeerContinuation(peerContinuation) {
534
+ this._peerContinuation = peerContinuation;
535
+ return this;
536
+ }
537
+ /**
538
+ * Adds an optional continuation previously received from the recipient.
539
+ */
540
+ withOptionalPeerContinuation(peerContinuation) {
541
+ this._peerContinuation = peerContinuation;
542
+ return this;
543
+ }
544
+ /**
545
+ * Returns the underlying request.
546
+ */
547
+ request() {
548
+ return this._request;
549
+ }
550
+ /**
551
+ * Returns the sender of the request.
552
+ */
553
+ sender() {
554
+ return this._sender;
555
+ }
556
+ /**
557
+ * Returns the state to be sent to the recipient.
558
+ */
559
+ state() {
560
+ return this._state;
561
+ }
562
+ /**
563
+ * Returns the continuation received from the recipient.
564
+ */
565
+ peerContinuation() {
566
+ return this._peerContinuation;
567
+ }
568
+ /**
569
+ * Converts the sealed request to a Request.
570
+ */
571
+ toRequest() {
572
+ return this._request;
573
+ }
574
+ /**
575
+ * Converts the sealed request to an Expression.
576
+ */
577
+ toExpression() {
578
+ return this._request.body();
579
+ }
580
+ /**
581
+ * Creates an envelope that can be decrypted by zero or one recipient.
582
+ *
583
+ * @param validUntil - Optional expiration date for the continuation
584
+ * @param signer - Optional signer for the envelope
585
+ * @param recipient - Optional recipient XID document for encryption
586
+ * @returns The sealed request as an envelope
587
+ */
588
+ toEnvelope(validUntil, signer, recipient) {
589
+ const recipients = recipient !== void 0 ? [recipient] : [];
590
+ return this.toEnvelopeForRecipients(validUntil, signer, recipients);
591
+ }
592
+ /**
593
+ * Creates an envelope that can be decrypted by zero or more recipients.
594
+ *
595
+ * @param validUntil - Optional expiration date for the continuation
596
+ * @param signer - Optional signer for the envelope
597
+ * @param recipients - Array of recipient XID documents for encryption
598
+ * @returns The sealed request as an envelope
599
+ */
600
+ toEnvelopeForRecipients(validUntil, signer, recipients) {
601
+ const continuation = new Continuation(this._state ?? Envelope.new(null), this.id(), validUntil);
602
+ const senderEncryptionKey = this._sender.inceptionKey()?.publicKeys()?.encapsulationPublicKey();
603
+ if (senderEncryptionKey === void 0) throw GstpError.senderMissingEncryptionKey();
604
+ const senderContinuation = continuation.toEnvelope(senderEncryptionKey);
605
+ let result = this._request.toEnvelope();
606
+ result = result.addAssertion(SENDER, this._sender.toEnvelope());
607
+ result = result.addAssertion(SENDER_CONTINUATION, senderContinuation);
608
+ if (this._peerContinuation !== void 0) result = result.addAssertion(RECIPIENT_CONTINUATION, this._peerContinuation);
609
+ if (signer !== void 0) result = result.sign(signer);
610
+ if (recipients !== void 0 && recipients.length > 0) {
611
+ const recipientKeys = recipients.map((recipient) => {
612
+ const key = recipient.encryptionKey();
613
+ if (key === void 0) throw GstpError.recipientMissingEncryptionKey();
614
+ return key;
615
+ });
616
+ result = result.wrap().encryptSubjectToRecipients(recipientKeys);
617
+ }
618
+ return result;
619
+ }
620
+ /**
621
+ * Parses a sealed request from an encrypted envelope.
622
+ *
623
+ * @param encryptedEnvelope - The encrypted envelope to parse
624
+ * @param expectedId - Optional expected request ID for validation
625
+ * @param now - Optional current time for continuation validation
626
+ * @param recipient - The recipient's private keys for decryption
627
+ * @returns The parsed sealed request
628
+ */
629
+ static tryFromEnvelope(encryptedEnvelope, expectedId, now, recipient) {
630
+ let signedEnvelope;
631
+ try {
632
+ signedEnvelope = encryptedEnvelope.decryptToRecipient(recipient);
633
+ } catch (e) {
634
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
635
+ }
636
+ let sender;
637
+ try {
638
+ const senderEnvelope = signedEnvelope.tryUnwrap().objectForPredicate(SENDER);
639
+ if (senderEnvelope === void 0) throw new Error("Missing sender");
640
+ sender = XIDDocument.fromEnvelope(senderEnvelope);
641
+ } catch (e) {
642
+ throw GstpError.xid(e instanceof Error ? e : new Error(String(e)));
643
+ }
644
+ const senderVerificationKey = sender.inceptionKey()?.publicKeys()?.signingPublicKey();
645
+ if (senderVerificationKey === void 0) throw GstpError.senderMissingVerificationKey();
646
+ let requestEnvelope;
647
+ try {
648
+ requestEnvelope = signedEnvelope.verify(senderVerificationKey);
649
+ } catch (e) {
650
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
651
+ }
652
+ const peerContinuation = requestEnvelope.optionalObjectForPredicate(SENDER_CONTINUATION);
653
+ if (peerContinuation !== void 0) {
654
+ if (!peerContinuation.subject().isEncrypted()) throw GstpError.peerContinuationNotEncrypted();
655
+ } else throw GstpError.missingPeerContinuation();
656
+ const encryptedContinuation = requestEnvelope.optionalObjectForPredicate(RECIPIENT_CONTINUATION);
657
+ let state;
658
+ if (encryptedContinuation !== void 0) state = Continuation.tryFromEnvelope(encryptedContinuation, expectedId, now, recipient).state();
659
+ let request;
660
+ try {
661
+ request = Request.fromEnvelope(requestEnvelope);
662
+ } catch (e) {
663
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
664
+ }
665
+ return new SealedRequest(request, sender, state, peerContinuation);
666
+ }
667
+ /**
668
+ * Returns a string representation of the sealed request.
669
+ */
670
+ toString() {
671
+ const stateStr = this._state !== void 0 ? this._state.formatFlat() : "None";
672
+ const peerStr = this._peerContinuation !== void 0 ? "Some" : "None";
673
+ return `SealedRequest(${this._request.summary()}, state: ${stateStr}, peer_continuation: ${peerStr})`;
674
+ }
675
+ /**
676
+ * Checks equality with another sealed request.
677
+ */
678
+ equals(other) {
679
+ if (!this._request.equals(other._request)) return false;
680
+ if (!this._sender.xid().equals(other._sender.xid())) return false;
681
+ if (this._state === void 0 && other._state === void 0) {} else if (this._state !== void 0 && other._state !== void 0) {
682
+ if (!this._state.digest().equals(other._state.digest())) return false;
683
+ } else return false;
684
+ if (this._peerContinuation === void 0 && other._peerContinuation === void 0) {} else if (this._peerContinuation !== void 0 && other._peerContinuation !== void 0) {
685
+ if (!this._peerContinuation.digest().equals(other._peerContinuation.digest())) return false;
686
+ } else return false;
687
+ return true;
688
+ }
689
+ };
690
+
691
+ //#endregion
692
+ //#region src/sealed-response.ts
693
+ /**
694
+ * A sealed response that combines a Response with sender information and
695
+ * state continuations for secure communication.
696
+ *
697
+ * @example
698
+ * ```typescript
699
+ * import { SealedResponse, ARID } from '@bcts/gstp';
700
+ * import { XIDDocument } from '@bcts/xid';
701
+ *
702
+ * // Create sender XID document
703
+ * const sender = XIDDocument.new();
704
+ * const requestId = ARID.new();
705
+ *
706
+ * // Create a successful sealed response
707
+ * const response = SealedResponse.newSuccess(requestId, sender)
708
+ * .withResult("Operation completed")
709
+ * .withState("next-page-state");
710
+ *
711
+ * // Convert to sealed envelope
712
+ * const envelope = response.toEnvelope(
713
+ * new Date(Date.now() + 60000), // Valid for 60 seconds
714
+ * senderPrivateKey,
715
+ * recipientXIDDocument
716
+ * );
717
+ * ```
718
+ */
719
+ var SealedResponse = class SealedResponse {
720
+ _response;
721
+ _sender;
722
+ _state;
723
+ _peerContinuation;
724
+ constructor(response, sender, state, peerContinuation) {
725
+ this._response = response;
726
+ this._sender = sender;
727
+ this._state = state;
728
+ this._peerContinuation = peerContinuation;
729
+ }
730
+ /**
731
+ * Creates a new successful sealed response.
732
+ *
733
+ * @param id - The request ID this response is for
734
+ * @param sender - The sender's XID document
735
+ */
736
+ static newSuccess(id, sender) {
737
+ return new SealedResponse(Response.newSuccess(id), sender);
738
+ }
739
+ /**
740
+ * Creates a new failure sealed response.
741
+ *
742
+ * @param id - The request ID this response is for
743
+ * @param sender - The sender's XID document
744
+ */
745
+ static newFailure(id, sender) {
746
+ return new SealedResponse(Response.newFailure(id), sender);
747
+ }
748
+ /**
749
+ * Creates a new early failure sealed response.
750
+ *
751
+ * An early failure takes place before the message has been decrypted,
752
+ * and therefore the ID and sender public key are not known.
753
+ *
754
+ * @param sender - The sender's XID document
755
+ */
756
+ static newEarlyFailure(sender) {
757
+ return new SealedResponse(Response.newEarlyFailure(), sender);
758
+ }
759
+ /**
760
+ * Adds state to the response that the peer may return at some future time.
761
+ *
762
+ * @throws Error if called on a failed response
763
+ */
764
+ withState(state) {
765
+ if (!this._response.isOk()) throw new Error("Cannot set state on a failed response");
766
+ this._state = Envelope.new(state);
767
+ return this;
768
+ }
769
+ /**
770
+ * Adds optional state to the response.
771
+ */
772
+ withOptionalState(state) {
773
+ if (state !== void 0) return this.withState(state);
774
+ this._state = void 0;
775
+ return this;
776
+ }
777
+ /**
778
+ * Adds a continuation previously received from the recipient.
779
+ */
780
+ withPeerContinuation(peerContinuation) {
781
+ this._peerContinuation = peerContinuation;
782
+ return this;
783
+ }
784
+ /**
785
+ * Returns the sender of the response.
786
+ */
787
+ sender() {
788
+ return this._sender;
789
+ }
790
+ /**
791
+ * Returns the state to be sent to the peer.
792
+ */
793
+ state() {
794
+ return this._state;
795
+ }
796
+ /**
797
+ * Returns the continuation received from the peer.
798
+ */
799
+ peerContinuation() {
800
+ return this._peerContinuation;
801
+ }
802
+ /**
803
+ * Sets the result value for a successful response.
804
+ */
805
+ withResult(result) {
806
+ this._response = this._response.withResult(result);
807
+ return this;
808
+ }
809
+ /**
810
+ * Sets an optional result value for a successful response.
811
+ * If the result is undefined, the value of the response will be the null envelope.
812
+ */
813
+ withOptionalResult(result) {
814
+ this._response = this._response.withOptionalResult(result);
815
+ return this;
816
+ }
817
+ /**
818
+ * Sets the error value for a failure response.
819
+ */
820
+ withError(error) {
821
+ this._response = this._response.withError(error);
822
+ return this;
823
+ }
824
+ /**
825
+ * Sets an optional error value for a failure response.
826
+ * If the error is undefined, the value of the response will be the unknown value.
827
+ */
828
+ withOptionalError(error) {
829
+ this._response = this._response.withOptionalError(error);
830
+ return this;
831
+ }
832
+ /**
833
+ * Returns true if this is a successful response.
834
+ */
835
+ isOk() {
836
+ return this._response.isOk();
837
+ }
838
+ /**
839
+ * Returns true if this is a failure response.
840
+ */
841
+ isErr() {
842
+ return this._response.isErr();
843
+ }
844
+ /**
845
+ * Returns the ID of the request this response is for, if known.
846
+ */
847
+ id() {
848
+ return this._response.id();
849
+ }
850
+ /**
851
+ * Returns the ID of the request this response is for.
852
+ * @throws Error if the ID is not known
853
+ */
854
+ expectId() {
855
+ return this._response.expectId();
856
+ }
857
+ /**
858
+ * Returns the result envelope if this is a successful response.
859
+ * @throws Error if this is a failure response
860
+ */
861
+ result() {
862
+ return this._response.result();
863
+ }
864
+ /**
865
+ * Extracts the result as a specific type.
866
+ */
867
+ extractResult(decoder) {
868
+ return this._response.extractResult(decoder);
869
+ }
870
+ /**
871
+ * Returns the error envelope if this is a failure response.
872
+ * @throws Error if this is a successful response
873
+ */
874
+ error() {
875
+ return this._response.error();
876
+ }
877
+ /**
878
+ * Extracts the error as a specific type.
879
+ */
880
+ extractError(decoder) {
881
+ return this._response.extractError(decoder);
882
+ }
883
+ /**
884
+ * Creates an envelope that can be decrypted by zero or one recipient.
885
+ *
886
+ * @param validUntil - Optional expiration date for the continuation
887
+ * @param signer - Optional signer for the envelope
888
+ * @param recipient - Optional recipient XID document for encryption
889
+ * @returns The sealed response as an envelope
890
+ */
891
+ toEnvelope(validUntil, signer, recipient) {
892
+ const recipients = recipient !== void 0 ? [recipient] : [];
893
+ return this.toEnvelopeForRecipients(validUntil, signer, recipients);
894
+ }
895
+ /**
896
+ * Creates an envelope that can be decrypted by zero or more recipients.
897
+ *
898
+ * @param validUntil - Optional expiration date for the continuation
899
+ * @param signer - Optional signer for the envelope
900
+ * @param recipients - Array of recipient XID documents for encryption
901
+ * @returns The sealed response as an envelope
902
+ */
903
+ toEnvelopeForRecipients(validUntil, signer, recipients) {
904
+ let senderContinuation;
905
+ if (this._state !== void 0) {
906
+ const continuation = new Continuation(this._state, void 0, validUntil);
907
+ const senderEncryptionKey = this._sender.inceptionKey()?.publicKeys()?.encapsulationPublicKey();
908
+ if (senderEncryptionKey === void 0) throw GstpError.senderMissingEncryptionKey();
909
+ senderContinuation = continuation.toEnvelope(senderEncryptionKey);
910
+ }
911
+ let result = this._response.toEnvelope();
912
+ result = result.addAssertion(SENDER, this._sender.toEnvelope());
913
+ if (senderContinuation !== void 0) result = result.addAssertion(SENDER_CONTINUATION, senderContinuation);
914
+ if (this._peerContinuation !== void 0) result = result.addAssertion(RECIPIENT_CONTINUATION, this._peerContinuation);
915
+ if (signer !== void 0) result = result.sign(signer);
916
+ if (recipients !== void 0 && recipients.length > 0) {
917
+ const recipientKeys = recipients.map((recipient) => {
918
+ const key = recipient.encryptionKey();
919
+ if (key === void 0) throw GstpError.recipientMissingEncryptionKey();
920
+ return key;
921
+ });
922
+ result = result.wrap().encryptSubjectToRecipients(recipientKeys);
923
+ }
924
+ return result;
925
+ }
926
+ /**
927
+ * Parses a sealed response from an encrypted envelope.
928
+ *
929
+ * @param encryptedEnvelope - The encrypted envelope to parse
930
+ * @param expectedId - Optional expected request ID for validation
931
+ * @param now - Optional current time for continuation validation
932
+ * @param recipientPrivateKey - The recipient's private keys for decryption
933
+ * @returns The parsed sealed response
934
+ */
935
+ static tryFromEncryptedEnvelope(encryptedEnvelope, expectedId, now, recipientPrivateKey) {
936
+ let signedEnvelope;
937
+ try {
938
+ signedEnvelope = encryptedEnvelope.decryptToRecipient(recipientPrivateKey);
939
+ } catch (e) {
940
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
941
+ }
942
+ let sender;
943
+ try {
944
+ const senderEnvelope = signedEnvelope.tryUnwrap().objectForPredicate(SENDER);
945
+ if (senderEnvelope === void 0) throw new Error("Missing sender");
946
+ sender = XIDDocument.fromEnvelope(senderEnvelope);
947
+ } catch (e) {
948
+ throw GstpError.xid(e instanceof Error ? e : new Error(String(e)));
949
+ }
950
+ const senderVerificationKey = sender.inceptionKey()?.publicKeys()?.signingPublicKey();
951
+ if (senderVerificationKey === void 0) throw GstpError.senderMissingVerificationKey();
952
+ let responseEnvelope;
953
+ try {
954
+ responseEnvelope = signedEnvelope.verify(senderVerificationKey);
955
+ } catch (e) {
956
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
957
+ }
958
+ const peerContinuation = responseEnvelope.optionalObjectForPredicate(SENDER_CONTINUATION);
959
+ if (peerContinuation !== void 0) {
960
+ if (!peerContinuation.subject().isEncrypted()) throw GstpError.peerContinuationNotEncrypted();
961
+ }
962
+ const encryptedContinuation = responseEnvelope.optionalObjectForPredicate(RECIPIENT_CONTINUATION);
963
+ let state;
964
+ if (encryptedContinuation !== void 0) {
965
+ const stateEnv = Continuation.tryFromEnvelope(encryptedContinuation, expectedId, now, recipientPrivateKey).state();
966
+ if (stateEnv.isNull()) state = void 0;
967
+ else state = stateEnv;
968
+ }
969
+ let response;
970
+ try {
971
+ response = Response.fromEnvelope(responseEnvelope);
972
+ } catch (e) {
973
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
974
+ }
975
+ return new SealedResponse(response, sender, state, peerContinuation);
976
+ }
977
+ /**
978
+ * Returns a string representation of the sealed response.
979
+ */
980
+ toString() {
981
+ const stateStr = this._state !== void 0 ? this._state.formatFlat() : "None";
982
+ const peerStr = this._peerContinuation !== void 0 ? "Some" : "None";
983
+ return `SealedResponse(${this._response.summary()}, state: ${stateStr}, peer_continuation: ${peerStr})`;
984
+ }
985
+ /**
986
+ * Checks equality with another sealed response.
987
+ */
988
+ equals(other) {
989
+ if (!this._response.equals(other._response)) return false;
990
+ if (!this._sender.xid().equals(other._sender.xid())) return false;
991
+ if (this._state === void 0 && other._state === void 0) {} else if (this._state !== void 0 && other._state !== void 0) {
992
+ if (!this._state.digest().equals(other._state.digest())) return false;
993
+ } else return false;
994
+ if (this._peerContinuation === void 0 && other._peerContinuation === void 0) {} else if (this._peerContinuation !== void 0 && other._peerContinuation !== void 0) {
995
+ if (!this._peerContinuation.digest().equals(other._peerContinuation.digest())) return false;
996
+ } else return false;
997
+ return true;
998
+ }
999
+ };
1000
+
1001
+ //#endregion
1002
+ //#region src/sealed-event.ts
1003
+ /**
1004
+ * A sealed event that combines an Event with sender information and
1005
+ * state continuations for secure communication.
1006
+ *
1007
+ * @typeParam T - The type of content this event carries
1008
+ *
1009
+ * @example
1010
+ * ```typescript
1011
+ * import { SealedEvent, ARID } from '@bcts/gstp';
1012
+ * import { XIDDocument } from '@bcts/xid';
1013
+ *
1014
+ * // Create sender XID document
1015
+ * const sender = XIDDocument.new();
1016
+ * const eventId = ARID.new();
1017
+ *
1018
+ * // Create a sealed event
1019
+ * const event = SealedEvent.new("System notification", eventId, sender)
1020
+ * .withNote("Status update")
1021
+ * .withDate(new Date());
1022
+ *
1023
+ * // Convert to sealed envelope
1024
+ * const envelope = event.toEnvelope(
1025
+ * new Date(Date.now() + 60000), // Valid for 60 seconds
1026
+ * senderPrivateKey,
1027
+ * recipientXIDDocument
1028
+ * );
1029
+ * ```
1030
+ */
1031
+ var SealedEvent = class SealedEvent {
1032
+ _event;
1033
+ _sender;
1034
+ _state;
1035
+ _peerContinuation;
1036
+ constructor(event, sender, state, peerContinuation) {
1037
+ this._event = event;
1038
+ this._sender = sender;
1039
+ this._state = state;
1040
+ this._peerContinuation = peerContinuation;
1041
+ }
1042
+ /**
1043
+ * Creates a new sealed event with the given content, ID, and sender.
1044
+ *
1045
+ * @param content - The content of the event
1046
+ * @param id - The event ID
1047
+ * @param sender - The sender's XID document
1048
+ */
1049
+ static new(content, id, sender) {
1050
+ return new SealedEvent(Event.new(content, id), sender);
1051
+ }
1052
+ /**
1053
+ * Adds a note to the event.
1054
+ */
1055
+ withNote(note) {
1056
+ this._event = this._event.withNote(note);
1057
+ return this;
1058
+ }
1059
+ /**
1060
+ * Adds a date to the event.
1061
+ */
1062
+ withDate(date) {
1063
+ this._event = this._event.withDate(date);
1064
+ return this;
1065
+ }
1066
+ /**
1067
+ * Returns the content of the event.
1068
+ */
1069
+ content() {
1070
+ return this._event.content();
1071
+ }
1072
+ /**
1073
+ * Returns the ID of the event.
1074
+ */
1075
+ id() {
1076
+ return this._event.id();
1077
+ }
1078
+ /**
1079
+ * Returns the note of the event.
1080
+ */
1081
+ note() {
1082
+ return this._event.note();
1083
+ }
1084
+ /**
1085
+ * Returns the date of the event.
1086
+ */
1087
+ date() {
1088
+ return this._event.date();
1089
+ }
1090
+ /**
1091
+ * Adds state to the event that the receiver must return in the response.
1092
+ */
1093
+ withState(state) {
1094
+ this._state = Envelope.new(state);
1095
+ return this;
1096
+ }
1097
+ /**
1098
+ * Adds optional state to the event.
1099
+ */
1100
+ withOptionalState(state) {
1101
+ if (state !== void 0) return this.withState(state);
1102
+ this._state = void 0;
1103
+ return this;
1104
+ }
1105
+ /**
1106
+ * Adds a continuation previously received from the recipient.
1107
+ */
1108
+ withPeerContinuation(peerContinuation) {
1109
+ this._peerContinuation = peerContinuation;
1110
+ return this;
1111
+ }
1112
+ /**
1113
+ * Adds an optional continuation previously received from the recipient.
1114
+ */
1115
+ withOptionalPeerContinuation(peerContinuation) {
1116
+ this._peerContinuation = peerContinuation;
1117
+ return this;
1118
+ }
1119
+ /**
1120
+ * Returns the underlying event.
1121
+ */
1122
+ event() {
1123
+ return this._event;
1124
+ }
1125
+ /**
1126
+ * Returns the sender of the event.
1127
+ */
1128
+ sender() {
1129
+ return this._sender;
1130
+ }
1131
+ /**
1132
+ * Returns the state to be sent to the recipient.
1133
+ */
1134
+ state() {
1135
+ return this._state;
1136
+ }
1137
+ /**
1138
+ * Returns the continuation received from the recipient.
1139
+ */
1140
+ peerContinuation() {
1141
+ return this._peerContinuation;
1142
+ }
1143
+ /**
1144
+ * Converts the sealed event to an Event.
1145
+ */
1146
+ toEvent() {
1147
+ return this._event;
1148
+ }
1149
+ /**
1150
+ * Creates an envelope that can be decrypted by zero or one recipient.
1151
+ *
1152
+ * @param validUntil - Optional expiration date for the continuation
1153
+ * @param signer - Optional signer for the envelope
1154
+ * @param recipient - Optional recipient XID document for encryption
1155
+ * @returns The sealed event as an envelope
1156
+ */
1157
+ toEnvelope(validUntil, signer, recipient) {
1158
+ const recipients = recipient !== void 0 ? [recipient] : [];
1159
+ return this.toEnvelopeForRecipients(validUntil, signer, recipients);
1160
+ }
1161
+ /**
1162
+ * Creates an envelope that can be decrypted by zero or more recipients.
1163
+ *
1164
+ * @param validUntil - Optional expiration date for the continuation
1165
+ * @param signer - Optional signer for the envelope
1166
+ * @param recipients - Array of recipient XID documents for encryption
1167
+ * @returns The sealed event as an envelope
1168
+ */
1169
+ toEnvelopeForRecipients(validUntil, signer, recipients) {
1170
+ const senderEncryptionKey = this._sender.inceptionKey()?.publicKeys()?.encapsulationPublicKey();
1171
+ if (senderEncryptionKey === void 0) throw GstpError.senderMissingEncryptionKey();
1172
+ let senderContinuation;
1173
+ if (this._state !== void 0) senderContinuation = new Continuation(this._state, void 0, validUntil).toEnvelope(senderEncryptionKey);
1174
+ else if (validUntil !== void 0) senderContinuation = new Continuation(Envelope.new(null), void 0, validUntil).toEnvelope(senderEncryptionKey);
1175
+ let result = this._event.toEnvelope();
1176
+ result = result.addAssertion(SENDER, this._sender.toEnvelope());
1177
+ if (senderContinuation !== void 0) result = result.addAssertion(SENDER_CONTINUATION, senderContinuation);
1178
+ if (this._peerContinuation !== void 0) result = result.addAssertion(RECIPIENT_CONTINUATION, this._peerContinuation);
1179
+ if (signer !== void 0) result = result.sign(signer);
1180
+ if (recipients !== void 0 && recipients.length > 0) {
1181
+ const recipientKeys = recipients.map((recipient) => {
1182
+ const key = recipient.encryptionKey();
1183
+ if (key === void 0) throw GstpError.recipientMissingEncryptionKey();
1184
+ return key;
1185
+ });
1186
+ result = result.wrap().encryptSubjectToRecipients(recipientKeys);
1187
+ }
1188
+ return result;
1189
+ }
1190
+ /**
1191
+ * Parses a sealed event from an encrypted envelope.
1192
+ *
1193
+ * @param encryptedEnvelope - The encrypted envelope to parse
1194
+ * @param expectedId - Optional expected event ID for validation
1195
+ * @param now - Optional current time for continuation validation
1196
+ * @param recipientPrivateKey - The recipient's private keys for decryption
1197
+ * @param contentExtractor - Function to extract content from envelope
1198
+ * @returns The parsed sealed event
1199
+ */
1200
+ static tryFromEnvelope(encryptedEnvelope, expectedId, now, recipientPrivateKey, contentExtractor) {
1201
+ let signedEnvelope;
1202
+ try {
1203
+ signedEnvelope = encryptedEnvelope.decryptToRecipient(recipientPrivateKey);
1204
+ } catch (e) {
1205
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
1206
+ }
1207
+ let sender;
1208
+ try {
1209
+ const senderEnvelope = signedEnvelope.tryUnwrap().objectForPredicate(SENDER);
1210
+ if (senderEnvelope === void 0) throw new Error("Missing sender");
1211
+ sender = XIDDocument.fromEnvelope(senderEnvelope);
1212
+ } catch (e) {
1213
+ throw GstpError.xid(e instanceof Error ? e : new Error(String(e)));
1214
+ }
1215
+ const senderVerificationKey = sender.inceptionKey()?.publicKeys()?.signingPublicKey();
1216
+ if (senderVerificationKey === void 0) throw GstpError.senderMissingVerificationKey();
1217
+ let eventEnvelope;
1218
+ try {
1219
+ eventEnvelope = signedEnvelope.verify(senderVerificationKey);
1220
+ } catch (e) {
1221
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
1222
+ }
1223
+ const peerContinuation = eventEnvelope.optionalObjectForPredicate(SENDER_CONTINUATION);
1224
+ if (peerContinuation !== void 0) {
1225
+ if (!peerContinuation.subject().isEncrypted()) throw GstpError.peerContinuationNotEncrypted();
1226
+ }
1227
+ const encryptedContinuation = eventEnvelope.optionalObjectForPredicate(RECIPIENT_CONTINUATION);
1228
+ let state;
1229
+ if (encryptedContinuation !== void 0) state = Continuation.tryFromEnvelope(encryptedContinuation, expectedId, now, recipientPrivateKey).state();
1230
+ let event;
1231
+ try {
1232
+ if (contentExtractor !== void 0) event = Event.fromEnvelope(eventEnvelope, contentExtractor);
1233
+ else event = Event.stringFromEnvelope(eventEnvelope);
1234
+ } catch (e) {
1235
+ throw GstpError.envelope(e instanceof Error ? e : new Error(String(e)));
1236
+ }
1237
+ return new SealedEvent(event, sender, state, peerContinuation);
1238
+ }
1239
+ /**
1240
+ * Returns a string representation of the sealed event.
1241
+ */
1242
+ toString() {
1243
+ const stateStr = this._state !== void 0 ? this._state.formatFlat() : "None";
1244
+ const peerStr = this._peerContinuation !== void 0 ? "Some" : "None";
1245
+ return `SealedEvent(${this._event.summary()}, state: ${stateStr}, peer_continuation: ${peerStr})`;
1246
+ }
1247
+ /**
1248
+ * Checks equality with another sealed event.
1249
+ */
1250
+ equals(other) {
1251
+ if (!this._event.equals(other._event)) return false;
1252
+ if (!this._sender.xid().equals(other._sender.xid())) return false;
1253
+ if (this._state === void 0 && other._state === void 0) {} else if (this._state !== void 0 && other._state !== void 0) {
1254
+ if (!this._state.digest().equals(other._state.digest())) return false;
1255
+ } else return false;
1256
+ if (this._peerContinuation === void 0 && other._peerContinuation === void 0) {} else if (this._peerContinuation !== void 0 && other._peerContinuation !== void 0) {
1257
+ if (!this._peerContinuation.digest().equals(other._peerContinuation.digest())) return false;
1258
+ } else return false;
1259
+ return true;
1260
+ }
1261
+ };
1262
+
1263
+ //#endregion
1264
+ //#region src/prelude.ts
1265
+ var prelude_exports = /* @__PURE__ */ __exportAll({
1266
+ Continuation: () => Continuation,
1267
+ GstpError: () => GstpError,
1268
+ GstpErrorCode: () => GstpErrorCode,
1269
+ SealedEvent: () => SealedEvent,
1270
+ SealedRequest: () => SealedRequest,
1271
+ SealedResponse: () => SealedResponse
1272
+ });
1273
+
1274
+ //#endregion
1275
+ //#region src/index.ts
1276
+ const VERSION = "0.13.0";
1277
+
1278
+ //#endregion
1279
+ export { Continuation, GstpError, GstpErrorCode, SealedEvent, SealedRequest, SealedResponse, VERSION, prelude_exports as prelude };
1280
+ //# sourceMappingURL=index.mjs.map