@sparkvault/sdk-js 11.0.1 → 11.0.3

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,699 @@
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, and
34
+ * the facts of a transfer token both services spell: its shape, and Core's
35
+ * revocation of an upload's token.
36
+ *
37
+ * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
38
+ * and on the final state it hands Core's activation (POST
39
+ * /v1/vaults/:vault_id/ingots/:ingot_id/activate); activation refuses any
40
+ * other version. The two services deploy separately, so a change to what
41
+ * either side sends or expects moves this number: a session or a finalize
42
+ * from the other side's contract then fails closed ("restart the upload")
43
+ * instead of publishing under a contract the other side does not hold.
44
+ *
45
+ * Version 2: an upload's own metadata (content type, original file name,
46
+ * uploader, content HMAC) travels on its upload token and its session, and
47
+ * activation publishes it from the session; the final state Forge sends
48
+ * carries only the storage facts Forge owns.
49
+ *
50
+ * Isomorphic: no Node imports.
51
+ */
52
+
53
+
54
+ /**
55
+ * The codes Core's activation refuses an upload with, which Forge's refusal
56
+ * map reads (the status is Core's):
57
+ * - UPLOAD_CONTRACT_MISMATCH (409): a finalize or session from another
58
+ * publication contract than Core's, a mixed deployment that converges — the
59
+ * upload is kept and its finalize tried again.
60
+ * - UPLOAD_PROTOCOL_RETIRED (410): a session from a contract Core no longer
61
+ * publishes, which never can be.
62
+ * - UPLOAD_SUPERSEDED (410): a session a later staging of its ingot
63
+ * superseded, which never can be.
64
+ * - UPLOAD_POOL_FULL (402): an upload the owner's storage pool cannot take at
65
+ * publication, which is final.
66
+ */
67
+ const UPLOAD_REFUSAL_CODES = Object.freeze({
68
+ UPLOAD_CONTRACT_MISMATCH: 'UPLOAD_CONTRACT_MISMATCH',
69
+ UPLOAD_PROTOCOL_RETIRED: 'UPLOAD_PROTOCOL_RETIRED',
70
+ UPLOAD_SUPERSEDED: 'UPLOAD_SUPERSEDED',
71
+ UPLOAD_POOL_FULL: 'UPLOAD_POOL_FULL'
72
+ });
73
+
74
+ /**
75
+ * The refusals of Core's that a new upload of the same file cannot remedy:
76
+ * the owner's storage pool cannot take it (UPLOAD_POOL_FULL), or a later
77
+ * upload of its ingot replaced it (UPLOAD_SUPERSEDED). Any other code Core
78
+ * ends an upload with ends its session alone, which a new upload starts
79
+ * over. Every client reads a terminal answer's code by it
80
+ * (transfer-retry.js): one of these is a refusal it reports in Core's words,
81
+ * any other a gone session.
82
+ */
83
+ const UPLOAD_FINAL_REFUSAL_CODES = Object.freeze([
84
+ UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL,
85
+ UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED
86
+ ]);
87
+
88
+ /**
89
+ * Core's revocation of an upload's encrypt token: the `status` it writes on
90
+ * the token's forge-transactions record, and the `revoked_reason` beside it,
91
+ * written by the write that ends the upload's staging. Each reason is the
92
+ * refusal every reader of the token answers the upload with from then on,
93
+ * as Core's activation refuses such an upload: Core's mint of a token it
94
+ * revoked before issuing it, and Forge on every request the token, or a
95
+ * session it opened, makes.
96
+ *
97
+ * - UPLOAD_SUPERSEDED: a later staging of its ingot superseded the upload
98
+ * (410 UPLOAD_SUPERSEDED, in UPLOAD_SUPERSEDED_MESSAGE's words), which no
99
+ * new upload remedies;
100
+ * - INGOT_DELETED: the ingot it was staged onto was deleted, by a delete or
101
+ * the cascade of its folder, vault or account (a 404 naming the ingot, as
102
+ * activation answers an upload whose ingot is gone), which ends the upload
103
+ * alone: a new upload can store the file again.
104
+ */
105
+ const UPLOAD_TOKEN_REVOCATION = Object.freeze({
106
+ status: 'revoked',
107
+ reasons: Object.freeze({
108
+ UPLOAD_SUPERSEDED: UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED,
109
+ INGOT_DELETED: 'INGOT_DELETED'
110
+ })
111
+ });
112
+
113
+ Object.values(UPLOAD_TOKEN_REVOCATION.reasons);
114
+
115
+ /**
116
+ * The response header that names the code Core refused an upload with for
117
+ * good: Forge sends it on every terminal answer to a tus request, a HEAD's
118
+ * (which has no body) included, so a client tells an upload the owner's pool
119
+ * cannot take from one a later upload superseded without reading a body.
120
+ */
121
+ const UPLOAD_REFUSAL_HEADER = 'X-Upload-Refusal';
122
+
123
+ /**
124
+ * The transfer retry policy: what every first-party client does with the
125
+ * answer to a Forge transfer request (a tus chunk PATCH, an offset HEAD, the
126
+ * receipt PATCH at the final offset), in one place, so the Node uploader
127
+ * (forge-tus), the browser SDK (sdk-js bundles this module) and the mobile SDK
128
+ * (sdk-mobile carries a generated copy) read every answer the same way.
129
+ *
130
+ * It encodes what Google Drive, Google Cloud Storage, OneDrive, Dropbox and
131
+ * AWS document for resumable transfers:
132
+ * - only a request that got no answer, 408, 425, 429 or a 5xx is retried;
133
+ * every other 4xx is the server's verdict on the request;
134
+ * - `Retry-After` is a floor, never a ceiling;
135
+ * - retries back off exponentially, capped, with jitter;
136
+ * - before a chunk is sent again the server is asked for the offset it
137
+ * committed, because a request whose answer was lost may have landed;
138
+ * - a session that is gone (404, 410) is never resumed: only a new upload
139
+ * from byte 0 can succeed;
140
+ * - a transfer's retries are bounded in time and in failures in a row, and
141
+ * both bounds start over whenever the server confirms progress.
142
+ *
143
+ * Forge's own answers beyond the general rule:
144
+ * - the 409, in two kinds: one carrying `Upload-Offset` names where the
145
+ * session stands (continue from there), and one without it means another
146
+ * request holds the session's write lease, a chunk or the finalization
147
+ * (retry after its `Retry-After`);
148
+ * - a terminal answer (a 404, 410 or 412) names the code Core ended the
149
+ * upload with: its error envelope in `error.details.coreCode` for the
150
+ * refusals it words itself, and every one of them in `X-Upload-Refusal`,
151
+ * which is all a HEAD's answer, having no body, can carry; the body's code
152
+ * wins when both name one. The code decides the verdict: a full storage
153
+ * pool or a later upload that replaced this one is a refusal no new upload
154
+ * of the same file remedies, and any other code (the file the upload was
155
+ * for gone, a retired contract, a replacement base that moved on, a code
156
+ * this policy does not know) ends the session, which a new upload can
157
+ * start over;
158
+ * - a 503 carrying `Retry-After` to the receipt (the PATCH at the final
159
+ * offset) is a deferral: Forge holds every byte and is still publishing,
160
+ * and finishes without the client, so it is asked again, each time after a
161
+ * longer backoff, for as long as the idle limit allows, and never counts as
162
+ * a failure. Forge's deferral always names when to ask again; a 503 that
163
+ * does not is an ordinary failure.
164
+ *
165
+ * Isomorphic: no Node imports, no host APIs, no randomness. The jitter only
166
+ * has to spread retries, so it hashes the transfer and the attempt
167
+ * (docs/CONVENTIONS.md → Randomness).
168
+ */
169
+
170
+
171
+ /** What a client does after a transfer request, read from its answer. */
172
+ const TRANSFER_VERDICT = Object.freeze({
173
+ /** 2xx: the request did what it asked. */
174
+ OK: 'ok',
175
+ /**
176
+ * No answer (a reset, a timeout), 408, 425, 429, a 5xx, or a 409 without
177
+ * `Upload-Offset` (another request holds the session's lease): back off,
178
+ * never sooner than `Retry-After`, then ask the server's offset before
179
+ * sending a chunk again.
180
+ */
181
+ RETRY: 'retry',
182
+ /** 409 with `Upload-Offset`: the session stands elsewhere; continue from that offset at once. */
183
+ RESYNC: 'resync',
184
+ /**
185
+ * 503 with `Retry-After` to the receipt: every byte is received and the
186
+ * publication is still running. Ask again after a backoff that grows with
187
+ * each deferral, never sooner than `Retry-After`; only the idle limit ends
188
+ * the asking, never the failures in a row.
189
+ */
190
+ DEFERRED: 'deferred',
191
+ /**
192
+ * 404 or 410 naming no code, or a 404, 410 or 412 naming a code of Core's
193
+ * that is not a final refusal (`coreCode` carries it): the session no
194
+ * longer exists; only a new upload from byte 0 can succeed.
195
+ */
196
+ GONE: 'gone',
197
+ /**
198
+ * Any other status, or a 404, 410 or 412 naming a final refusal of Core's
199
+ * (`coreCode`: UPLOAD_POOL_FULL, UPLOAD_SUPERSEDED): the server's verdict on
200
+ * this request, which repeating it, or a new upload of the same file,
201
+ * earns again.
202
+ */
203
+ REFUSED: 'refused'
204
+ });
205
+
206
+ /** The failures a transfer recovers from by trying again: the verdicts a budget's `failed` records. */
207
+ const RETRYABLE_VERDICTS = new Set([TRANSFER_VERDICT.RETRY, TRANSFER_VERDICT.RESYNC]);
208
+
209
+ /** RFC 8470: the server refused a request sent in TLS early data; the same request succeeds once the handshake completes. */
210
+ const TOO_EARLY = 425;
211
+
212
+ /** Forge's answer to a receipt whose publication it deferred. */
213
+ const SERVICE_UNAVAILABLE = 503;
214
+
215
+ /**
216
+ * The statuses a terminal answer naming Core's code arrives with: Forge's 410
217
+ * (UPLOAD_GONE, or Core's own relayed), a relayed 404, and Core's own 412.
218
+ */
219
+ const TERMINAL_STATUSES = new Set([404, 410, 412]);
220
+
221
+ /** Core's error codes are upper-case words joined by underscores; anything else names no code. */
222
+ const CORE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
223
+
224
+
225
+ const UPLOAD_OFFSET_HEADER = 'Upload-Offset';
226
+ const RETRY_AFTER_HEADER = 'Retry-After';
227
+
228
+ /**
229
+ * How long a client waits for the answer to an offset HEAD or a receipt
230
+ * PATCH, whatever its other requests get: on a received upload, Forge answers
231
+ * either only after its own call to Core (up to 30 s) has published the
232
+ * upload or deferred it, so each gets twice that.
233
+ */
234
+ const HEAD_AND_RECEIPT_TIMEOUT_MS = 60_000;
235
+
236
+ /** How a retry's delay spreads past its backoff: up to this much more. */
237
+ const JITTER_SPAN_MS = 1000;
238
+
239
+ /** How long a transfer may sit without progress or a sign of life by default. */
240
+ const DEFAULT_IDLE_LIMIT_MS = 10 * 60 * 1000;
241
+
242
+ /** How many failures in a row, without progress between them, end a transfer by default. */
243
+ const DEFAULT_MAX_CONSECUTIVE_FAILURES = 8;
244
+
245
+ /**
246
+ * @typedef {'ok'|'retry'|'resync'|'deferred'|'gone'|'refused'} TransferVerdict
247
+ */
248
+
249
+ /**
250
+ * The verdicts a transfer recovers from by trying again that count as
251
+ * failures: the ones a budget's `failed` records.
252
+ * @typedef {'retry'|'resync'} RetryableTransferVerdict
253
+ */
254
+
255
+ /**
256
+ * @typedef {Object} TransferOutcome
257
+ * @property {TransferVerdict} verdict - What the client does next
258
+ * @property {number|null} retryAfterMs - The answer's `Retry-After`, in ms from
259
+ * the answer (an HTTP-date already past reads as 0); null when absent or unreadable
260
+ * @property {number|null} offset - The answer's `Upload-Offset`; null when absent or unreadable
261
+ * @property {string|null} coreCode - The code Core ended the upload with, as a
262
+ * terminal answer named it (a 404, 410 or 412: its body's details or, those
263
+ * naming none, its `X-Upload-Refusal`): REFUSED for a final refusal
264
+ * (`UPLOAD_POOL_FULL`, `UPLOAD_SUPERSEDED`), GONE for any other code
265
+ * (`NOT_FOUND`, `UPLOAD_PROTOCOL_RETIRED`, a 412's, one this policy does not
266
+ * know); null when the answer names none
267
+ */
268
+
269
+ /**
270
+ * Read the answer to a transfer request the way the policy does.
271
+ *
272
+ * @param {Object} response
273
+ * @param {number} response.status - The HTTP status; 0 when the request got no answer
274
+ * @param {((name: string) => string|null)|null} [response.headers] - Reads a
275
+ * response header by name: a fetch `Headers`' `get` or an XHR's
276
+ * `getResponseHeader`, bound to its owner (`(name) => xhr.getResponseHeader(name)`)
277
+ * @param {unknown} [response.details] - The `details` of the error envelope the
278
+ * answer's body carries (`{ error: { code, message, details } }`), as the
279
+ * runtime's one reader of a failed answer parsed it from the whole body;
280
+ * where Forge names the refusal Core decided (`coreCode`), ahead of the
281
+ * answer's `X-Upload-Refusal`. Anything that is not an object names none.
282
+ * @param {boolean} [response.receipt] - The request was the receipt: the PATCH
283
+ * at the final offset, whose 503 carrying `Retry-After` is a deferral
284
+ * @param {number} [response.now] - When the answer arrived (epoch ms), which an
285
+ * HTTP-date `Retry-After` counts from
286
+ * @returns {TransferOutcome}
287
+ * @throws {TypeError} When the status is not a whole number, headers is not a
288
+ * function, or receipt is not a boolean
289
+ */
290
+ function classifyTransferResponse({ status, headers = null, details = null, receipt = false, now = Date.now() }) {
291
+ if (!Number.isSafeInteger(status) || status < 0) {
292
+ throw new TypeError(`A transfer answer's status is a whole number (0 for no answer), not ${status}`);
293
+ }
294
+ if (headers !== null && typeof headers !== 'function') {
295
+ throw new TypeError('A transfer answer\'s headers are read through a function from a header name to its value');
296
+ }
297
+ if (typeof receipt !== 'boolean') {
298
+ throw new TypeError(`Whether a transfer request was the receipt is a boolean, not ${receipt}`);
299
+ }
300
+ if (status === 0) {
301
+ return { verdict: TRANSFER_VERDICT.RETRY, retryAfterMs: null, offset: null, coreCode: null };
302
+ }
303
+ const header = (name) => (headers === null ? null : headers(name));
304
+ const offset = readCount(header(UPLOAD_OFFSET_HEADER));
305
+ const coreCode = TERMINAL_STATUSES.has(status)
306
+ ? coreCodeIn(details) ?? coreCodeOf(header(UPLOAD_REFUSAL_HEADER))
307
+ : null;
308
+ const retryAfterMs = readRetryAfterMs(header(RETRY_AFTER_HEADER), now);
309
+ return {
310
+ verdict: verdictFor(status, { offset, coreCode, deferral: receipt && retryAfterMs !== null }),
311
+ retryAfterMs,
312
+ offset,
313
+ coreCode
314
+ };
315
+ }
316
+
317
+ /**
318
+ * The verdict on a status that came with an answer: `offset` its readable
319
+ * `Upload-Offset`, `coreCode` the code of Core's a terminal answer names,
320
+ * `deferral` whether it answered the receipt with a readable `Retry-After`.
321
+ */
322
+ function verdictFor(status, { offset, coreCode, deferral }) {
323
+ if (status >= 200 && status < 300) return TRANSFER_VERDICT.OK;
324
+ if (status === 409) return offset === null ? TRANSFER_VERDICT.RETRY : TRANSFER_VERDICT.RESYNC;
325
+ if (coreCode !== null) return UPLOAD_FINAL_REFUSAL_CODES.includes(coreCode) ? TRANSFER_VERDICT.REFUSED : TRANSFER_VERDICT.GONE;
326
+ if (status === 404 || status === 410) return TRANSFER_VERDICT.GONE;
327
+ if (deferral && status === SERVICE_UNAVAILABLE) return TRANSFER_VERDICT.DEFERRED;
328
+ if (status === TOO_EARLY || isTransientHttpStatus(status)) return TRANSFER_VERDICT.RETRY;
329
+ return TRANSFER_VERDICT.REFUSED;
330
+ }
331
+
332
+ /** The code an error envelope's details name (`coreCode`), or null. */
333
+ function coreCodeIn(details) {
334
+ return details && typeof details === 'object' ? coreCodeOf(details.coreCode) : null;
335
+ }
336
+
337
+ /** A value that is one of Core's codes (surrounding whitespace allowed), or null. */
338
+ function coreCodeOf(value) {
339
+ if (typeof value !== 'string') return null;
340
+ const code = value.trim();
341
+ return CORE_CODE.test(code) ? code : null;
342
+ }
343
+
344
+ /** A header's non-negative whole number (surrounding whitespace allowed), or null. */
345
+ function readCount(value) {
346
+ if (typeof value !== 'string') return null;
347
+ const text = value.trim();
348
+ if (!/^\d+$/.test(text)) return null;
349
+ const count = Number(text);
350
+ return Number.isSafeInteger(count) ? count : null;
351
+ }
352
+
353
+ /** RFC 9110 §10.2.3: `Retry-After` is delay-seconds or an HTTP-date. */
354
+ function readRetryAfterMs(value, now) {
355
+ const seconds = readCount(value);
356
+ if (seconds !== null) {
357
+ const ms = seconds * 1000;
358
+ return Number.isSafeInteger(ms) ? ms : null;
359
+ }
360
+ const at = typeof value === 'string' ? parseHttpDate(value.trim(), now) : null;
361
+ return at === null ? null : Math.max(0, at - now);
362
+ }
363
+
364
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
365
+ const DAY_NAME = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)';
366
+ const LONG_DAY_NAME = '(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)';
367
+ const MONTH = `(${MONTHS.join('|')})`;
368
+ const TIME_OF_DAY = '(\\d{2}):(\\d{2}):(\\d{2})';
369
+
370
+ /** IMF-fixdate, what every current server sends: `Sun, 06 Nov 1994 08:49:37 GMT`. */
371
+ const IMF_FIXDATE = new RegExp(`^${DAY_NAME}, (\\d{2}) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`);
372
+ /** The obsolete RFC 850 form a recipient still accepts: `Sunday, 06-Nov-94 08:49:37 GMT`. */
373
+ const RFC850_DATE = new RegExp(`^${LONG_DAY_NAME}, (\\d{2})-${MONTH}-(\\d{2}) ${TIME_OF_DAY} GMT$`);
374
+ /** The obsolete asctime form a recipient still accepts: `Sun Nov 6 08:49:37 1994`. */
375
+ const ASCTIME_DATE = new RegExp(`^${DAY_NAME} ${MONTH} ( \\d|\\d{2}) ${TIME_OF_DAY} (\\d{4})$`);
376
+
377
+ /**
378
+ * An HTTP-date (RFC 9110 §5.6.7, all three forms a recipient must accept) as
379
+ * epoch ms, or null when it is not one or names no real moment.
380
+ *
381
+ * @param {string} text
382
+ * @param {number} now - epoch ms, which places an RFC 850 two-digit year
383
+ * @returns {number|null}
384
+ */
385
+ function parseHttpDate(text, now) {
386
+ let match = IMF_FIXDATE.exec(text);
387
+ if (match) {
388
+ const [, day, month, year, hours, minutes, seconds] = match;
389
+ return utcMs(Number(year), month, Number(day), hours, minutes, seconds);
390
+ }
391
+ match = RFC850_DATE.exec(text);
392
+ if (match) {
393
+ const [, day, month, shortYear, hours, minutes, seconds] = match;
394
+ return utcMs(rfc850Year(Number(shortYear), now), month, Number(day), hours, minutes, seconds);
395
+ }
396
+ match = ASCTIME_DATE.exec(text);
397
+ if (match) {
398
+ const [, month, day, hours, minutes, seconds, year] = match;
399
+ return utcMs(Number(year), month, Number(day.trim()), hours, minutes, seconds);
400
+ }
401
+ return null;
402
+ }
403
+
404
+ /** RFC 9110: a two-digit year more than 50 years ahead is the latest past year with those digits. */
405
+ function rfc850Year(shortYear, now) {
406
+ const currentYear = new Date(now).getUTCFullYear();
407
+ const year = currentYear - (currentYear % 100) + shortYear;
408
+ return year > currentYear + 50 ? year - 100 : year;
409
+ }
410
+
411
+ /** The UTC instant of a calendar date and time of day, or null for a date or time that does not exist. */
412
+ function utcMs(year, monthName, day, hours, minutes, seconds) {
413
+ const monthIndex = MONTHS.indexOf(monthName);
414
+ const [h, m, s] = [Number(hours), Number(minutes), Number(seconds)];
415
+ // A leap second (60) is a real time of day; the instant rolls into the next minute.
416
+ if (h > 23 || m > 59 || s > 60) return null;
417
+ const date = new Date(0);
418
+ date.setUTCFullYear(year, monthIndex, day);
419
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== day) {
420
+ return null;
421
+ }
422
+ return date.getTime() + ((h * 60 + m) * 60 + s) * 1000;
423
+ }
424
+
425
+ const FNV_OFFSET_BASIS = 0x811c9dc5;
426
+ const FNV_PRIME = 0x01000193;
427
+
428
+ /**
429
+ * 32-bit FNV-1a over the text's UTF-8 bytes: the jitter's hash. A retry's
430
+ * delay only has to spread, so it hashes what identifies the retry and draws
431
+ * nothing (docs/CONVENTIONS.md → Randomness).
432
+ *
433
+ * @param {string} text
434
+ * @returns {number} An unsigned 32-bit integer
435
+ * @throws {TypeError} When the text is not a string
436
+ */
437
+ function fnv1a32(text) {
438
+ if (typeof text !== 'string') {
439
+ throw new TypeError(`fnv1a32 hashes a string, not ${typeof text}`);
440
+ }
441
+ let hash = FNV_OFFSET_BASIS;
442
+ const mix = (byte) => {
443
+ hash = Math.imul(hash ^ byte, FNV_PRIME) >>> 0;
444
+ };
445
+ for (const character of text) {
446
+ let point = character.codePointAt(0);
447
+ // A lone surrogate has no UTF-8 form; it encodes as U+FFFD, as TextEncoder does.
448
+ if (point >= 0xd800 && point <= 0xdfff) point = 0xfffd;
449
+ if (point < 0x80) {
450
+ mix(point);
451
+ } else if (point < 0x800) {
452
+ mix(0xc0 | (point >> 6));
453
+ mix(0x80 | (point & 0x3f));
454
+ } else if (point < 0x10000) {
455
+ mix(0xe0 | (point >> 12));
456
+ mix(0x80 | ((point >> 6) & 0x3f));
457
+ mix(0x80 | (point & 0x3f));
458
+ } else {
459
+ mix(0xf0 | (point >> 18));
460
+ mix(0x80 | ((point >> 12) & 0x3f));
461
+ mix(0x80 | ((point >> 6) & 0x3f));
462
+ mix(0x80 | (point & 0x3f));
463
+ }
464
+ }
465
+ return hash;
466
+ }
467
+
468
+ /** Transfers this runtime has keyed by `transferJitterKey`: with the start time, what tells them apart. */
469
+ let transfersKeyed = 0;
470
+
471
+ /**
472
+ * What a transfer's retries spread by when no session URL keys them yet (a
473
+ * session create) or ever (a download, whose link carries its token): the
474
+ * scope (the create endpoint, or the kind of transfer), when the transfer
475
+ * started, and this runtime's count of keyed transfers, which tell
476
+ * concurrent transfers apart. A transfer's token is a credential and never
477
+ * feeds anything observable such as a delay, so no part of the key derives
478
+ * from it (docs/CONVENTIONS.md → Randomness).
479
+ *
480
+ * @param {string} scope - The endpoint or the kind of transfer
481
+ * @returns {string} The key, for every retry of this one transfer
482
+ * @throws {TypeError} For a scope that is not a non-empty string
483
+ */
484
+ function transferJitterKey(scope) {
485
+ if (typeof scope !== 'string' || scope.length === 0) {
486
+ throw new TypeError('A transfer jitter key needs the scope its transfer runs in');
487
+ }
488
+ transfersKeyed += 1;
489
+ return `${scope}#${Date.now()}-${transfersKeyed}`;
490
+ }
491
+
492
+ /**
493
+ * How long to wait before retry `attempt` of a transfer: `baseMs` doubling per
494
+ * attempt, capped at `capMs`, plus a jitter in [0, 1000) ms hashed from the
495
+ * transfer and the attempt, and never less than the server's `Retry-After`.
496
+ * The same transfer and attempt always wait the same; different transfers
497
+ * failing together spread out.
498
+ *
499
+ * @param {Object} options
500
+ * @param {number} options.attempt - Which retry this is, from 1
501
+ * @param {number|null} [options.retryAfterMs] - The answer's `Retry-After`: a floor
502
+ * @param {number} [options.baseMs] - The first retry's backoff
503
+ * @param {number} [options.capMs] - The longest backoff, before jitter
504
+ * @param {string} options.jitterKey - What identifies the transfer (its session
505
+ * URL, or a `transferJitterKey`)
506
+ * @returns {number} ms
507
+ * @throws {TypeError} For an attempt that is not a whole number from 1, a
508
+ * missing jitter key, or a delay bound that is not a positive number of ms
509
+ */
510
+ function retryDelayMs({ attempt, retryAfterMs = null, baseMs = 1000, capMs = 32000, jitterKey }) {
511
+ if (!Number.isSafeInteger(attempt) || attempt < 1) {
512
+ throw new TypeError(`A retry's attempt is a whole number from 1, not ${attempt}`);
513
+ }
514
+ if (typeof jitterKey !== 'string' || jitterKey.length === 0) {
515
+ throw new TypeError('A retry delay needs the key its transfer spreads by');
516
+ }
517
+ if (!isDuration(baseMs) || baseMs === 0 || !isDuration(capMs) || capMs < baseMs) {
518
+ throw new TypeError(`A retry backs off from a positive base (${baseMs} ms) up to a cap no smaller (${capMs} ms)`);
519
+ }
520
+ if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
521
+ throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
522
+ }
523
+ const backoff = Math.min(capMs, baseMs * 2 ** (attempt - 1));
524
+ const jitter = Math.floor((fnv1a32(`${jitterKey}|${attempt}`) / 2 ** 32) * JITTER_SPAN_MS);
525
+ return Math.max(backoff + jitter, retryAfterMs ?? 0);
526
+ }
527
+
528
+ function isDuration(ms) {
529
+ return Number.isFinite(ms) && ms >= 0;
530
+ }
531
+
532
+ /**
533
+ * @typedef {Object} TransferBudget
534
+ * @property {() => void} progressed - The server confirmed progress (bytes
535
+ * landed, or the offset it names moved forward): the failures in a row and
536
+ * the idle clock start over
537
+ * @property {() => void} alive - A sign of life the server has not confirmed
538
+ * (bytes are leaving, or the device is back online): the idle clock starts
539
+ * over and the failures in a row stand, so attempts that die before the
540
+ * server confirms anything still end the transfer
541
+ * @property {(verdict: RetryableTransferVerdict, retryAfterMs?: number|null) => boolean} failed -
542
+ * Records a retryable answer (RETRY or RESYNC) and says whether another
543
+ * attempt is allowed: the failures in a row stay under the max, and the
544
+ * attempt `retryAfterMs` allows would start inside the idle limit, so a
545
+ * transfer never sleeps on a Retry-After longer than its budget. The limit
546
+ * bounds when a retry is decided; a retry decided inside it still waits its
547
+ * own backoff, so a transfer ends within one backoff of the limit.
548
+ * @property {(retryAfterMs?: number|null) => boolean} deferred - Records a
549
+ * DEFERRED answer and says whether to ask again: only the idle limit bounds
550
+ * it, as `failed` applies it, because a deferral is the server at work,
551
+ * never a failure, so the failures in a row stand
552
+ * @property {number} consecutiveFailures - Retryable failures since the last progress
553
+ * @property {number} attempt - Failures and deferrals since the last progress:
554
+ * the attempt the next wait's delay is computed for, so each deferral backs
555
+ * the next ask off as a failure does, sparing a Core that is struggling to
556
+ * publish
557
+ * @property {number} msSinceProgress - ms since the last progress or sign of life
558
+ */
559
+
560
+ /**
561
+ * The retry budget of one transfer: retries are bounded by failures in a row
562
+ * and by time without progress, deferrals by time alone, and both bounds
563
+ * start over whenever the server confirms progress, so a slow transfer that
564
+ * keeps landing bytes is never cut off while a dead one ends in bounded time.
565
+ *
566
+ * @param {Object} [options]
567
+ * @param {number} [options.idleLimitMs] - How long the transfer may go without
568
+ * progress or a sign of life
569
+ * @param {number} [options.maxConsecutiveFailures] - Failures in a row that end the transfer
570
+ * @param {() => number} [options.now] - The clock, epoch ms
571
+ * @returns {TransferBudget}
572
+ * @throws {TypeError} For a limit that is not a positive number, or a clock that is not a function
573
+ */
574
+ function createTransferBudget({
575
+ idleLimitMs = DEFAULT_IDLE_LIMIT_MS,
576
+ maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,
577
+ now = () => Date.now()
578
+ } = {}) {
579
+ if (!isDuration(idleLimitMs) || idleLimitMs === 0) {
580
+ throw new TypeError(`A transfer's idle limit is a positive number of ms, not ${idleLimitMs}`);
581
+ }
582
+ if (!Number.isSafeInteger(maxConsecutiveFailures) || maxConsecutiveFailures < 1) {
583
+ throw new TypeError(`A transfer's failure limit is a whole number from 1, not ${maxConsecutiveFailures}`);
584
+ }
585
+ if (typeof now !== 'function') {
586
+ throw new TypeError('A transfer budget reads time from a clock function');
587
+ }
588
+
589
+ let consecutiveFailures = 0;
590
+ let deferrals = 0;
591
+ let lastSignOfLifeAt = now();
592
+ const msIdle = () => now() - lastSignOfLifeAt;
593
+ const startsInsideIdleLimit = (retryAfterMs) => {
594
+ if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
595
+ throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
596
+ }
597
+ return msIdle() + (retryAfterMs ?? 0) < idleLimitMs;
598
+ };
599
+
600
+ return Object.freeze({
601
+ progressed() {
602
+ consecutiveFailures = 0;
603
+ deferrals = 0;
604
+ lastSignOfLifeAt = now();
605
+ },
606
+ alive() {
607
+ lastSignOfLifeAt = now();
608
+ },
609
+ failed(verdict, retryAfterMs = null) {
610
+ if (!RETRYABLE_VERDICTS.has(verdict)) {
611
+ throw new TypeError(`A transfer budget records retryable answers only, not '${verdict}'`);
612
+ }
613
+ const allowed = startsInsideIdleLimit(retryAfterMs);
614
+ consecutiveFailures += 1;
615
+ return allowed && consecutiveFailures < maxConsecutiveFailures;
616
+ },
617
+ deferred(retryAfterMs = null) {
618
+ const allowed = startsInsideIdleLimit(retryAfterMs);
619
+ deferrals += 1;
620
+ return allowed;
621
+ },
622
+ get consecutiveFailures() {
623
+ return consecutiveFailures;
624
+ },
625
+ get attempt() {
626
+ return consecutiveFailures + deferrals;
627
+ },
628
+ get msSinceProgress() {
629
+ return msIdle();
630
+ }
631
+ });
632
+ }
633
+
634
+ /** Why an offset the server names cannot be resumed from. */
635
+ const RESUME_OFFSET_PROBLEM = Object.freeze({
636
+ /** Not a non-negative whole number of bytes. */
637
+ INVALID: 'invalid',
638
+ /** Past the upload's length: resuming from it would report a partial upload complete. */
639
+ BEYOND_TOTAL: 'beyond_total',
640
+ /** Inside a chunk: a session commits whole chunks only, so the answer is corrupt. */
641
+ MISALIGNED: 'misaligned'
642
+ });
643
+
644
+ /**
645
+ * Why a session offset the server named (a HEAD's, or a 409's `Upload-Offset`)
646
+ * cannot be resumed from, or null when it can. Forge commits whole chunks, so
647
+ * a session stands at a multiple of its chunk size or at its total.
648
+ *
649
+ * @param {number|null} offset
650
+ * @param {Object} geometry
651
+ * @param {number} geometry.totalSize - The upload's length (a non-negative whole number)
652
+ * @param {number} geometry.chunkSize - The session's chunk size (a positive whole number)
653
+ * @returns {'invalid'|'beyond_total'|'misaligned'|null}
654
+ * @throws {TypeError} When the length is not a non-negative whole number or
655
+ * the chunk size not a positive one
656
+ */
657
+ function resumeOffsetProblem(offset, { totalSize, chunkSize }) {
658
+ if (!Number.isSafeInteger(totalSize) || totalSize < 0 || !Number.isSafeInteger(chunkSize) || chunkSize < 1) {
659
+ throw new TypeError(`An upload's geometry is a whole length and a positive chunk size, not ${totalSize} and ${chunkSize}`);
660
+ }
661
+ if (!Number.isSafeInteger(offset) || offset < 0) return RESUME_OFFSET_PROBLEM.INVALID;
662
+ if (offset > totalSize) return RESUME_OFFSET_PROBLEM.BEYOND_TOTAL;
663
+ if (offset !== totalSize && offset % chunkSize !== 0) return RESUME_OFFSET_PROBLEM.MISALIGNED;
664
+ return null;
665
+ }
666
+
5
667
  /**
6
668
  * SparkVault SDK Error Types
7
669
  */
