@open-e2ee/signal-protocol-sdk 13.4.0 → 13.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +417 -0
  2. package/README.md +1 -1
  3. package/SECURITY.md +2 -2
  4. package/dist/client/binary-send.d.ts +28 -0
  5. package/dist/client/binary-send.d.ts.map +1 -0
  6. package/dist/client/binary-send.js +26 -0
  7. package/dist/client/binary-send.js.map +1 -0
  8. package/dist/client/client.d.ts +46 -6
  9. package/dist/client/client.d.ts.map +1 -1
  10. package/dist/client/client.js +181 -66
  11. package/dist/client/client.js.map +1 -1
  12. package/dist/client/content-adapter.d.ts +18 -0
  13. package/dist/client/content-adapter.d.ts.map +1 -1
  14. package/dist/client/content-adapter.js.map +1 -1
  15. package/dist/client/device-set-reconciliation.d.ts +23 -8
  16. package/dist/client/device-set-reconciliation.d.ts.map +1 -1
  17. package/dist/client/device-set-reconciliation.js +25 -11
  18. package/dist/client/device-set-reconciliation.js.map +1 -1
  19. package/dist/client/event-hooks.d.ts +88 -8
  20. package/dist/client/event-hooks.d.ts.map +1 -1
  21. package/dist/client/event-hooks.js +1 -0
  22. package/dist/client/event-hooks.js.map +1 -1
  23. package/dist/client/group-outbox.d.ts +45 -10
  24. package/dist/client/group-outbox.d.ts.map +1 -1
  25. package/dist/client/group-outbox.js +246 -154
  26. package/dist/client/group-outbox.js.map +1 -1
  27. package/dist/client/group-receive-authorization.d.ts +10 -1
  28. package/dist/client/group-receive-authorization.d.ts.map +1 -1
  29. package/dist/client/group-receive-authorization.js.map +1 -1
  30. package/dist/client/hosted-anonymous-delivery.d.ts +18 -1
  31. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  32. package/dist/client/hosted-anonymous-delivery.js +84 -12
  33. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  34. package/dist/client/hosted-connection.js +1 -1
  35. package/dist/client/hosted-connection.js.map +1 -1
  36. package/dist/client/hosted-group-authority.d.ts +6 -2
  37. package/dist/client/hosted-group-authority.d.ts.map +1 -1
  38. package/dist/client/hosted-group-authority.js +11 -7
  39. package/dist/client/hosted-group-authority.js.map +1 -1
  40. package/dist/client/hosted-groups.d.ts +5 -1
  41. package/dist/client/hosted-groups.d.ts.map +1 -1
  42. package/dist/client/hosted-groups.js +8 -4
  43. package/dist/client/hosted-groups.js.map +1 -1
  44. package/dist/client/hosted-http-error.d.ts +5 -1
  45. package/dist/client/hosted-http-error.d.ts.map +1 -1
  46. package/dist/client/hosted-http-error.js +5 -1
  47. package/dist/client/hosted-http-error.js.map +1 -1
  48. package/dist/client/hosted-mailbox-subscription.d.ts +2 -0
  49. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  50. package/dist/client/hosted-mailbox-subscription.js +5 -5
  51. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  52. package/dist/client/hosted-transport.d.ts +11 -1
  53. package/dist/client/hosted-transport.d.ts.map +1 -1
  54. package/dist/client/hosted-transport.js +75 -30
  55. package/dist/client/hosted-transport.js.map +1 -1
  56. package/dist/client/hosted.d.ts.map +1 -1
  57. package/dist/client/hosted.js +1 -1
  58. package/dist/client/hosted.js.map +1 -1
  59. package/dist/client/index.d.ts +1 -1
  60. package/dist/client/index.d.ts.map +1 -1
  61. package/dist/client/index.js.map +1 -1
  62. package/dist/client/receive-queue.d.ts +5 -2
  63. package/dist/client/receive-queue.d.ts.map +1 -1
  64. package/dist/client/receive-queue.js +55 -18
  65. package/dist/client/receive-queue.js.map +1 -1
  66. package/dist/client/relay-acceptance.d.ts +49 -6
  67. package/dist/client/relay-acceptance.d.ts.map +1 -1
  68. package/dist/client/relay-acceptance.js +49 -3
  69. package/dist/client/relay-acceptance.js.map +1 -1
  70. package/dist/client/relay-protocol.d.ts +37 -7
  71. package/dist/client/relay-protocol.d.ts.map +1 -1
  72. package/dist/client/relay-protocol.js +53 -10
  73. package/dist/client/relay-protocol.js.map +1 -1
  74. package/dist/client/retry-family.d.ts +3 -3
  75. package/dist/client/retry-family.js +1 -1
  76. package/dist/client/retry-family.js.map +1 -1
  77. package/dist/client/retry-request-envelope.d.ts +18 -8
  78. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  79. package/dist/client/retry-request-envelope.js +57 -29
  80. package/dist/client/retry-request-envelope.js.map +1 -1
  81. package/dist/client/retry-request-lifecycle.d.ts +24 -11
  82. package/dist/client/retry-request-lifecycle.d.ts.map +1 -1
  83. package/dist/client/retry-request-lifecycle.js +46 -20
  84. package/dist/client/retry-request-lifecycle.js.map +1 -1
  85. package/dist/client/retry-terminal-recovery.d.ts +11 -8
  86. package/dist/client/retry-terminal-recovery.d.ts.map +1 -1
  87. package/dist/client/retry-terminal-recovery.js +18 -12
  88. package/dist/client/retry-terminal-recovery.js.map +1 -1
  89. package/dist/client/retry.d.ts +8 -7
  90. package/dist/client/retry.d.ts.map +1 -1
  91. package/dist/client/retry.js +30 -22
  92. package/dist/client/retry.js.map +1 -1
  93. package/dist/client/send-deadline.d.ts +308 -0
  94. package/dist/client/send-deadline.d.ts.map +1 -0
  95. package/dist/client/send-deadline.js +914 -0
  96. package/dist/client/send-deadline.js.map +1 -0
  97. package/dist/client/send-intent-driver.d.ts +116 -0
  98. package/dist/client/send-intent-driver.d.ts.map +1 -0
  99. package/dist/client/send-intent-driver.js +373 -0
  100. package/dist/client/send-intent-driver.js.map +1 -0
  101. package/dist/client/signal-service-cipher.d.ts +257 -27
  102. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  103. package/dist/client/signal-service-cipher.js +1274 -283
  104. package/dist/client/signal-service-cipher.js.map +1 -1
  105. package/dist/client/types.d.ts +48 -5
  106. package/dist/client/types.d.ts.map +1 -1
  107. package/dist/client/types.js.map +1 -1
  108. package/dist/index.d.ts +1 -1
  109. package/dist/index.d.ts.map +1 -1
  110. package/dist/index.js.map +1 -1
  111. package/dist/local/store/conformance/cases/metadata.d.ts +3 -2
  112. package/dist/local/store/conformance/cases/metadata.d.ts.map +1 -1
  113. package/dist/local/store/conformance/cases/metadata.js +153 -2
  114. package/dist/local/store/conformance/cases/metadata.js.map +1 -1
  115. package/dist/local/store/key-value/adapter.d.ts +2 -1
  116. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  117. package/dist/local/store/key-value/adapter.js +9 -0
  118. package/dist/local/store/key-value/adapter.js.map +1 -1
  119. package/dist/local/store/memory/adapter.d.ts +2 -1
  120. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  121. package/dist/local/store/memory/adapter.js +4 -0
  122. package/dist/local/store/memory/adapter.js.map +1 -1
  123. package/dist/local/store/metadata-keys.d.ts +13 -0
  124. package/dist/local/store/metadata-keys.d.ts.map +1 -0
  125. package/dist/local/store/metadata-keys.js +20 -0
  126. package/dist/local/store/metadata-keys.js.map +1 -0
  127. package/dist/local/store/receive-work.d.ts.map +1 -1
  128. package/dist/local/store/receive-work.js +12 -1
  129. package/dist/local/store/receive-work.js.map +1 -1
  130. package/dist/local/store/reliability.d.ts +482 -33
  131. package/dist/local/store/reliability.d.ts.map +1 -1
  132. package/dist/local/store/reliability.js +690 -48
  133. package/dist/local/store/reliability.js.map +1 -1
  134. package/dist/local/store/sqlite/key-storage/index.d.ts +2 -1
  135. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
  136. package/dist/local/store/sqlite/key-storage/index.js +3 -0
  137. package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
  138. package/dist/local/store/sqlite/key-storage/metadata.d.ts +9 -0
  139. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  140. package/dist/local/store/sqlite/key-storage/metadata.js +12 -0
  141. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  142. package/dist/local/store/sqlite/store.d.ts +2 -1
  143. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  144. package/dist/local/store/sqlite/store.js +3 -0
  145. package/dist/local/store/sqlite/store.js.map +1 -1
  146. package/dist/local/store/web/adapter.d.ts +8 -1
  147. package/dist/local/store/web/adapter.d.ts.map +1 -1
  148. package/dist/local/store/web/adapter.js +18 -0
  149. package/dist/local/store/web/adapter.js.map +1 -1
  150. package/dist/remote/relay/request-admission.d.ts +49 -0
  151. package/dist/remote/relay/request-admission.d.ts.map +1 -0
  152. package/dist/remote/relay/request-admission.js +74 -0
  153. package/dist/remote/relay/request-admission.js.map +1 -0
  154. package/dist/types/api.d.ts +77 -0
  155. package/dist/types/api.d.ts.map +1 -1
  156. package/dist/types/errors.d.ts +144 -1
  157. package/dist/types/errors.d.ts.map +1 -1
  158. package/dist/types/errors.js +146 -1
  159. package/dist/types/errors.js.map +1 -1
  160. package/docs/ASSURANCE.md +5 -5
  161. package/docs/DEVIATIONS.md +34 -4
  162. package/docs/ERROR_HANDLING.md +134 -7
  163. package/package.json +1 -1
