@sparkvault/sdk-js 11.0.1 → 11.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,36 +2,670 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ /**
6
+ * Whether sending the SAME request again can succeed, read from its HTTP
7
+ * status: the one retry rule every client and every provider adapter applies.
8
+ *
9
+ * A retry rule restated beside every client drifts, and the copy that drifted
10
+ * decides whether a deliverable message is retried or abandoned, or whether a
11
+ * download is tried again. Each caller keeps its provider's own extras on top of
12
+ * this rule (a success body, a dead-token reason, a vendor error name).
13
+ *
14
+ * Browser-safe and import-free: sdk-js bundles it and sdk-mobile mirrors it.
15
+ */
16
+
17
+ /**
18
+ * Is this HTTP status one a retry of the same request can turn into a success?
19
+ *
20
+ * RFC 9110: 408 means the server never received the whole request, 429 that it
21
+ * throttled it, and a 5xx that it failed; every other status is the server's
22
+ * verdict on this exact request. A caller that got no response at all (a network
23
+ * error, a timeout) has no status to pass and decides that case itself.
24
+ *
25
+ * @param {number} status
26
+ * @returns {boolean}
27
+ */
28
+ function isTransientHttpStatus(status) {
29
+ return status === 408 || status === 429 || status >= 500;
30
+ }
31
+
32
+ /**
33
+ * The upload publication contract between Forge and Core's activation.
34
+ *
35
+ * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
36
+ * and on the final state it hands Core's activation (POST
37
+ * /v1/vaults/:vault_id/ingots/:ingot_id/activate); activation refuses any
38
+ * other version. The two services deploy separately, so a change to what
39
+ * either side sends or expects moves this number: a session or a finalize
40
+ * from the other side's contract then fails closed ("restart the upload")
41
+ * instead of publishing under a contract the other side does not hold.
42
+ *
43
+ * Version 2: an upload's own metadata (content type, original file name,
44
+ * uploader, content HMAC) travels on its upload token and its session, and
45
+ * activation publishes it from the session; the final state Forge sends
46
+ * carries only the storage facts Forge owns.
47
+ *
48
+ * Isomorphic: no Node imports.
49
+ */
50
+
51
+
52
+ /**
53
+ * The codes Core's activation refuses an upload with, which Forge's refusal
54
+ * map reads (the status is Core's):
55
+ * - UPLOAD_CONTRACT_MISMATCH (409): a finalize or session from another
56
+ * publication contract than Core's, a mixed deployment that converges — the
57
+ * upload is kept and its finalize tried again.
58
+ * - UPLOAD_PROTOCOL_RETIRED (410): a session from a contract Core no longer
59
+ * publishes, which never can be.
60
+ * - UPLOAD_SUPERSEDED (410): a session a later staging of its ingot
61
+ * superseded, which never can be.
62
+ * - UPLOAD_POOL_FULL (402): an upload the owner's storage pool cannot take at
63
+ * publication, which is final.
64
+ */
65
+ const UPLOAD_REFUSAL_CODES = Object.freeze({
66
+ UPLOAD_CONTRACT_MISMATCH: 'UPLOAD_CONTRACT_MISMATCH',
67
+ UPLOAD_PROTOCOL_RETIRED: 'UPLOAD_PROTOCOL_RETIRED',
68
+ UPLOAD_SUPERSEDED: 'UPLOAD_SUPERSEDED',
69
+ UPLOAD_POOL_FULL: 'UPLOAD_POOL_FULL'
70
+ });
71
+
72
+ /**
73
+ * The refusals of Core's that a new upload of the same file cannot remedy:
74
+ * the owner's storage pool cannot take it (UPLOAD_POOL_FULL), or a later
75
+ * upload of its ingot replaced it (UPLOAD_SUPERSEDED). Any other code Core
76
+ * ends an upload with ends its session alone, which a new upload starts
77
+ * over. Every client reads a terminal answer's code by it
78
+ * (transfer-retry.js): one of these is a refusal it reports in Core's words,
79
+ * any other a gone session.
80
+ */
81
+ const UPLOAD_FINAL_REFUSAL_CODES = Object.freeze([
82
+ UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL,
83
+ UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED
84
+ ]);
85
+
86
+ /**
87
+ * The response header that names the code Core refused an upload with for
88
+ * good: Forge sends it on every terminal answer to a tus request, a HEAD's
89
+ * (which has no body) included, so a client tells an upload the owner's pool
90
+ * cannot take from one a later upload superseded without reading a body.
91
+ */
92
+ const UPLOAD_REFUSAL_HEADER = 'X-Upload-Refusal';
93
+
94
+ /**
95
+ * The transfer retry policy: what every first-party client does with the
96
+ * answer to a Forge transfer request (a tus chunk PATCH, an offset HEAD, the
97
+ * receipt PATCH at the final offset), in one place, so the Node uploader
98
+ * (forge-tus), the browser SDK (sdk-js bundles this module) and the mobile SDK
99
+ * (sdk-mobile carries a generated copy) read every answer the same way.
100
+ *
101
+ * It encodes what Google Drive, Google Cloud Storage, OneDrive, Dropbox and
102
+ * AWS document for resumable transfers:
103
+ * - only a request that got no answer, 408, 425, 429 or a 5xx is retried;
104
+ * every other 4xx is the server's verdict on the request;
105
+ * - `Retry-After` is a floor, never a ceiling;
106
+ * - retries back off exponentially, capped, with jitter;
107
+ * - before a chunk is sent again the server is asked for the offset it
108
+ * committed, because a request whose answer was lost may have landed;
109
+ * - a session that is gone (404, 410) is never resumed: only a new upload
110
+ * from byte 0 can succeed;
111
+ * - a transfer's retries are bounded in time and in failures in a row, and
112
+ * both bounds start over whenever the server confirms progress.
113
+ *
114
+ * Forge's own answers beyond the general rule:
115
+ * - the 409, in two kinds: one carrying `Upload-Offset` names where the
116
+ * session stands (continue from there), and one without it means another
117
+ * request holds the session's write lease, a chunk or the finalization
118
+ * (retry after its `Retry-After`);
119
+ * - a terminal answer (a 404, 410 or 412) names the code Core ended the
120
+ * upload with: its error envelope in `error.details.coreCode` for the
121
+ * refusals it words itself, and every one of them in `X-Upload-Refusal`,
122
+ * which is all a HEAD's answer, having no body, can carry; the body's code
123
+ * wins when both name one. The code decides the verdict: a full storage
124
+ * pool or a later upload that replaced this one is a refusal no new upload
125
+ * of the same file remedies, and any other code (the file the upload was
126
+ * for gone, a retired contract, a replacement base that moved on, a code
127
+ * this policy does not know) ends the session, which a new upload can
128
+ * start over;
129
+ * - a 503 carrying `Retry-After` to the receipt (the PATCH at the final
130
+ * offset) is a deferral: Forge holds every byte and is still publishing,
131
+ * and finishes without the client, so it is asked again, each time after a
132
+ * longer backoff, for as long as the idle limit allows, and never counts as
133
+ * a failure. Forge's deferral always names when to ask again; a 503 that
134
+ * does not is an ordinary failure.
135
+ *
136
+ * Isomorphic: no Node imports, no host APIs, no randomness. The jitter only
137
+ * has to spread retries, so it hashes the transfer and the attempt
138
+ * (docs/CONVENTIONS.md → Randomness).
139
+ */
140
+
141
+
142
+ /** What a client does after a transfer request, read from its answer. */
143
+ const TRANSFER_VERDICT = Object.freeze({
144
+ /** 2xx: the request did what it asked. */
145
+ OK: 'ok',
146
+ /**
147
+ * No answer (a reset, a timeout), 408, 425, 429, a 5xx, or a 409 without
148
+ * `Upload-Offset` (another request holds the session's lease): back off,
149
+ * never sooner than `Retry-After`, then ask the server's offset before
150
+ * sending a chunk again.
151
+ */
152
+ RETRY: 'retry',
153
+ /** 409 with `Upload-Offset`: the session stands elsewhere; continue from that offset at once. */
154
+ RESYNC: 'resync',
155
+ /**
156
+ * 503 with `Retry-After` to the receipt: every byte is received and the
157
+ * publication is still running. Ask again after a backoff that grows with
158
+ * each deferral, never sooner than `Retry-After`; only the idle limit ends
159
+ * the asking, never the failures in a row.
160
+ */
161
+ DEFERRED: 'deferred',
162
+ /**
163
+ * 404 or 410 naming no code, or a 404, 410 or 412 naming a code of Core's
164
+ * that is not a final refusal (`coreCode` carries it): the session no
165
+ * longer exists; only a new upload from byte 0 can succeed.
166
+ */
167
+ GONE: 'gone',
168
+ /**
169
+ * Any other status, or a 404, 410 or 412 naming a final refusal of Core's
170
+ * (`coreCode`: UPLOAD_POOL_FULL, UPLOAD_SUPERSEDED): the server's verdict on
171
+ * this request, which repeating it, or a new upload of the same file,
172
+ * earns again.
173
+ */
174
+ REFUSED: 'refused'
175
+ });
176
+
177
+ /** The failures a transfer recovers from by trying again: the verdicts a budget's `failed` records. */
178
+ const RETRYABLE_VERDICTS = new Set([TRANSFER_VERDICT.RETRY, TRANSFER_VERDICT.RESYNC]);
179
+
180
+ /** RFC 8470: the server refused a request sent in TLS early data; the same request succeeds once the handshake completes. */
181
+ const TOO_EARLY = 425;
182
+
183
+ /** Forge's answer to a receipt whose publication it deferred. */
184
+ const SERVICE_UNAVAILABLE = 503;
185
+
186
+ /**
187
+ * The statuses a terminal answer naming Core's code arrives with: Forge's 410
188
+ * (UPLOAD_GONE, or Core's own relayed), a relayed 404, and Core's own 412.
189
+ */
190
+ const TERMINAL_STATUSES = new Set([404, 410, 412]);
191
+
192
+ /** Core's error codes are upper-case words joined by underscores; anything else names no code. */
193
+ const CORE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
194
+
195
+
196
+ const UPLOAD_OFFSET_HEADER = 'Upload-Offset';
197
+ const RETRY_AFTER_HEADER = 'Retry-After';
198
+
199
+ /**
200
+ * How long a client waits for the answer to an offset HEAD or a receipt
201
+ * PATCH, whatever its other requests get: on a received upload, Forge answers
202
+ * either only after its own call to Core (up to 30 s) has published the
203
+ * upload or deferred it, so each gets twice that.
204
+ */
205
+ const HEAD_AND_RECEIPT_TIMEOUT_MS = 60_000;
206
+
207
+ /** How a retry's delay spreads past its backoff: up to this much more. */
208
+ const JITTER_SPAN_MS = 1000;
209
+
210
+ /** How long a transfer may sit without progress or a sign of life by default. */
211
+ const DEFAULT_IDLE_LIMIT_MS = 10 * 60 * 1000;
212
+
213
+ /** How many failures in a row, without progress between them, end a transfer by default. */
214
+ const DEFAULT_MAX_CONSECUTIVE_FAILURES = 8;
215
+
216
+ /**
217
+ * @typedef {'ok'|'retry'|'resync'|'deferred'|'gone'|'refused'} TransferVerdict
218
+ */
219
+
220
+ /**
221
+ * The verdicts a transfer recovers from by trying again that count as
222
+ * failures: the ones a budget's `failed` records.
223
+ * @typedef {'retry'|'resync'} RetryableTransferVerdict
224
+ */
225
+
226
+ /**
227
+ * @typedef {Object} TransferOutcome
228
+ * @property {TransferVerdict} verdict - What the client does next
229
+ * @property {number|null} retryAfterMs - The answer's `Retry-After`, in ms from
230
+ * the answer (an HTTP-date already past reads as 0); null when absent or unreadable
231
+ * @property {number|null} offset - The answer's `Upload-Offset`; null when absent or unreadable
232
+ * @property {string|null} coreCode - The code Core ended the upload with, as a
233
+ * terminal answer named it (a 404, 410 or 412: its body's details or, those
234
+ * naming none, its `X-Upload-Refusal`): REFUSED for a final refusal
235
+ * (`UPLOAD_POOL_FULL`, `UPLOAD_SUPERSEDED`), GONE for any other code
236
+ * (`NOT_FOUND`, `UPLOAD_PROTOCOL_RETIRED`, a 412's, one this policy does not
237
+ * know); null when the answer names none
238
+ */
239
+
240
+ /**
241
+ * Read the answer to a transfer request the way the policy does.
242
+ *
243
+ * @param {Object} response
244
+ * @param {number} response.status - The HTTP status; 0 when the request got no answer
245
+ * @param {((name: string) => string|null)|null} [response.headers] - Reads a
246
+ * response header by name: a fetch `Headers`' `get` or an XHR's
247
+ * `getResponseHeader`, bound to its owner (`(name) => xhr.getResponseHeader(name)`)
248
+ * @param {unknown} [response.details] - The `details` of the error envelope the
249
+ * answer's body carries (`{ error: { code, message, details } }`), as the
250
+ * runtime's one reader of a failed answer parsed it from the whole body;
251
+ * where Forge names the refusal Core decided (`coreCode`), ahead of the
252
+ * answer's `X-Upload-Refusal`. Anything that is not an object names none.
253
+ * @param {boolean} [response.receipt] - The request was the receipt: the PATCH
254
+ * at the final offset, whose 503 carrying `Retry-After` is a deferral
255
+ * @param {number} [response.now] - When the answer arrived (epoch ms), which an
256
+ * HTTP-date `Retry-After` counts from
257
+ * @returns {TransferOutcome}
258
+ * @throws {TypeError} When the status is not a whole number, headers is not a
259
+ * function, or receipt is not a boolean
260
+ */
261
+ function classifyTransferResponse({ status, headers = null, details = null, receipt = false, now = Date.now() }) {
262
+ if (!Number.isSafeInteger(status) || status < 0) {
263
+ throw new TypeError(`A transfer answer's status is a whole number (0 for no answer), not ${status}`);
264
+ }
265
+ if (headers !== null && typeof headers !== 'function') {
266
+ throw new TypeError('A transfer answer\'s headers are read through a function from a header name to its value');
267
+ }
268
+ if (typeof receipt !== 'boolean') {
269
+ throw new TypeError(`Whether a transfer request was the receipt is a boolean, not ${receipt}`);
270
+ }
271
+ if (status === 0) {
272
+ return { verdict: TRANSFER_VERDICT.RETRY, retryAfterMs: null, offset: null, coreCode: null };
273
+ }
274
+ const header = (name) => (headers === null ? null : headers(name));
275
+ const offset = readCount(header(UPLOAD_OFFSET_HEADER));
276
+ const coreCode = TERMINAL_STATUSES.has(status)
277
+ ? coreCodeIn(details) ?? coreCodeOf(header(UPLOAD_REFUSAL_HEADER))
278
+ : null;
279
+ const retryAfterMs = readRetryAfterMs(header(RETRY_AFTER_HEADER), now);
280
+ return {
281
+ verdict: verdictFor(status, { offset, coreCode, deferral: receipt && retryAfterMs !== null }),
282
+ retryAfterMs,
283
+ offset,
284
+ coreCode
285
+ };
286
+ }
287
+
288
+ /**
289
+ * The verdict on a status that came with an answer: `offset` its readable
290
+ * `Upload-Offset`, `coreCode` the code of Core's a terminal answer names,
291
+ * `deferral` whether it answered the receipt with a readable `Retry-After`.
292
+ */
293
+ function verdictFor(status, { offset, coreCode, deferral }) {
294
+ if (status >= 200 && status < 300) return TRANSFER_VERDICT.OK;
295
+ if (status === 409) return offset === null ? TRANSFER_VERDICT.RETRY : TRANSFER_VERDICT.RESYNC;
296
+ if (coreCode !== null) return UPLOAD_FINAL_REFUSAL_CODES.includes(coreCode) ? TRANSFER_VERDICT.REFUSED : TRANSFER_VERDICT.GONE;
297
+ if (status === 404 || status === 410) return TRANSFER_VERDICT.GONE;
298
+ if (deferral && status === SERVICE_UNAVAILABLE) return TRANSFER_VERDICT.DEFERRED;
299
+ if (status === TOO_EARLY || isTransientHttpStatus(status)) return TRANSFER_VERDICT.RETRY;
300
+ return TRANSFER_VERDICT.REFUSED;
301
+ }
302
+
303
+ /** The code an error envelope's details name (`coreCode`), or null. */
304
+ function coreCodeIn(details) {
305
+ return details && typeof details === 'object' ? coreCodeOf(details.coreCode) : null;
306
+ }
307
+
308
+ /** A value that is one of Core's codes (surrounding whitespace allowed), or null. */
309
+ function coreCodeOf(value) {
310
+ if (typeof value !== 'string') return null;
311
+ const code = value.trim();
312
+ return CORE_CODE.test(code) ? code : null;
313
+ }
314
+
315
+ /** A header's non-negative whole number (surrounding whitespace allowed), or null. */
316
+ function readCount(value) {
317
+ if (typeof value !== 'string') return null;
318
+ const text = value.trim();
319
+ if (!/^\d+$/.test(text)) return null;
320
+ const count = Number(text);
321
+ return Number.isSafeInteger(count) ? count : null;
322
+ }
323
+
324
+ /** RFC 9110 §10.2.3: `Retry-After` is delay-seconds or an HTTP-date. */
325
+ function readRetryAfterMs(value, now) {
326
+ const seconds = readCount(value);
327
+ if (seconds !== null) {
328
+ const ms = seconds * 1000;
329
+ return Number.isSafeInteger(ms) ? ms : null;
330
+ }
331
+ const at = typeof value === 'string' ? parseHttpDate(value.trim(), now) : null;
332
+ return at === null ? null : Math.max(0, at - now);
333
+ }
334
+
335
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
336
+ const DAY_NAME = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)';
337
+ const LONG_DAY_NAME = '(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)';
338
+ const MONTH = `(${MONTHS.join('|')})`;
339
+ const TIME_OF_DAY = '(\\d{2}):(\\d{2}):(\\d{2})';
340
+
341
+ /** IMF-fixdate, what every current server sends: `Sun, 06 Nov 1994 08:49:37 GMT`. */
342
+ const IMF_FIXDATE = new RegExp(`^${DAY_NAME}, (\\d{2}) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`);
343
+ /** The obsolete RFC 850 form a recipient still accepts: `Sunday, 06-Nov-94 08:49:37 GMT`. */
344
+ const RFC850_DATE = new RegExp(`^${LONG_DAY_NAME}, (\\d{2})-${MONTH}-(\\d{2}) ${TIME_OF_DAY} GMT$`);
345
+ /** The obsolete asctime form a recipient still accepts: `Sun Nov 6 08:49:37 1994`. */
346
+ const ASCTIME_DATE = new RegExp(`^${DAY_NAME} ${MONTH} ( \\d|\\d{2}) ${TIME_OF_DAY} (\\d{4})$`);
347
+
348
+ /**
349
+ * An HTTP-date (RFC 9110 §5.6.7, all three forms a recipient must accept) as
350
+ * epoch ms, or null when it is not one or names no real moment.
351
+ *
352
+ * @param {string} text
353
+ * @param {number} now - epoch ms, which places an RFC 850 two-digit year
354
+ * @returns {number|null}
355
+ */
356
+ function parseHttpDate(text, now) {
357
+ let match = IMF_FIXDATE.exec(text);
358
+ if (match) {
359
+ const [, day, month, year, hours, minutes, seconds] = match;
360
+ return utcMs(Number(year), month, Number(day), hours, minutes, seconds);
361
+ }
362
+ match = RFC850_DATE.exec(text);
363
+ if (match) {
364
+ const [, day, month, shortYear, hours, minutes, seconds] = match;
365
+ return utcMs(rfc850Year(Number(shortYear), now), month, Number(day), hours, minutes, seconds);
366
+ }
367
+ match = ASCTIME_DATE.exec(text);
368
+ if (match) {
369
+ const [, month, day, hours, minutes, seconds, year] = match;
370
+ return utcMs(Number(year), month, Number(day.trim()), hours, minutes, seconds);
371
+ }
372
+ return null;
373
+ }
374
+
375
+ /** RFC 9110: a two-digit year more than 50 years ahead is the latest past year with those digits. */
376
+ function rfc850Year(shortYear, now) {
377
+ const currentYear = new Date(now).getUTCFullYear();
378
+ const year = currentYear - (currentYear % 100) + shortYear;
379
+ return year > currentYear + 50 ? year - 100 : year;
380
+ }
381
+
382
+ /** The UTC instant of a calendar date and time of day, or null for a date or time that does not exist. */
383
+ function utcMs(year, monthName, day, hours, minutes, seconds) {
384
+ const monthIndex = MONTHS.indexOf(monthName);
385
+ const [h, m, s] = [Number(hours), Number(minutes), Number(seconds)];
386
+ // A leap second (60) is a real time of day; the instant rolls into the next minute.
387
+ if (h > 23 || m > 59 || s > 60) return null;
388
+ const date = new Date(0);
389
+ date.setUTCFullYear(year, monthIndex, day);
390
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== day) {
391
+ return null;
392
+ }
393
+ return date.getTime() + ((h * 60 + m) * 60 + s) * 1000;
394
+ }
395
+
396
+ const FNV_OFFSET_BASIS = 0x811c9dc5;
397
+ const FNV_PRIME = 0x01000193;
398
+
399
+ /**
400
+ * 32-bit FNV-1a over the text's UTF-8 bytes: the jitter's hash. A retry's
401
+ * delay only has to spread, so it hashes what identifies the retry and draws
402
+ * nothing (docs/CONVENTIONS.md → Randomness).
403
+ *
404
+ * @param {string} text
405
+ * @returns {number} An unsigned 32-bit integer
406
+ * @throws {TypeError} When the text is not a string
407
+ */
408
+ function fnv1a32(text) {
409
+ if (typeof text !== 'string') {
410
+ throw new TypeError(`fnv1a32 hashes a string, not ${typeof text}`);
411
+ }
412
+ let hash = FNV_OFFSET_BASIS;
413
+ const mix = (byte) => {
414
+ hash = Math.imul(hash ^ byte, FNV_PRIME) >>> 0;
415
+ };
416
+ for (const character of text) {
417
+ let point = character.codePointAt(0);
418
+ // A lone surrogate has no UTF-8 form; it encodes as U+FFFD, as TextEncoder does.
419
+ if (point >= 0xd800 && point <= 0xdfff) point = 0xfffd;
420
+ if (point < 0x80) {
421
+ mix(point);
422
+ } else if (point < 0x800) {
423
+ mix(0xc0 | (point >> 6));
424
+ mix(0x80 | (point & 0x3f));
425
+ } else if (point < 0x10000) {
426
+ mix(0xe0 | (point >> 12));
427
+ mix(0x80 | ((point >> 6) & 0x3f));
428
+ mix(0x80 | (point & 0x3f));
429
+ } else {
430
+ mix(0xf0 | (point >> 18));
431
+ mix(0x80 | ((point >> 12) & 0x3f));
432
+ mix(0x80 | ((point >> 6) & 0x3f));
433
+ mix(0x80 | (point & 0x3f));
434
+ }
435
+ }
436
+ return hash;
437
+ }
438
+
439
+ /** Transfers this runtime has keyed by `transferJitterKey`: with the start time, what tells them apart. */
440
+ let transfersKeyed = 0;
441
+
442
+ /**
443
+ * What a transfer's retries spread by when no session URL keys them yet (a
444
+ * session create) or ever (a download, whose link carries its token): the
445
+ * scope (the create endpoint, or the kind of transfer), when the transfer
446
+ * started, and this runtime's count of keyed transfers, which tell
447
+ * concurrent transfers apart. A transfer's token is a credential and never
448
+ * feeds anything observable such as a delay, so no part of the key derives
449
+ * from it (docs/CONVENTIONS.md → Randomness).
450
+ *
451
+ * @param {string} scope - The endpoint or the kind of transfer
452
+ * @returns {string} The key, for every retry of this one transfer
453
+ * @throws {TypeError} For a scope that is not a non-empty string
454
+ */
455
+ function transferJitterKey(scope) {
456
+ if (typeof scope !== 'string' || scope.length === 0) {
457
+ throw new TypeError('A transfer jitter key needs the scope its transfer runs in');
458
+ }
459
+ transfersKeyed += 1;
460
+ return `${scope}#${Date.now()}-${transfersKeyed}`;
461
+ }
462
+
463
+ /**
464
+ * How long to wait before retry `attempt` of a transfer: `baseMs` doubling per
465
+ * attempt, capped at `capMs`, plus a jitter in [0, 1000) ms hashed from the
466
+ * transfer and the attempt, and never less than the server's `Retry-After`.
467
+ * The same transfer and attempt always wait the same; different transfers
468
+ * failing together spread out.
469
+ *
470
+ * @param {Object} options
471
+ * @param {number} options.attempt - Which retry this is, from 1
472
+ * @param {number|null} [options.retryAfterMs] - The answer's `Retry-After`: a floor
473
+ * @param {number} [options.baseMs] - The first retry's backoff
474
+ * @param {number} [options.capMs] - The longest backoff, before jitter
475
+ * @param {string} options.jitterKey - What identifies the transfer (its session
476
+ * URL, or a `transferJitterKey`)
477
+ * @returns {number} ms
478
+ * @throws {TypeError} For an attempt that is not a whole number from 1, a
479
+ * missing jitter key, or a delay bound that is not a positive number of ms
480
+ */
481
+ function retryDelayMs({ attempt, retryAfterMs = null, baseMs = 1000, capMs = 32000, jitterKey }) {
482
+ if (!Number.isSafeInteger(attempt) || attempt < 1) {
483
+ throw new TypeError(`A retry's attempt is a whole number from 1, not ${attempt}`);
484
+ }
485
+ if (typeof jitterKey !== 'string' || jitterKey.length === 0) {
486
+ throw new TypeError('A retry delay needs the key its transfer spreads by');
487
+ }
488
+ if (!isDuration(baseMs) || baseMs === 0 || !isDuration(capMs) || capMs < baseMs) {
489
+ throw new TypeError(`A retry backs off from a positive base (${baseMs} ms) up to a cap no smaller (${capMs} ms)`);
490
+ }
491
+ if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
492
+ throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
493
+ }
494
+ const backoff = Math.min(capMs, baseMs * 2 ** (attempt - 1));
495
+ const jitter = Math.floor((fnv1a32(`${jitterKey}|${attempt}`) / 2 ** 32) * JITTER_SPAN_MS);
496
+ return Math.max(backoff + jitter, retryAfterMs ?? 0);
497
+ }
498
+
499
+ function isDuration(ms) {
500
+ return Number.isFinite(ms) && ms >= 0;
501
+ }
502
+
503
+ /**
504
+ * @typedef {Object} TransferBudget
505
+ * @property {() => void} progressed - The server confirmed progress (bytes
506
+ * landed, or the offset it names moved forward): the failures in a row and
507
+ * the idle clock start over
508
+ * @property {() => void} alive - A sign of life the server has not confirmed
509
+ * (bytes are leaving, or the device is back online): the idle clock starts
510
+ * over and the failures in a row stand, so attempts that die before the
511
+ * server confirms anything still end the transfer
512
+ * @property {(verdict: RetryableTransferVerdict, retryAfterMs?: number|null) => boolean} failed -
513
+ * Records a retryable answer (RETRY or RESYNC) and says whether another
514
+ * attempt is allowed: the failures in a row stay under the max, and the
515
+ * attempt `retryAfterMs` allows would start inside the idle limit, so a
516
+ * transfer never sleeps on a Retry-After longer than its budget. The limit
517
+ * bounds when a retry is decided; a retry decided inside it still waits its
518
+ * own backoff, so a transfer ends within one backoff of the limit.
519
+ * @property {(retryAfterMs?: number|null) => boolean} deferred - Records a
520
+ * DEFERRED answer and says whether to ask again: only the idle limit bounds
521
+ * it, as `failed` applies it, because a deferral is the server at work,
522
+ * never a failure, so the failures in a row stand
523
+ * @property {number} consecutiveFailures - Retryable failures since the last progress
524
+ * @property {number} attempt - Failures and deferrals since the last progress:
525
+ * the attempt the next wait's delay is computed for, so each deferral backs
526
+ * the next ask off as a failure does, sparing a Core that is struggling to
527
+ * publish
528
+ * @property {number} msSinceProgress - ms since the last progress or sign of life
529
+ */
530
+
531
+ /**
532
+ * The retry budget of one transfer: retries are bounded by failures in a row
533
+ * and by time without progress, deferrals by time alone, and both bounds
534
+ * start over whenever the server confirms progress, so a slow transfer that
535
+ * keeps landing bytes is never cut off while a dead one ends in bounded time.
536
+ *
537
+ * @param {Object} [options]
538
+ * @param {number} [options.idleLimitMs] - How long the transfer may go without
539
+ * progress or a sign of life
540
+ * @param {number} [options.maxConsecutiveFailures] - Failures in a row that end the transfer
541
+ * @param {() => number} [options.now] - The clock, epoch ms
542
+ * @returns {TransferBudget}
543
+ * @throws {TypeError} For a limit that is not a positive number, or a clock that is not a function
544
+ */
545
+ function createTransferBudget({
546
+ idleLimitMs = DEFAULT_IDLE_LIMIT_MS,
547
+ maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,
548
+ now = () => Date.now()
549
+ } = {}) {
550
+ if (!isDuration(idleLimitMs) || idleLimitMs === 0) {
551
+ throw new TypeError(`A transfer's idle limit is a positive number of ms, not ${idleLimitMs}`);
552
+ }
553
+ if (!Number.isSafeInteger(maxConsecutiveFailures) || maxConsecutiveFailures < 1) {
554
+ throw new TypeError(`A transfer's failure limit is a whole number from 1, not ${maxConsecutiveFailures}`);
555
+ }
556
+ if (typeof now !== 'function') {
557
+ throw new TypeError('A transfer budget reads time from a clock function');
558
+ }
559
+
560
+ let consecutiveFailures = 0;
561
+ let deferrals = 0;
562
+ let lastSignOfLifeAt = now();
563
+ const msIdle = () => now() - lastSignOfLifeAt;
564
+ const startsInsideIdleLimit = (retryAfterMs) => {
565
+ if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
566
+ throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
567
+ }
568
+ return msIdle() + (retryAfterMs ?? 0) < idleLimitMs;
569
+ };
570
+
571
+ return Object.freeze({
572
+ progressed() {
573
+ consecutiveFailures = 0;
574
+ deferrals = 0;
575
+ lastSignOfLifeAt = now();
576
+ },
577
+ alive() {
578
+ lastSignOfLifeAt = now();
579
+ },
580
+ failed(verdict, retryAfterMs = null) {
581
+ if (!RETRYABLE_VERDICTS.has(verdict)) {
582
+ throw new TypeError(`A transfer budget records retryable answers only, not '${verdict}'`);
583
+ }
584
+ const allowed = startsInsideIdleLimit(retryAfterMs);
585
+ consecutiveFailures += 1;
586
+ return allowed && consecutiveFailures < maxConsecutiveFailures;
587
+ },
588
+ deferred(retryAfterMs = null) {
589
+ const allowed = startsInsideIdleLimit(retryAfterMs);
590
+ deferrals += 1;
591
+ return allowed;
592
+ },
593
+ get consecutiveFailures() {
594
+ return consecutiveFailures;
595
+ },
596
+ get attempt() {
597
+ return consecutiveFailures + deferrals;
598
+ },
599
+ get msSinceProgress() {
600
+ return msIdle();
601
+ }
602
+ });
603
+ }
604
+
605
+ /** Why an offset the server names cannot be resumed from. */
606
+ const RESUME_OFFSET_PROBLEM = Object.freeze({
607
+ /** Not a non-negative whole number of bytes. */
608
+ INVALID: 'invalid',
609
+ /** Past the upload's length: resuming from it would report a partial upload complete. */
610
+ BEYOND_TOTAL: 'beyond_total',
611
+ /** Inside a chunk: a session commits whole chunks only, so the answer is corrupt. */
612
+ MISALIGNED: 'misaligned'
613
+ });
614
+
615
+ /**
616
+ * Why a session offset the server named (a HEAD's, or a 409's `Upload-Offset`)
617
+ * cannot be resumed from, or null when it can. Forge commits whole chunks, so
618
+ * a session stands at a multiple of its chunk size or at its total.
619
+ *
620
+ * @param {number|null} offset
621
+ * @param {Object} geometry
622
+ * @param {number} geometry.totalSize - The upload's length (a non-negative whole number)
623
+ * @param {number} geometry.chunkSize - The session's chunk size (a positive whole number)
624
+ * @returns {'invalid'|'beyond_total'|'misaligned'|null}
625
+ * @throws {TypeError} When the length is not a non-negative whole number or
626
+ * the chunk size not a positive one
627
+ */
628
+ function resumeOffsetProblem(offset, { totalSize, chunkSize }) {
629
+ if (!Number.isSafeInteger(totalSize) || totalSize < 0 || !Number.isSafeInteger(chunkSize) || chunkSize < 1) {
630
+ throw new TypeError(`An upload's geometry is a whole length and a positive chunk size, not ${totalSize} and ${chunkSize}`);
631
+ }
632
+ if (!Number.isSafeInteger(offset) || offset < 0) return RESUME_OFFSET_PROBLEM.INVALID;
633
+ if (offset > totalSize) return RESUME_OFFSET_PROBLEM.BEYOND_TOTAL;
634
+ if (offset !== totalSize && offset % chunkSize !== 0) return RESUME_OFFSET_PROBLEM.MISALIGNED;
635
+ return null;
636
+ }
637
+
5
638
  /**
6
639
  * SparkVault SDK Error Types
7
640
  */