8
670
  class SparkVaultError extends Error {
9
- constructor(message, code, statusCode, details) {
671
+ constructor(message, code, statusCode, details, retryAfterMs = null) {
10
672
  super(message);
11
673
  this.name = 'SparkVaultError';
12
674
  this.code = code;
13
675
  this.statusCode = statusCode;
14
676
  this.details = details;
677
+ this.retryAfterMs = retryAfterMs;
15
678
  Object.setPrototypeOf(this, SparkVaultError.prototype);
16
679
  }
17
680
  }
18
681
  class AuthenticationError extends SparkVaultError {
19
- constructor(message, details) {
20
- super(message, 'authentication_error', 401, details);
682
+ constructor(message, details, retryAfterMs = null) {
683
+ super(message, 'authentication_error', 401, details, retryAfterMs);
21
684
  this.name = 'AuthenticationError';
22
685
  Object.setPrototypeOf(this, AuthenticationError.prototype);
23
686
  }
24
687
  }
25
688
  class AuthorizationError extends SparkVaultError {
26
- constructor(message, details) {
27
- super(message, 'authorization_error', 403, details);
689
+ constructor(message, details, retryAfterMs = null) {
690
+ super(message, 'authorization_error', 403, details, retryAfterMs);
28
691
  this.name = 'AuthorizationError';
29
692
  Object.setPrototypeOf(this, AuthorizationError.prototype);
30
693
  }
31
694
  }
32
695
  class ValidationError extends SparkVaultError {
33
- constructor(message, details) {
34
- super(message, 'validation_error', 400, details);
696
+ constructor(message, details, retryAfterMs = null) {
697
+ super(message, 'validation_error', 400, details, retryAfterMs);
35
698
  this.name = 'ValidationError';
36
699
  Object.setPrototypeOf(this, ValidationError.prototype);
37
700
  }
@@ -42,8 +705,8 @@ class ValidationError extends SparkVaultError {
42
705
  * to admins, or "ask your account admin" to members.
43
706
  */
44
707
  class PlanRequiredError extends SparkVaultError {
45
- constructor(message, details) {
46
- super(message, 'PLAN_REQUIRED', 402, details);
708
+ constructor(message, details, retryAfterMs = null) {
709
+ super(message, 'PLAN_REQUIRED', 402, details, retryAfterMs);
47
710
  this.name = 'PlanRequiredError';
48
711
  Object.setPrototypeOf(this, PlanRequiredError.prototype);
49
712
  }
@@ -54,8 +717,8 @@ class PlanRequiredError extends SparkVaultError {
54
717
  * the right capacity block.
55
718
  */
56
719
  class QuotaExceededError extends SparkVaultError {
57
- constructor(message, details) {
58
- super(message, 'QUOTA_EXCEEDED', 402, details);
720
+ constructor(message, details, retryAfterMs = null) {
721
+ super(message, 'QUOTA_EXCEEDED', 402, details, retryAfterMs);
59
722
  this.name = 'QuotaExceededError';
60
723
  const resource = details?.resource;
61
724
  this.resource =
@@ -70,8 +733,8 @@ class QuotaExceededError extends SparkVaultError {
70
733
  * nothing, so surface a subscribe CTA rather than a sign-in prompt.
71
734
  */
72
735
  class NotifySubscriptionRequiredError extends SparkVaultError {
73
- constructor(message, details) {
74
- super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details);
736
+ constructor(message, details, retryAfterMs = null) {
737
+ super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details, retryAfterMs);
75
738
  this.name = 'NotifySubscriptionRequiredError';
76
739
  Object.setPrototypeOf(this, NotifySubscriptionRequiredError.prototype);
77
740
  }
@@ -127,24 +790,51 @@ function recordField(value) {
127
790
  ? value
128
791
  : undefined;
129
792
  }
793
+ function parseJson(text) {
794
+ try {
795
+ return JSON.parse(text);
796
+ }
797
+ catch {
798
+ return null;
799
+ }
800
+ }
130
801
  /**
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.
802
+ * Read a failed answer from its parsed body: the one reading every SDK
803
+ * transport shares, so an error built from an answer carries the same of it
804
+ * whichever client made the request, and whether fetch or an XMLHttpRequest
805
+ * received it. SparkVault services answer `{ error: { code, message,
806
+ * details } }`; a framework or gateway answers flat (`{ code, message }`,
807
+ * `{ message }`) or with no JSON at all, so each field falls back to its flat
808
+ * form and then to a default. The body is read leniently: a failure's status
809
+ * and class never depend on the body being JSON. The `Retry-After` is read by
810
+ * the transfer policy's one parser (`@sparkvault/app-sdk/transfer-retry`),
811
+ * never a second one: the policy reads a whole answer at once, and only its
812
+ * header reading is kept here, because an API answer is the service's
813
+ * verdict, never a transfer answer the policy's verdict applies to.
137
814
  */
138
- async function readApiErrorBody(response) {
139
- const body = await response.json().catch(() => null);
815
+ function failureOf(status, body, header) {
140
816
  const root = recordField(body) ?? {};
141
817
  const nested = recordField(root.error);
142
818
  return {
819
+ status,
143
820
  message: stringField(nested?.message) ?? stringField(root.message) ?? stringField(root.error) ?? 'Request failed',
144
821
  code: stringField(nested?.code) ?? stringField(root.code) ?? 'api_error',
145
822
  details: recordField(nested?.details) ?? recordField(root.details),
823
+ retryAfterMs: classifyTransferResponse({ status, headers: header }).retryAfterMs,
146
824
  };
147
825
  }
826
+ /**
827
+ * Read a failed answer a transport holds as text (an XMLHttpRequest's
828
+ * `responseText`, a body it also keeps a snippet of), parsed whole, so
829
+ * nothing past any length is lost to the reading.
830
+ */
831
+ function apiFailureOf(answer) {
832
+ return failureOf(answer.status, parseJson(answer.body), answer.header);
833
+ }
834
+ /** Read a failed fetch response; a body that is not JSON, or cannot be read, reads as none. */
835
+ async function readApiFailure(response) {
836
+ return failureOf(response.status, await response.json().catch(() => null), (name) => response.headers.get(name));
837
+ }
148
838
 
149
839
  /**
150
840
  * SparkVault resource ids: the one grammar every surface reads an id by before
@@ -480,10 +1170,14 @@ class SparkVaultApi {
480
1170
  * here, when the request starts. resetSession() can swap the controller
481
1171
  * while the request is in flight, and reading the live one afterwards would
482
1172
  * misreport a genuine cancel as a timeout.
1173
+ *
1174
+ * @param timeoutMs - The deadline of a request whose server-side wait is
1175
+ * its own (a tus HEAD or receipt, which Forge answers only after its call
1176
+ * to Core); every other request takes the client's.
483
1177
  */
484
- send(url, init, copy, read) {
1178
+ send(url, init, copy, read, timeoutMs = this.timeoutMs) {
485
1179
  return exchange(url, init, {
486
- timeoutMs: this.timeoutMs,
1180
+ timeoutMs,
487
1181
  closeSignal: this.closeController.signal,
488
1182
  read,
489
1183
  fail: (failure, cause) => {
@@ -503,8 +1197,9 @@ class SparkVaultApi {
503
1197
  /**
504
1198
  * Issue a JSON API request. Returns the parsed JSON body (whatever shape it
505
1199
  * 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.
1200
+ * answer throws the subclass error carrying the server's code, message,
1201
+ * details and `Retry-After`, read by the one failed-answer reader every
1202
+ * transport shares.
508
1203
  */
509
1204
  rawRequest(url, options) {
510
1205
  // Only send Content-Type when there's actually a body — otherwise GETs
@@ -520,8 +1215,8 @@ class SparkVaultApi {
520
1215
  network: 'Unable to connect. Please check your connection and try again.',
521
1216
  }, async (response) => {
522
1217
  if (!response.ok) {
523
- const { message, code, details } = await readApiErrorBody(response);
524
- throw this.makeError(message, code, response.status, details);
1218
+ const { status, message, code, details, retryAfterMs } = await readApiFailure(response);
1219
+ throw this.makeError(message, code, status, details, retryAfterMs);
525
1220
  }
526
1221
  return { data: await readJsonBody(response), status: response.status };
527
1222
  });
@@ -649,7 +1344,7 @@ class HttpClient {
649
1344
  timeoutMs: timeout,
650
1345
  read: async (response) => {
651
1346
  if (!response.ok) {
652
- throw this.createErrorFromResponse(response.status, await readApiErrorBody(response));
1347
+ throw this.createErrorFromResponse(await readApiFailure(response));
653
1348
  }
654
1349
  const parsed = await this.parseResponse(response);
655
1350
  return {
@@ -687,26 +1382,34 @@ class HttpClient {
687
1382
  const text = await response.text();
688
1383
  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
1384
  }
690
- createErrorFromResponse(status, { message, code, details }) {
1385
+ /**
1386
+ * The SDK error for a failed answer, typed by its status: the gates a host
1387
+ * page branches on get their own class, and every other answer is the base
1388
+ * error under the service's own code. Each carries the answer's
1389
+ * `Retry-After` (`retryAfterMs`), the floor for whoever retries it — the
1390
+ * SDK's own transfers when the answer is a download link's mint, and the
1391
+ * host page otherwise.
1392
+ */
1393
+ createErrorFromResponse({ status, message, code, details, retryAfterMs }) {
691
1394
  switch (status) {
692
1395
  case 400:
693
- return new ValidationError(message, details);
1396
+ return new ValidationError(message, details, retryAfterMs);
694
1397
  case 401:
695
- return new AuthenticationError(message, details);
1398
+ return new AuthenticationError(message, details, retryAfterMs);
696
1399
  case 402:
697
1400
  if (code === 'QUOTA_EXCEEDED')
698
- return new QuotaExceededError(message, details);
1401
+ return new QuotaExceededError(message, details, retryAfterMs);
699
1402
  // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
700
- return new PlanRequiredError(message, details);
1403
+ return new PlanRequiredError(message, details, retryAfterMs);
701
1404
  case 403:
702
1405
  // A Notify send refused for want of a subscription is a billing gate, not
703
1406
  // a credential problem — give it its own catchable type.
704
1407
  if (code === 'NOTIFY_SUBSCRIPTION_REQUIRED') {
705
- return new NotifySubscriptionRequiredError(message, details);
1408
+ return new NotifySubscriptionRequiredError(message, details, retryAfterMs);
706
1409
  }
707
- return new AuthorizationError(message, details);
1410
+ return new AuthorizationError(message, details, retryAfterMs);
708
1411
  default:
709
- return new SparkVaultError(message, code, status, details);
1412
+ return new SparkVaultError(message, code, status, details, retryAfterMs);
710
1413
  }
711
1414
  }
712
1415
  unwrapApiResponse(data) {
@@ -1502,8 +2205,8 @@ class IdentityApi extends SparkVaultApi {
1502
2205
  get baseUrl() {
1503
2206
  return `${this.config.identityBaseUrl}${apiPath `/${this.config.accountId}`}`;
1504
2207
  }
1505
- makeError(message, code, statusCode, details) {
1506
- return new IdentityApiError(message, code, statusCode, details);
2208
+ makeError(message, code, statusCode, details, retryAfterMs = null) {
2209
+ return new IdentityApiError(message, code, statusCode, details, retryAfterMs);
1507
2210
  }
1508
2211
  async request(method, endpoint, body, query) {
1509
2212
  const { data } = await this.rawRequest(`${this.baseUrl}${endpoint}${queryString(query)}`, {
@@ -1879,8 +2582,8 @@ function mapRecommendations(raw) {
1879
2582
  return result;
1880
2583
  }
1881
2584
  class IdentityApiError extends SparkVaultError {
1882
- constructor(message, code, statusCode, details) {
1883
- super(message, code, statusCode, details);
2585
+ constructor(message, code, statusCode, details, retryAfterMs = null) {
2586
+ super(message, code, statusCode, details, retryAfterMs);
1884
2587
  this.name = 'IdentityApiError';
1885
2588
  Object.setPrototypeOf(this, IdentityApiError.prototype);
1886
2589
  }
@@ -10988,11 +11691,21 @@ function refused(reason) {
10988
11691
  /**
10989
11692
  * Error class for upload API errors. Inherits `code` and `statusCode` from
10990
11693
  * SparkVaultError — no duplicate `httpStatus` field.
11694
+ *
11695
+ * A failed transfer request also carries what the transfer policy
11696
+ * (`@sparkvault/app-sdk/transfer-retry`) makes of its answer, read where the
11697
+ * answer arrived: its `verdict` and its `Upload-Offset` (`serverOffset`),
11698
+ * beside the `Retry-After` every SDK error carries (`retryAfterMs`). They are
11699
+ * the retry loop's bookkeeping, so they ride on the instance, never in
11700
+ * `details`. Every other failure (a cancel, a refused URL, a protocol
11701
+ * violation) is `refused`: nothing retries it.
10991
11702
  */
10992
11703
  class UploadApiError extends SparkVaultError {
10993
- constructor(message, code, statusCode, details) {
10994
- super(message, code, statusCode, details);
11704
+ constructor(message, code, statusCode, details, outcome) {
11705
+ super(message, code, statusCode, details, outcome?.retryAfterMs ?? null);
10995
11706
  this.name = 'UploadApiError';
11707
+ this.verdict = outcome?.verdict ?? TRANSFER_VERDICT.REFUSED;
11708
+ this.serverOffset = outcome?.offset ?? null;
10996
11709
  Object.setPrototypeOf(this, UploadApiError.prototype);
10997
11710
  }
10998
11711
  }
@@ -11055,51 +11768,91 @@ function parseChunkSizeHeader(raw) {
11055
11768
  */
11056
11769
  const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
11057
11770
  /**
11058
- * Per-chunk retry budget for the PATCH loop.
11771
+ * How many consecutive timeouts end the finalization receipt early.
11059
11772
  *
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.
11773
+ * A genuinely slow finalize shows up as ONE timeout — the PATCH that started
11774
+ * the re-drive — followed by 409s from the writer that is working on it.
11775
+ * Back-to-back timeouts mean nobody is answering at all, and spending the
11776
+ * whole retry budget on a black-holed socket would freeze the widget at 100%
11777
+ * for minutes with nothing for the user to act on.
11066
11778
  */
11067
- const CHUNK_MAX_ATTEMPTS = 3;
11068
- const CHUNK_RETRY_BASE_MS = 500;
11779
+ const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
11780
+ /** The copy a person reads when the session their upload ran in no longer exists. */
11781
+ const SESSION_GONE_MESSAGE = 'Upload could not be finished: the server has ended this upload session. Please upload the file again.';
11069
11782
  /**
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.
11783
+ * The copy a person reads when the server kept deferring the publication
11784
+ * until the upload's idle limit: nothing failed, and nothing is left for
11785
+ * them to do.
11076
11786
  */
11077
- const FINALIZE_MAX_ATTEMPTS = 10;
11078
- const FINALIZE_RETRY_MS = 1000;
11787
+ const RECEIVED_PUBLISHING_MESSAGE = 'The server received every byte of this file and is still saving it. It finishes on its own.';
11079
11788
  /**
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.
11789
+ * The copy a person reads for a final refusal whose answer carried no
11790
+ * sentence of Core's (a HEAD's, which has no body, naming Core's code in
11791
+ * `X-Upload-Refusal` alone): this SDK's own words for each code, none of them
11792
+ * asking for the file again.
11087
11793
  */
11088
- const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
11794
+ const REFUSAL_WORDING = new Map([
11795
+ [UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL, 'This upload could not be saved: the owner\'s storage cannot take the file.'],
11796
+ [UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED, 'This upload was not saved: a newer upload of this file replaced it.'],
11797
+ ]);
11798
+ /** The copy for a final refusal of a code this SDK has no words of its own for. */
11799
+ const REFUSED_MESSAGE = 'This upload could not be saved: the server refused it.';
11800
+ /**
11801
+ * The error of an upload Core refused for good (UPLOAD_FINAL_REFUSAL_CODES):
11802
+ * `upload_refused` in Core's own sentence, this SDK's for an answer that
11803
+ * carried none (a HEAD's), Core's code in `details.coreCode`; never retried,
11804
+ * and no new upload of the same file remedies it. The one reading of that
11805
+ * verdict, whichever answer carries it: a transfer answer naming Core's code
11806
+ * ({@link readTransferAnswer}), or Core's own refusal of the request that
11807
+ * stages the upload ({@link stagingRefusal}).
11808
+ */
11809
+ function uploadRefusedError(coreCode, message, status, outcome) {
11810
+ return new UploadApiError(message ?? REFUSAL_WORDING.get(coreCode) ?? REFUSED_MESSAGE, 'upload_refused', status, { status, coreCode }, outcome);
11811
+ }
11812
+ /**
11813
+ * Core's refusal of a request that stages an upload — a create, a
11814
+ * replacement, the widget's initiation — read as the upload's verdict: a final
11815
+ * refusal of Core's (UPLOAD_FINAL_REFUSAL_CODES, the answer's own code: a
11816
+ * later staging of the same file superseded it before its token was minted,
11817
+ * 410 UPLOAD_SUPERSEDED) is the `upload_refused` a transfer answer naming it
11818
+ * throws ({@link uploadRefusedError}); null for any other refusal.
11819
+ */
11820
+ function stagingRefusal(code, message, status, retryAfterMs) {
11821
+ if (!UPLOAD_FINAL_REFUSAL_CODES.includes(code))
11822
+ return null;
11823
+ return uploadRefusedError(code, message, status, {
11824
+ verdict: TRANSFER_VERDICT.REFUSED,
11825
+ retryAfterMs,
11826
+ offset: null,
11827
+ coreCode: code,
11828
+ });
11829
+ }
11830
+ /**
11831
+ * The error a request that stages an upload throws, from the error Core's
11832
+ * answer made: its final refusal of the upload as `upload_refused`
11833
+ * ({@link stagingRefusal}), any other error as it is.
11834
+ */
11835
+ function stagingRefusalOf(error) {
11836
+ if (!(error instanceof SparkVaultError) || error instanceof UploadApiError || error.statusCode === undefined)
11837
+ return error;
11838
+ return stagingRefusal(error.code, error.message, error.statusCode, error.retryAfterMs) ?? error;
11839
+ }
11840
+ function cancelledError() {
11841
+ return new UploadApiError('Upload cancelled', 'cancelled', 0);
11842
+ }
11089
11843
  /**
11090
11844
  * A delay that a cancel cuts short: resolves after `ms`, rejects with the
11091
11845
  * canonical cancelled error the moment the signal aborts.
11092
11846
  */
11093
11847
  function abortableDelay(ms, signal) {
11094
11848
  return new Promise((resolve, reject) => {
11095
- const cancelled = () => new UploadApiError('Upload cancelled', 'cancelled', 0);
11096
11849
  if (signal.aborted) {
11097
- reject(cancelled());
11850
+ reject(cancelledError());
11098
11851
  return;
11099
11852
  }
11100
11853
  const onAbort = () => {
11101
11854
  clearTimeout(timer);
11102
- reject(cancelled());
11855
+ reject(cancelledError());
11103
11856
  };
11104
11857
  const timer = setTimeout(() => {
11105
11858
  signal.removeEventListener('abort', onAbort);
@@ -11108,63 +11861,162 @@ function abortableDelay(ms, signal) {
11108
11861
  signal.addEventListener('abort', onAbort, { once: true });
11109
11862
  });
11110
11863
  }
11864
+ /** Whether the browser knows it has no network: `onLine` false is definite, true is only a hope. */
11865
+ function isOffline() {
11866
+ return typeof navigator !== 'undefined' && navigator.onLine === false;
11867
+ }
11111
11868
  /**
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.
11869
+ * Resolve once the browser is back online; reject with the canonical
11870
+ * cancelled error the moment the session closes, which is the only bound on
11871
+ * the wait.
11128
11872
  */
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;
11873
+ function waitUntilOnline(signal) {
11874
+ return new Promise((resolve, reject) => {
11875
+ if (signal.aborted) {
11876
+ reject(cancelledError());
11877
+ return;
11878
+ }
11879
+ const settle = (outcome) => {
11880
+ globalThis.removeEventListener('online', onOnline);
11881
+ signal.removeEventListener('abort', onAbort);
11882
+ outcome();
11883
+ };
11884
+ const onOnline = () => settle(resolve);
11885
+ const onAbort = () => settle(() => reject(cancelledError()));
11886
+ globalThis.addEventListener('online', onOnline);
11887
+ signal.addEventListener('abort', onAbort, { once: true });
11888
+ // The network may have come back between the caller's check and these
11889
+ // listeners, and its `online` event would then never arrive.
11890
+ if (!isOffline())
11891
+ settle(resolve);
11892
+ });
11893
+ }
11894
+ /** A failed request of this upload's transfer; anything else is rethrown as it is. */
11895
+ function transferFailure(error) {
11896
+ if (error instanceof UploadApiError)
11897
+ return error;
11898
+ throw error;
11899
+ }
11900
+ /**
11901
+ * The session the upload ran in is gone (cancelled, expired, or its file
11902
+ * removed): only a new upload from byte 0 can store the file, which the caller
11903
+ * starts (`ingots.upload` / `createUpload` again, or the widget's next upload).
11904
+ */
11905
+ function sessionGoneError(failure) {
11906
+ 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 });
11907
+ }
11908
+ /**
11909
+ * Wait out the backoff of a failed request, spending a retry of the upload's
11910
+ * budget, or of a deferred one, spending none for as long as the idle limit
11911
+ * allows; never shorter than the answer's `Retry-After`, and longer with
11912
+ * every failure and deferral since the last progress. Throws an answer no
11913
+ * retry follows as it is, and the last failure, or the deferral, once the
11914
+ * budget is spent. While the browser is offline a failure spends nothing: the
11915
+ * wait is for the network to come back (or the session to close), and the
11916
+ * idle clock starts over when it does.
11917
+ */
11918
+ async function waitToRetry(budget, failure, jitterKey, sessionSignal) {
11919
+ const { verdict, retryAfterMs } = failure;
11920
+ if (verdict === TRANSFER_VERDICT.DEFERRED) {
11921
+ if (!budget.deferred(retryAfterMs))
11922
+ throw failure;
11923
+ }
11924
+ else if (verdict !== TRANSFER_VERDICT.RETRY) {
11925
+ throw failure;
11926
+ }
11927
+ else if (isOffline()) {
11928
+ await waitUntilOnline(sessionSignal);
11929
+ budget.alive();
11930
+ return;
11931
+ }
11932
+ else if (!budget.failed(verdict, retryAfterMs)) {
11933
+ throw failure;
11934
+ }
11935
+ const delayMs = retryDelayMs({
11936
+ attempt: budget.attempt,
11937
+ retryAfterMs,
11938
+ jitterKey,
11939
+ });
11940
+ await abortableDelay(delayMs, sessionSignal);
11141
11941
  }
11142
11942
  /**
11143
11943
  * A server's error body, reduced to something safe to carry on an error:
11144
11944
  * whitespace collapsed and length clipped, so an HTML error page or a stack
11145
- * trace can never become the payload.
11945
+ * trace can never become the payload. The clip is only for what the error
11946
+ * carries: the body is read whole first ({@link readTransferAnswer}).
11146
11947
  */
11147
11948
  const ERROR_DETAIL_MAX_CHARS = 200;
11148
11949
  function summarizeErrorBody(body) {
11149
11950
  return body.replace(/\s+/g, ' ').trim().slice(0, ERROR_DETAIL_MAX_CHARS);
11150
11951
  }
11952
+ /**
11953
+ * What the transfer policy makes of a transfer request's answer, and the
11954
+ * error it throws when it is not a 2xx. A failed answer's body is read whole
11955
+ * by the SDK's one reader of a failed answer ({@link apiFailureOf}), so the
11956
+ * code Core ended the upload with reaches the policy however long Core's
11957
+ * sentence is, and an answer with no body (a HEAD's) names it in
11958
+ * `X-Upload-Refusal`: a final refusal throws `upload_refused` in Core's own
11959
+ * words (this SDK's for a HEAD's), Core's code in `details.coreCode`, and a
11960
+ * new upload is no remedy. The receipt's deferral throws
11961
+ * `upload_received_publishing`, which the upload only ever throws once the
11962
+ * idle limit ends the asking. Any other failure throws the request's own
11963
+ * copy, the server's detail and any other code of Core's in `details` (a gone
11964
+ * session's, which the upload reports as `session_gone`).
11965
+ *
11966
+ * @param answer - The status, the headers, and the body's whole text (empty for a 2xx)
11967
+ */
11968
+ function readTransferAnswer(answer, read) {
11969
+ const served = answer.body ? apiFailureOf(answer) : null;
11970
+ const outcome = classifyTransferResponse({
11971
+ status: answer.status,
11972
+ headers: answer.header,
11973
+ details: served?.details ?? null,
11974
+ receipt: read.receipt,
11975
+ });
11976
+ if (outcome.verdict === TRANSFER_VERDICT.OK)
11977
+ return { outcome, failure: null };
11978
+ const { status } = answer;
11979
+ if (outcome.verdict === TRANSFER_VERDICT.REFUSED && outcome.coreCode !== null) {
11980
+ return { outcome, failure: uploadRefusedError(outcome.coreCode, served?.message ?? null, status, outcome) };
11981
+ }
11982
+ if (outcome.verdict === TRANSFER_VERDICT.DEFERRED) {
11983
+ return {
11984
+ outcome,
11985
+ failure: new UploadApiError(RECEIVED_PUBLISHING_MESSAGE, 'upload_received_publishing', status, { status }, outcome),
11986
+ };
11987
+ }
11988
+ const detail = summarizeErrorBody(answer.body);
11989
+ return {
11990
+ outcome,
11991
+ failure: new UploadApiError(read.failureMessage, read.code, status, {
11992
+ status,
11993
+ ...(detail ? { serverDetail: detail } : {}),
11994
+ ...(outcome.coreCode !== null ? { coreCode: outcome.coreCode } : {}),
11995
+ }, outcome),
11996
+ };
11997
+ }
11151
11998
  const SESSION_CREATION = {
11152
11999
  name: 'Upload session creation',
11153
12000
  code: 'tus_create_failed',
11154
- serverFailureMessage: 'The upload could not be started: the server did not open an upload session.',
12001
+ failureMessage: 'The upload could not be started: the server did not open an upload session.',
11155
12002
  networkMessage: 'Unable to start the upload. Please check your connection and try again.',
12003
+ receipt: false,
11156
12004
  };
11157
12005
  const RESUME_CHECK = {
11158
12006
  name: 'Upload resume check',
11159
12007
  code: 'resume_check_failed',
11160
- serverFailureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
12008
+ failureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
11161
12009
  networkMessage: 'Unable to resume upload. Please check your connection and try again.',
12010
+ receipt: false,
12011
+ timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
11162
12012
  };
11163
12013
  const FINALIZATION_CHECK = {
11164
12014
  name: 'Upload finalization check',
11165
12015
  code: 'finalization_check_failed',
11166
- serverFailureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
12016
+ failureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
11167
12017
  networkMessage: 'Unable to confirm upload. Please check your connection and try again.',
12018
+ receipt: true,
12019
+ timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
11168
12020
  };
11169
12021
  class UploadApi extends SparkVaultApi {
11170
12022
  constructor(config) {
@@ -11180,8 +12032,23 @@ class UploadApi extends SparkVaultApi {
11180
12032
  this.vaultInfoMemo = new Map();
11181
12033
  this.config = config;
11182
12034
  }
11183
- makeError(message, code, statusCode, details) {
11184
- return new UploadApiError(message, code, statusCode, details);
12035
+ /**
12036
+ * The shared transport's errors. It raises a request that got no answer (a
12037
+ * dropped connection, a timeout) with status 0, which the transfer policy
12038
+ * retries, a cancel aside; a refused API call it raises with its status is
12039
+ * Core's verdict, never a transfer's, so of the policy's reading it carries
12040
+ * only the floor Core named (`retryAfterMs`), for whoever acts on the
12041
+ * refusal — and Core's final refusal of the upload a call stages is that
12042
+ * upload's `upload_refused` ({@link stagingRefusal}).
12043
+ */
12044
+ makeError(message, code, statusCode, details, retryAfterMs = null) {
12045
+ const refused = statusCode > 0 ? stagingRefusal(code, message, statusCode, retryAfterMs) : null;
12046
+ if (refused)
12047
+ return refused;
12048
+ const unanswered = statusCode === 0 && code !== 'cancelled';
12049
+ return new UploadApiError(message, code, statusCode, details, unanswered
12050
+ ? classifyTransferResponse({ status: 0 })
12051
+ : { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs, offset: null, coreCode: null });
11185
12052
  }
11186
12053
  /**
11187
12054
  * Issue a request to a Core route and unwrap the standard `{ data, meta }`
@@ -11298,13 +12165,22 @@ class UploadApi extends SparkVaultApi {
11298
12165
  * every server-reported offset, and honors the session abort signal plus
11299
12166
  * per-request timeouts.
11300
12167
  *
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}.
12168
+ * Every answer is read through the transfer policy
12169
+ * (`@sparkvault/app-sdk/transfer-retry`) and every retry spends one budget
12170
+ * ({@link TusTransfer}). A chunk that fails in transit is resent only from
12171
+ * an offset the server just named — a 409's own `Upload-Offset` at once,
12172
+ * otherwise a HEAD after the backoff ({@link offsetAfterFailure}); a session
12173
+ * the server no longer holds throws `session_gone`, which only a new upload
12174
+ * recovers from (any code of Core's the server named rides
12175
+ * `details.coreCode`); an upload Core refused for good (a full storage pool,
12176
+ * a later upload that replaced it) throws `upload_refused` in Core's words,
12177
+ * which no new upload recovers from. While the browser is offline, the loop
12178
+ * waits for the network instead of spending attempts.
11304
12179
  *
11305
12180
  * Resolves only once the server has confirmed finalization
11306
12181
  * ({@link confirmServerFinalized}), so a caller that gets a resolved promise
11307
- * is always looking at a published ingot.
12182
+ * is always looking at a published ingot; a publication the server still
12183
+ * defers at the idle limit throws `upload_received_publishing`.
11308
12184
  */
11309
12185
  async uploadFileToForge(file, forgeUrl, onProgress) {
11310
12186
  if (typeof XMLHttpRequest === 'undefined') {
@@ -11320,15 +12196,21 @@ class UploadApi extends SparkVaultApi {
11320
12196
  // The session this upload runs in: a close ends this upload even if a new
11321
12197
  // session starts before the loop next looks.
11322
12198
  const sessionSignal = this.getAbortSignal();
11323
- const session = await this.createTusSession(target.endpoint, target.istk, file.size);
12199
+ const budget = createTransferBudget();
12200
+ const session = await this.createTusSession(target.endpoint, target.istk, file.size, budget, sessionSignal);
11324
12201
  // Every chunk carries the file's bytes, so the session must live under the
11325
12202
  // endpoint it was created at.
11326
12203
  const uploadUrl = resolveForgeSessionUrl(session.location, target.endpoint);
11327
12204
  if (!uploadUrl) {
11328
12205
  throw new UploadApiError('Upload session is outside the upload endpoint', 'tus_create_failed', 0);
11329
12206
  }
11330
- let offset = 0;
11331
- let failedAttempts = 0;
12207
+ const transfer = {
12208
+ uploadUrl,
12209
+ totalSize: file.size,
12210
+ chunkSize: session.chunkSize,
12211
+ budget,
12212
+ sessionSignal,
12213
+ };
11332
12214
  // Retries make raw progress non-monotonic (a chunk that streamed to 90%
11333
12215
  // then failed re-reports from its start on resend); callers get only the
11334
12216
  // high-water mark so a progress bar never runs backwards.
@@ -11341,55 +12223,90 @@ class UploadApi extends SparkVaultApi {
11341
12223
  }
11342
12224
  }
11343
12225
  : undefined;
11344
- while (offset < file.size) {
12226
+ let offset = 0;
12227
+ for (;;) {
11345
12228
  if (sessionSignal.aborted) {
11346
- throw new UploadApiError('Upload cancelled', 'cancelled', 0);
12229
+ throw cancelledError();
12230
+ }
12231
+ // One exit, one receipt: however the loop learned that every byte is on
12232
+ // the server (a chunk's 204, a HEAD, a 409), publication is confirmed
12233
+ // before the upload resolves.
12234
+ if (offset === file.size) {
12235
+ const receipt = await this.confirmServerFinalized(transfer);
12236
+ if (receipt.published)
12237
+ return;
12238
+ offset = receipt.resumeAt;
12239
+ continue;
11347
12240
  }
11348
12241
  const chunkEnd = Math.min(offset + session.chunkSize, file.size);
11349
12242
  try {
11350
- offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, monotonicProgress);
11351
- failedAttempts = 0;
11352
- continue;
12243
+ offset = await this.patchChunk(transfer, file.slice(offset, chunkEnd), offset, monotonicProgress);
12244
+ transfer.budget.progressed();
11353
12245
  }
11354
12246
  catch (error) {
11355
- failedAttempts += 1;
11356
- if (failedAttempts >= CHUNK_MAX_ATTEMPTS || !isRetryableTransferFailure(error)) {
11357
- throw error;
11358
- }
12247
+ offset = await this.offsetAfterFailure(transfer, error, offset);
11359
12248
  }
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
- }
12249
+ }
12250
+ }
12251
+ /**
12252
+ * Where the upload stands after a failed chunk PATCH, in the server's words:
12253
+ * a 409's own `Upload-Offset` at once, otherwise the session's HEAD after
12254
+ * the backoff. The failed chunk may have landed with its answer lost, and a
12255
+ * PATCH at the client's stale offset is refused, so no chunk is ever sent
12256
+ * again at an offset the server did not just name. The blip that killed the
12257
+ * PATCH is also the likeliest thing to kill the HEAD moments later, so the
12258
+ * HEAD is retried the same way, out of the same budget.
12259
+ */
12260
+ async offsetAfterFailure(transfer, error, sentOffset) {
12261
+ let failure = transferFailure(error);
12262
+ for (;;) {
12263
+ if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
12264
+ return this.resyncedOffset(transfer, failure, sentOffset);
12265
+ }
12266
+ await this.backOff(transfer, failure);
12267
+ try {
12268
+ const serverOffset = await this.readResumeOffset(transfer);
12269
+ if (serverOffset > sentOffset) {
12270
+ // Bytes reached the server despite the failure, so the transfer is
12271
+ // alive: the budget starts over rather than being spent down across
12272
+ // the many chunks of a large file.
12273
+ transfer.budget.progressed();
11382
12274
  }
12275
+ return serverOffset;
11383
12276
  }
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;
12277
+ catch (headError) {
12278
+ failure = transferFailure(headError);
11389
12279
  }
11390
- offset = serverOffset;
11391
12280
  }
11392
- await this.confirmServerFinalized(uploadUrl, file.size);
12281
+ }
12282
+ /**
12283
+ * Continue from the offset a 409 named, at once and without a HEAD: the
12284
+ * server just said where the session stands. Past what this client sent,
12285
+ * the server holds more than it knew, which is progress; anywhere else the
12286
+ * answer contradicts the request, so it spends the budget like any failure
12287
+ * and repeating it ends the upload.
12288
+ */
12289
+ resyncedOffset(transfer, failure, sentOffset) {
12290
+ const offset = this.checkResumeOffset(failure.serverOffset, transfer);
12291
+ if (offset > sentOffset) {
12292
+ transfer.budget.progressed();
12293
+ }
12294
+ else if (!transfer.budget.failed(TRANSFER_VERDICT.RESYNC)) {
12295
+ throw failure;
12296
+ }
12297
+ return offset;
12298
+ }
12299
+ /**
12300
+ * Wait out the backoff of a failed or deferred request to the upload's
12301
+ * session ({@link waitToRetry}, keyed by the session URL), or throw: a gone
12302
+ * session as `session_gone`, an answer no retry follows as it is, and the
12303
+ * last failure, or the deferral, once the budget is spent.
12304
+ */
12305
+ async backOff(transfer, failure) {
12306
+ if (failure.verdict === TRANSFER_VERDICT.GONE) {
12307
+ throw sessionGoneError(failure);
12308
+ }
12309
+ await waitToRetry(transfer.budget, failure, transfer.uploadUrl, transfer.sessionSignal);
11393
12310
  }
11394
12311
  /**
11395
12312
  * Confirm the server finalized a fully received upload — the one receipt
@@ -11403,42 +12320,62 @@ class UploadApi extends SparkVaultApi {
11403
12320
  * re-drive — it short-circuits to 204 on an already-finalized session, and
11404
12321
  * on a received-but-unfinalized one it answers only after publication.
11405
12322
  *
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.
12323
+ * While another request finalizes the receipt answers 409 with
12324
+ * `Retry-After`, polled again after the policy's backoff as a failure; while
12325
+ * the publication is deferred it answers 503 with `Retry-After`, a deferral
12326
+ * the receipt is polled through without spending a failure, each ask after
12327
+ * a longer backoff, until the idle limit throws
12328
+ * `upload_received_publishing`: every byte is on the server, which finishes
12329
+ * the publication on its own. A 503 naming no `Retry-After` is no deferral
12330
+ * of Forge's, so it is polled as a failure. A 400 is the server's verdict
12331
+ * and fails immediately, as does the refusal Core decided
12332
+ * (`upload_refused`); a 409 naming an earlier offset means bytes are
12333
+ * missing, and the upload continues from there.
11410
12334
  */
11411
- async confirmServerFinalized(uploadUrl, totalSize) {
12335
+ async confirmServerFinalized(transfer) {
11412
12336
  let consecutiveTimeouts = 0;
11413
- for (let attempt = 1;; attempt++) {
12337
+ for (;;) {
11414
12338
  try {
11415
- await this.tusRequest(uploadUrl, {
12339
+ await this.tusRequest(transfer.uploadUrl, {
11416
12340
  method: 'PATCH',
11417
12341
  headers: {
11418
12342
  'Tus-Resumable': TUS_VERSION,
11419
- 'Upload-Offset': String(totalSize),
12343
+ 'Upload-Offset': String(transfer.totalSize),
11420
12344
  'Content-Type': 'application/offset+octet-stream',
11421
12345
  },
11422
12346
  }, FINALIZATION_CHECK);
11423
- return;
12347
+ return { published: true };
11424
12348
  }
11425
12349
  catch (error) {
11426
- const timedOut = error instanceof UploadApiError && error.code === 'timeout';
12350
+ const failure = transferFailure(error);
11427
12351
  // Any answer at all — a 409 above all — proves someone is on the other
11428
12352
  // 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;
12353
+ consecutiveTimeouts = failure.code === 'timeout' ? consecutiveTimeouts + 1 : 0;
12354
+ if (consecutiveTimeouts >= FINALIZE_MAX_CONSECUTIVE_TIMEOUTS) {
12355
+ throw failure;
12356
+ }
12357
+ if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
12358
+ const resumeAt = this.resyncedOffset(transfer, failure, transfer.totalSize);
12359
+ if (resumeAt < transfer.totalSize)
12360
+ return { published: false, resumeAt };
12361
+ continue;
11434
12362
  }
11435
- await abortableDelay(FINALIZE_RETRY_MS, this.getAbortSignal());
12363
+ await this.backOff(transfer, failure);
11436
12364
  }
11437
12365
  }
11438
12366
  }
11439
12367
  /**
11440
- * Read the offset a failed chunk should resume from — the one place a
11441
- * server-reported resume point is judged.
12368
+ * Read the offset a failed chunk should resume from, from the session's
12369
+ * HEAD. At the full offset it proves receipt only, published or not, so the
12370
+ * loop then takes the receipt.
12371
+ */
12372
+ async readResumeOffset(transfer) {
12373
+ return this.checkResumeOffset(await this.headUploadOffset(transfer.uploadUrl, RESUME_CHECK), transfer);
12374
+ }
12375
+ /**
12376
+ * Judge an offset the server named for the upload to resume from — a HEAD's,
12377
+ * or a 409's `Upload-Offset` — the one place a server-reported resume point
12378
+ * is judged.
11442
12379
  *
11443
12380
  * Forge commits a chunk before it answers, so a PATCH that died in transit
11444
12381
  * may have landed in full or not at all (never in part — the chunk object
@@ -11446,21 +12383,19 @@ class UploadApi extends SparkVaultApi {
11446
12383
  * persisted offset knows which, and the client's arithmetic is worthless
11447
12384
  * here.
11448
12385
  *
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.
12386
+ * Two contracts disqualify an answer (`resumeOffsetProblem`). TUS sanity: an
12387
+ * offset past the declared total would end the loop early and report a
12388
+ * partial upload as complete, the same trap {@link patchChunk} guards
12389
+ * against on a PATCH's own offset. Forge chunk granularity: a session
12390
+ * advances only in whole committed chunks, so an offset that is neither
12391
+ * chunk-aligned nor the file end is a corrupt session, and resuming from it
12392
+ * would send a short non-final chunk Forge rejects anyway.
11456
12393
  */
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);
12394
+ checkResumeOffset(offset, transfer) {
12395
+ const problem = resumeOffsetProblem(offset, transfer);
12396
+ if (offset === null || problem !== null) {
12397
+ const shape = problem === RESUME_OFFSET_PROBLEM.MISALIGNED ? 'misaligned' : 'invalid';
12398
+ throw new UploadApiError(`Server returned ${shape} upload offset (${offset})`, 'invalid_offset', 0);
11464
12399
  }
11465
12400
  return offset;
11466
12401
  }
@@ -11468,16 +12403,39 @@ class UploadApi extends SparkVaultApi {
11468
12403
  * Create the TUS upload session. Forge reads only `Tus-Resumable`,
11469
12404
  * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
11470
12405
  * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
12406
+ *
12407
+ * A create the transfer policy calls RETRY (no answer, 408, 425, 429, a 5xx)
12408
+ * is sent again under the upload's budget: Forge refuses such a create
12409
+ * before it claims the token, or hands the claim back on a transient
12410
+ * key-service failure (503 + `Retry-After`), so the same ISTK opens the
12411
+ * session on a later attempt. Every other answer is final, a 401 included:
12412
+ * the token was already used, by an earlier attempt whose answer was lost,
12413
+ * and no `Location` survives to continue that session from. No session URL
12414
+ * exists yet to spread the retries by, and the ISTK never feeds one, so
12415
+ * they spread by a key of the endpoint (`transferJitterKey`).
11471
12416
  */
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);
12417
+ async createTusSession(endpoint, istk, totalSize, budget, sessionSignal) {
12418
+ const jitterKey = transferJitterKey(endpoint);
12419
+ let response;
12420
+ for (;;) {
12421
+ try {
12422
+ ({ response } = await this.tusRequest(endpoint, {
12423
+ method: 'POST',
12424
+ headers: {
12425
+ 'Tus-Resumable': TUS_VERSION,
12426
+ 'Upload-Length': String(totalSize),
12427
+ 'X-ISTK': istk,
12428
+ },
12429
+ }, SESSION_CREATION));
12430
+ break;
12431
+ }
12432
+ catch (error) {
12433
+ const failure = transferFailure(error);
12434
+ if (failure.verdict !== TRANSFER_VERDICT.RETRY)
12435
+ throw failure;
12436
+ await waitToRetry(budget, failure, jitterKey, sessionSignal);
12437
+ }
12438
+ }
11481
12439
  const location = response.headers.get('Location');
11482
12440
  if (!location) {
11483
12441
  throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
@@ -11490,23 +12448,31 @@ class UploadApi extends SparkVaultApi {
11490
12448
  if (chunkSize === null) {
11491
12449
  throw new UploadApiError('Server did not return a valid X-Chunk-Size', 'tus_create_failed', response.status, { header: 'X-Chunk-Size', received: chunkSizeHeader });
11492
12450
  }
12451
+ // The session exists: the server confirmed progress.
12452
+ budget.progressed();
11493
12453
  return { location, chunkSize };
11494
12454
  }
11495
12455
  /**
11496
12456
  * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
11497
- * Resolves with the server-confirmed offset for the next iteration.
12457
+ * Resolves with the server-confirmed offset for the next iteration; a
12458
+ * failure carries the transfer policy's verdict on its answer, read here.
11498
12459
  *
11499
12460
  * 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
12461
+ * whole number that strictly advances past this chunk's start (this client
11501
12462
  * never sends an empty chunk, so a non-advancing 2xx would loop forever)
11502
12463
  * and never exceeds the file size (an inflated offset would skip real
11503
12464
  * chunks and report a partial upload as success).
12465
+ *
12466
+ * Bytes leaving are a sign of life: they restart the transfer's idle clock
12467
+ * (never its failure count, which only the server's confirmation resets), so
12468
+ * a slow chunk is never counted as idle time.
11504
12469
  */
11505
- patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
12470
+ patchChunk(transfer, chunk, chunkStart, onProgress) {
12471
+ const { uploadUrl, totalSize, budget } = transfer;
11506
12472
  return new Promise((resolve, reject) => {
11507
- const closeSignal = this.getAbortSignal();
12473
+ const closeSignal = transfer.sessionSignal;
11508
12474
  if (closeSignal.aborted) {
11509
- reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
12475
+ reject(cancelledError());
11510
12476
  return;
11511
12477
  }
11512
12478
  const xhr = new XMLHttpRequest();
@@ -11536,28 +12502,33 @@ class UploadApi extends SparkVaultApi {
11536
12502
  closeSignal.addEventListener('abort', onCloseAbort);
11537
12503
  xhr.upload.onprogress = (event) => {
11538
12504
  resetWatchdog();
12505
+ budget.alive();
11539
12506
  if (event.lengthComputable) {
11540
12507
  onProgress?.(chunkStart + event.loaded, totalSize);
11541
12508
  }
11542
12509
  };
11543
12510
  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));
12511
+ const { status } = xhr;
12512
+ const { outcome, failure } = readTransferAnswer({
12513
+ status,
12514
+ header: (name) => xhr.getResponseHeader(name),
12515
+ body: status >= 200 && status < 300 ? '' : xhr.responseText,
12516
+ }, { receipt: false, code: 'chunk_upload_failed', failureMessage: `Chunk upload failed with status ${status}` });
12517
+ if (failure) {
12518
+ finish(() => reject(failure));
12519
+ return;
11552
12520
  }
11553
- else {
11554
- finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
12521
+ const newOffset = outcome.offset;
12522
+ if (newOffset === null || newOffset <= chunkStart || newOffset > totalSize) {
12523
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${xhr.getResponseHeader('Upload-Offset')})`, 'invalid_offset', xhr.status)));
12524
+ return;
11555
12525
  }
12526
+ finish(() => resolve(newOffset));
11556
12527
  };
11557
- xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
12528
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0, undefined, classifyTransferResponse({ status: 0 }))));
11558
12529
  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)));
12530
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0, undefined, classifyTransferResponse({ status: 0 }))
12531
+ : cancelledError()));
11561
12532
  xhr.open('PATCH', uploadUrl);
11562
12533
  xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
11563
12534
  xhr.setRequestHeader('Upload-Offset', String(chunkStart));
@@ -11573,13 +12544,11 @@ class UploadApi extends SparkVaultApi {
11573
12544
  * @param check - Which caller this read serves; shapes the failure copy.
11574
12545
  */
11575
12546
  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) {
12547
+ const { response, outcome } = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
12548
+ if (outcome.offset === null) {
11580
12549
  throw new UploadApiError(`${check.name} returned an invalid offset`, check.code, response.status);
11581
12550
  }
11582
- return offset;
12551
+ return outcome.offset;
11583
12552
  }
11584
12553
  /**
11585
12554
  * Issue one bodyless TUS request: the single transport behind every
@@ -11589,26 +12558,33 @@ class UploadApi extends SparkVaultApi {
11589
12558
  * Uses the raw response rather than the JSON envelope helper: TUS responses
11590
12559
  * carry an empty body and surface state in headers. Runs through the one SDK
11591
12560
  * transport (session close signal, deadline, failure classification) and
11592
- * resolves only on a 2xx so no caller has to re-check `response.ok`.
12561
+ * resolves only on a 2xx, with the transfer policy's reading of it, so no
12562
+ * caller has to re-check `response.ok`; a non-2xx throws carrying the
12563
+ * policy's verdict on its answer.
11593
12564
  *
11594
12565
  * @param check - Which caller this request serves; shapes the failure copy.
11595
12566
  */
11596
12567
  tusRequest(uploadUrl, init, check) {
12568
+ const timeoutMs = check.timeoutMs ?? this.timeoutMs;
11597
12569
  return this.send(uploadUrl, { method: init.method, headers: init.headers }, {
11598
12570
  cancelled: 'Upload cancelled',
11599
- timeout: `${check.name} timed out after ${this.timeoutMs}ms`,
12571
+ timeout: `${check.name} timed out after ${timeoutMs}ms`,
11600
12572
  network: check.networkMessage,
11601
12573
  }, 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
- });
12574
+ // A failed answer's body is read whole: an unread body pins its
12575
+ // connection, and a retried receipt would strand one per attempt.
12576
+ // Forge's error envelope in it is what names the refusal Core
12577
+ // decided, and otherwise the only server-side detail this client
12578
+ // ever sees, so it rides along in `details` for support.
12579
+ const { outcome, failure } = readTransferAnswer({
12580
+ status: response.status,
12581
+ header: (name) => response.headers.get(name),
12582
+ body: response.ok ? '' : await response.text().catch(() => ''),
12583
+ }, check);
12584
+ if (failure)
12585
+ throw failure;
12586
+ return { response, outcome };
12587
+ }, timeoutMs);
11612
12588
  }
11613
12589
  }
11614
12590
 
@@ -13853,7 +14829,34 @@ class UploadRenderer {
13853
14829
  statusCode: error.statusCode,
13854
14830
  });
13855
14831
  }
13856
- else if (error.statusCode === 404) {
14832
+ else if (error.code === 'upload_received_publishing') {
14833
+ // Every byte reached the server, which is still saving the file and
14834
+ // finishes it on its own: nothing failed, and nothing is left to do.
14835
+ // The host still hears it through onError, with this code, which
14836
+ // tells it never to upload the file again.
14837
+ this.setState({
14838
+ view: 'error',
14839
+ title: 'Upload Received',
14840
+ message: error.message,
14841
+ code: error.code,
14842
+ statusCode: error.statusCode,
14843
+ });
14844
+ }
14845
+ else if (error.code === 'upload_refused') {
14846
+ // Core refused the upload for good, in its own words (whom to contact
14847
+ // about a full storage pool, or the later upload that replaced this
14848
+ // one): a sentence that never asks for the file again.
14849
+ this.setState({
14850
+ view: 'error',
14851
+ title: 'Upload Not Saved',
14852
+ message: error.message,
14853
+ code: error.code,
14854
+ statusCode: error.statusCode,
14855
+ });
14856
+ }
14857
+ else if (error.statusCode === 404 && error.code !== 'session_gone') {
14858
+ // A vault or upload route that does not exist. A gone upload session
14859
+ // can answer 404 too, and its own sentence says what became of the file.
13857
14860
  this.setState({
13858
14861
  view: 'error',
13859
14862
  title: 'Upload Page Not Found',
@@ -14477,38 +15480,13 @@ function readIngotAccess(entry) {
14477
15480
  };
14478
15481
  }
14479
15482
 
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
15483
  /**
14508
15484
  * 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
15485
+ * Blob under liveness bounds, resuming from the bytes it holds when the caller
15486
+ * can mint another link. `sv.ingots.download` uses it, and so can a caller
14510
15487
  * that mints its own link (`createDownloadLink`, or its own authenticated
14511
- * call) and needs cancellation, byte progress or the published revision.
15488
+ * call) and needs cancellation, byte progress, resumption or the published
15489
+ * revision.
14512
15490
  */
14513
15491
  /**
14514
15492
  * Time-to-first-byte bound: how long the download host may take to return
@@ -14573,15 +15551,104 @@ function assertDownloadUrl(url, isAllowedHost = isSparkVaultOwnedHostname) {
14573
15551
  }
14574
15552
  /**
14575
15553
  * 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);
15554
+ * for each response's headers, then an idle deadline rearmed on every body
15555
+ * chunk. Nothing caps the transfer as a whole, so file size never decides
15556
+ * whether a download can finish. The link is single-use, so a failed transfer
15557
+ * is retried only through `options.remint`, on a link minted for the retry. A
15558
+ * link that is not a Forge decrypt URL on an allowed host, the first or a
15559
+ * minted one, is refused before anything is sent to it (assertDownloadUrl).
15560
+ */
15561
+ function fetchDownload(url, options = {}) {
15562
+ return runDownload(() => Promise.resolve(url), options);
15563
+ }
15564
+ /**
15565
+ * {@link fetchDownload} for a caller whose every link is minted, the first
15566
+ * included: a mint that fails before any byte has moved is retried under the
15567
+ * same policy as any other failure. `sv.ingots.download` runs this.
15568
+ */
15569
+ function fetchMintedDownload(mint, options = {}) {
15570
+ return runDownload(mint, { ...options, remint: mint });
15571
+ }
15572
+ /** A failure no answer came with (a reset, a deadline, a lost connection): the policy retries it. */
15573
+ const UNANSWERED = classifyTransferResponse({ status: 0 });
15574
+ /** A failure that is this transfer's own verdict (content that is not the file held, a range that does not continue it): final. */
15575
+ const FINAL = { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs: null, offset: null, coreCode: null };
15576
+ /** `bytes <first>-<last>/<length>`: the one Content-Range form a 206 continuing a download carries. */
15577
+ const CONTENT_RANGE = /^bytes (\d+)-(\d+)\/(\d+)$/;
15578
+ /** A strong entity tag (RFC 9110 §8.8.3): an If-Range never carries a weak one. */
15579
+ const STRONG_ETAG = /^"[^"]*"$/;
15580
+ const CONTENT_CHANGED_MESSAGE = 'The file changed while it was downloading. Please try again.';
15581
+ /**
15582
+ * The transfer: an attempt on the link `firstLink` resolves to, then, while
15583
+ * the transfer policy retries a failure and the caller can mint, one attempt
15584
+ * per minted link, each after the policy's backoff. Retries are bounded by the
15585
+ * policy's budget, failures in a row and time without progress, both of which
15586
+ * start over whenever bytes arrive past what any attempt held.
15587
+ */
15588
+ async function runDownload(firstLink, options) {
15589
+ const { signal, remint } = options;
15590
+ const state = { received: new ReceivedBytes(), budget: createTransferBudget(), held: null, furthest: 0 };
15591
+ // The link carries the ISTK, a credential, which never feeds anything
15592
+ // observable such as a delay: the retries spread by a key of the download's
15593
+ // kind and start instead (transferJitterKey).
15594
+ const jitterKey = transferJitterKey('download');
15595
+ for (let nextLink = firstLink;;) {
15596
+ const result = await attemptWith(nextLink, state, options);
15597
+ if (result.ok)
15598
+ return result.download;
15599
+ if (signal?.aborted)
15600
+ throw signal.reason;
15601
+ const { error, outcome } = result;
15602
+ if (!remint || outcome.verdict !== TRANSFER_VERDICT.RETRY || !state.budget.failed(TRANSFER_VERDICT.RETRY, outcome.retryAfterMs)) {
15603
+ throw error;
15604
+ }
15605
+ await waitBeforeRetry(retryDelayMs({ attempt: state.budget.attempt, retryAfterMs: outcome.retryAfterMs, jitterKey }), signal);
15606
+ // A link is spent once its request has reached Forge, whatever came back:
15607
+ // every retry fetches one minted for it.
15608
+ nextLink = remint;
15609
+ }
15610
+ }
15611
+ /**
15612
+ * One attempt: take its link, minted when the source mints, hold it to the
15613
+ * transfer-URL rule, then fetch it. A mint that fails is read the way a
15614
+ * transfer answer is ({@link mintOutcome}).
15615
+ */
15616
+ async function attemptWith(source, state, options) {
15617
+ let link;
15618
+ try {
15619
+ link = await source();
15620
+ assertDownloadUrl(link, options.isAllowedHost);
15621
+ }
15622
+ catch (error) {
15623
+ return { ok: false, error, outcome: mintOutcome(error) };
15624
+ }
15625
+ return attemptDownload(link, state, options);
15626
+ }
15627
+ /**
15628
+ * The transfer policy's reading of a failed mint. The HTTP client read the
15629
+ * answer when it built the error: its status gives the verdict (a refused link
15630
+ * is a 400, so final) and the `Retry-After` it named rides on the error
15631
+ * (`retryAfterMs`), so a mint Core defers waits out Core's floor exactly as a
15632
+ * deferred Forge answer does. A failure with no status got no answer.
15633
+ */
15634
+ function mintOutcome(error) {
15635
+ if (!(error instanceof SparkVaultError) || typeof error.statusCode !== 'number')
15636
+ return UNANSWERED;
15637
+ return { ...classifyTransferResponse({ status: error.statusCode }), retryAfterMs: error.retryAfterMs };
15638
+ }
15639
+ /**
15640
+ * Fetch one link: the rest of the file held, conditioned on its validator,
15641
+ * when the bytes held can be resumed, the whole file otherwise. A 206 appends
15642
+ * to the bytes held; any whole-file answer replaces them, so a file replaced
15643
+ * since the bytes held began starts over as its new content, never spliced
15644
+ * onto the old.
15645
+ */
15646
+ async function attemptDownload(link, state, options) {
15647
+ const { signal, onProgress, expectedContentVersion } = options;
15648
+ const { received } = state;
15649
+ const resume = resumePoint(state);
15650
+ if (!resume)
15651
+ received.discard();
14585
15652
  const controller = new AbortController();
14586
15653
  const abortFromCaller = () => controller.abort(signal?.reason);
14587
15654
  if (signal?.aborted) {
@@ -14590,61 +15657,231 @@ async function fetchDownload(url, options = {}) {
14590
15657
  else {
14591
15658
  signal?.addEventListener('abort', abortFromCaller, { once: true });
14592
15659
  }
15660
+ // What a whole download is, once the answer has named its content.
15661
+ const whole = (content) => ({
15662
+ ok: true,
15663
+ download: { blob: received.toBlob(content.contentType), contentVersion: content.contentVersion },
15664
+ });
15665
+ let held = null;
15666
+ let delivered = false;
14593
15667
  try {
14594
- const response = await withDeadline(fetch(url, { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
15668
+ const response = await withDeadline(fetch(link, resume
15669
+ ? { signal: controller.signal, headers: { Range: `bytes=${resume.at}-`, 'If-Range': resume.validator } }
15670
+ : { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
14595
15671
  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);
15672
+ return {
15673
+ ok: false,
15674
+ error: new SparkVaultError(`Download failed with status ${response.status}`, 'download_failed', response.status),
15675
+ outcome: classifyTransferResponse({ status: response.status, headers: (name) => response.headers.get(name) }),
15676
+ };
14601
15677
  }
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;
15678
+ if (resume && response.status === 206) {
15679
+ const continued = continuation(response, resume);
15680
+ if (continued instanceof SparkVaultError)
15681
+ return { ok: false, error: continued, outcome: FINAL };
15682
+ held = continued;
15683
+ }
15684
+ else {
15685
+ received.discard();
15686
+ const contentVersion = response.headers.get('x-content-version') || null;
15687
+ if (expectedContentVersion && contentVersion && contentVersion !== expectedContentVersion) {
15688
+ return { ok: false, error: new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed'), outcome: FINAL };
14637
15689
  }
15690
+ held = {
15691
+ contentType: response.headers.get('content-type') ?? '',
15692
+ contentVersion,
15693
+ total: Number(response.headers.get('content-length')) || 0,
15694
+ validator: resumeValidator(response.headers),
15695
+ };
14638
15696
  }
14639
- if (pending.length > 0) {
14640
- parts.push(new Blob(pending));
15697
+ // Named before the body is read: a body that fails part-way leaves the
15698
+ // next attempt what it needs to resume.
15699
+ state.held = held;
15700
+ await readBody(response, controller, state, held.total, onProgress);
15701
+ delivered = true;
15702
+ return whole(held);
15703
+ }
15704
+ catch (error) {
15705
+ if (error instanceof ProgressCallbackFailure)
15706
+ return { ok: false, error: error.failure, outcome: FINAL };
15707
+ // Every declared byte arrived before the body failed to end: the file is
15708
+ // whole, and a resume would ask for a range past its end (a 416).
15709
+ if (held !== null && held.total > 0 && received.loaded === held.total && !signal?.aborted) {
15710
+ return whole(held);
14641
15711
  }
14642
- return { blob: new Blob(parts, { type: contentType }), contentVersion };
15712
+ return { ok: false, error, outcome: UNANSWERED };
14643
15713
  }
14644
15714
  finally {
15715
+ // An attempt that ends short of its body leaves a connection that no
15716
+ // deadline will reap any more: abort it, or every retry leaks one socket.
15717
+ if (!delivered)
15718
+ controller.abort();
14645
15719
  signal?.removeEventListener('abort', abortFromCaller);
14646
15720
  }
14647
15721
  }
15722
+ /** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
15723
+ function resumePoint(state) {
15724
+ const { held, received } = state;
15725
+ if (held === null || held.validator === null || received.loaded === 0)
15726
+ return null;
15727
+ return { held, validator: held.validator, at: received.loaded };
15728
+ }
15729
+ /**
15730
+ * What a resume conditions its range on: the response's ETag when it is
15731
+ * strong and the response accepts byte ranges, or null. An edge that rewrites
15732
+ * a body (compression) weakens its ETag, and then nothing binds the bytes held
15733
+ * to the bytes a range would be served from.
15734
+ */
15735
+ function resumeValidator(headers) {
15736
+ const etag = headers.get('etag');
15737
+ const acceptsBytes = (headers.get('accept-ranges') ?? '')
15738
+ .split(',')
15739
+ .some((unit) => unit.trim().toLowerCase() === 'bytes');
15740
+ return etag !== null && STRONG_ETAG.test(etag) && acceptsBytes ? etag : null;
15741
+ }
15742
+ /**
15743
+ * The content a 206 answering a resume continues, or why it cannot: it must
15744
+ * start at the first byte lacking, run to the end of the same file, and name
15745
+ * the publication the bytes held are when it names one (a server that honored
15746
+ * the range despite a changed publication would splice two of them).
15747
+ */
15748
+ function continuation(response, resume) {
15749
+ const etag = response.headers.get('etag');
15750
+ if (etag !== null && etag.replace(/^W\//, '') !== resume.validator) {
15751
+ return new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed');
15752
+ }
15753
+ const range = CONTENT_RANGE.exec(response.headers.get('content-range') ?? '');
15754
+ const [first, last, length] = range ? range.slice(1).map(Number) : [NaN, NaN, NaN];
15755
+ const { total } = resume.held;
15756
+ if (first !== resume.at || last !== length - 1 || (total > 0 && length !== total)) {
15757
+ return new SparkVaultError('The resumed download did not continue where it stopped', 'download_failed', response.status, { reason: 'range_mismatch' });
15758
+ }
15759
+ return { ...resume.held, total: length };
15760
+ }
15761
+ /**
15762
+ * Read a response body onto the bytes held under liveness bounds, reporting
15763
+ * cumulative progress against the file's declared length.
15764
+ */
15765
+ async function readBody(response, controller, state, total, onProgress) {
15766
+ const { received } = state;
15767
+ // Safari 10.1-14.4 ships fetch without `Response.body`, and the SDK's
15768
+ // support floor reaches back into that range. There the transfer keeps
15769
+ // whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals,
15770
+ // so there is no liveness to observe, and a failure holds no bytes to
15771
+ // resume from.
15772
+ if (!response.body) {
15773
+ received.appendBlob(await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out'));
15774
+ noteArrival(state);
15775
+ reportProgress(onProgress, received.loaded, total);
15776
+ return;
15777
+ }
15778
+ const reader = response.body.getReader();
15779
+ for (;;) {
15780
+ const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
15781
+ if (done)
15782
+ return;
15783
+ received.append(value);
15784
+ noteArrival(state);
15785
+ reportProgress(onProgress, received.loaded, total);
15786
+ }
15787
+ }
15788
+ /**
15789
+ * The caller's progress callback failed: its own error, which no retry can
15790
+ * cure. Unmarked, it would read as a transfer that lost its connection, and a
15791
+ * callback that throws on every report would cost a mint and a request per
15792
+ * chunk until the file completed.
15793
+ */
15794
+ class ProgressCallbackFailure extends Error {
15795
+ constructor(failure) {
15796
+ super('onProgress threw');
15797
+ this.failure = failure;
15798
+ }
15799
+ }
15800
+ function reportProgress(onProgress, loaded, total) {
15801
+ if (!onProgress)
15802
+ return;
15803
+ try {
15804
+ onProgress(loaded, total);
15805
+ }
15806
+ catch (failure) {
15807
+ throw new ProgressCallbackFailure(failure);
15808
+ }
15809
+ }
15810
+ /** Bytes arrived: past the most any attempt held, progress; short of it, a sign of life. */
15811
+ function noteArrival(state) {
15812
+ if (state.received.loaded > state.furthest) {
15813
+ state.furthest = state.received.loaded;
15814
+ state.budget.progressed();
15815
+ }
15816
+ else {
15817
+ state.budget.alive();
15818
+ }
15819
+ }
15820
+ /** Wait out a retry's backoff; the caller's cancel ends the wait with the signal's reason. */
15821
+ function waitBeforeRetry(ms, signal) {
15822
+ return new Promise((resolve, reject) => {
15823
+ if (signal?.aborted) {
15824
+ reject(signal.reason);
15825
+ return;
15826
+ }
15827
+ const onAbort = () => {
15828
+ clearTimeout(timer);
15829
+ reject(signal?.reason);
15830
+ };
15831
+ const timer = setTimeout(() => {
15832
+ signal?.removeEventListener('abort', onAbort);
15833
+ resolve();
15834
+ }, ms);
15835
+ signal?.addEventListener('abort', onAbort, { once: true });
15836
+ });
15837
+ }
15838
+ /**
15839
+ * The bytes a transfer holds, in the order they arrived: at most one window
15840
+ * on the JS heap, the rest folded into Blob parts the platform's blob store
15841
+ * owns, so heap growth is capped whatever the file's size.
15842
+ */
15843
+ class ReceivedBytes {
15844
+ constructor() {
15845
+ this.parts = [];
15846
+ this.pending = [];
15847
+ this.pendingBytes = 0;
15848
+ this.count = 0;
15849
+ }
15850
+ get loaded() {
15851
+ return this.count;
15852
+ }
15853
+ append(chunk) {
15854
+ this.pending.push(chunk);
15855
+ this.pendingBytes += chunk.byteLength;
15856
+ this.count += chunk.byteLength;
15857
+ if (this.pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES)
15858
+ this.fold();
15859
+ }
15860
+ appendBlob(blob) {
15861
+ this.fold();
15862
+ this.parts.push(blob);
15863
+ this.count += blob.size;
15864
+ }
15865
+ discard() {
15866
+ this.parts = [];
15867
+ this.pending = [];
15868
+ this.pendingBytes = 0;
15869
+ this.count = 0;
15870
+ }
15871
+ toBlob(type) {
15872
+ this.fold();
15873
+ return new Blob(this.parts, { type });
15874
+ }
15875
+ fold() {
15876
+ if (this.pending.length === 0)
15877
+ return;
15878
+ // Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
15879
+ // to ArrayBufferLike, which the Blob constructor's part type rejects.
15880
+ this.parts.push(new Blob(this.pending));
15881
+ this.pending = [];
15882
+ this.pendingBytes = 0;
15883
+ }
15884
+ }
14648
15885
 
14649
15886
  /**
14650
15887
  * Folders Module
@@ -14819,8 +16056,6 @@ const NAME_CONFLICT_POLICIES = ['upsert', 'complete_pending', 'refuse', 'new_nam
14819
16056
  * (shared with the public upload widget), with server-side finalization and
14820
16057
  * download-host allowlisting enforced — no per-size branching.
14821
16058
  */
14822
- const DOWNLOAD_MAX_ATTEMPTS = 3;
14823
- const DOWNLOAD_RETRY_BASE_MS = 500;
14824
16059
  class IngotsModule {
14825
16060
  constructor(config, http) {
14826
16061
  /** The client's transfer-host allowlist (`allowedDownloadHostPatterns`), as a download link is read against it. */
@@ -14833,7 +16068,10 @@ class IngotsModule {
14833
16068
  *
14834
16069
  * Reserves the ingot record and returns the Forge upload URL (carrying the
14835
16070
  * ISTK upload session token). Use this when you want to drive the TUS
14836
- * transfer yourself; otherwise prefer {@link upload}.
16071
+ * transfer yourself; otherwise prefer {@link upload}. A create another
16072
+ * upload of the same file superseded before its token was issued rejects
16073
+ * with code `upload_refused` (`details.coreCode` UPLOAD_SUPERSEDED): the
16074
+ * later upload is the one kept, so a new upload is no remedy.
14837
16075
  *
14838
16076
  * @example
14839
16077
  * const session = await sv.ingots.createUpload({
@@ -14878,6 +16116,18 @@ class IngotsModule {
14878
16116
  * published, so a resolved promise never stands for a stored file whose
14879
16117
  * ingot never went live.
14880
16118
  *
16119
+ * Transient failures are retried inside the transfer; a session the server
16120
+ * no longer holds (it expired, was cancelled, or its ingot was removed)
16121
+ * rejects with code `session_gone`, and only a new upload session — a new
16122
+ * {@link createUpload}, or {@link upload} again — can store the file. An
16123
+ * upload the server refused for good (the account's storage pool cannot
16124
+ * take it, or a later upload replaced it) rejects with code
16125
+ * `upload_refused`, its message the server's own sentence and its code in
16126
+ * `details.coreCode`: a new upload is no remedy. A publication the server
16127
+ * still defers at the transfer's idle limit rejects with code
16128
+ * `upload_received_publishing`: every byte is received, and the server
16129
+ * finishes the publication on its own, so never upload the file again.
16130
+ *
14881
16131
  * @param options.signal - Cancels this transfer (it rejects with code
14882
16132
  * `cancelled`); other transfers carry on.
14883
16133
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
@@ -14909,7 +16159,10 @@ class IngotsModule {
14909
16159
  * Upload a file as a new ingot (high-level flow).
14910
16160
  *
14911
16161
  * Creates the upload session, streams the file to Forge over TUS, then
14912
- * confirms the server finalized the upload before resolving.
16162
+ * confirms the server finalized the upload before resolving. A file the
16163
+ * server refused for good — another upload of it superseded this one, at
16164
+ * its create or while it streamed, or the storage pool cannot take it —
16165
+ * rejects with code `upload_refused`, as {@link sendUpload} does.
14913
16166
  *
14914
16167
  * @example
14915
16168
  * const ingot = await sv.ingots.upload(unsealed, {
@@ -14935,7 +16188,9 @@ class IngotsModule {
14935
16188
  return this.transferAndFinalize(created, created.created, options.file, options.onProgress);
14936
16189
  }
14937
16190
  /**
14938
- * Replace an existing ingot's content (high-level flow).
16191
+ * Replace an existing ingot's content (high-level flow). Rejects as
16192
+ * {@link upload} does, a replacement another upload of the same ingot
16193
+ * superseded included (`upload_refused`).
14939
16194
  *
14940
16195
  * @example
14941
16196
  * await sv.ingots.replace(unsealed, 'ing_abc', { file: updatedFile });
@@ -14951,7 +16206,9 @@ class IngotsModule {
14951
16206
  content_type: contentType,
14952
16207
  size_bytes: options.file.size,
14953
16208
  ...(options.contentHmac && { content_hmac: options.contentHmac }),
14954
- }, { vat: vault.vatToken });
16209
+ }, { vat: vault.vatToken }).catch((error) => {
16210
+ throw stagingRefusalOf(error);
16211
+ });
14955
16212
  if (!response.data.forge_url) {
14956
16213
  throw new ValidationError('Replace endpoint did not return a Forge upload URL');
14957
16214
  }
@@ -15074,11 +16331,15 @@ class IngotsModule {
15074
16331
  * Create a signed download link for an ingot (discrete primitive).
15075
16332
  *
15076
16333
  * Validates the returned URL against the download-host allowlist. Use this
15077
- * when you want the URL itself; otherwise prefer {@link download}.
16334
+ * when you want the URL itself; otherwise prefer {@link download}. The link
16335
+ * is single-use: Forge claims it the moment a request arrives, so a retry or
16336
+ * a resume needs a link of its own (`fetchDownload`'s `remint`).
15078
16337
  *
15079
16338
  * @example
15080
16339
  * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
15081
- * window.location.href = link.downloadUrl;
16340
+ * const { blob } = await fetchDownload(link.downloadUrl, {
16341
+ * remint: async () => (await sv.ingots.createDownloadLink(unsealed, 'ing_abc')).downloadUrl,
16342
+ * });
15082
16343
  */
15083
16344
  async createDownloadLink(vault, ingotId) {
15084
16345
  const vaultId = requireVaultId(vault);
@@ -15100,35 +16361,26 @@ class IngotsModule {
15100
16361
  /**
15101
16362
  * Download an ingot as a Blob (high-level flow).
15102
16363
  *
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.
16364
+ * Every attempt fetches a signed link minted for it ({@link createDownloadLink}:
16365
+ * a link is single-use), under liveness bounds, never a cap on total
16366
+ * duration: a deadline on the response headers, then an idle deadline
16367
+ * rearmed on every body chunk. A failure the platform's transfer policy
16368
+ * retries (`@sparkvault/app-sdk/transfer-retry`: no answer, 408, 425, 429 or
16369
+ * a 5xx, a mint's included) is retried after the policy's backoff, never
16370
+ * sooner than `Retry-After`, until its budget ends. Once bytes have arrived
16371
+ * the retry resumes from the first byte it lacks, conditioned on the
16372
+ * publication's ETag (`If-Range`), so a stall at 90% fetches only the rest;
16373
+ * a file replaced meanwhile starts over as its new content, and one served
16374
+ * with no strong ETag starts over from its first byte. Any other refusal,
16375
+ * and a link that is not a Forge decrypt URL on an allowed host, is final.
15111
16376
  *
15112
16377
  * @example
15113
16378
  * const blob = await sv.ingots.download(unsealed, 'ing_abc');
15114
16379
  * const url = URL.createObjectURL(blob);
15115
16380
  */
15116
16381
  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');
16382
+ const mint = async () => (await this.createDownloadLink(vault, ingotId)).downloadUrl;
16383
+ return (await fetchMintedDownload(mint, { isAllowedHost: this.allowsTransferHost })).blob;
15132
16384
  }
15133
16385
  /**
15134
16386
  * Get an ingot's sharing configuration.
@@ -15250,7 +16502,9 @@ class IngotsModule {
15250
16502
  payload.on_name_conflict = body.onNameConflict;
15251
16503
  }
15252
16504
  const vaultId = requireVaultId(vault);
15253
- const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots`, payload, { vat: vault.vatToken });
16505
+ const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots`, payload, { vat: vault.vatToken }).catch((error) => {
16506
+ throw stagingRefusalOf(error);
16507
+ });
15254
16508
  if (!response.data.forge_url) {
15255
16509
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
15256
16510
  }
@@ -15331,22 +16585,6 @@ function mapInvite(wire) {
15331
16585
  identityType: wire.identity_type ?? 'email',
15332
16586
  };
15333
16587
  }
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
16588
 
15351
16589
  /**
15352
16590
  * Sparks Module
@@ -16056,7 +17294,7 @@ class SparkVault {
16056
17294
  }
16057
17295
  /** Get the SDK version */
16058
17296
  static get version() {
16059
- return '11.0.1';
17297
+ return '11.0.3';
16060
17298
  }
16061
17299
  }
16062
17300
  if (typeof window !== 'undefined') {