@@ -0,0 +1,914 @@
1
+ import { deviceSetRefusal } from '../remote/relay/device-set.js';
2
+ import { followedRepeatedRequest } from '../remote/relay/request-admission.js';
3
+ import { outgoingDestinationProgressKey, outgoingMessageDeadlineAt, outgoingMessageIntentResult, } from '../local/store/reliability.js';
4
+ import { SealedSenderAuthError, SendAcceptanceUnknownError, SendNeverAcceptedByRelayError, } from '../types/errors.js';
5
+ import { conflictAcceptance, isConflictAcceptance, relayHoldsMessageId, relayOperationRefusal, } from './relay-acceptance.js';
6
+ import { markRelayDeviceRefusal, relayDeviceRefusal } from './relay-device-refusal.js';
7
+ /**
8
+ * The posting deadline of a direct or group send: the time after which the
9
+ * SDK starts no relay request for the send, and the classification of the
10
+ * send when it ends at that time.
11
+ *
12
+ * The outbox stores the deadline with the intent (`deadlineAt`). Each post
13
+ * of the send checks it before each request, also before a transport repeat
14
+ * and before the identified fallback of a sealed post. The outbox also
15
+ * stores the progress of each destination: the requests that started for
16
+ * it and the class of its last answer. The evidence of one `send()` call
17
+ * records each answer that a request of the call got, and writes it to the
18
+ * stored progress. A destination is one device under the client message ID
19
+ * of its posts, so a pre-message and the group message of one device are
20
+ * two destinations. When an open destination remains at the deadline, or
21
+ * when every open destination got OPERATION_EXPIRED in the call or has a
22
+ * stored refusal that the SDK cannot recover, the send ends, and the stored
23
+ * progress decides its class.
24
+ *
25
+ * No package entry exports this module.
26
+ */
27
+ /** The internal error of a request that the posting deadline refused. */
28
+ export class PostingDeadlineReachedError extends Error {
29
+ deadlineAt;
30
+ name = 'PostingDeadlineReachedError';
31
+ constructor(deadlineAt) {
32
+ super('The posting deadline of the send ended before the request');
33
+ this.deadlineAt = deadlineAt;
34
+ }
35
+ }
36
+ /** True when the posting deadline refused the request. */
37
+ export function isPostingDeadlineReached(error) {
38
+ return error instanceof PostingDeadlineReachedError;
39
+ }
40
+ /**
41
+ * The check that each request of a send meets before it starts. It rejects
42
+ * with `PostingDeadlineReachedError` at or after the deadline.
43
+ */
44
+ export function postingDeadlineCheck(deadlineAt, clock) {
45
+ return async () => {
46
+ if (clock() >= deadlineAt)
47
+ throw new PostingDeadlineReachedError(deadlineAt);
48
+ };
49
+ }
50
+ /**
51
+ * Record whether the posting deadline refused a request of one post. The
52
+ * returned check runs the deadline check and records its refusal.
53
+ */
54
+ export function recordDeadlineStop(check) {
55
+ let stopped = false;
56
+ return {
57
+ check: async () => {
58
+ try {
59
+ await check?.();
60
+ }
61
+ catch (error) {
62
+ if (isPostingDeadlineReached(error))
63
+ stopped = true;
64
+ throw error;
65
+ }
66
+ },
67
+ stopped: () => stopped,
68
+ };
69
+ }
70
+ /** The order in which the destinations of one device decide its class. */
71
+ const DESTINATION_STATE_RANK = {
72
+ accepted: 0,
73
+ refused: 1,
74
+ unknown: 2,
75
+ };
76
+ /** The codes of a refusal of one request. The Relay did not store the post. */
77
+ const REFUSAL_CODES = new Set([
78
+ 'STALE_DEVICE',
79
+ 'NOT_FOUND',
80
+ 'TOKEN_INVALID',
81
+ 'AUTHORITY_DENIED',
82
+ 'SCOPE_MISMATCH',
83
+ ]);
84
+ /** The codes of a refusal for now. The post can succeed later. */
85
+ const PENDING_CODES = new Set([
86
+ 'MAILBOX_FULL',
87
+ 'QUOTA_EXCEEDED',
88
+ 'DEPLOYMENT_SUSPENDED',
89
+ 'PROTOCOL_UNSUPPORTED',
90
+ ]);
91
+ /**
92
+ * The codes of an error that keeps its own retry rule. The answer ends the
93
+ * send at once as a terminal failure (contract C-7): no later request of
94
+ * this SDK can change it.
95
+ */
96
+ const OWN_RETRY_CODES = new Set(['UPGRADE_REQUIRED', 'DEVICE_REVOKED']);
97
+ /**
98
+ * The stored refusal codes that no recovery in a send call can change. A
99
+ * replay does not post a device that has one of them. Each other refused
100
+ * code counts only when the entry records a spent recovery.
101
+ */
102
+ const TERMINAL_REFUSAL_CODES = new Set([
103
+ 'NOT_FOUND',
104
+ 'TOKEN_INVALID',
105
+ 'AUTHORITY_DENIED',
106
+ 'SCOPE_MISMATCH',
107
+ 'OPERATION_EXPIRED',
108
+ 'UPGRADE_REQUIRED',
109
+ 'DEVICE_REVOKED',
110
+ ]);
111
+ /**
112
+ * True when the stored entry proves that the Relay refused every request of
113
+ * the destination, and that no recovery in a send call can change the
114
+ * refusal: the entry is `refused` with no uncertain request, and its code
115
+ * is terminal or its recovery already ran and the Relay refused the repost.
116
+ */
117
+ export function provenRefused(entry) {
118
+ return (entry?.state === 'refused' &&
119
+ entry.uncertain !== true &&
120
+ ((entry.refusalCode !== undefined && TERMINAL_REFUSAL_CODES.has(entry.refusalCode)) ||
121
+ entry.repairSpent === true));
122
+ }
123
+ /**
124
+ * The acceptance of a destination that a stored entry records. The call got
125
+ * no receipt for it, so it counts as a conflict acceptance: it carries the
126
+ * stored Relay message ID when there is one, and no device-set mark.
127
+ */
128
+ export function storedAcceptance(entry, clock) {
129
+ const acceptance = conflictAcceptance(entry.messageId ?? entry.postMessageId, entry.enqueuedAt ?? clock());
130
+ if (entry.expiresAt !== undefined)
131
+ acceptance.expiresAt = entry.expiresAt;
132
+ if (entry.duplicate)
133
+ acceptance.duplicate = true;
134
+ return acceptance;
135
+ }
136
+ /** The stored fields of an accepted answer. A conflict acceptance has no receipt. */
137
+ function acceptedAnswer(acceptance) {
138
+ const receipt = isConflictAcceptance(acceptance) ? undefined : acceptance;
139
+ return {
140
+ answer: 'accepted',
141
+ enqueuedAt: acceptance.serverTimestamp,
142
+ ...(receipt && { messageId: receipt.messageId }),
143
+ ...(receipt?.expiresAt !== undefined && { expiresAt: receipt.expiresAt }),
144
+ ...(receipt?.duplicate === true && { duplicate: true }),
145
+ };
146
+ }
147
+ function deviceKey(device) {
148
+ return `${device.userId}\u0000${String(device.deviceId)}`;
149
+ }
150
+ function destinationKey({ device, postMessageId }) {
151
+ return outgoingDestinationProgressKey(postMessageId, device);
152
+ }
153
+ function sendDevice(device) {
154
+ return { userId: device.userId, deviceId: device.deviceId };
155
+ }
156
+ function errorCode(error) {
157
+ const { code, data } = error;
158
+ if (typeof code === 'string')
159
+ return code;
160
+ return data !== null && typeof data === 'object' ? data.code : undefined;
161
+ }
162
+ /**
163
+ * The evidence of one `send()` call of a direct or group send: the requests
164
+ * and the answers of each destination in the call, and the stored progress
165
+ * of each destination when the call started.
166
+ */
167
+ export class SendCallEvidence {
168
+ options;
169
+ /** The posting deadline check of each request of the call. */
170
+ check;
171
+ destinations = new Map();
172
+ firstRefusal;
173
+ lastError;
174
+ hasRefusal = false;
175
+ hasError = false;
176
+ /** The first UPGRADE_REQUIRED or DEVICE_REVOKED answer of the call. */
177
+ terminalAnswer;
178
+ constructor(options) {
179
+ this.options = options;
180
+ this.check = postingDeadlineCheck(options.deadlineAt, options.clock);
181
+ for (const [key, entry] of Object.entries(options.progress ?? {})) {
182
+ if (entry.phase === 'recipient')
183
+ this.evidenceAt(key).entry = entry;
184
+ }
185
+ }
186
+ get deadlineAt() {
187
+ return this.options.deadlineAt;
188
+ }
189
+ /**
190
+ * Take the stored entry of a device that a repair in this call returned.
191
+ * The entry names the client message ID of the repaired post. A later
192
+ * RETRY_CONFLICT of that destination reads its repair mark.
193
+ */
194
+ refreshEntry(device, entry) {
195
+ this.evidenceAt(destinationKey({ device, postMessageId: entry.postMessageId })).entry = entry;
196
+ }
197
+ /**
198
+ * Run one post of a destination, record its answer, and store the class
199
+ * of the answer. `post` gives `onRequest` to the control of the post,
200
+ * which calls it when a request starts, also for a transport repeat and
201
+ * the identified fallback. A RETRY_CONFLICT, or a version 2
202
+ * DELIVERY_ALREADY_ACCEPTED, resolves the post as accepted when no repair
203
+ * replaced the message of the destination. A
204
+ * message that the stored progress records as accepted is not posted
205
+ * again: the post resolves with the stored acceptance. The post resolves
206
+ * only when the destination is accepted. Each other answer rejects.
207
+ */
208
+ async post(destination, post) {
209
+ const key = destinationKey(destination);
210
+ const evidence = this.evidenceAt(key);
211
+ if (evidence.entry?.state === 'accepted') {
212
+ return storedAcceptance(evidence.entry, this.options.clock);
213
+ }
214
+ const stored = {
215
+ phase: 'recipient',
216
+ userId: destination.device.userId,
217
+ deviceId: destination.device.deviceId,
218
+ postMessageId: destination.postMessageId,
219
+ };
220
+ let requests = 0;
221
+ let acceptance;
222
+ try {
223
+ acceptance = await post((repeat) => {
224
+ requests += 1;
225
+ evidence.requests += 1;
226
+ // The first request can have stored the post before the repeat.
227
+ if (repeat === 'uncertain')
228
+ evidence.uncertainRepeat = true;
229
+ });
230
+ }
231
+ catch (error) {
232
+ // A post that started no request is no evidence. The deadline check
233
+ // rejects before its request starts.
234
+ if (requests === 0)
235
+ throw error;
236
+ const answer = this.classifyAnswer(evidence.entry, error);
237
+ if (answer === 'accepted') {
238
+ const conflict = conflictAcceptance(destination.postMessageId, this.options.clock());
239
+ this.accept(evidence, conflict);
240
+ await this.options.recordProgress?.(key, { ...stored, ...acceptedAnswer(conflict) });
241
+ return conflict;
242
+ }
243
+ evidence.answers.push(answer);
244
+ evidence.expired = relayOperationRefusal(error) === 'OPERATION_EXPIRED';
245
+ this.keepTerminalAnswer(error);
246
+ if (answer === 'refused' && !this.hasRefusal) {
247
+ this.hasRefusal = true;
248
+ this.firstRefusal = error;
249
+ }
250
+ this.hasError = true;
251
+ this.lastError = error;
252
+ await this.options.recordProgress?.(key, {
253
+ ...stored,
254
+ ...storedAnswer(answer, error, this.options),
255
+ });
256
+ throw error;
257
+ }
258
+ this.accept(evidence, acceptance);
259
+ await this.options.recordProgress?.(key, { ...stored, ...acceptedAnswer(acceptance) });
260
+ return acceptance;
261
+ }
262
+ /**
263
+ * Run one shared post of the destinations of a group body, and record its
264
+ * one answer on each destination. `post` gives `onRequest` to the control
265
+ * of the post, and each request counts for each destination. When the
266
+ * stored progress records each destination as accepted, the body is not
267
+ * posted again.
268
+ *
269
+ * - A receipt accepts each destination, except each destination of a user
270
+ * in `uuids404` and each destination that `refusals` names. Those are
271
+ * refused, as a thrown refusal of the post refuses its destination, and
272
+ * the first one gives the terminal error of a failed end. The count
273
+ * `refusedDestinationCount` names no device, so it refuses no
274
+ * destination.
275
+ * - A RETRY_CONFLICT, or a version 2 DELIVERY_ALREADY_ACCEPTED, accepts
276
+ * each destination whose current entry has no repair mark, and it resolves the post with a conflict
277
+ * acceptance when each destination is accepted. A destination with a
278
+ * repair mark is uncertain, and the post rejects.
279
+ * - Each other answer gives its class to each destination, so after
280
+ * OPERATION_EXPIRED each destination is expired.
281
+ */
282
+ async postShared(destinations, post) {
283
+ const targets = destinations.map((destination) => {
284
+ const key = destinationKey(destination);
285
+ return {
286
+ destination,
287
+ key,
288
+ evidence: this.evidenceAt(key),
289
+ stored: {
290
+ phase: 'recipient',
291
+ userId: destination.device.userId,
292
+ deviceId: destination.device.deviceId,
293
+ postMessageId: destination.postMessageId,
294
+ },
295
+ };
296
+ });
297
+ const storedEntries = targets.map(({ evidence }) => evidence.entry);
298
+ // Only a body whose destinations are all stored as accepted stays
299
+ // unposted. The receipt writes one entry at a time, so a crash between
300
+ // them can leave some destinations accepted. The body is sealed for every
301
+ // recipient and cannot go to a subset, so the replay posts it again to
302
+ // each destination, and the Relay answers an accepted one from its dedup
303
+ // record. Only the request count and the bytes of the replay grow.
304
+ if (storedEntries.length > 0 && storedEntries.every((entry) => entry?.state === 'accepted')) {
305
+ // The same object keeps the conflict mark of a stored acceptance.
306
+ return Object.assign(storedAcceptance(storedEntries[0], this.options.clock), {
307
+ uuids404: [],
308
+ });
309
+ }
310
+ let requests = 0;
311
+ let result;
312
+ try {
313
+ result = await post((repeat) => {
314
+ requests += 1;
315
+ for (const { evidence } of targets) {
316
+ evidence.requests += 1;
317
+ if (repeat === 'uncertain')
318
+ evidence.uncertainRepeat = true;
319
+ }
320
+ });
321
+ }
322
+ catch (error) {
323
+ if (requests === 0)
324
+ throw error;
325
+ const expired = relayOperationRefusal(error) === 'OPERATION_EXPIRED';
326
+ const conflict = conflictAcceptance(this.options.clientMessageId, this.options.clock());
327
+ let accepted = 0;
328
+ for (const target of targets) {
329
+ const answer = this.classifyAnswer(target.evidence.entry, error);
330
+ if (answer === 'accepted') {
331
+ accepted += 1;
332
+ this.accept(target.evidence, conflict);
333
+ await this.options.recordProgress?.(target.key, {
334
+ ...target.stored,
335
+ ...acceptedAnswer(conflict),
336
+ });
337
+ continue;
338
+ }
339
+ target.evidence.answers.push(answer);
340
+ target.evidence.expired = expired;
341
+ this.keepTerminalAnswer(error);
342
+ if (answer === 'refused' && !this.hasRefusal) {
343
+ this.hasRefusal = true;
344
+ this.firstRefusal = error;
345
+ }
346
+ await this.options.recordProgress?.(target.key, {
347
+ ...target.stored,
348
+ ...storedAnswer(answer, error, this.options),
349
+ });
350
+ }
351
+ if (accepted === targets.length) {
352
+ // The same object keeps the conflict mark.
353
+ return Object.assign(conflict, { uuids404: [] });
354
+ }
355
+ this.hasError = true;
356
+ this.lastError = error;
357
+ throw error;
358
+ }
359
+ const missing = new Set(result.uuids404);
360
+ const refusals = new Map((result.refusals ?? []).map((refusal) => [deviceKey(refusal), refusal.code]));
361
+ for (const target of targets) {
362
+ const { device } = target.destination;
363
+ const code = missing.has(device.userId) ? 'NOT_FOUND' : refusals.get(deviceKey(device));
364
+ if (code === undefined) {
365
+ this.accept(target.evidence, result);
366
+ await this.options.recordProgress?.(target.key, {
367
+ ...target.stored,
368
+ ...acceptedAnswer(result),
369
+ });
370
+ continue;
371
+ }
372
+ target.evidence.answers.push('refused');
373
+ target.evidence.expired = code === 'OPERATION_EXPIRED';
374
+ if (!this.hasRefusal) {
375
+ this.hasRefusal = true;
376
+ this.firstRefusal = receiptRefusal(device, code);
377
+ }
378
+ await this.options.recordProgress?.(target.key, {
379
+ ...target.stored,
380
+ answer: 'refused',
381
+ refusalCode: code,
382
+ });
383
+ }
384
+ return result;
385
+ }
386
+ /**
387
+ * Run one sync copy of the send to an own device, and store its progress
388
+ * under the device key `destination`. A sync entry never counts for the
389
+ * end of the send. A copy that the stored progress records as accepted is
390
+ * not posted again.
391
+ *
392
+ * `post` gets the gate of each request of the copy, by the client message
393
+ * ID of the copy that the request posts. A copy with no client message ID
394
+ * gets its gate by `undefined`, and its request is stored under the sync
395
+ * ID of `destination`. The gate runs `check`, then stores the request.
396
+ * After the copy settles, its answer is stored. An undefined result means
397
+ * that the device refused the copy and its repair, and the copy left the
398
+ * intent.
399
+ */
400
+ async postSync(destination, check, post) {
401
+ const key = outgoingDestinationProgressKey(destination.postMessageId, destination.device);
402
+ let entry = this.options.progress?.[key];
403
+ if (entry?.state === 'accepted')
404
+ return storedAcceptance(entry, this.options.clock);
405
+ let postMessageId = destination.postMessageId;
406
+ let requests = 0;
407
+ const stored = () => ({
408
+ phase: 'sync',
409
+ userId: destination.device.userId,
410
+ deviceId: destination.device.deviceId,
411
+ postMessageId,
412
+ });
413
+ const gate = (copy) => async () => {
414
+ await check();
415
+ postMessageId = copy ?? destination.postMessageId;
416
+ entry =
417
+ (await this.options.recordProgress?.(key, { ...stored(), request: true })) ?? entry;
418
+ requests += 1;
419
+ };
420
+ let acceptance;
421
+ try {
422
+ acceptance = await post(gate);
423
+ }
424
+ catch (error) {
425
+ if (requests === 0)
426
+ throw error;
427
+ const answer = this.classifyAnswer(entry, error);
428
+ if (answer === 'accepted') {
429
+ const conflict = conflictAcceptance(postMessageId, this.options.clock());
430
+ await this.options.recordProgress?.(key, { ...stored(), ...acceptedAnswer(conflict) });
431
+ return conflict;
432
+ }
433
+ await this.options.recordProgress?.(key, {
434
+ ...stored(),
435
+ ...storedAnswer(answer, error, this.options),
436
+ });
437
+ throw error;
438
+ }
439
+ await this.options.recordProgress?.(key, acceptance
440
+ ? { ...stored(), ...acceptedAnswer(acceptance) }
441
+ : {
442
+ ...stored(),
443
+ answer: 'refused',
444
+ refusalCode: 'device-rejection',
445
+ repairSpent: true,
446
+ });
447
+ return acceptance;
448
+ }
449
+ /**
450
+ * The end of the send at a classification point, or undefined when the
451
+ * send stays open. `progress` is the stored progress of the intent, read
452
+ * under the intent lock. The send ends when `isDue` holds for its open
453
+ * destinations: those with no acceptance in the call or in the stored
454
+ * progress (contract §3.4). The end is the one that `classify` gives.
455
+ */
456
+ end(destinations, progress = {}) {
457
+ const open = this.openDestinations(destinations, progress);
458
+ if (open.length === 0)
459
+ return undefined;
460
+ if (!this.isDue(open, progress))
461
+ return undefined;
462
+ return this.classify(destinations, progress);
463
+ }
464
+ /**
465
+ * The class of the send if it ended now (contract §3.4), or undefined when
466
+ * the call or the stored progress accepted each destination. Unlike `end`,
467
+ * it does not check that the send is due: the caller decides that the
468
+ * send ends. The error of a failed end follows the rule of
469
+ * `failedEndError`. Its thrown refusal is the first UPGRADE_REQUIRED or
470
+ * DEVICE_REVOKED answer of this call, else the first refusal of this
471
+ * call, and its entries are the progress that the end stores.
472
+ */
473
+ classify(destinations, progress = {}) {
474
+ const entryOf = (destination) => progress[destinationKey(destination)];
475
+ if (this.openDestinations(destinations, progress).length === 0)
476
+ return undefined;
477
+ // A device with more than one destination, such as a pre-message and a
478
+ // group message, is unknown when one of them is unknown, refused when one
479
+ // of them is refused, and accepted only when each of them is accepted.
480
+ const devices = new Map();
481
+ const destinationProgress = {};
482
+ for (const destination of destinations) {
483
+ const { device, postMessageId } = destination;
484
+ const evidence = this.destinations.get(destinationKey(destination));
485
+ const entry = entryOf(destination);
486
+ const state = this.classifyDestination(evidence, entry);
487
+ const folded = devices.get(deviceKey(device));
488
+ if (!folded)
489
+ devices.set(deviceKey(device), { device: sendDevice(device), state });
490
+ else if (DESTINATION_STATE_RANK[state] > DESTINATION_STATE_RANK[folded.state]) {
491
+ folded.state = state;
492
+ }
493
+ const acceptance = evidence?.acceptance;
494
+ const receipt = acceptance && !isConflictAcceptance(acceptance) ? acceptance : undefined;
495
+ destinationProgress[outgoingDestinationProgressKey(postMessageId, device)] = {
496
+ ...entry,
497
+ phase: 'recipient',
498
+ userId: device.userId,
499
+ deviceId: device.deviceId,
500
+ postMessageId,
501
+ state,
502
+ requests: Math.max(entry?.requests ?? 0, evidence?.requests ?? 0),
503
+ ...((entry?.uncertain ||
504
+ evidence?.uncertainRepeat ||
505
+ evidence?.answers.includes('uncertain')) && {
506
+ uncertain: true,
507
+ }),
508
+ ...(receipt && { messageId: receipt.messageId }),
509
+ ...(receipt?.expiresAt !== undefined && { expiresAt: receipt.expiresAt }),
510
+ ...(receipt?.duplicate === true && { duplicate: true }),
511
+ };
512
+ }
513
+ const devicesIn = (state) => [...devices.values()].filter((folded) => folded.state === state).map(({ device }) => device);
514
+ const accepted = devicesIn('accepted');
515
+ const unknown = devicesIn('unknown');
516
+ const refused = devicesIn('refused');
517
+ const details = {
518
+ clientMessageId: this.options.clientMessageId,
519
+ deadlineAt: this.options.deadlineAt,
520
+ acceptedDevices: accepted,
521
+ refusedDevices: refused,
522
+ };
523
+ if (unknown.length > 0) {
524
+ return {
525
+ outcome: 'acceptance-unknown',
526
+ destinationProgress,
527
+ error: new SendAcceptanceUnknownError({
528
+ ...details,
529
+ unknownDevices: unknown,
530
+ ...(this.hasError && { cause: this.lastError }),
531
+ }),
532
+ };
533
+ }
534
+ return {
535
+ outcome: 'failed',
536
+ destinationProgress,
537
+ error: failedEndError(destinations.map(({ device, postMessageId }) => destinationProgress[outgoingDestinationProgressKey(postMessageId, device)]), details, this.terminalAnswer ?? (this.hasRefusal ? this.firstRefusal : undefined)),
538
+ };
539
+ }
540
+ /** The destinations with no acceptance in the call or in `progress`. */
541
+ openDestinations(destinations, progress) {
542
+ return destinations.filter((destination) => this.destinations.get(destinationKey(destination))?.acceptance === undefined &&
543
+ progress[destinationKey(destination)]?.state !== 'accepted');
544
+ }
545
+ /** Keep the first UPGRADE_REQUIRED or DEVICE_REVOKED answer of the call. */
546
+ keepTerminalAnswer(error) {
547
+ if (this.terminalAnswer !== undefined)
548
+ return;
549
+ if (!(error instanceof Error))
550
+ return;
551
+ const code = errorCode(error);
552
+ if (typeof code === 'string' && OWN_RETRY_CODES.has(code))
553
+ this.terminalAnswer = error;
554
+ }
555
+ /**
556
+ * True when the send ends now: at or after the deadline, after an
557
+ * UPGRADE_REQUIRED or DEVICE_REVOKED answer in this call, or when each
558
+ * open destination got OPERATION_EXPIRED as the last answer in this call
559
+ * or has a stored refusal that no recovery in a call can change.
560
+ */
561
+ isDue(open, progress) {
562
+ if (this.options.clock() >= this.options.deadlineAt)
563
+ return true;
564
+ if (this.terminalAnswer !== undefined)
565
+ return true;
566
+ return open.every((destination) => this.destinations.get(destinationKey(destination))?.expired === true ||
567
+ provenRefused(progress[destinationKey(destination)]));
568
+ }
569
+ evidenceAt(key) {
570
+ let evidence = this.destinations.get(key);
571
+ if (!evidence) {
572
+ evidence = { requests: 0, answers: [], expired: false, uncertainRepeat: false };
573
+ this.destinations.set(key, evidence);
574
+ }
575
+ return evidence;
576
+ }
577
+ accept(evidence, acceptance) {
578
+ evidence.answers.push('accepted');
579
+ evidence.expired = false;
580
+ evidence.acceptance ??= acceptance;
581
+ }
582
+ /**
583
+ * The class of the answer to one post that started a request (contract
584
+ * §3.5). An answer that followed a repeat after an uncertain answer is
585
+ * uncertain, because the first request can have stored the post. A
586
+ * RETRY_CONFLICT is an earlier acceptance only when the current entry of
587
+ * the destination has no repair mark: then the Relay holds the same bytes
588
+ * under the message ID. A version 2 DELIVERY_ALREADY_ACCEPTED says that
589
+ * the Relay holds an accepted post under the message ID, and it follows
590
+ * the same rule. An intent that did not write progress from its start can
591
+ * have had a repair that left no mark, so its answer stays uncertain.
592
+ */
593
+ classifyAnswer(entry, error) {
594
+ if (followedRepeatedRequest(error))
595
+ return 'uncertain';
596
+ if (relayHoldsMessageId(error)) {
597
+ return this.options.progressFromStart && !entry?.repaired
598
+ ? 'accepted'
599
+ : 'uncertain';
600
+ }
601
+ if (error === null || typeof error !== 'object')
602
+ return 'uncertain';
603
+ if (relayOperationRefusal(error) === 'OPERATION_EXPIRED' ||
604
+ deviceSetRefusal(error) !== undefined ||
605
+ relayDeviceRefusal(error) !== undefined ||
606
+ error instanceof SealedSenderAuthError ||
607
+ this.options.refusesDevice?.(error) === true) {
608
+ return 'refused';
609
+ }
610
+ const code = errorCode(error);
611
+ if (typeof code === 'string' && REFUSAL_CODES.has(code))
612
+ return 'refused';
613
+ // The Relay refused the request for this SDK or this device, so it did
614
+ // not store the post.
615
+ if (typeof code === 'string' && OWN_RETRY_CODES.has(code))
616
+ return 'refused';
617
+ const { status } = error;
618
+ if (status === 423 || status === 429)
619
+ return 'pending';
620
+ if (typeof code === 'string' && PENDING_CODES.has(code))
621
+ return 'pending';
622
+ return 'uncertain';
623
+ }
624
+ /**
625
+ * The class of a destination at the end (contract §3.4), from its stored
626
+ * entry and the acceptance of this call. An `accepted` entry is accepted.
627
+ * A destination is refused, so never accepted, when its stored entry is
628
+ * `refused` or `pending`, or has no request, with no uncertain request.
629
+ * The Relay gives a pending answer before it stores the post, so that
630
+ * answer also proves that the request was not accepted. A destination
631
+ * with no entry had no request when the intent wrote progress from its
632
+ * start. Each other destination is unknown: a request with no answer, an
633
+ * uncertain answer, and every entry with the uncertain flag.
634
+ */
635
+ classifyDestination(evidence, entry) {
636
+ if (evidence?.acceptance || entry?.state === 'accepted')
637
+ return 'accepted';
638
+ if (!entry)
639
+ return this.options.progressFromStart ? 'refused' : 'unknown';
640
+ if (entry.uncertain)
641
+ return 'unknown';
642
+ return entry.state === 'refused' || entry.state === 'pending' || entry.requests === 0 ? 'refused' : 'unknown';
643
+ }
644
+ }
645
+ /**
646
+ * The error of a destination that the receipt of a shared post refused, or
647
+ * of the stored refusal that `failedEndError` reads. It carries the code of
648
+ * the refusal, as a thrown refusal does. A NOT_FOUND or STALE_DEVICE refusal
649
+ * also carries the refusal mark of its device.
650
+ */
651
+ function receiptRefusal(device, code) {
652
+ const error = Object.assign(new Error(`The Relay refused a destination of the send with ${code}`), { code });
653
+ if (code === 'NOT_FOUND' || code === 'STALE_DEVICE') {
654
+ markRelayDeviceRefusal(error, { code, userId: device.userId, deviceId: device.deviceId });
655
+ }
656
+ return error;
657
+ }
658
+ /** The stored answer of a refused, pending or uncertain answer to a post. */
659
+ function storedAnswer(answer, error, options) {
660
+ if (answer === 'pending')
661
+ return { answer: 'pending' };
662
+ if (answer === 'uncertain')
663
+ return { answer: 'unknown' };
664
+ const sealedAuth = error instanceof SealedSenderAuthError;
665
+ return {
666
+ answer: 'refused',
667
+ refusalCode: refusalCode(error, options.refusesDevice),
668
+ // A required sealed post has no identified fallback to recover it.
669
+ ...(sealedAuth && options.sealedSenderRequired && { repairSpent: true }),
670
+ };
671
+ }
672
+ /** The Relay code of a refusal, or the kind of a refusal with no Relay code. */
673
+ function refusalCode(error, refusesDevice) {
674
+ const operation = relayOperationRefusal(error);
675
+ if (operation !== undefined)
676
+ return operation;
677
+ if (deviceSetRefusal(error) !== undefined)
678
+ return 'device-set';
679
+ const device = relayDeviceRefusal(error);
680
+ if (device !== undefined)
681
+ return device.code;
682
+ if (error instanceof SealedSenderAuthError)
683
+ return 'sealed-sender-auth';
684
+ const code = error !== null && typeof error === 'object' ? errorCode(error) : undefined;
685
+ if (typeof code === 'string' && (REFUSAL_CODES.has(code) || OWN_RETRY_CODES.has(code))) {
686
+ return code;
687
+ }
688
+ if (refusesDevice?.(error) === true)
689
+ return 'device-rejection';
690
+ return undefined;
691
+ }
692
+ /** The destinations of the device messages of a direct intent. */
693
+ export function sendDestinations(clientMessageId, messages) {
694
+ return messages.map((message) => ({
695
+ device: { userId: message.recipientUserId, deviceId: message.recipientDeviceId },
696
+ postMessageId: message.clientMessageId ?? clientMessageId,
697
+ }));
698
+ }
699
+ /**
700
+ * The error of a replay of an ended send. The replay reads the stored end
701
+ * and starts no request.
702
+ *
703
+ * An `acceptance-unknown` end gives `SendAcceptanceUnknownError`. A `failed`
704
+ * end gives the error of `failedEndError` with no thrown refusal, from the
705
+ * stored entries in the order of the destinations.
706
+ */
707
+ export function storedSendEndError(intent) {
708
+ // The end stored the class of each destination of the intent. A device
709
+ // with more than one destination takes the class of highest rank, as at
710
+ // the end.
711
+ const devices = new Map();
712
+ const destinations = sendDestinations(intent.clientMessageId, [
713
+ ...(intent.preMessages ?? []),
714
+ ...intent.deviceMessages,
715
+ ]);
716
+ const entries = [];
717
+ for (const destination of destinations) {
718
+ const entry = intent.destinationProgress?.[destinationKey(destination)];
719
+ if (entry?.phase !== 'recipient')
720
+ continue;
721
+ entries.push(entry);
722
+ const state = storedDestinationState(entry.state);
723
+ const folded = devices.get(deviceKey(entry));
724
+ if (!folded)
725
+ devices.set(deviceKey(entry), { device: sendDevice(entry), state });
726
+ else if (DESTINATION_STATE_RANK[state] > DESTINATION_STATE_RANK[folded.state]) {
727
+ folded.state = state;
728
+ }
729
+ }
730
+ const devicesIn = (state) => [...devices.values()].filter((folded) => folded.state === state).map(({ device }) => device);
731
+ const deadlineAt = outgoingMessageDeadlineAt(intent);
732
+ const details = {
733
+ clientMessageId: intent.clientMessageId,
734
+ deadlineAt,
735
+ acceptedDevices: devicesIn('accepted'),
736
+ refusedDevices: devicesIn('refused'),
737
+ };
738
+ if (intent.outcome === 'acceptance-unknown') {
739
+ return new SendAcceptanceUnknownError({ ...details, unknownDevices: devicesIn('unknown') });
740
+ }
741
+ return failedEndError(entries, details);
742
+ }
743
+ /**
744
+ * The error of a failed end of a send. The end in the call
745
+ * (`SendCallEvidence.end`) and each replay of the stored end
746
+ * (`storedSendEndError`) use this one rule:
747
+ *
748
+ * 1. When a post of the call that ended the send threw a refusal, or the
749
+ * receipt of a shared body refused a destination, the first such refusal
750
+ * of the call is the error (`thrown`), even when a later post of the same
751
+ * call accepted that device. A replay has no thrown refusal.
752
+ * 2. Otherwise the first entry in the order of the destinations that is
753
+ * `refused` and has a stored `refusalCode` gives a generic refusal
754
+ * `Error` with that code (`receiptRefusal`). A NOT_FOUND or STALE_DEVICE
755
+ * code also gives the refusal mark of its device. The store clears the
756
+ * code when a later request or answer supersedes the refusal, and a code
757
+ * on an entry in another state does not count.
758
+ * 3. With no such entry, the error is `SendNeverAcceptedByRelayError`.
759
+ *
760
+ * The end stores the code of each refusal on the entry of its destination,
761
+ * so a replay gives the code that the call threw only when the thrown
762
+ * refusal is the first coded refusal in the order of the destinations. When
763
+ * the thrown refusal and that first stored refusal are different
764
+ * destinations, the call gives the thrown refusal and a replay gives the
765
+ * first stored refusal. A thrown refusal with no Relay code stores its kind
766
+ * (`device-set`, `sealed-sender-auth` or `device-rejection`), and a replay
767
+ * gives that kind as the `code` of a generic refusal `Error`. Each error has
768
+ * the fields of the end, and its `retryable` is false.
769
+ */
770
+ function failedEndError(entries, details, thrown) {
771
+ if (thrown !== undefined)
772
+ return attachTerminalFailure(thrown, details);
773
+ let firstRefusal;
774
+ for (const entry of entries) {
775
+ if (entry === undefined || entry.state !== 'refused')
776
+ continue;
777
+ if (entry.refusalCode !== undefined) {
778
+ firstRefusal ??= { device: sendDevice(entry), code: entry.refusalCode };
779
+ }
780
+ }
781
+ return firstRefusal
782
+ ? attachTerminalFailure(receiptRefusal(firstRefusal.device, firstRefusal.code), details)
783
+ : new SendNeverAcceptedByRelayError(details);
784
+ }
785
+ /**
786
+ * The class of a stored entry of an ended send. The end writes `accepted`,
787
+ * `refused` or `unknown` on each destination. The open states read as
788
+ * `classifyDestination` reads them: a `pending` entry proves that the Relay
789
+ * did not accept it, and a `posted` entry has no answer.
790
+ */
791
+ function storedDestinationState(state) {
792
+ if (state === 'accepted')
793
+ return 'accepted';
794
+ return state === 'refused' || state === 'pending' ? 'refused' : 'unknown';
795
+ }
796
+ function defineSendField(error, name, value) {
797
+ Object.defineProperty(error, name, {
798
+ value,
799
+ enumerable: true,
800
+ configurable: true,
801
+ writable: true,
802
+ });
803
+ }
804
+ /** Keep the Relay's own `retryable` hint in `relayRetryable`. */
805
+ function keepRelayRetryable(error) {
806
+ const { retryable, relayRetryable } = error;
807
+ if (relayRetryable === undefined && typeof retryable === 'boolean') {
808
+ defineSendField(error, 'relayRetryable', retryable);
809
+ }
810
+ }
811
+ /**
812
+ * Mark an error of a send that failed before its posting deadline. The send
813
+ * stays open, so a replay with the same `clientMessageId` before `deadlineAt`
814
+ * can post it: `retryable` is true. The Relay's own hint moves to
815
+ * `relayRetryable`. An error that keeps its own retry rule, such as
816
+ * UPGRADE_REQUIRED or DEVICE_REVOKED, does not change.
817
+ */
818
+ export function attachSendDeadline(error, deadlineAt) {
819
+ if (error === null || typeof error !== 'object')
820
+ return error;
821
+ if (error instanceof PostingDeadlineReachedError ||
822
+ error instanceof SendAcceptanceUnknownError ||
823
+ error instanceof SendNeverAcceptedByRelayError) {
824
+ return error;
825
+ }
826
+ const code = error.code;
827
+ if (typeof code === 'string' && OWN_RETRY_CODES.has(code))
828
+ return error;
829
+ keepRelayRetryable(error);
830
+ defineSendField(error, 'deadlineAt', deadlineAt);
831
+ defineSendField(error, 'retryable', true);
832
+ return error;
833
+ }
834
+ /**
835
+ * Mark the raw refusal of a send that ended at its posting deadline with no
836
+ * device of unknown acceptance. The error keeps its class, and `retryable`
837
+ * is false.
838
+ */
839
+ export function attachTerminalFailure(error, details) {
840
+ keepRelayRetryable(error);
841
+ defineSendField(error, 'acceptedDevices', details.acceptedDevices);
842
+ defineSendField(error, 'refusedDevices', details.refusedDevices);
843
+ defineSendField(error, 'deadlineAt', details.deadlineAt);
844
+ defineSendField(error, 'retryable', false);
845
+ return error;
846
+ }
847
+ /** The key of the end report mark of a send call. No package subpath exports it. */
848
+ export const SEND_END_REPORT = Symbol('sendEndReport');
849
+ /**
850
+ * The `onSendOutcome` event of an intent that ended or completed. A
851
+ * completed intent gives `completed` with its result, and an ended intent
852
+ * gives its outcome with the error that a replay of it throws.
853
+ */
854
+ export function sendOutcomeEvent(intent) {
855
+ const deadlineAt = outgoingMessageDeadlineAt(intent);
856
+ const result = outgoingMessageIntentResult(intent);
857
+ if (result) {
858
+ return {
859
+ clientMessageId: intent.clientMessageId,
860
+ outcome: 'completed',
861
+ deadlineAt,
862
+ result: { ...result, clientTimestamp: intent.clientTimestamp },
863
+ };
864
+ }
865
+ if (intent.outcome === undefined) {
866
+ throw new Error('An open outgoing message intent has no send outcome');
867
+ }
868
+ return {
869
+ clientMessageId: intent.clientMessageId,
870
+ outcome: intent.outcome,
871
+ deadlineAt,
872
+ error: storedSendEndError(intent),
873
+ };
874
+ }
875
+ /**
876
+ * A manual resend of an intent, read as an intent of its own: its device
877
+ * messages, its progress, its end and its posting deadline. It has no
878
+ * sync phase. `storedSendEndError` and `sendOutcomeEvent` read it as they
879
+ * read an intent.
880
+ */
881
+ export function manualResendIntent(intent, resend) {
882
+ const view = {
883
+ ...intent,
884
+ createdAt: resend.createdAt,
885
+ deadlineAt: resend.deadlineAt,
886
+ deviceMessages: resend.messages.map(({ message }) => message),
887
+ syncMessages: [],
888
+ progressFromStart: true,
889
+ };
890
+ delete view.manualResends;
891
+ delete view.preMessages;
892
+ delete view.syncPending;
893
+ delete view.outcomeReportPending;
894
+ delete view.destinationProgress;
895
+ delete view.result;
896
+ delete view.outcome;
897
+ if (resend.destinationProgress)
898
+ view.destinationProgress = resend.destinationProgress;
899
+ if (resend.result)
900
+ view.result = resend.result;
901
+ if (resend.outcome !== undefined)
902
+ view.outcome = resend.outcome;
903
+ return view;
904
+ }
905
+ /**
906
+ * The `onSendOutcome` event of a manual resend that ended. It carries the
907
+ * `clientMessageId` of the intent, the posting deadline of the resend, and
908
+ * `manualResend`, the number of the resend from 1.
909
+ */
910
+ export function manualResendOutcomeEvent(intent, resend) {
911
+ const number = Number(resend.manualMessageId.slice(resend.manualMessageId.lastIndexOf(':') + 1));
912
+ return { ...sendOutcomeEvent(manualResendIntent(intent, resend)), manualResend: number };
913
+ }
914
+ //# sourceMappingURL=send-deadline.js.map