8
641
  class SparkVaultError extends Error {
9
- constructor(message, code, statusCode, details) {
642
+ constructor(message, code, statusCode, details, retryAfterMs = null) {
10
643
  super(message);
11
644
  this.name = 'SparkVaultError';
12
645
  this.code = code;
13
646
  this.statusCode = statusCode;
14
647
  this.details = details;
648
+ this.retryAfterMs = retryAfterMs;
15
649
  Object.setPrototypeOf(this, SparkVaultError.prototype);
16
650
  }
17
651
  }
18
652
  class AuthenticationError extends SparkVaultError {
19
- constructor(message, details) {
20
- super(message, 'authentication_error', 401, details);
653
+ constructor(message, details, retryAfterMs = null) {
654
+ super(message, 'authentication_error', 401, details, retryAfterMs);
21
655
  this.name = 'AuthenticationError';
22
656
  Object.setPrototypeOf(this, AuthenticationError.prototype);
23
657
  }
24
658
  }
25
659
  class AuthorizationError extends SparkVaultError {
26
- constructor(message, details) {
27
- super(message, 'authorization_error', 403, details);
660
+ constructor(message, details, retryAfterMs = null) {
661
+ super(message, 'authorization_error', 403, details, retryAfterMs);
28
662
  this.name = 'AuthorizationError';
29
663
  Object.setPrototypeOf(this, AuthorizationError.prototype);
30
664
  }
31
665
  }
32
666
  class ValidationError extends SparkVaultError {
33
- constructor(message, details) {
34
- super(message, 'validation_error', 400, details);
667
+ constructor(message, details, retryAfterMs = null) {
668
+ super(message, 'validation_error', 400, details, retryAfterMs);
35
669
  this.name = 'ValidationError';
36
670
  Object.setPrototypeOf(this, ValidationError.prototype);
37
671
  }
@@ -42,8 +676,8 @@ class ValidationError extends SparkVaultError {
42
676
  * to admins, or "ask your account admin" to members.
43
677
  */
44
678
  class PlanRequiredError extends SparkVaultError {
45
- constructor(message, details) {
46
- super(message, 'PLAN_REQUIRED', 402, details);
679
+ constructor(message, details, retryAfterMs = null) {
680
+ super(message, 'PLAN_REQUIRED', 402, details, retryAfterMs);
47
681
  this.name = 'PlanRequiredError';
48
682
  Object.setPrototypeOf(this, PlanRequiredError.prototype);
49
683
  }
@@ -54,8 +688,8 @@ class PlanRequiredError extends SparkVaultError {
54
688
  * the right capacity block.
55
689
  */
56
690
  class QuotaExceededError extends SparkVaultError {
57
- constructor(message, details) {
58
- super(message, 'QUOTA_EXCEEDED', 402, details);
691
+ constructor(message, details, retryAfterMs = null) {
692
+ super(message, 'QUOTA_EXCEEDED', 402, details, retryAfterMs);
59
693
  this.name = 'QuotaExceededError';
60
694
  const resource = details?.resource;
61
695
  this.resource =
@@ -70,8 +704,8 @@ class QuotaExceededError extends SparkVaultError {
70
704
  * nothing, so surface a subscribe CTA rather than a sign-in prompt.
71
705
  */
72
706
  class NotifySubscriptionRequiredError extends SparkVaultError {
73
- constructor(message, details) {
74
- super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details);
707
+ constructor(message, details, retryAfterMs = null) {
708
+ super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details, retryAfterMs);
75
709
  this.name = 'NotifySubscriptionRequiredError';
76
710
  Object.setPrototypeOf(this, NotifySubscriptionRequiredError.prototype);
77
711
  }
@@ -127,24 +761,51 @@ function recordField(value) {
127
761
  ? value
128
762
  : undefined;
129
763
  }
764
+ function parseJson(text) {
765
+ try {
766
+ return JSON.parse(text);
767
+ }
768
+ catch {
769
+ return null;
770
+ }
771
+ }
130
772
  /**
131
- * Read a failed response's error body: the one reading every SDK transport
132
- * shares. SparkVault services answer `{ error: { code, message, details } }`;
133
- * a framework or gateway answers flat (`{ code, message }`, `{ message }`) or
134
- * with no JSON at all, so each field falls back to its flat form and then to a
135
- * default. The body is read leniently: a failure's status and class never
136
- * depend on the body being JSON.
773
+ * Read a failed answer from its parsed body: the one reading every SDK
774
+ * transport shares, so an error built from an answer carries the same of it
775
+ * whichever client made the request, and whether fetch or an XMLHttpRequest
776
+ * received it. SparkVault services answer `{ error: { code, message,
777
+ * details } }`; a framework or gateway answers flat (`{ code, message }`,
778
+ * `{ message }`) or with no JSON at all, so each field falls back to its flat
779
+ * form and then to a default. The body is read leniently: a failure's status
780
+ * and class never depend on the body being JSON. The `Retry-After` is read by
781
+ * the transfer policy's one parser (`@sparkvault/app-sdk/transfer-retry`),
782
+ * never a second one: the policy reads a whole answer at once, and only its
783
+ * header reading is kept here, because an API answer is the service's
784
+ * verdict, never a transfer answer the policy's verdict applies to.
137
785
  */
138
- async function readApiErrorBody(response) {
139
- const body = await response.json().catch(() => null);
786
+ function failureOf(status, body, header) {
140
787
  const root = recordField(body) ?? {};
141
788
  const nested = recordField(root.error);
142
789
  return {
790
+ status,
143
791
  message: stringField(nested?.message) ?? stringField(root.message) ?? stringField(root.error) ?? 'Request failed',
144
792
  code: stringField(nested?.code) ?? stringField(root.code) ?? 'api_error',
145
793
  details: recordField(nested?.details) ?? recordField(root.details),
794
+ retryAfterMs: classifyTransferResponse({ status, headers: header }).retryAfterMs,
146
795
  };
147
796
  }
797
+ /**
798
+ * Read a failed answer a transport holds as text (an XMLHttpRequest's
799
+ * `responseText`, a body it also keeps a snippet of), parsed whole, so
800
+ * nothing past any length is lost to the reading.
801
+ */
802
+ function apiFailureOf(answer) {
803
+ return failureOf(answer.status, parseJson(answer.body), answer.header);
804
+ }
805
+ /** Read a failed fetch response; a body that is not JSON, or cannot be read, reads as none. */
806
+ async function readApiFailure(response) {
807
+ return failureOf(response.status, await response.json().catch(() => null), (name) => response.headers.get(name));
808
+ }
148
809
 
149
810
  /**
150
811
  * SparkVault resource ids: the one grammar every surface reads an id by before
@@ -480,10 +1141,14 @@ class SparkVaultApi {
480
1141
  * here, when the request starts. resetSession() can swap the controller
481
1142
  * while the request is in flight, and reading the live one afterwards would
482
1143
  * misreport a genuine cancel as a timeout.
1144
+ *
1145
+ * @param timeoutMs - The deadline of a request whose server-side wait is
1146
+ * its own (a tus HEAD or receipt, which Forge answers only after its call
1147
+ * to Core); every other request takes the client's.
483
1148
  */
484
- send(url, init, copy, read) {
1149
+ send(url, init, copy, read, timeoutMs = this.timeoutMs) {
485
1150
  return exchange(url, init, {
486
- timeoutMs: this.timeoutMs,
1151
+ timeoutMs,
487
1152
  closeSignal: this.closeController.signal,
488
1153
  read,
489
1154
  fail: (failure, cause) => {
@@ -503,8 +1168,9 @@ class SparkVaultApi {
503
1168
  /**
504
1169
  * Issue a JSON API request. Returns the parsed JSON body (whatever shape it
505
1170
  * takes; null when the body is not JSON) plus the status code. A non-2xx
506
- * answer throws the subclass error carrying the server's code, message and
507
- * details, read by the one error-body reader every transport shares.
1171
+ * answer throws the subclass error carrying the server's code, message,
1172
+ * details and `Retry-After`, read by the one failed-answer reader every
1173
+ * transport shares.
508
1174
  */
509
1175
  rawRequest(url, options) {
510
1176
  // Only send Content-Type when there's actually a body — otherwise GETs
@@ -520,8 +1186,8 @@ class SparkVaultApi {
520
1186
  network: 'Unable to connect. Please check your connection and try again.',
521
1187
  }, async (response) => {
522
1188
  if (!response.ok) {
523
- const { message, code, details } = await readApiErrorBody(response);
524
- throw this.makeError(message, code, response.status, details);
1189
+ const { status, message, code, details, retryAfterMs } = await readApiFailure(response);
1190
+ throw this.makeError(message, code, status, details, retryAfterMs);
525
1191
  }
526
1192
  return { data: await readJsonBody(response), status: response.status };
527
1193
  });
@@ -649,7 +1315,7 @@ class HttpClient {
649
1315
  timeoutMs: timeout,
650
1316
  read: async (response) => {
651
1317
  if (!response.ok) {
652
- throw this.createErrorFromResponse(response.status, await readApiErrorBody(response));
1318
+ throw this.createErrorFromResponse(await readApiFailure(response));
653
1319
  }
654
1320
  const parsed = await this.parseResponse(response);
655
1321
  return {
@@ -687,26 +1353,34 @@ class HttpClient {
687
1353
  const text = await response.text();
688
1354
  throw new SparkVaultError(`Unexpected response format: expected JSON but received ${contentType ?? 'unknown content type'}`, 'invalid_response_format', response.status, { body: text.slice(0, 500) });
689
1355
  }
690
- createErrorFromResponse(status, { message, code, details }) {
1356
+ /**
1357
+ * The SDK error for a failed answer, typed by its status: the gates a host
1358
+ * page branches on get their own class, and every other answer is the base
1359
+ * error under the service's own code. Each carries the answer's
1360
+ * `Retry-After` (`retryAfterMs`), the floor for whoever retries it — the
1361
+ * SDK's own transfers when the answer is a download link's mint, and the
1362
+ * host page otherwise.
1363
+ */
1364
+ createErrorFromResponse({ status, message, code, details, retryAfterMs }) {
691
1365
  switch (status) {
692
1366
  case 400:
693
- return new ValidationError(message, details);
1367
+ return new ValidationError(message, details, retryAfterMs);
694
1368
  case 401:
695
- return new AuthenticationError(message, details);
1369
+ return new AuthenticationError(message, details, retryAfterMs);
696
1370
  case 402:
697
1371
  if (code === 'QUOTA_EXCEEDED')
698
- return new QuotaExceededError(message, details);
1372
+ return new QuotaExceededError(message, details, retryAfterMs);
699
1373
  // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
700
- return new PlanRequiredError(message, details);
1374
+ return new PlanRequiredError(message, details, retryAfterMs);
701
1375
  case 403:
702
1376
  // A Notify send refused for want of a subscription is a billing gate, not
703
1377
  // a credential problem — give it its own catchable type.
704
1378
  if (code === 'NOTIFY_SUBSCRIPTION_REQUIRED') {
705
- return new NotifySubscriptionRequiredError(message, details);
1379
+ return new NotifySubscriptionRequiredError(message, details, retryAfterMs);
706
1380
  }
707
- return new AuthorizationError(message, details);
1381
+ return new AuthorizationError(message, details, retryAfterMs);
708
1382
  default:
709
- return new SparkVaultError(message, code, status, details);
1383
+ return new SparkVaultError(message, code, status, details, retryAfterMs);
710
1384
  }
711
1385
  }
712
1386
  unwrapApiResponse(data) {
@@ -1502,8 +2176,8 @@ class IdentityApi extends SparkVaultApi {
1502
2176
  get baseUrl() {
1503
2177
  return `${this.config.identityBaseUrl}${apiPath `/${this.config.accountId}`}`;
1504
2178
  }
1505
- makeError(message, code, statusCode, details) {
1506
- return new IdentityApiError(message, code, statusCode, details);
2179
+ makeError(message, code, statusCode, details, retryAfterMs = null) {
2180
+ return new IdentityApiError(message, code, statusCode, details, retryAfterMs);
1507
2181
  }
1508
2182
  async request(method, endpoint, body, query) {
1509
2183
  const { data } = await this.rawRequest(`${this.baseUrl}${endpoint}${queryString(query)}`, {
@@ -1879,8 +2553,8 @@ function mapRecommendations(raw) {
1879
2553
  return result;
1880
2554
  }
1881
2555
  class IdentityApiError extends SparkVaultError {
1882
- constructor(message, code, statusCode, details) {
1883
- super(message, code, statusCode, details);
2556
+ constructor(message, code, statusCode, details, retryAfterMs = null) {
2557
+ super(message, code, statusCode, details, retryAfterMs);
1884
2558
  this.name = 'IdentityApiError';
1885
2559
  Object.setPrototypeOf(this, IdentityApiError.prototype);
1886
2560
  }
@@ -10988,11 +11662,21 @@ function refused(reason) {
10988
11662
  /**
10989
11663
  * Error class for upload API errors. Inherits `code` and `statusCode` from
10990
11664
  * SparkVaultError — no duplicate `httpStatus` field.
11665
+ *
11666
+ * A failed transfer request also carries what the transfer policy
11667
+ * (`@sparkvault/app-sdk/transfer-retry`) makes of its answer, read where the
11668
+ * answer arrived: its `verdict` and its `Upload-Offset` (`serverOffset`),
11669
+ * beside the `Retry-After` every SDK error carries (`retryAfterMs`). They are
11670
+ * the retry loop's bookkeeping, so they ride on the instance, never in
11671
+ * `details`. Every other failure (a cancel, a refused URL, a protocol
11672
+ * violation) is `refused`: nothing retries it.
10991
11673
  */
10992
11674
  class UploadApiError extends SparkVaultError {
10993
- constructor(message, code, statusCode, details) {
10994
- super(message, code, statusCode, details);
11675
+ constructor(message, code, statusCode, details, outcome) {
11676
+ super(message, code, statusCode, details, outcome?.retryAfterMs ?? null);
10995
11677
  this.name = 'UploadApiError';
11678
+ this.verdict = outcome?.verdict ?? TRANSFER_VERDICT.REFUSED;
11679
+ this.serverOffset = outcome?.offset ?? null;
10996
11680
  Object.setPrototypeOf(this, UploadApiError.prototype);
10997
11681
  }
10998
11682
  }
@@ -11055,51 +11739,51 @@ function parseChunkSizeHeader(raw) {
11055
11739
  */
11056
11740
  const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
11057
11741
  /**
11058
- * Per-chunk retry budget for the PATCH loop.
11742
+ * How many consecutive timeouts end the finalization receipt early.
11059
11743
  *
11060
- * Forge sessions are resumable, so a chunk that fails in transit is a blip to
11061
- * recover from rather than an upload to abandon — a multi-gigabyte transfer is
11062
- * otherwise one dropped packet away from starting over. The budget counts only
11063
- * failures that produced no server-side progress: a retry cycle that finds
11064
- * bytes actually landed earns the budget back, so a slow-but-alive transfer is
11065
- * never capped while a genuinely dead one still fails in bounded time.
11744
+ * A genuinely slow finalize shows up as ONE timeout — the PATCH that started
11745
+ * the re-drive — followed by 409s from the writer that is working on it.
11746
+ * Back-to-back timeouts mean nobody is answering at all, and spending the
11747
+ * whole retry budget on a black-holed socket would freeze the widget at 100%
11748
+ * for minutes with nothing for the user to act on.
11066
11749
  */
11067
- const CHUNK_MAX_ATTEMPTS = 3;
11068
- const CHUNK_RETRY_BASE_MS = 500;
11750
+ const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
11751
+ /** The copy a person reads when the session their upload ran in no longer exists. */
11752
+ const SESSION_GONE_MESSAGE = 'Upload could not be finished: the server has ended this upload session. Please upload the file again.';
11069
11753
  /**
11070
- * Retry budget for the finalization receipt.
11071
- *
11072
- * Forge answers the zero-length PATCH with a 409 while another writer is still
11073
- * inside the finalizer, so the confirmation has to out-wait a finalization
11074
- * already in flight rather than give up on it — a budget measured in seconds
11075
- * rather than in the sub-second blips a chunk retry recovers from.
11754
+ * The copy a person reads when the server kept deferring the publication
11755
+ * until the upload's idle limit: nothing failed, and nothing is left for
11756
+ * them to do.
11076
11757
  */
11077
- const FINALIZE_MAX_ATTEMPTS = 10;
11078
- const FINALIZE_RETRY_MS = 1000;
11758
+ const RECEIVED_PUBLISHING_MESSAGE = 'The server received every byte of this file and is still saving it. It finishes on its own.';
11079
11759
  /**
11080
- * How many consecutive timeouts end the confirmation early.
11081
- *
11082
- * A genuinely slow finalize shows up as ONE timeout — the PATCH that started
11083
- * the re-drive — followed by 409s from the writer that is working on it.
11084
- * Back-to-back timeouts mean nobody is answering at all, and spending the full
11085
- * budget on a black-holed socket would freeze the widget at 100% for minutes
11086
- * with nothing for the user to act on.
11760
+ * The copy a person reads for a final refusal whose answer carried no
11761
+ * sentence of Core's (a HEAD's, which has no body, naming Core's code in
11762
+ * `X-Upload-Refusal` alone): this SDK's own words for each code, none of them
11763
+ * asking for the file again.
11087
11764
  */
11088
- const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
11765
+ const REFUSAL_WORDING = new Map([
11766
+ [UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL, 'This upload could not be saved: the owner\'s storage cannot take the file.'],
11767
+ [UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED, 'This upload was not saved: a newer upload of this file replaced it.'],
11768
+ ]);
11769
+ /** The copy for a final refusal of a code this SDK has no words of its own for. */
11770
+ const REFUSED_MESSAGE = 'This upload could not be saved: the server refused it.';
11771
+ function cancelledError() {
11772
+ return new UploadApiError('Upload cancelled', 'cancelled', 0);
11773
+ }
11089
11774
  /**
11090
11775
  * A delay that a cancel cuts short: resolves after `ms`, rejects with the
11091
11776
  * canonical cancelled error the moment the signal aborts.
11092
11777
  */
11093
11778
  function abortableDelay(ms, signal) {
11094
11779
  return new Promise((resolve, reject) => {
11095
- const cancelled = () => new UploadApiError('Upload cancelled', 'cancelled', 0);
11096
11780
  if (signal.aborted) {
11097
- reject(cancelled());
11781
+ reject(cancelledError());
11098
11782
  return;
11099
11783
  }
11100
11784
  const onAbort = () => {
11101
11785
  clearTimeout(timer);
11102
- reject(cancelled());
11786
+ reject(cancelledError());
11103
11787
  };
11104
11788
  const timer = setTimeout(() => {
11105
11789
  signal.removeEventListener('abort', onAbort);
@@ -11108,63 +11792,166 @@ function abortableDelay(ms, signal) {
11108
11792
  signal.addEventListener('abort', onAbort, { once: true });
11109
11793
  });
11110
11794
  }
11795
+ /** Whether the browser knows it has no network: `onLine` false is definite, true is only a hope. */
11796
+ function isOffline() {
11797
+ return typeof navigator !== 'undefined' && navigator.onLine === false;
11798
+ }
11111
11799
  /**
11112
- * Whether a failed transfer request is worth another attempt. Every retrying
11113
- * stage of an upload asks this one question:
11114
- *
11115
- * - the chunk PATCH loop — may this chunk be re-sent?
11116
- * - the resume-HEAD loop — may the session's offset be re-read?
11117
- * - the finalization receipt — may publication be asked about again?
11118
- *
11119
- * A transport-level failure (status 0 — a dropped connection, a timeout, or
11120
- * the inactivity watchdog aborting a silent socket) says nothing about whether
11121
- * the request reached Forge, 409 is Forge's documented "another writer holds
11122
- * the session lease; re-check and retry" (on the receipt: a finalizer is
11123
- * running right now), and a 5xx is a server-side blip. Every other outcome is
11124
- * the server's considered answer about this exact request — a rejected offset,
11125
- * a bad ISTK, a vanished session, or a 2xx carrying a protocol-violating
11126
- * offset — and re-sending would only earn it again. A cancelled session is the
11127
- * user's decision, never a failure to retry.
11800
+ * Resolve once the browser is back online; reject with the canonical
11801
+ * cancelled error the moment the session closes, which is the only bound on
11802
+ * the wait.
11128
11803
  */
11129
- function isRetryableTransferFailure(error) {
11130
- if (!(error instanceof UploadApiError))
11131
- return false;
11132
- // Verdicts, not blips: a cancel is the user's decision, and an invalid or
11133
- // misaligned offset is a protocol violation the server would only repeat.
11134
- // The code exclusion is load-bearing for the statusCode-0 sites (the resume
11135
- // and misalignment guards); patchChunk's own invalid_offset rides a 2xx
11136
- // status the heuristic below would reject anyway.
11137
- if (error.code === 'cancelled' || error.code === 'invalid_offset')
11138
- return false;
11139
- const status = error.statusCode ?? 0;
11140
- return status === 0 || status === 409 || status >= 500;
11804
+ function waitUntilOnline(signal) {
11805
+ return new Promise((resolve, reject) => {
11806
+ if (signal.aborted) {
11807
+ reject(cancelledError());
11808
+ return;
11809
+ }
11810
+ const settle = (outcome) => {
11811
+ globalThis.removeEventListener('online', onOnline);
11812
+ signal.removeEventListener('abort', onAbort);
11813
+ outcome();
11814
+ };
11815
+ const onOnline = () => settle(resolve);
11816
+ const onAbort = () => settle(() => reject(cancelledError()));
11817
+ globalThis.addEventListener('online', onOnline);
11818
+ signal.addEventListener('abort', onAbort, { once: true });
11819
+ // The network may have come back between the caller's check and these
11820
+ // listeners, and its `online` event would then never arrive.
11821
+ if (!isOffline())
11822
+ settle(resolve);
11823
+ });
11824
+ }
11825
+ /** A failed request of this upload's transfer; anything else is rethrown as it is. */
11826
+ function transferFailure(error) {
11827
+ if (error instanceof UploadApiError)
11828
+ return error;
11829
+ throw error;
11830
+ }
11831
+ /**
11832
+ * The session the upload ran in is gone (cancelled, expired, or its file
11833
+ * removed): only a new upload from byte 0 can store the file, which the caller
11834
+ * starts (`ingots.upload` / `createUpload` again, or the widget's next upload).
11835
+ */
11836
+ function sessionGoneError(failure) {
11837
+ return new UploadApiError(SESSION_GONE_MESSAGE, 'session_gone', failure.statusCode ?? 0, { status: failure.statusCode, ...failure.details }, { verdict: TRANSFER_VERDICT.GONE, retryAfterMs: null, offset: null, coreCode: null });
11838
+ }
11839
+ /**
11840
+ * Wait out the backoff of a failed request, spending a retry of the upload's
11841
+ * budget, or of a deferred one, spending none for as long as the idle limit
11842
+ * allows; never shorter than the answer's `Retry-After`, and longer with
11843
+ * every failure and deferral since the last progress. Throws an answer no
11844
+ * retry follows as it is, and the last failure, or the deferral, once the
11845
+ * budget is spent. While the browser is offline a failure spends nothing: the
11846
+ * wait is for the network to come back (or the session to close), and the
11847
+ * idle clock starts over when it does.
11848
+ */
11849
+ async function waitToRetry(budget, failure, jitterKey, sessionSignal) {
11850
+ const { verdict, retryAfterMs } = failure;
11851
+ if (verdict === TRANSFER_VERDICT.DEFERRED) {
11852
+ if (!budget.deferred(retryAfterMs))
11853
+ throw failure;
11854
+ }
11855
+ else if (verdict !== TRANSFER_VERDICT.RETRY) {
11856
+ throw failure;
11857
+ }
11858
+ else if (isOffline()) {
11859
+ await waitUntilOnline(sessionSignal);
11860
+ budget.alive();
11861
+ return;
11862
+ }
11863
+ else if (!budget.failed(verdict, retryAfterMs)) {
11864
+ throw failure;
11865
+ }
11866
+ const delayMs = retryDelayMs({
11867
+ attempt: budget.attempt,
11868
+ retryAfterMs,
11869
+ jitterKey,
11870
+ });
11871
+ await abortableDelay(delayMs, sessionSignal);
11141
11872
  }
11142
11873
  /**
11143
11874
  * A server's error body, reduced to something safe to carry on an error:
11144
11875
  * whitespace collapsed and length clipped, so an HTML error page or a stack
11145
- * trace can never become the payload.
11876
+ * trace can never become the payload. The clip is only for what the error
11877
+ * carries: the body is read whole first ({@link readTransferAnswer}).
11146
11878
  */
11147
11879
  const ERROR_DETAIL_MAX_CHARS = 200;
11148
11880
  function summarizeErrorBody(body) {
11149
11881
  return body.replace(/\s+/g, ' ').trim().slice(0, ERROR_DETAIL_MAX_CHARS);
11150
11882
  }
11883
+ /**
11884
+ * What the transfer policy makes of a transfer request's answer, and the
11885
+ * error it throws when it is not a 2xx. A failed answer's body is read whole
11886
+ * by the SDK's one reader of a failed answer ({@link apiFailureOf}), so the
11887
+ * code Core ended the upload with reaches the policy however long Core's
11888
+ * sentence is, and an answer with no body (a HEAD's) names it in
11889
+ * `X-Upload-Refusal`: a final refusal throws `upload_refused` in Core's own
11890
+ * words (this SDK's for a HEAD's), Core's code in `details.coreCode`, and a
11891
+ * new upload is no remedy. The receipt's deferral throws
11892
+ * `upload_received_publishing`, which the upload only ever throws once the
11893
+ * idle limit ends the asking. Any other failure throws the request's own
11894
+ * copy, the server's detail and any other code of Core's in `details` (a gone
11895
+ * session's, which the upload reports as `session_gone`).
11896
+ *
11897
+ * @param answer - The status, the headers, and the body's whole text (empty for a 2xx)
11898
+ */
11899
+ function readTransferAnswer(answer, read) {
11900
+ const served = answer.body ? apiFailureOf(answer) : null;
11901
+ const outcome = classifyTransferResponse({
11902
+ status: answer.status,
11903
+ headers: answer.header,
11904
+ details: served?.details ?? null,
11905
+ receipt: read.receipt,
11906
+ });
11907
+ if (outcome.verdict === TRANSFER_VERDICT.OK)
11908
+ return { outcome, failure: null };
11909
+ const { status } = answer;
11910
+ if (outcome.verdict === TRANSFER_VERDICT.REFUSED && outcome.coreCode !== null) {
11911
+ const message = served?.message ?? REFUSAL_WORDING.get(outcome.coreCode) ?? REFUSED_MESSAGE;
11912
+ return {
11913
+ outcome,
11914
+ failure: new UploadApiError(message, 'upload_refused', status, { status, coreCode: outcome.coreCode }, outcome),
11915
+ };
11916
+ }
11917
+ if (outcome.verdict === TRANSFER_VERDICT.DEFERRED) {
11918
+ return {
11919
+ outcome,
11920
+ failure: new UploadApiError(RECEIVED_PUBLISHING_MESSAGE, 'upload_received_publishing', status, { status }, outcome),
11921
+ };
11922
+ }
11923
+ const detail = summarizeErrorBody(answer.body);
11924
+ return {
11925
+ outcome,
11926
+ failure: new UploadApiError(read.failureMessage, read.code, status, {
11927
+ status,
11928
+ ...(detail ? { serverDetail: detail } : {}),
11929
+ ...(outcome.coreCode !== null ? { coreCode: outcome.coreCode } : {}),
11930
+ }, outcome),
11931
+ };
11932
+ }
11151
11933
  const SESSION_CREATION = {
11152
11934
  name: 'Upload session creation',
11153
11935
  code: 'tus_create_failed',
11154
- serverFailureMessage: 'The upload could not be started: the server did not open an upload session.',
11936
+ failureMessage: 'The upload could not be started: the server did not open an upload session.',
11155
11937
  networkMessage: 'Unable to start the upload. Please check your connection and try again.',
11938
+ receipt: false,
11156
11939
  };
11157
11940
  const RESUME_CHECK = {
11158
11941
  name: 'Upload resume check',
11159
11942
  code: 'resume_check_failed',
11160
- serverFailureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
11943
+ failureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
11161
11944
  networkMessage: 'Unable to resume upload. Please check your connection and try again.',
11945
+ receipt: false,
11946
+ timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
11162
11947
  };
11163
11948
  const FINALIZATION_CHECK = {
11164
11949
  name: 'Upload finalization check',
11165
11950
  code: 'finalization_check_failed',
11166
- serverFailureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
11951
+ failureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
11167
11952
  networkMessage: 'Unable to confirm upload. Please check your connection and try again.',
11953
+ receipt: true,
11954
+ timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
11168
11955
  };
11169
11956
  class UploadApi extends SparkVaultApi {
11170
11957
  constructor(config) {
@@ -11180,8 +11967,19 @@ class UploadApi extends SparkVaultApi {
11180
11967
  this.vaultInfoMemo = new Map();
11181
11968
  this.config = config;
11182
11969
  }
11183
- makeError(message, code, statusCode, details) {
11184
- return new UploadApiError(message, code, statusCode, details);
11970
+ /**
11971
+ * The shared transport's errors. It raises a request that got no answer (a
11972
+ * dropped connection, a timeout) with status 0, which the transfer policy
11973
+ * retries, a cancel aside; a refused API call it raises with its status is
11974
+ * Core's verdict, never a transfer's, so of the policy's reading it carries
11975
+ * only the floor Core named (`retryAfterMs`), for whoever acts on the
11976
+ * refusal.
11977
+ */
11978
+ makeError(message, code, statusCode, details, retryAfterMs = null) {
11979
+ const unanswered = statusCode === 0 && code !== 'cancelled';
11980
+ return new UploadApiError(message, code, statusCode, details, unanswered
11981
+ ? classifyTransferResponse({ status: 0 })
11982
+ : { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs, offset: null, coreCode: null });
11185
11983
  }
11186
11984
  /**
11187
11985
  * Issue a request to a Core route and unwrap the standard `{ data, meta }`
@@ -11298,13 +12096,22 @@ class UploadApi extends SparkVaultApi {
11298
12096
  * every server-reported offset, and honors the session abort signal plus
11299
12097
  * per-request timeouts.
11300
12098
  *
11301
- * A chunk that fails in transit is retried against the session's *true*
11302
- * offset rather than failing the whole transfer — see {@link CHUNK_MAX_ATTEMPTS}
11303
- * and {@link readResumeOffset}.
12099
+ * Every answer is read through the transfer policy
12100
+ * (`@sparkvault/app-sdk/transfer-retry`) and every retry spends one budget
12101
+ * ({@link TusTransfer}). A chunk that fails in transit is resent only from
12102
+ * an offset the server just named — a 409's own `Upload-Offset` at once,
12103
+ * otherwise a HEAD after the backoff ({@link offsetAfterFailure}); a session
12104
+ * the server no longer holds throws `session_gone`, which only a new upload
12105
+ * recovers from (any code of Core's the server named rides
12106
+ * `details.coreCode`); an upload Core refused for good (a full storage pool,
12107
+ * a later upload that replaced it) throws `upload_refused` in Core's words,
12108
+ * which no new upload recovers from. While the browser is offline, the loop
12109
+ * waits for the network instead of spending attempts.
11304
12110
  *
11305
12111
  * Resolves only once the server has confirmed finalization
11306
12112
  * ({@link confirmServerFinalized}), so a caller that gets a resolved promise
11307
- * is always looking at a published ingot.
12113
+ * is always looking at a published ingot; a publication the server still
12114
+ * defers at the idle limit throws `upload_received_publishing`.
11308
12115
  */
11309
12116
  async uploadFileToForge(file, forgeUrl, onProgress) {
11310
12117
  if (typeof XMLHttpRequest === 'undefined') {
@@ -11320,15 +12127,21 @@ class UploadApi extends SparkVaultApi {
11320
12127
  // The session this upload runs in: a close ends this upload even if a new
11321
12128
  // session starts before the loop next looks.
11322
12129
  const sessionSignal = this.getAbortSignal();
11323
- const session = await this.createTusSession(target.endpoint, target.istk, file.size);
12130
+ const budget = createTransferBudget();
12131
+ const session = await this.createTusSession(target.endpoint, target.istk, file.size, budget, sessionSignal);
11324
12132
  // Every chunk carries the file's bytes, so the session must live under the
11325
12133
  // endpoint it was created at.
11326
12134
  const uploadUrl = resolveForgeSessionUrl(session.location, target.endpoint);
11327
12135
  if (!uploadUrl) {
11328
12136
  throw new UploadApiError('Upload session is outside the upload endpoint', 'tus_create_failed', 0);
11329
12137
  }
11330
- let offset = 0;
11331
- let failedAttempts = 0;
12138
+ const transfer = {
12139
+ uploadUrl,
12140
+ totalSize: file.size,
12141
+ chunkSize: session.chunkSize,
12142
+ budget,
12143
+ sessionSignal,
12144
+ };
11332
12145
  // Retries make raw progress non-monotonic (a chunk that streamed to 90%
11333
12146
  // then failed re-reports from its start on resend); callers get only the
11334
12147
  // high-water mark so a progress bar never runs backwards.
@@ -11341,55 +12154,90 @@ class UploadApi extends SparkVaultApi {
11341
12154
  }
11342
12155
  }
11343
12156
  : undefined;
11344
- while (offset < file.size) {
12157
+ let offset = 0;
12158
+ for (;;) {
11345
12159
  if (sessionSignal.aborted) {
11346
- throw new UploadApiError('Upload cancelled', 'cancelled', 0);
12160
+ throw cancelledError();
12161
+ }
12162
+ // One exit, one receipt: however the loop learned that every byte is on
12163
+ // the server (a chunk's 204, a HEAD, a 409), publication is confirmed
12164
+ // before the upload resolves.
12165
+ if (offset === file.size) {
12166
+ const receipt = await this.confirmServerFinalized(transfer);
12167
+ if (receipt.published)
12168
+ return;
12169
+ offset = receipt.resumeAt;
12170
+ continue;
11347
12171
  }
11348
12172
  const chunkEnd = Math.min(offset + session.chunkSize, file.size);
11349
12173
  try {
11350
- offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, monotonicProgress);
11351
- failedAttempts = 0;
11352
- continue;
12174
+ offset = await this.patchChunk(transfer, file.slice(offset, chunkEnd), offset, monotonicProgress);
12175
+ transfer.budget.progressed();
11353
12176
  }
11354
12177
  catch (error) {
11355
- failedAttempts += 1;
11356
- if (failedAttempts >= CHUNK_MAX_ATTEMPTS || !isRetryableTransferFailure(error)) {
11357
- throw error;
11358
- }
12178
+ offset = await this.offsetAfterFailure(transfer, error, offset);
11359
12179
  }
11360
- // Resync against server truth before ANY further PATCH: the failed
11361
- // chunk may have landed (the acknowledgment was lost), and a PATCH at
11362
- // the client's stale offset is an offset mismatch the server rejects
11363
- // as a terminal 400. The blip that killed the PATCH is also the
11364
- // likeliest thing to kill this HEAD moments later, so the HEAD is
11365
- // retried out of the same per-position budget — the backoff races the
11366
- // session's abort signal so cancellation stays prompt.
11367
- let serverOffset;
11368
- for (;;) {
11369
- await abortableDelay(CHUNK_RETRY_BASE_MS * 2 ** (failedAttempts - 1), sessionSignal);
11370
- try {
11371
- serverOffset = await this.readResumeOffset(uploadUrl, file.size, session.chunkSize);
11372
- break;
11373
- }
11374
- catch (headError) {
11375
- if (!isRetryableTransferFailure(headError)) {
11376
- throw headError;
11377
- }
11378
- failedAttempts += 1;
11379
- if (failedAttempts >= CHUNK_MAX_ATTEMPTS) {
11380
- throw headError;
11381
- }
12180
+ }
12181
+ }
12182
+ /**
12183
+ * Where the upload stands after a failed chunk PATCH, in the server's words:
12184
+ * a 409's own `Upload-Offset` at once, otherwise the session's HEAD after
12185
+ * the backoff. The failed chunk may have landed with its answer lost, and a
12186
+ * PATCH at the client's stale offset is refused, so no chunk is ever sent
12187
+ * again at an offset the server did not just name. The blip that killed the
12188
+ * PATCH is also the likeliest thing to kill the HEAD moments later, so the
12189
+ * HEAD is retried the same way, out of the same budget.
12190
+ */
12191
+ async offsetAfterFailure(transfer, error, sentOffset) {
12192
+ let failure = transferFailure(error);
12193
+ for (;;) {
12194
+ if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
12195
+ return this.resyncedOffset(transfer, failure, sentOffset);
12196
+ }
12197
+ await this.backOff(transfer, failure);
12198
+ try {
12199
+ const serverOffset = await this.readResumeOffset(transfer);
12200
+ if (serverOffset > sentOffset) {
12201
+ // Bytes reached the server despite the failure, so the transfer is
12202
+ // alive: the budget starts over rather than being spent down across
12203
+ // the many chunks of a large file.
12204
+ transfer.budget.progressed();
11382
12205
  }
12206
+ return serverOffset;
11383
12207
  }
11384
- if (serverOffset > offset) {
11385
- // Bytes reached the server despite the failure, so the transfer is
11386
- // alive: the budget is earned back rather than spent down across the
11387
- // many chunks of a large file.
11388
- failedAttempts = 0;
12208
+ catch (headError) {
12209
+ failure = transferFailure(headError);
11389
12210
  }
11390
- offset = serverOffset;
11391
12211
  }
11392
- await this.confirmServerFinalized(uploadUrl, file.size);
12212
+ }
12213
+ /**
12214
+ * Continue from the offset a 409 named, at once and without a HEAD: the
12215
+ * server just said where the session stands. Past what this client sent,
12216
+ * the server holds more than it knew, which is progress; anywhere else the
12217
+ * answer contradicts the request, so it spends the budget like any failure
12218
+ * and repeating it ends the upload.
12219
+ */
12220
+ resyncedOffset(transfer, failure, sentOffset) {
12221
+ const offset = this.checkResumeOffset(failure.serverOffset, transfer);
12222
+ if (offset > sentOffset) {
12223
+ transfer.budget.progressed();
12224
+ }
12225
+ else if (!transfer.budget.failed(TRANSFER_VERDICT.RESYNC)) {
12226
+ throw failure;
12227
+ }
12228
+ return offset;
12229
+ }
12230
+ /**
12231
+ * Wait out the backoff of a failed or deferred request to the upload's
12232
+ * session ({@link waitToRetry}, keyed by the session URL), or throw: a gone
12233
+ * session as `session_gone`, an answer no retry follows as it is, and the
12234
+ * last failure, or the deferral, once the budget is spent.
12235
+ */
12236
+ async backOff(transfer, failure) {
12237
+ if (failure.verdict === TRANSFER_VERDICT.GONE) {
12238
+ throw sessionGoneError(failure);
12239
+ }
12240
+ await waitToRetry(transfer.budget, failure, transfer.uploadUrl, transfer.sessionSignal);
11393
12241
  }
11394
12242
  /**
11395
12243
  * Confirm the server finalized a fully received upload — the one receipt
@@ -11403,42 +12251,62 @@ class UploadApi extends SparkVaultApi {
11403
12251
  * re-drive — it short-circuits to 204 on an already-finalized session, and
11404
12252
  * on a received-but-unfinalized one it answers only after publication.
11405
12253
  *
11406
- * A 409 means another writer is inside the finalizer right now; that is the
11407
- * outcome the budget exists for, so the retry waits it out rather than
11408
- * failing a transfer that is about to succeed. A 400 is the opposite — the
11409
- * server is behind the offset we claim — and fails immediately.
12254
+ * While another request finalizes the receipt answers 409 with
12255
+ * `Retry-After`, polled again after the policy's backoff as a failure; while
12256
+ * the publication is deferred it answers 503 with `Retry-After`, a deferral
12257
+ * the receipt is polled through without spending a failure, each ask after
12258
+ * a longer backoff, until the idle limit throws
12259
+ * `upload_received_publishing`: every byte is on the server, which finishes
12260
+ * the publication on its own. A 503 naming no `Retry-After` is no deferral
12261
+ * of Forge's, so it is polled as a failure. A 400 is the server's verdict
12262
+ * and fails immediately, as does the refusal Core decided
12263
+ * (`upload_refused`); a 409 naming an earlier offset means bytes are
12264
+ * missing, and the upload continues from there.
11410
12265
  */
11411
- async confirmServerFinalized(uploadUrl, totalSize) {
12266
+ async confirmServerFinalized(transfer) {
11412
12267
  let consecutiveTimeouts = 0;
11413
- for (let attempt = 1;; attempt++) {
12268
+ for (;;) {
11414
12269
  try {
11415
- await this.tusRequest(uploadUrl, {
12270
+ await this.tusRequest(transfer.uploadUrl, {
11416
12271
  method: 'PATCH',
11417
12272
  headers: {
11418
12273
  'Tus-Resumable': TUS_VERSION,
11419
- 'Upload-Offset': String(totalSize),
12274
+ 'Upload-Offset': String(transfer.totalSize),
11420
12275
  'Content-Type': 'application/offset+octet-stream',
11421
12276
  },
11422
12277
  }, FINALIZATION_CHECK);
11423
- return;
12278
+ return { published: true };
11424
12279
  }
11425
12280
  catch (error) {
11426
- const timedOut = error instanceof UploadApiError && error.code === 'timeout';
12281
+ const failure = transferFailure(error);
11427
12282
  // Any answer at all — a 409 above all — proves someone is on the other
11428
12283
  // end, so the timeout tally starts over.
11429
- consecutiveTimeouts = timedOut ? consecutiveTimeouts + 1 : 0;
11430
- if (attempt >= FINALIZE_MAX_ATTEMPTS ||
11431
- consecutiveTimeouts >= FINALIZE_MAX_CONSECUTIVE_TIMEOUTS ||
11432
- !isRetryableTransferFailure(error)) {
11433
- throw error;
12284
+ consecutiveTimeouts = failure.code === 'timeout' ? consecutiveTimeouts + 1 : 0;
12285
+ if (consecutiveTimeouts >= FINALIZE_MAX_CONSECUTIVE_TIMEOUTS) {
12286
+ throw failure;
11434
12287
  }
11435
- await abortableDelay(FINALIZE_RETRY_MS, this.getAbortSignal());
12288
+ if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
12289
+ const resumeAt = this.resyncedOffset(transfer, failure, transfer.totalSize);
12290
+ if (resumeAt < transfer.totalSize)
12291
+ return { published: false, resumeAt };
12292
+ continue;
12293
+ }
12294
+ await this.backOff(transfer, failure);
11436
12295
  }
11437
12296
  }
11438
12297
  }
11439
12298
  /**
11440
- * Read the offset a failed chunk should resume from — the one place a
11441
- * server-reported resume point is judged.
12299
+ * Read the offset a failed chunk should resume from, from the session's
12300
+ * HEAD. At the full offset it proves receipt only, published or not, so the
12301
+ * loop then takes the receipt.
12302
+ */
12303
+ async readResumeOffset(transfer) {
12304
+ return this.checkResumeOffset(await this.headUploadOffset(transfer.uploadUrl, RESUME_CHECK), transfer);
12305
+ }
12306
+ /**
12307
+ * Judge an offset the server named for the upload to resume from — a HEAD's,
12308
+ * or a 409's `Upload-Offset` — the one place a server-reported resume point
12309
+ * is judged.
11442
12310
  *
11443
12311
  * Forge commits a chunk before it answers, so a PATCH that died in transit
11444
12312
  * may have landed in full or not at all (never in part — the chunk object
@@ -11446,21 +12314,19 @@ class UploadApi extends SparkVaultApi {
11446
12314
  * persisted offset knows which, and the client's arithmetic is worthless
11447
12315
  * here.
11448
12316
  *
11449
- * Two contracts disqualify an answer. TUS sanity: an offset past the
11450
- * declared total would end the loop early and report a partial upload as
11451
- * complete, the same trap {@link patchChunk} guards against on a PATCH's own
11452
- * offset. Forge chunk granularity: a session advances only in whole
11453
- * committed chunks, so an offset that is neither chunk-aligned nor the file
11454
- * end is a corrupt session, and resuming from it would send a short
11455
- * non-final chunk Forge rejects anyway.
12317
+ * Two contracts disqualify an answer (`resumeOffsetProblem`). TUS sanity: an
12318
+ * offset past the declared total would end the loop early and report a
12319
+ * partial upload as complete, the same trap {@link patchChunk} guards
12320
+ * against on a PATCH's own offset. Forge chunk granularity: a session
12321
+ * advances only in whole committed chunks, so an offset that is neither
12322
+ * chunk-aligned nor the file end is a corrupt session, and resuming from it
12323
+ * would send a short non-final chunk Forge rejects anyway.
11456
12324
  */
11457
- async readResumeOffset(uploadUrl, totalSize, chunkSize) {
11458
- const offset = await this.headUploadOffset(uploadUrl, RESUME_CHECK);
11459
- if (offset > totalSize) {
11460
- throw new UploadApiError(`Server returned invalid upload offset (${offset})`, 'invalid_offset', 0);
11461
- }
11462
- if (offset % chunkSize !== 0 && offset !== totalSize) {
11463
- throw new UploadApiError(`Server returned misaligned upload offset (${offset})`, 'invalid_offset', 0);
12325
+ checkResumeOffset(offset, transfer) {
12326
+ const problem = resumeOffsetProblem(offset, transfer);
12327
+ if (offset === null || problem !== null) {
12328
+ const shape = problem === RESUME_OFFSET_PROBLEM.MISALIGNED ? 'misaligned' : 'invalid';
12329
+ throw new UploadApiError(`Server returned ${shape} upload offset (${offset})`, 'invalid_offset', 0);
11464
12330
  }
11465
12331
  return offset;
11466
12332
  }
@@ -11468,16 +12334,39 @@ class UploadApi extends SparkVaultApi {
11468
12334
  * Create the TUS upload session. Forge reads only `Tus-Resumable`,
11469
12335
  * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
11470
12336
  * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
12337
+ *
12338
+ * A create the transfer policy calls RETRY (no answer, 408, 425, 429, a 5xx)
12339
+ * is sent again under the upload's budget: Forge refuses such a create
12340
+ * before it claims the token, or hands the claim back on a transient
12341
+ * key-service failure (503 + `Retry-After`), so the same ISTK opens the
12342
+ * session on a later attempt. Every other answer is final, a 401 included:
12343
+ * the token was already used, by an earlier attempt whose answer was lost,
12344
+ * and no `Location` survives to continue that session from. No session URL
12345
+ * exists yet to spread the retries by, and the ISTK never feeds one, so
12346
+ * they spread by a key of the endpoint (`transferJitterKey`).
11471
12347
  */
11472
- async createTusSession(endpoint, istk, totalSize) {
11473
- const response = await this.tusRequest(endpoint, {
11474
- method: 'POST',
11475
- headers: {
11476
- 'Tus-Resumable': TUS_VERSION,
11477
- 'Upload-Length': String(totalSize),
11478
- 'X-ISTK': istk,
11479
- },
11480
- }, SESSION_CREATION);
12348
+ async createTusSession(endpoint, istk, totalSize, budget, sessionSignal) {
12349
+ const jitterKey = transferJitterKey(endpoint);
12350
+ let response;
12351
+ for (;;) {
12352
+ try {
12353
+ ({ response } = await this.tusRequest(endpoint, {
12354
+ method: 'POST',
12355
+ headers: {
12356
+ 'Tus-Resumable': TUS_VERSION,
12357
+ 'Upload-Length': String(totalSize),
12358
+ 'X-ISTK': istk,
12359
+ },
12360
+ }, SESSION_CREATION));
12361
+ break;
12362
+ }
12363
+ catch (error) {
12364
+ const failure = transferFailure(error);
12365
+ if (failure.verdict !== TRANSFER_VERDICT.RETRY)
12366
+ throw failure;
12367
+ await waitToRetry(budget, failure, jitterKey, sessionSignal);
12368
+ }
12369
+ }
11481
12370
  const location = response.headers.get('Location');
11482
12371
  if (!location) {
11483
12372
  throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
@@ -11490,23 +12379,31 @@ class UploadApi extends SparkVaultApi {
11490
12379
  if (chunkSize === null) {
11491
12380
  throw new UploadApiError('Server did not return a valid X-Chunk-Size', 'tus_create_failed', response.status, { header: 'X-Chunk-Size', received: chunkSizeHeader });
11492
12381
  }
12382
+ // The session exists: the server confirmed progress.
12383
+ budget.progressed();
11493
12384
  return { location, chunkSize };
11494
12385
  }
11495
12386
  /**
11496
12387
  * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
11497
- * Resolves with the server-confirmed offset for the next iteration.
12388
+ * Resolves with the server-confirmed offset for the next iteration; a
12389
+ * failure carries the transfer policy's verdict on its answer, read here.
11498
12390
  *
11499
12391
  * The server's `Upload-Offset` is validated, never trusted: it must be a
11500
- * finite number that strictly advances past this chunk's start (this client
12392
+ * whole number that strictly advances past this chunk's start (this client
11501
12393
  * never sends an empty chunk, so a non-advancing 2xx would loop forever)
11502
12394
  * and never exceeds the file size (an inflated offset would skip real
11503
12395
  * chunks and report a partial upload as success).
12396
+ *
12397
+ * Bytes leaving are a sign of life: they restart the transfer's idle clock
12398
+ * (never its failure count, which only the server's confirmation resets), so
12399
+ * a slow chunk is never counted as idle time.
11504
12400
  */
11505
- patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
12401
+ patchChunk(transfer, chunk, chunkStart, onProgress) {
12402
+ const { uploadUrl, totalSize, budget } = transfer;
11506
12403
  return new Promise((resolve, reject) => {
11507
- const closeSignal = this.getAbortSignal();
12404
+ const closeSignal = transfer.sessionSignal;
11508
12405
  if (closeSignal.aborted) {
11509
- reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
12406
+ reject(cancelledError());
11510
12407
  return;
11511
12408
  }
11512
12409
  const xhr = new XMLHttpRequest();
@@ -11536,28 +12433,33 @@ class UploadApi extends SparkVaultApi {
11536
12433
  closeSignal.addEventListener('abort', onCloseAbort);
11537
12434
  xhr.upload.onprogress = (event) => {
11538
12435
  resetWatchdog();
12436
+ budget.alive();
11539
12437
  if (event.lengthComputable) {
11540
12438
  onProgress?.(chunkStart + event.loaded, totalSize);
11541
12439
  }
11542
12440
  };
11543
12441
  xhr.onload = () => {
11544
- if (xhr.status >= 200 && xhr.status < 300) {
11545
- const header = xhr.getResponseHeader('Upload-Offset');
11546
- const newOffset = header !== null ? parseInt(header, 10) : NaN;
11547
- if (!Number.isFinite(newOffset) || newOffset <= chunkStart || newOffset > totalSize) {
11548
- finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${newOffset})`, 'invalid_offset', xhr.status)));
11549
- return;
11550
- }
11551
- finish(() => resolve(newOffset));
12442
+ const { status } = xhr;
12443
+ const { outcome, failure } = readTransferAnswer({
12444
+ status,
12445
+ header: (name) => xhr.getResponseHeader(name),
12446
+ body: status >= 200 && status < 300 ? '' : xhr.responseText,
12447
+ }, { receipt: false, code: 'chunk_upload_failed', failureMessage: `Chunk upload failed with status ${status}` });
12448
+ if (failure) {
12449
+ finish(() => reject(failure));
12450
+ return;
11552
12451
  }
11553
- else {
11554
- finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
12452
+ const newOffset = outcome.offset;
12453
+ if (newOffset === null || newOffset <= chunkStart || newOffset > totalSize) {
12454
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${xhr.getResponseHeader('Upload-Offset')})`, 'invalid_offset', xhr.status)));
12455
+ return;
11555
12456
  }
12457
+ finish(() => resolve(newOffset));
11556
12458
  };
11557
- xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
12459
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0, undefined, classifyTransferResponse({ status: 0 }))));
11558
12460
  xhr.onabort = () => finish(() => reject(timedOut
11559
- ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
11560
- : new UploadApiError('Upload cancelled', 'cancelled', 0)));
12461
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0, undefined, classifyTransferResponse({ status: 0 }))
12462
+ : cancelledError()));
11561
12463
  xhr.open('PATCH', uploadUrl);
11562
12464
  xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
11563
12465
  xhr.setRequestHeader('Upload-Offset', String(chunkStart));
@@ -11573,13 +12475,11 @@ class UploadApi extends SparkVaultApi {
11573
12475
  * @param check - Which caller this read serves; shapes the failure copy.
11574
12476
  */
11575
12477
  async headUploadOffset(uploadUrl, check) {
11576
- const response = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
11577
- const header = response.headers.get('Upload-Offset');
11578
- const offset = header !== null ? parseInt(header, 10) : NaN;
11579
- if (!Number.isFinite(offset) || offset < 0) {
12478
+ const { response, outcome } = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
12479
+ if (outcome.offset === null) {
11580
12480
  throw new UploadApiError(`${check.name} returned an invalid offset`, check.code, response.status);
11581
12481
  }
11582
- return offset;
12482
+ return outcome.offset;
11583
12483
  }
11584
12484
  /**
11585
12485
  * Issue one bodyless TUS request: the single transport behind every
@@ -11589,26 +12489,33 @@ class UploadApi extends SparkVaultApi {
11589
12489
  * Uses the raw response rather than the JSON envelope helper: TUS responses
11590
12490
  * carry an empty body and surface state in headers. Runs through the one SDK
11591
12491
  * transport (session close signal, deadline, failure classification) and
11592
- * resolves only on a 2xx so no caller has to re-check `response.ok`.
12492
+ * resolves only on a 2xx, with the transfer policy's reading of it, so no
12493
+ * caller has to re-check `response.ok`; a non-2xx throws carrying the
12494
+ * policy's verdict on its answer.
11593
12495
  *
11594
12496
  * @param check - Which caller this request serves; shapes the failure copy.
11595
12497
  */
11596
12498
  tusRequest(uploadUrl, init, check) {
12499
+ const timeoutMs = check.timeoutMs ?? this.timeoutMs;
11597
12500
  return this.send(uploadUrl, { method: init.method, headers: init.headers }, {
11598
12501
  cancelled: 'Upload cancelled',
11599
- timeout: `${check.name} timed out after ${this.timeoutMs}ms`,
12502
+ timeout: `${check.name} timed out after ${timeoutMs}ms`,
11600
12503
  network: check.networkMessage,
11601
12504
  }, async (response) => {
11602
- if (!response.ok) {
11603
- // Read the body even though the message does not need it: an unread
11604
- // body pins its connection, and a retried receipt would strand one per
11605
- // attempt. What it says is the only server-side detail this client
11606
- // ever sees, so it rides along in `details` for support.
11607
- const detail = summarizeErrorBody(await response.text().catch(() => ''));
11608
- throw new UploadApiError(check.serverFailureMessage, check.code, response.status, { status: response.status, ...(detail ? { serverDetail: detail } : {}) });
11609
- }
11610
- return response;
11611
- });
12505
+ // A failed answer's body is read whole: an unread body pins its
12506
+ // connection, and a retried receipt would strand one per attempt.
12507
+ // Forge's error envelope in it is what names the refusal Core
12508
+ // decided, and otherwise the only server-side detail this client
12509
+ // ever sees, so it rides along in `details` for support.
12510
+ const { outcome, failure } = readTransferAnswer({
12511
+ status: response.status,
12512
+ header: (name) => response.headers.get(name),
12513
+ body: response.ok ? '' : await response.text().catch(() => ''),
12514
+ }, check);
12515
+ if (failure)
12516
+ throw failure;
12517
+ return { response, outcome };
12518
+ }, timeoutMs);
11612
12519
  }
11613
12520
  }
11614
12521
 
@@ -13853,7 +14760,34 @@ class UploadRenderer {
13853
14760
  statusCode: error.statusCode,
13854
14761
  });
13855
14762
  }
13856
- else if (error.statusCode === 404) {
14763
+ else if (error.code === 'upload_received_publishing') {
14764
+ // Every byte reached the server, which is still saving the file and
14765
+ // finishes it on its own: nothing failed, and nothing is left to do.
14766
+ // The host still hears it through onError, with this code, which
14767
+ // tells it never to upload the file again.
14768
+ this.setState({
14769
+ view: 'error',
14770
+ title: 'Upload Received',
14771
+ message: error.message,
14772
+ code: error.code,
14773
+ statusCode: error.statusCode,
14774
+ });
14775
+ }
14776
+ else if (error.code === 'upload_refused') {
14777
+ // Core refused the upload for good, in its own words (whom to contact
14778
+ // about a full storage pool, or the later upload that replaced this
14779
+ // one): a sentence that never asks for the file again.
14780
+ this.setState({
14781
+ view: 'error',
14782
+ title: 'Upload Not Saved',
14783
+ message: error.message,
14784
+ code: error.code,
14785
+ statusCode: error.statusCode,
14786
+ });
14787
+ }
14788
+ else if (error.statusCode === 404 && error.code !== 'session_gone') {
14789
+ // A vault or upload route that does not exist. A gone upload session
14790
+ // can answer 404 too, and its own sentence says what became of the file.
13857
14791
  this.setState({
13858
14792
  view: 'error',
13859
14793
  title: 'Upload Page Not Found',
@@ -14477,38 +15411,13 @@ function readIngotAccess(entry) {
14477
15411
  };
14478
15412
  }
14479
15413
 
14480
- /**
14481
- * Whether sending the SAME request again can succeed, read from its HTTP
14482
- * status: the one retry rule every client and every provider adapter applies.
14483
- *
14484
- * A retry rule restated beside every client drifts, and the copy that drifted
14485
- * decides whether a deliverable message is retried or abandoned, or whether a
14486
- * download is tried again. Each caller keeps its provider's own extras on top of
14487
- * this rule (a success body, a dead-token reason, a vendor error name).
14488
- *
14489
- * Browser-safe and import-free: sdk-js bundles it and sdk-mobile mirrors it.
14490
- */
14491
-
14492
- /**
14493
- * Is this HTTP status one a retry of the same request can turn into a success?
14494
- *
14495
- * RFC 9110: 408 means the server never received the whole request, 429 that it
14496
- * throttled it, and a 5xx that it failed; every other status is the server's
14497
- * verdict on this exact request. A caller that got no response at all (a network
14498
- * error, a timeout) has no status to pass and decides that case itself.
14499
- *
14500
- * @param {number} status
14501
- * @returns {boolean}
14502
- */
14503
- function isTransientHttpStatus(status) {
14504
- return status === 408 || status === 429 || status >= 500;
14505
- }
14506
-
14507
15414
  /**
14508
15415
  * The one browser transfer for a signed ingot download link: fetch it into a
14509
- * Blob under liveness bounds. `sv.ingots.download` uses it, and so can a caller
15416
+ * Blob under liveness bounds, resuming from the bytes it holds when the caller
15417
+ * can mint another link. `sv.ingots.download` uses it, and so can a caller
14510
15418
  * that mints its own link (`createDownloadLink`, or its own authenticated
14511
- * call) and needs cancellation, byte progress or the published revision.
15419
+ * call) and needs cancellation, byte progress, resumption or the published
15420
+ * revision.
14512
15421
  */
14513
15422
  /**
14514
15423
  * Time-to-first-byte bound: how long the download host may take to return
@@ -14573,15 +15482,104 @@ function assertDownloadUrl(url, isAllowedHost = isSparkVaultOwnedHostname) {
14573
15482
  }
14574
15483
  /**
14575
15484
  * Fetch a signed download URL as a Blob under liveness bounds: one deadline
14576
- * for the response headers, then an idle deadline rearmed on every body chunk.
14577
- * Nothing caps the transfer as a whole, so file size never decides whether a
14578
- * download can finish. The link is single-use: a caller that retries mints a
14579
- * fresh one first. A link that is not a Forge decrypt URL on an allowed host is
14580
- * refused before anything is sent (assertDownloadUrl).
14581
- */
14582
- async function fetchDownload(url, options = {}) {
14583
- const { signal, onProgress, expectedContentVersion, isAllowedHost } = options;
14584
- assertDownloadUrl(url, isAllowedHost);
15485
+ * for each response's headers, then an idle deadline rearmed on every body
15486
+ * chunk. Nothing caps the transfer as a whole, so file size never decides
15487
+ * whether a download can finish. The link is single-use, so a failed transfer
15488
+ * is retried only through `options.remint`, on a link minted for the retry. A
15489
+ * link that is not a Forge decrypt URL on an allowed host, the first or a
15490
+ * minted one, is refused before anything is sent to it (assertDownloadUrl).
15491
+ */
15492
+ function fetchDownload(url, options = {}) {
15493
+ return runDownload(() => Promise.resolve(url), options);
15494
+ }
15495
+ /**
15496
+ * {@link fetchDownload} for a caller whose every link is minted, the first
15497
+ * included: a mint that fails before any byte has moved is retried under the
15498
+ * same policy as any other failure. `sv.ingots.download` runs this.
15499
+ */
15500
+ function fetchMintedDownload(mint, options = {}) {
15501
+ return runDownload(mint, { ...options, remint: mint });
15502
+ }
15503
+ /** A failure no answer came with (a reset, a deadline, a lost connection): the policy retries it. */
15504
+ const UNANSWERED = classifyTransferResponse({ status: 0 });
15505
+ /** A failure that is this transfer's own verdict (content that is not the file held, a range that does not continue it): final. */
15506
+ const FINAL = { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs: null, offset: null, coreCode: null };
15507
+ /** `bytes <first>-<last>/<length>`: the one Content-Range form a 206 continuing a download carries. */
15508
+ const CONTENT_RANGE = /^bytes (\d+)-(\d+)\/(\d+)$/;
15509
+ /** A strong entity tag (RFC 9110 §8.8.3): an If-Range never carries a weak one. */
15510
+ const STRONG_ETAG = /^"[^"]*"$/;
15511
+ const CONTENT_CHANGED_MESSAGE = 'The file changed while it was downloading. Please try again.';
15512
+ /**
15513
+ * The transfer: an attempt on the link `firstLink` resolves to, then, while
15514
+ * the transfer policy retries a failure and the caller can mint, one attempt
15515
+ * per minted link, each after the policy's backoff. Retries are bounded by the
15516
+ * policy's budget, failures in a row and time without progress, both of which
15517
+ * start over whenever bytes arrive past what any attempt held.
15518
+ */
15519
+ async function runDownload(firstLink, options) {
15520
+ const { signal, remint } = options;
15521
+ const state = { received: new ReceivedBytes(), budget: createTransferBudget(), held: null, furthest: 0 };
15522
+ // The link carries the ISTK, a credential, which never feeds anything
15523
+ // observable such as a delay: the retries spread by a key of the download's
15524
+ // kind and start instead (transferJitterKey).
15525
+ const jitterKey = transferJitterKey('download');
15526
+ for (let nextLink = firstLink;;) {
15527
+ const result = await attemptWith(nextLink, state, options);
15528
+ if (result.ok)
15529
+ return result.download;
15530
+ if (signal?.aborted)
15531
+ throw signal.reason;
15532
+ const { error, outcome } = result;
15533
+ if (!remint || outcome.verdict !== TRANSFER_VERDICT.RETRY || !state.budget.failed(TRANSFER_VERDICT.RETRY, outcome.retryAfterMs)) {
15534
+ throw error;
15535
+ }
15536
+ await waitBeforeRetry(retryDelayMs({ attempt: state.budget.attempt, retryAfterMs: outcome.retryAfterMs, jitterKey }), signal);
15537
+ // A link is spent once its request has reached Forge, whatever came back:
15538
+ // every retry fetches one minted for it.
15539
+ nextLink = remint;
15540
+ }
15541
+ }
15542
+ /**
15543
+ * One attempt: take its link, minted when the source mints, hold it to the
15544
+ * transfer-URL rule, then fetch it. A mint that fails is read the way a
15545
+ * transfer answer is ({@link mintOutcome}).
15546
+ */
15547
+ async function attemptWith(source, state, options) {
15548
+ let link;
15549
+ try {
15550
+ link = await source();
15551
+ assertDownloadUrl(link, options.isAllowedHost);
15552
+ }
15553
+ catch (error) {
15554
+ return { ok: false, error, outcome: mintOutcome(error) };
15555
+ }
15556
+ return attemptDownload(link, state, options);
15557
+ }
15558
+ /**
15559
+ * The transfer policy's reading of a failed mint. The HTTP client read the
15560
+ * answer when it built the error: its status gives the verdict (a refused link
15561
+ * is a 400, so final) and the `Retry-After` it named rides on the error
15562
+ * (`retryAfterMs`), so a mint Core defers waits out Core's floor exactly as a
15563
+ * deferred Forge answer does. A failure with no status got no answer.
15564
+ */
15565
+ function mintOutcome(error) {
15566
+ if (!(error instanceof SparkVaultError) || typeof error.statusCode !== 'number')
15567
+ return UNANSWERED;
15568
+ return { ...classifyTransferResponse({ status: error.statusCode }), retryAfterMs: error.retryAfterMs };
15569
+ }
15570
+ /**
15571
+ * Fetch one link: the rest of the file held, conditioned on its validator,
15572
+ * when the bytes held can be resumed, the whole file otherwise. A 206 appends
15573
+ * to the bytes held; any whole-file answer replaces them, so a file replaced
15574
+ * since the bytes held began starts over as its new content, never spliced
15575
+ * onto the old.
15576
+ */
15577
+ async function attemptDownload(link, state, options) {
15578
+ const { signal, onProgress, expectedContentVersion } = options;
15579
+ const { received } = state;
15580
+ const resume = resumePoint(state);
15581
+ if (!resume)
15582
+ received.discard();
14585
15583
  const controller = new AbortController();
14586
15584
  const abortFromCaller = () => controller.abort(signal?.reason);
14587
15585
  if (signal?.aborted) {
@@ -14590,61 +15588,231 @@ async function fetchDownload(url, options = {}) {
14590
15588
  else {
14591
15589
  signal?.addEventListener('abort', abortFromCaller, { once: true });
14592
15590
  }
15591
+ // What a whole download is, once the answer has named its content.
15592
+ const whole = (content) => ({
15593
+ ok: true,
15594
+ download: { blob: received.toBlob(content.contentType), contentVersion: content.contentVersion },
15595
+ });
15596
+ let held = null;
15597
+ let delivered = false;
14593
15598
  try {
14594
- const response = await withDeadline(fetch(url, { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
15599
+ const response = await withDeadline(fetch(link, resume
15600
+ ? { signal: controller.signal, headers: { Range: `bytes=${resume.at}-`, 'If-Range': resume.validator } }
15601
+ : { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
14595
15602
  if (!response.ok) {
14596
- // The TTFB timer cleared when headers arrived, so nothing else would ever
14597
- // reap this connection: abort it or a retrying caller leaks one socket
14598
- // per failed attempt.
14599
- controller.abort();
14600
- throw new SparkVaultError(`Download failed with status ${response.status}`, 'download_failed', response.status);
15603
+ return {
15604
+ ok: false,
15605
+ error: new SparkVaultError(`Download failed with status ${response.status}`, 'download_failed', response.status),
15606
+ outcome: classifyTransferResponse({ status: response.status, headers: (name) => response.headers.get(name) }),
15607
+ };
14601
15608
  }
14602
- const contentVersion = response.headers.get('x-content-version') || null;
14603
- if (expectedContentVersion && contentVersion && contentVersion !== expectedContentVersion) {
14604
- controller.abort();
14605
- throw new SparkVaultError('The file changed while it was downloading. Please try again.', 'content_changed');
14606
- }
14607
- const contentType = response.headers.get('content-type') ?? '';
14608
- const total = Number(response.headers.get('content-length')) || 0;
14609
- // Safari 10.1-14.4 ships fetch without `Response.body`, and the SDK's
14610
- // support floor reaches back into that range. There the transfer keeps
14611
- // whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals,
14612
- // so there is no liveness to observe.
14613
- if (!response.body) {
14614
- const blob = await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out');
14615
- onProgress?.(blob.size, total);
14616
- return { blob, contentVersion };
14617
- }
14618
- const reader = response.body.getReader();
14619
- const parts = [];
14620
- let pending = [];
14621
- let pendingBytes = 0;
14622
- let loaded = 0;
14623
- for (;;) {
14624
- const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
14625
- if (done)
14626
- break;
14627
- pending.push(value);
14628
- pendingBytes += value.byteLength;
14629
- loaded += value.byteLength;
14630
- onProgress?.(loaded, total);
14631
- if (pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES) {
14632
- // Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
14633
- // to ArrayBufferLike, which the Blob constructor's part type rejects.
14634
- parts.push(new Blob(pending));
14635
- pending = [];
14636
- pendingBytes = 0;
15609
+ if (resume && response.status === 206) {
15610
+ const continued = continuation(response, resume);
15611
+ if (continued instanceof SparkVaultError)
15612
+ return { ok: false, error: continued, outcome: FINAL };
15613
+ held = continued;
15614
+ }
15615
+ else {
15616
+ received.discard();
15617
+ const contentVersion = response.headers.get('x-content-version') || null;
15618
+ if (expectedContentVersion && contentVersion && contentVersion !== expectedContentVersion) {
15619
+ return { ok: false, error: new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed'), outcome: FINAL };
14637
15620
  }
15621
+ held = {
15622
+ contentType: response.headers.get('content-type') ?? '',
15623
+ contentVersion,
15624
+ total: Number(response.headers.get('content-length')) || 0,
15625
+ validator: resumeValidator(response.headers),
15626
+ };
14638
15627
  }
14639
- if (pending.length > 0) {
14640
- parts.push(new Blob(pending));
15628
+ // Named before the body is read: a body that fails part-way leaves the
15629
+ // next attempt what it needs to resume.
15630
+ state.held = held;
15631
+ await readBody(response, controller, state, held.total, onProgress);
15632
+ delivered = true;
15633
+ return whole(held);
15634
+ }
15635
+ catch (error) {
15636
+ if (error instanceof ProgressCallbackFailure)
15637
+ return { ok: false, error: error.failure, outcome: FINAL };
15638
+ // Every declared byte arrived before the body failed to end: the file is
15639
+ // whole, and a resume would ask for a range past its end (a 416).
15640
+ if (held !== null && held.total > 0 && received.loaded === held.total && !signal?.aborted) {
15641
+ return whole(held);
14641
15642
  }
14642
- return { blob: new Blob(parts, { type: contentType }), contentVersion };
15643
+ return { ok: false, error, outcome: UNANSWERED };
14643
15644
  }
14644
15645
  finally {
15646
+ // An attempt that ends short of its body leaves a connection that no
15647
+ // deadline will reap any more: abort it, or every retry leaks one socket.
15648
+ if (!delivered)
15649
+ controller.abort();
14645
15650
  signal?.removeEventListener('abort', abortFromCaller);
14646
15651
  }
14647
15652
  }
15653
+ /** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
15654
+ function resumePoint(state) {
15655
+ const { held, received } = state;
15656
+ if (held === null || held.validator === null || received.loaded === 0)
15657
+ return null;
15658
+ return { held, validator: held.validator, at: received.loaded };
15659
+ }
15660
+ /**
15661
+ * What a resume conditions its range on: the response's ETag when it is
15662
+ * strong and the response accepts byte ranges, or null. An edge that rewrites
15663
+ * a body (compression) weakens its ETag, and then nothing binds the bytes held
15664
+ * to the bytes a range would be served from.
15665
+ */
15666
+ function resumeValidator(headers) {
15667
+ const etag = headers.get('etag');
15668
+ const acceptsBytes = (headers.get('accept-ranges') ?? '')
15669
+ .split(',')
15670
+ .some((unit) => unit.trim().toLowerCase() === 'bytes');
15671
+ return etag !== null && STRONG_ETAG.test(etag) && acceptsBytes ? etag : null;
15672
+ }
15673
+ /**
15674
+ * The content a 206 answering a resume continues, or why it cannot: it must
15675
+ * start at the first byte lacking, run to the end of the same file, and name
15676
+ * the publication the bytes held are when it names one (a server that honored
15677
+ * the range despite a changed publication would splice two of them).
15678
+ */
15679
+ function continuation(response, resume) {
15680
+ const etag = response.headers.get('etag');
15681
+ if (etag !== null && etag.replace(/^W\//, '') !== resume.validator) {
15682
+ return new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed');
15683
+ }
15684
+ const range = CONTENT_RANGE.exec(response.headers.get('content-range') ?? '');
15685
+ const [first, last, length] = range ? range.slice(1).map(Number) : [NaN, NaN, NaN];
15686
+ const { total } = resume.held;
15687
+ if (first !== resume.at || last !== length - 1 || (total > 0 && length !== total)) {
15688
+ return new SparkVaultError('The resumed download did not continue where it stopped', 'download_failed', response.status, { reason: 'range_mismatch' });
15689
+ }
15690
+ return { ...resume.held, total: length };
15691
+ }
15692
+ /**
15693
+ * Read a response body onto the bytes held under liveness bounds, reporting
15694
+ * cumulative progress against the file's declared length.
15695
+ */
15696
+ async function readBody(response, controller, state, total, onProgress) {
15697
+ const { received } = state;
15698
+ // Safari 10.1-14.4 ships fetch without `Response.body`, and the SDK's
15699
+ // support floor reaches back into that range. There the transfer keeps
15700
+ // whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals,
15701
+ // so there is no liveness to observe, and a failure holds no bytes to
15702
+ // resume from.
15703
+ if (!response.body) {
15704
+ received.appendBlob(await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out'));
15705
+ noteArrival(state);
15706
+ reportProgress(onProgress, received.loaded, total);
15707
+ return;
15708
+ }
15709
+ const reader = response.body.getReader();
15710
+ for (;;) {
15711
+ const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
15712
+ if (done)
15713
+ return;
15714
+ received.append(value);
15715
+ noteArrival(state);
15716
+ reportProgress(onProgress, received.loaded, total);
15717
+ }
15718
+ }
15719
+ /**
15720
+ * The caller's progress callback failed: its own error, which no retry can
15721
+ * cure. Unmarked, it would read as a transfer that lost its connection, and a
15722
+ * callback that throws on every report would cost a mint and a request per
15723
+ * chunk until the file completed.
15724
+ */
15725
+ class ProgressCallbackFailure extends Error {
15726
+ constructor(failure) {
15727
+ super('onProgress threw');
15728
+ this.failure = failure;
15729
+ }
15730
+ }
15731
+ function reportProgress(onProgress, loaded, total) {
15732
+ if (!onProgress)
15733
+ return;
15734
+ try {
15735
+ onProgress(loaded, total);
15736
+ }
15737
+ catch (failure) {
15738
+ throw new ProgressCallbackFailure(failure);
15739
+ }
15740
+ }
15741
+ /** Bytes arrived: past the most any attempt held, progress; short of it, a sign of life. */
15742
+ function noteArrival(state) {
15743
+ if (state.received.loaded > state.furthest) {
15744
+ state.furthest = state.received.loaded;
15745
+ state.budget.progressed();
15746
+ }
15747
+ else {
15748
+ state.budget.alive();
15749
+ }
15750
+ }
15751
+ /** Wait out a retry's backoff; the caller's cancel ends the wait with the signal's reason. */
15752
+ function waitBeforeRetry(ms, signal) {
15753
+ return new Promise((resolve, reject) => {
15754
+ if (signal?.aborted) {
15755
+ reject(signal.reason);
15756
+ return;
15757
+ }
15758
+ const onAbort = () => {
15759
+ clearTimeout(timer);
15760
+ reject(signal?.reason);
15761
+ };
15762
+ const timer = setTimeout(() => {
15763
+ signal?.removeEventListener('abort', onAbort);
15764
+ resolve();
15765
+ }, ms);
15766
+ signal?.addEventListener('abort', onAbort, { once: true });
15767
+ });
15768
+ }
15769
+ /**
15770
+ * The bytes a transfer holds, in the order they arrived: at most one window
15771
+ * on the JS heap, the rest folded into Blob parts the platform's blob store
15772
+ * owns, so heap growth is capped whatever the file's size.
15773
+ */
15774
+ class ReceivedBytes {
15775
+ constructor() {
15776
+ this.parts = [];
15777
+ this.pending = [];
15778
+ this.pendingBytes = 0;
15779
+ this.count = 0;
15780
+ }
15781
+ get loaded() {
15782
+ return this.count;
15783
+ }
15784
+ append(chunk) {
15785
+ this.pending.push(chunk);
15786
+ this.pendingBytes += chunk.byteLength;
15787
+ this.count += chunk.byteLength;
15788
+ if (this.pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES)
15789
+ this.fold();
15790
+ }
15791
+ appendBlob(blob) {
15792
+ this.fold();
15793
+ this.parts.push(blob);
15794
+ this.count += blob.size;
15795
+ }
15796
+ discard() {
15797
+ this.parts = [];
15798
+ this.pending = [];
15799
+ this.pendingBytes = 0;
15800
+ this.count = 0;
15801
+ }
15802
+ toBlob(type) {
15803
+ this.fold();
15804
+ return new Blob(this.parts, { type });
15805
+ }
15806
+ fold() {
15807
+ if (this.pending.length === 0)
15808
+ return;
15809
+ // Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
15810
+ // to ArrayBufferLike, which the Blob constructor's part type rejects.
15811
+ this.parts.push(new Blob(this.pending));
15812
+ this.pending = [];
15813
+ this.pendingBytes = 0;
15814
+ }
15815
+ }
14648
15816
 
14649
15817
  /**
14650
15818
  * Folders Module
@@ -14819,8 +15987,6 @@ const NAME_CONFLICT_POLICIES = ['upsert', 'complete_pending', 'refuse', 'new_nam
14819
15987
  * (shared with the public upload widget), with server-side finalization and
14820
15988
  * download-host allowlisting enforced — no per-size branching.
14821
15989
  */
14822
- const DOWNLOAD_MAX_ATTEMPTS = 3;
14823
- const DOWNLOAD_RETRY_BASE_MS = 500;
14824
15990
  class IngotsModule {
14825
15991
  constructor(config, http) {
14826
15992
  /** The client's transfer-host allowlist (`allowedDownloadHostPatterns`), as a download link is read against it. */
@@ -14878,6 +16044,18 @@ class IngotsModule {
14878
16044
  * published, so a resolved promise never stands for a stored file whose
14879
16045
  * ingot never went live.
14880
16046
  *
16047
+ * Transient failures are retried inside the transfer; a session the server
16048
+ * no longer holds (it expired, was cancelled, or its ingot was removed)
16049
+ * rejects with code `session_gone`, and only a new upload session — a new
16050
+ * {@link createUpload}, or {@link upload} again — can store the file. An
16051
+ * upload the server refused for good (the account's storage pool cannot
16052
+ * take it, or a later upload replaced it) rejects with code
16053
+ * `upload_refused`, its message the server's own sentence and its code in
16054
+ * `details.coreCode`: a new upload is no remedy. A publication the server
16055
+ * still defers at the transfer's idle limit rejects with code
16056
+ * `upload_received_publishing`: every byte is received, and the server
16057
+ * finishes the publication on its own, so never upload the file again.
16058
+ *
14881
16059
  * @param options.signal - Cancels this transfer (it rejects with code
14882
16060
  * `cancelled`); other transfers carry on.
14883
16061
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
@@ -15074,11 +16252,15 @@ class IngotsModule {
15074
16252
  * Create a signed download link for an ingot (discrete primitive).
15075
16253
  *
15076
16254
  * Validates the returned URL against the download-host allowlist. Use this
15077
- * when you want the URL itself; otherwise prefer {@link download}.
16255
+ * when you want the URL itself; otherwise prefer {@link download}. The link
16256
+ * is single-use: Forge claims it the moment a request arrives, so a retry or
16257
+ * a resume needs a link of its own (`fetchDownload`'s `remint`).
15078
16258
  *
15079
16259
  * @example
15080
16260
  * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
15081
- * window.location.href = link.downloadUrl;
16261
+ * const { blob } = await fetchDownload(link.downloadUrl, {
16262
+ * remint: async () => (await sv.ingots.createDownloadLink(unsealed, 'ing_abc')).downloadUrl,
16263
+ * });
15082
16264
  */
15083
16265
  async createDownloadLink(vault, ingotId) {
15084
16266
  const vaultId = requireVaultId(vault);
@@ -15100,35 +16282,26 @@ class IngotsModule {
15100
16282
  /**
15101
16283
  * Download an ingot as a Blob (high-level flow).
15102
16284
  *
15103
- * Requests a fresh signed link on every attempt (server URLs are
15104
- * short-lived) and retries transient transport failures with exponential
15105
- * backoff. Validation failures (bad host, non-HTTPS) are never retried.
15106
- *
15107
- * Each attempt is bounded by liveness, never by total duration: a deadline
15108
- * on the response headers, then an idle deadline rearmed on every body
15109
- * chunk. A stalled transfer restarts from byte zero: this path requests no
15110
- * byte range, so a full retry is the only recovery.
16285
+ * Every attempt fetches a signed link minted for it ({@link createDownloadLink}:
16286
+ * a link is single-use), under liveness bounds, never a cap on total
16287
+ * duration: a deadline on the response headers, then an idle deadline
16288
+ * rearmed on every body chunk. A failure the platform's transfer policy
16289
+ * retries (`@sparkvault/app-sdk/transfer-retry`: no answer, 408, 425, 429 or
16290
+ * a 5xx, a mint's included) is retried after the policy's backoff, never
16291
+ * sooner than `Retry-After`, until its budget ends. Once bytes have arrived
16292
+ * the retry resumes from the first byte it lacks, conditioned on the
16293
+ * publication's ETag (`If-Range`), so a stall at 90% fetches only the rest;
16294
+ * a file replaced meanwhile starts over as its new content, and one served
16295
+ * with no strong ETag starts over from its first byte. Any other refusal,
16296
+ * and a link that is not a Forge decrypt URL on an allowed host, is final.
15111
16297
  *
15112
16298
  * @example
15113
16299
  * const blob = await sv.ingots.download(unsealed, 'ing_abc');
15114
16300
  * const url = URL.createObjectURL(blob);
15115
16301
  */
15116
16302
  async download(vault, ingotId) {
15117
- let lastError = null;
15118
- for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
15119
- try {
15120
- const link = await this.createDownloadLink(vault, ingotId);
15121
- return (await fetchDownload(link.downloadUrl, { isAllowedHost: this.allowsTransferHost })).blob;
15122
- }
15123
- catch (err) {
15124
- lastError = err instanceof Error ? err : new Error(String(err));
15125
- if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
15126
- throw lastError;
15127
- }
15128
- await delayExponential(attempt);
15129
- }
15130
- }
15131
- throw lastError ?? new Error('Download failed');
16303
+ const mint = async () => (await this.createDownloadLink(vault, ingotId)).downloadUrl;
16304
+ return (await fetchMintedDownload(mint, { isAllowedHost: this.allowsTransferHost })).blob;
15132
16305
  }
15133
16306
  /**
15134
16307
  * Get an ingot's sharing configuration.
@@ -15331,22 +16504,6 @@ function mapInvite(wire) {
15331
16504
  identityType: wire.identity_type ?? 'email',
15332
16505
  };
15333
16506
  }
15334
- function delayExponential(attempt) {
15335
- return new Promise((resolve) => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
15336
- }
15337
- /**
15338
- * True when retrying a failed download can succeed. A validation failure always
15339
- * fails the same way again, and a refused download carries its status, retried
15340
- * only when the platform's retry rule (`@sparkvault/app-sdk/transient`) calls it
15341
- * transient; every other failure (connectivity, an answer that could not be
15342
- * read) is worth another attempt.
15343
- */
15344
- function isRetryableDownloadError(err) {
15345
- if (err instanceof ValidationError)
15346
- return false;
15347
- const status = err instanceof SparkVaultError ? err.statusCode : undefined;
15348
- return typeof status !== 'number' || status < 400 || isTransientHttpStatus(status);
15349
- }
15350
16507
 
15351
16508
  /**
15352
16509
  * Sparks Module
@@ -16056,7 +17213,7 @@ class SparkVault {
16056
17213
  }
16057
17214
  /** Get the SDK version */
16058
17215
  static get version() {
16059
- return '11.0.1';
17216
+ return '11.0.2';
16060
17217
  }
16061
17218
  }
16062
17219
  if (typeof window !== 'undefined') {