@cardinali-studio/adminkit 2.2.48 → 2.2.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/app/App.js +6 -6
  2. package/dist/app/app.css +67 -1
  3. package/dist/app/delivery.js +7 -7
  4. package/dist/app/guide/TransferGuide.js +1 -1
  5. package/dist/app/lib/deliveries.d.ts +6 -0
  6. package/dist/app/lib/delivery-capabilities.d.ts +31 -0
  7. package/dist/app/lib/delivery-capabilities.js +115 -0
  8. package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
  9. package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
  10. package/dist/app/lib/delivery-finalize.d.ts +21 -0
  11. package/dist/app/lib/delivery-finalize.js +42 -0
  12. package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
  13. package/dist/app/lib/delivery-multipart-large.js +28 -0
  14. package/dist/app/lib/delivery-network.d.ts +7 -1
  15. package/dist/app/lib/delivery-network.js +85 -18
  16. package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
  17. package/dist/app/lib/delivery-part-pipeline.js +270 -0
  18. package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
  19. package/dist/app/lib/delivery-upload-coordinator.js +229 -0
  20. package/dist/app/lib/delivery-upload.d.ts +19 -3
  21. package/dist/app/lib/delivery-upload.js +226 -29
  22. package/dist/app/lib/upload-queue.d.ts +5 -0
  23. package/dist/app/lib/upload-queue.js +54 -29
  24. package/dist/app/routes/Deliveries.d.ts +9 -3
  25. package/dist/app/routes/Deliveries.js +299 -164
  26. package/dist/app/routes/DeliveryDashboard.js +1 -1
  27. package/dist/app/routes/DeliveryEmail.d.ts +8 -1
  28. package/dist/app/routes/DeliveryEmail.js +63 -23
  29. package/dist/app/routes/Overview.js +5 -5
  30. package/dist/app/routes/UploadDock.js +4 -3
  31. package/dist/form/media/MediaGrid.js +1 -1
  32. package/dist/functions/_shared/b2.js +108 -19
  33. package/dist/functions/_shared/delivery-activation.js +98 -0
  34. package/dist/functions/_shared/delivery-download-bundle.js +280 -0
  35. package/dist/functions/_shared/delivery-email.js +92 -13
  36. package/dist/functions/_shared/delivery-file-names.js +19 -0
  37. package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
  38. package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
  39. package/dist/functions/_shared/delivery-manifest-free.js +74 -0
  40. package/dist/functions/_shared/delivery-manifest.js +277 -20
  41. package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
  42. package/dist/functions/_shared/delivery-request.js +74 -0
  43. package/dist/functions/_shared/delivery-storage-access.js +14 -0
  44. package/dist/functions/_shared/delivery-upload-admission.js +221 -0
  45. package/dist/functions/_shared/delivery-upload-contract.js +44 -0
  46. package/dist/functions/_shared/delivery-upload-free.js +80 -0
  47. package/dist/functions/_shared/delivery-upload-policy.js +64 -0
  48. package/dist/functions/_shared/delivery-upload-session.js +365 -0
  49. package/dist/functions/_shared/delivery-work-budget.js +49 -0
  50. package/dist/functions/_shared/diagnostics.js +59 -0
  51. package/dist/functions/api/deliveries.js +61 -17
  52. package/dist/functions/api/delivery/multipart.js +156 -16
  53. package/dist/functions/delivery-public/assets/client.js +59 -54
  54. package/dist/functions/delivery-public/assets/delivery.css +6 -2
  55. package/dist/functions/delivery-public/index.js +43 -15
  56. package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
  57. package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
  58. package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
  59. package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
  60. package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
  61. package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
  62. package/dist/functions/index.js +3 -1
  63. package/dist/theme.css +2 -1
  64. package/package.json +1 -1
@@ -0,0 +1,195 @@
1
+ import { checkCancelled, UploadCancelled } from './delivery-network.js';
2
+ export const ASYNC_CHECKPOINT_ROLLOUT_ENABLED = false;
3
+ const PART = 16 * 1024 * 1024;
4
+ async function abortable(promise, control) {
5
+ checkCancelled(control);
6
+ let abort;
7
+ try {
8
+ return await Promise.race([promise, new Promise((_, reject) => {
9
+ abort = () => reject(new UploadCancelled());
10
+ control.signal?.addEventListener('abort', abort, { once: true });
11
+ if (control.signal?.aborted)
12
+ abort();
13
+ })]);
14
+ }
15
+ finally {
16
+ if (abort)
17
+ control.signal?.removeEventListener('abort', abort);
18
+ }
19
+ }
20
+ function immutable(value) {
21
+ const copy = structuredClone(value);
22
+ const freeze = (v) => {
23
+ if (v && typeof v === 'object') {
24
+ for (const child of Object.values(v))
25
+ freeze(child);
26
+ Object.freeze(v);
27
+ }
28
+ };
29
+ freeze(copy);
30
+ return copy;
31
+ }
32
+ /** One active snapshot and one replaceable candidate, each with fixed
33
+ * dependencies. A later producer state can never mutate an accepted snapshot. */
34
+ export class DeliveryCheckpointPipeline {
35
+ persist;
36
+ control;
37
+ onPersisted;
38
+ active = null;
39
+ candidate = null;
40
+ failure = null;
41
+ offset;
42
+ offered;
43
+ stopped = false;
44
+ abort = () => { this.failure ??= new UploadCancelled(); this.candidate = null; };
45
+ constructor(initialOffset, persist, control, onPersisted = () => { }) {
46
+ this.persist = persist;
47
+ this.control = control;
48
+ this.onPersisted = onPersisted;
49
+ if (!Number.isSafeInteger(initialOffset) || initialOffset < 0)
50
+ throw new Error('Offset iniziale non valido');
51
+ this.offset = this.offered = initialOffset;
52
+ control.signal?.addEventListener('abort', this.abort, { once: true });
53
+ if (control.signal?.aborted)
54
+ this.abort();
55
+ }
56
+ get stats() { return { persistedOffset: this.offset, active: this.active !== null, candidates: Number(this.candidate !== null) }; }
57
+ due(offset) { this.check(); return offset - this.offered >= 4 * PART; }
58
+ offer(snapshot, ready) {
59
+ this.check();
60
+ if (!Number.isSafeInteger(snapshot.offset) || snapshot.offset % PART || snapshot.offset <= this.offered || snapshot.offset - this.offset > 8 * PART)
61
+ throw new Error('Snapshot fuori sequenza');
62
+ if (new TextEncoder().encode(JSON.stringify(snapshot)).length > 30000)
63
+ throw new Error('Snapshot troppo grande');
64
+ // Observe dependencies immediately even if a newer candidate replaces this.
65
+ void ready.catch(error => { this.failure ??= error; });
66
+ this.candidate = { snapshot: immutable(snapshot), ready };
67
+ this.offered = snapshot.offset;
68
+ this.start();
69
+ }
70
+ start() {
71
+ if (this.active || !this.candidate || this.failure !== null || this.stopped)
72
+ return;
73
+ const item = this.candidate;
74
+ this.candidate = null;
75
+ const task = (async () => {
76
+ await abortable(item.ready, this.control);
77
+ this.check();
78
+ await abortable(this.persist(item.snapshot), this.control);
79
+ this.check();
80
+ this.offset = item.snapshot.offset;
81
+ this.onPersisted(this.offset);
82
+ })().catch(error => { this.failure ??= error; this.candidate = null; }).finally(() => {
83
+ this.active = null;
84
+ this.start();
85
+ });
86
+ this.active = task;
87
+ }
88
+ async beforeWrite(nextOffset) {
89
+ this.check();
90
+ if (!Number.isSafeInteger(nextOffset) || nextOffset < this.offset)
91
+ throw new Error('Avanzamento ZIP non valido');
92
+ while (nextOffset - this.offset > 8 * PART) {
93
+ if (!this.active)
94
+ throw new Error('Manca uno snapshot per avanzare entro il budget');
95
+ await this.active;
96
+ this.check();
97
+ }
98
+ }
99
+ async drain() {
100
+ while (this.active) {
101
+ await this.active;
102
+ this.check();
103
+ }
104
+ this.check();
105
+ }
106
+ async settle() {
107
+ this.stopped = true;
108
+ this.candidate = null;
109
+ if (this.active)
110
+ await this.active;
111
+ this.control.signal?.removeEventListener('abort', this.abort);
112
+ }
113
+ check() { if (this.failure !== null)
114
+ throw this.failure; checkCancelled(this.control); if (this.stopped)
115
+ throw new Error('Pipeline checkpoint chiusa'); }
116
+ }
117
+ /** Content-addressed groups, durable per-entry original claims, bounded queue.
118
+ * The single producer awaits append/capture; network persistence is serialized. */
119
+ export class DeliveryMetadataJournal {
120
+ packageId;
121
+ send;
122
+ control;
123
+ rows = [];
124
+ tail = Promise.resolve();
125
+ jobs = [];
126
+ failure = null;
127
+ sequence;
128
+ busy = false;
129
+ constructor(packageId, initialSequence, send, control) {
130
+ this.packageId = packageId;
131
+ this.send = send;
132
+ this.control = control;
133
+ this.sequence = initialSequence;
134
+ }
135
+ get stats() { return { queuedBatches: this.jobs.length, bufferedEntries: this.rows.length, sequence: this.sequence }; }
136
+ async append(row) {
137
+ this.check();
138
+ if (this.busy)
139
+ throw new Error('Produttori metadati concorrenti');
140
+ this.busy = true;
141
+ try {
142
+ const clean = immutable({ index: row.index, entry: { name: row.entry.name, type: row.entry.type,
143
+ original: { offset: row.entry.original.offset, length: row.entry.original.length, crc32: row.entry.original.crc32 } } });
144
+ if (new TextEncoder().encode(JSON.stringify([clean])).length > 250 * 1024)
145
+ throw new Error('Singolo metadato troppo grande');
146
+ if (this.rows.length >= 200 || new TextEncoder().encode(JSON.stringify([...this.rows, clean])).length > 250 * 1024)
147
+ await this.captureRows();
148
+ this.rows.push(clean);
149
+ }
150
+ finally {
151
+ this.busy = false;
152
+ }
153
+ }
154
+ async capture() {
155
+ this.check();
156
+ if (this.busy)
157
+ throw new Error('Produttori metadati concorrenti');
158
+ this.busy = true;
159
+ try {
160
+ return await this.captureRows();
161
+ }
162
+ finally {
163
+ this.busy = false;
164
+ }
165
+ }
166
+ async captureRows() {
167
+ this.check();
168
+ if (!this.rows.length)
169
+ return { sequence: this.sequence, ready: this.tail };
170
+ while (this.jobs.length >= 2) {
171
+ await this.jobs[0];
172
+ this.check();
173
+ }
174
+ const entries = immutable(this.rows.slice().sort((a, b) => a.index - b.index));
175
+ this.rows = [];
176
+ const previous = this.tail;
177
+ const job = previous.then(async () => {
178
+ this.check();
179
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([this.packageId, entries]))));
180
+ const batchId = 'm3_' + [...hash].map(n => n.toString(16).padStart(2, '0')).join('');
181
+ await abortable(this.send({ batchId, entries }), this.control);
182
+ this.check();
183
+ });
184
+ this.tail = job;
185
+ this.jobs.push(job);
186
+ this.sequence++;
187
+ void job.catch(error => { this.failure ??= error; });
188
+ void job.finally(() => { this.jobs = this.jobs.filter(p => p !== job); }).catch(() => { });
189
+ return { sequence: this.sequence, ready: job };
190
+ }
191
+ async flush() { const barrier = await this.capture(); await barrier.ready; this.check(); }
192
+ async settle() { await Promise.allSettled(this.jobs); }
193
+ check() { if (this.failure !== null)
194
+ throw this.failure; checkCancelled(this.control); }
195
+ }
@@ -0,0 +1,21 @@
1
+ import { type UploadControl } from './delivery-network.js';
2
+ export declare const COMMON_FINALIZATION_ROLLOUT_ENABLED = false;
3
+ export declare const PAID_FINALIZATION_ROLLOUT_ENABLED = false;
4
+ interface Step {
5
+ done: boolean;
6
+ phase: 'sealed' | 'pages' | 'verified' | 'ready';
7
+ cursor: number;
8
+ total: number;
9
+ }
10
+ interface Activated {
11
+ activated: true;
12
+ id: string;
13
+ status: 'active';
14
+ generation: string;
15
+ notificationIntent: string;
16
+ }
17
+ /** Separate bounded server steps; transport retries stay in deliveryJson. No
18
+ * upload/ZIP operation is repeated merely because finalization must resume. */
19
+ export declare function finalizeDeliveryCommon(id: string, packageId: string, control: UploadControl, onStep?: (step: Step) => void): Promise<Activated>;
20
+ export declare function finalizeDeliveryPaid(id: string, packageId: string, control: UploadControl, onStep?: (step: Step) => void): Promise<Activated>;
21
+ export {};
@@ -0,0 +1,42 @@
1
+ import { deliveryGate, deliveryJson } from './delivery-network.js';
2
+ export const COMMON_FINALIZATION_ROLLOUT_ENABLED = false;
3
+ export const PAID_FINALIZATION_ROLLOUT_ENABLED = false;
4
+ /** Separate bounded server steps; transport retries stay in deliveryJson. No
5
+ * upload/ZIP operation is repeated merely because finalization must resume. */
6
+ export async function finalizeDeliveryCommon(id, packageId, control, onStep) {
7
+ return finalizeSteps('segmentedFinalize', id, packageId, control, onStep);
8
+ }
9
+ // Future negotiated Paid path. No queue selects this helper while flags are
10
+ // false, and the server independently enforces its installation profile.
11
+ export async function finalizeDeliveryPaid(id, packageId, control, onStep) {
12
+ return finalizeSteps('coalescedFinalize', id, packageId, control, onStep);
13
+ }
14
+ async function finalizeSteps(action, id, packageId, control, onStep) {
15
+ let previous = '', cursor = -1, total = -1;
16
+ for (let calls = 0;; calls++) {
17
+ if (calls > 100002)
18
+ throw new Error('Budget di finalizzazione superato');
19
+ await deliveryGate(control);
20
+ const step = await deliveryJson('/admin/api/deliveries', { action, id, packageId }, control);
21
+ if (!step || typeof step.done !== 'boolean' || !['sealed', 'pages', 'verified', 'ready'].includes(step.phase) ||
22
+ !Number.isSafeInteger(step.cursor) || !Number.isSafeInteger(step.total) || step.total < 1 ||
23
+ step.cursor < cursor || step.cursor < 0 || step.cursor > step.total || step.done && step.cursor !== step.total ||
24
+ step.done !== ['verified', 'ready'].includes(step.phase) || total !== -1 && step.total !== total) {
25
+ throw new Error('Risposta di finalizzazione incoerente');
26
+ }
27
+ const progress = `${step.phase}:${step.cursor}:${step.total}`;
28
+ if (!step.done && progress === previous)
29
+ throw new Error('La finalizzazione non avanza');
30
+ previous = progress;
31
+ cursor = step.cursor;
32
+ total = step.total;
33
+ onStep?.(step);
34
+ if (step.done)
35
+ break;
36
+ }
37
+ await deliveryGate(control);
38
+ const activated = await deliveryJson('/admin/api/deliveries', { action: 'minimalActivate', id, packageId }, control);
39
+ if (activated.activated !== true || activated.id !== id || activated.status !== 'active')
40
+ throw new Error('Attivazione non confermata');
41
+ return activated;
42
+ }
@@ -0,0 +1,18 @@
1
+ import { type UploadControl } from './delivery-network.js';
2
+ export declare const LARGE_MULTIPART_ROLLOUT_ENABLED = false;
3
+ interface Progress {
4
+ done: boolean;
5
+ phase: 'parts';
6
+ cursor: number;
7
+ total: number;
8
+ bytes: number;
9
+ proof: string;
10
+ }
11
+ /** Optional preparation, never an authorization to skip reconciliation or the
12
+ * final checkpoint proof. The completed archive is confirmed only by completePaid. */
13
+ export declare function completeMultipartLarge(uploadId: string, bytes: number, partCount: number, control: UploadControl, onStep?: (step: Progress) => void): Promise<{
14
+ uploadId: string;
15
+ key: string;
16
+ bytes: number;
17
+ }>;
18
+ export {};
@@ -0,0 +1,28 @@
1
+ import { deliveryGate, deliveryJson } from './delivery-network.js';
2
+ export const LARGE_MULTIPART_ROLLOUT_ENABLED = false;
3
+ /** Optional preparation, never an authorization to skip reconciliation or the
4
+ * final checkpoint proof. The completed archive is confirmed only by completePaid. */
5
+ export async function completeMultipartLarge(uploadId, bytes, partCount, control, onStep) {
6
+ let cursor = -1, verifiedBytes = -1;
7
+ for (let calls = 0;; calls++) {
8
+ if (calls > 10_000)
9
+ throw new Error('Budget di verifica multipart superato');
10
+ await deliveryGate(control);
11
+ const step = await deliveryJson('/admin/api/delivery/multipart', { action: 'multipartVerifyStep', uploadId, bytes, partCount }, control);
12
+ if (!step || typeof step.done !== 'boolean' || step.phase !== 'parts' || step.total !== partCount ||
13
+ !Number.isSafeInteger(step.cursor) || step.cursor <= cursor || step.cursor < 1 || step.cursor > partCount ||
14
+ !Number.isSafeInteger(step.bytes) || step.bytes <= verifiedBytes || step.bytes < 1 || step.bytes > bytes ||
15
+ !/^[a-f0-9]{64}$/.test(step.proof) || step.done !== (step.cursor === partCount) || step.done && step.bytes !== bytes)
16
+ throw new Error('Verifica multipart incoerente');
17
+ cursor = step.cursor;
18
+ verifiedBytes = step.bytes;
19
+ onStep?.(step);
20
+ if (step.done)
21
+ break;
22
+ }
23
+ await deliveryGate(control);
24
+ const result = await deliveryJson('/admin/api/delivery/multipart', { action: 'completePaid', uploadId, bytes, partCount }, control);
25
+ if (result.uploadId !== uploadId || result.bytes !== bytes || typeof result.key !== 'string' || !result.key)
26
+ throw new Error('Completamento multipart non confermato');
27
+ return result;
28
+ }
@@ -4,6 +4,8 @@ export declare class UploadCancelled extends Error {
4
4
  }
5
5
  export interface UploadControl {
6
6
  writerToken?: string;
7
+ /** Invocation-local coordinator; never serialized into the HTTP body. */
8
+ json?<T>(url: string, body: Record<string, unknown>, control: UploadControl): Promise<T>;
7
9
  gate(): Promise<void>;
8
10
  signal?: AbortSignal;
9
11
  networkWaiting?(waiting: boolean): void;
@@ -11,7 +13,9 @@ export interface UploadControl {
11
13
  export declare class DeliveryRequestError extends Error {
12
14
  readonly retryable: boolean;
13
15
  readonly retryAfter: number;
14
- constructor(message: string, retryable?: boolean, retryAfter?: number);
16
+ readonly code?: string | undefined;
17
+ readonly status?: number | undefined;
18
+ constructor(message: string, retryable?: boolean, retryAfter?: number, code?: string | undefined, status?: number | undefined);
15
19
  }
16
20
  export declare function checkCancelled(control?: UploadControl): void;
17
21
  export declare function deliveryGate(control?: UploadControl): Promise<void>;
@@ -23,3 +27,5 @@ export declare function retryDelivery<T>(operation: () => Promise<T>, control?:
23
27
  export declare function deliveryJson<T>(url: string, body: Record<string, unknown>, control?: UploadControl, retry?: boolean): Promise<T>;
24
28
  /** La callback viene richiamata a ogni tentativo: le firme scadute non vengono riusate. */
25
29
  export declare function deliveryPut(sign: () => Promise<string>, body: BodyInit, contentType: string, control?: UploadControl): Promise<string>;
30
+ /** Keep transport diagnostics out of the sender’s form and upload queue. */
31
+ export declare function transferErrorMessage(error: unknown): string;
@@ -5,12 +5,18 @@ export class UploadCancelled extends Error {
5
5
  export class DeliveryRequestError extends Error {
6
6
  retryable;
7
7
  retryAfter;
8
- constructor(message, retryable = false, retryAfter = 0) {
8
+ code;
9
+ status;
10
+ constructor(message, retryable = false, retryAfter = 0, code, status) {
9
11
  super(message);
10
12
  this.retryable = retryable;
11
13
  this.retryAfter = retryAfter;
14
+ this.code = code;
15
+ this.status = status;
12
16
  }
13
17
  }
18
+ const UPLOAD_POLICY_CODES = new Set(['upload_capability_changed', 'upload_budget_exceeded',
19
+ 'upload_budget_unknown', 'upload_profile_required', 'upload_quota_exhausted']);
14
20
  export function checkCancelled(control) {
15
21
  if (control?.signal?.aborted)
16
22
  throw new UploadCancelled();
@@ -62,7 +68,7 @@ export async function retryDelivery(operation, control, policy = { maxElapsedMs:
62
68
  }
63
69
  catch (error) {
64
70
  checkCancelled(control);
65
- if (!(error instanceof DeliveryRequestError) || !error.retryable ||
71
+ if (!(error instanceof DeliveryRequestError) || !error.retryable || UPLOAD_POLICY_CODES.has(error.code || '') ||
66
72
  Date.now() - started >= policy.maxElapsedMs)
67
73
  throw error;
68
74
  if (!waiting) {
@@ -110,22 +116,31 @@ async function request(url, init, read, control, timeoutMs = 60_000) {
110
116
  control?.signal?.removeEventListener("abort", abort);
111
117
  }
112
118
  }
113
- function httpError(res, message, renewSignature = false) {
114
- const transient = [408, 429, 500, 502, 503, 504].includes(res.status) || (renewSignature && res.status === 403);
119
+ function httpError(res, message) {
120
+ const transient = [408, 429, 500, 502, 503, 504].includes(res.status);
115
121
  const header = res.headers.get("retry-after");
116
122
  const seconds = Number(header);
117
123
  const retryAfter = header ? (Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now()) : 0;
118
- return new DeliveryRequestError(message || `Richiesta non riuscita (HTTP ${res.status})`, transient, Number.isFinite(retryAfter) ? Math.max(0, Math.min(60_000, retryAfter)) : 0);
124
+ return new DeliveryRequestError(message || `Richiesta non riuscita (HTTP ${res.status})`, transient, Number.isFinite(retryAfter) ? Math.max(0, Math.min(60_000, retryAfter)) : 0, undefined, res.status);
119
125
  }
120
126
  export function deliveryJson(url, body, control, retry = true) {
127
+ if (control?.json)
128
+ return control.json(url, body, control);
129
+ const sessionRequest = typeof body.action === 'string' && /^uploadSession(Create|Status|Unit|Pause|Recover)$/.test(body.action);
130
+ const wire = sessionRequest ? JSON.stringify(control?.writerToken ? { ...body, writerToken: control.writerToken } : body) : '';
131
+ if (sessionRequest && new TextEncoder().encode(wire).byteLength > 278528)
132
+ return Promise.reject(new DeliveryRequestError('Richiesta oltre il budget di upload', false, 0, 'upload_budget_exceeded', 413));
121
133
  const operation = () => request(url, {
122
- method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(control?.writerToken ? { ...body, writerToken: control.writerToken } : body),
134
+ method: "POST", headers: { "Content-Type": "application/json", ...(sessionRequest ? { 'X-Delivery-Upload-Protocol': '1' } : {}) },
135
+ body: sessionRequest ? wire : JSON.stringify(control?.writerToken ? { ...body, writerToken: control.writerToken } : body),
123
136
  }, async (res) => {
124
137
  let value;
125
138
  try {
126
- value = await res.json();
139
+ value = sessionRequest ? await boundedUploadResponse(res) : await res.json();
127
140
  }
128
141
  catch (error) {
142
+ if (error instanceof DeliveryRequestError)
143
+ throw error;
129
144
  if (!res.ok)
130
145
  throw httpError(res);
131
146
  if (error instanceof TypeError || res.headers.get("content-type")?.includes("application/json")) {
@@ -135,25 +150,77 @@ export function deliveryJson(url, body, control, retry = true) {
135
150
  }
136
151
  if (!res.ok || value.ok !== true) {
137
152
  const error = httpError(res, value.error);
138
- throw value.retryable === false ? new DeliveryRequestError(error.message) : error;
153
+ const code = typeof value.code === 'string' ? value.code : undefined;
154
+ const retryable = value.retryable !== false && !UPLOAD_POLICY_CODES.has(code || '') && error.retryable;
155
+ throw new DeliveryRequestError(error.message, retryable, error.retryAfter, code, res.status);
139
156
  }
140
157
  return value;
141
158
  }, control);
142
159
  return retry ? retryDelivery(operation, control) : operation();
143
160
  }
161
+ async function boundedUploadResponse(res) {
162
+ const max = 278528, reader = res.body?.getReader(), chunks = [], decoder = new TextDecoder('utf-8', { fatal: true });
163
+ let bytes = 0;
164
+ try {
165
+ if (Number(res.headers.get('content-length')) > max)
166
+ throw new DeliveryRequestError('Risposta oltre il budget di upload', false, 0, 'upload_budget_exceeded', 413);
167
+ if (reader)
168
+ for (;;) {
169
+ const { value, done } = await reader.read();
170
+ if (done)
171
+ break;
172
+ bytes += value.byteLength;
173
+ if (bytes > max)
174
+ throw new DeliveryRequestError('Risposta oltre il budget di upload', false, 0, 'upload_budget_exceeded', 413);
175
+ chunks.push(decoder.decode(value, { stream: true }));
176
+ }
177
+ chunks.push(decoder.decode());
178
+ return JSON.parse(chunks.join(''));
179
+ }
180
+ finally {
181
+ void reader?.cancel().catch(() => { });
182
+ reader?.releaseLock();
183
+ }
184
+ }
144
185
  /** La callback viene richiamata a ogni tentativo: le firme scadute non vengono riusate. */
145
186
  export function deliveryPut(sign, body, contentType, control) {
187
+ const accessDenied = (status) => new DeliveryRequestError("Il servizio non può accedere ai file. Avvisa chi gestisce il sito, poi riprendi il caricamento.", false, 0, "upload_storage_access_denied", status);
146
188
  return retryDelivery(async () => {
147
- const url = await sign();
148
- await deliveryGate(control);
149
- return request(url, { method: "PUT", body, headers: { "Content-Type": contentType } }, async (res) => {
150
- if (!res.ok) {
189
+ // A presigned URL may have expired while paused. Renew it once on 403.
190
+ for (let attempt = 0; attempt < 2; attempt++) {
191
+ await deliveryGate(control);
192
+ const url = await sign();
193
+ await deliveryGate(control);
194
+ const etag = await request(url, { method: "PUT", body, headers: { "Content-Type": contentType } }, async (res) => {
151
195
  await res.body?.cancel();
152
- throw httpError(res, undefined, true);
153
- }
154
- const etag = res.headers.get("etag") || "";
155
- await res.body?.cancel();
156
- return etag;
157
- }, control, 30 * 60_000);
196
+ if (res.status === 403)
197
+ return null;
198
+ if (res.status === 401)
199
+ throw accessDenied(401);
200
+ if (!res.ok)
201
+ throw httpError(res);
202
+ return res.headers.get("etag") || "";
203
+ }, control, 30 * 60_000);
204
+ if (etag !== null)
205
+ return etag;
206
+ }
207
+ throw accessDenied(403);
158
208
  }, control);
159
209
  }
210
+ /** Keep transport diagnostics out of the sender’s form and upload queue. */
211
+ export function transferErrorMessage(error) {
212
+ const raw = error instanceof Error ? error.message : String(error);
213
+ if (error instanceof DOMException && error.name === "NotReadableError" || /requested file could not be read/i.test(raw)) {
214
+ return "Il browser non riesce più a leggere i file. Riseleziona gli stessi file o la stessa cartella.";
215
+ }
216
+ if (/checkpoint|checksum|fingerprint|digest|impronta|writer.token/i.test(raw)) {
217
+ return "Non è stato possibile riprendere il caricamento. Riseleziona gli stessi file originali.";
218
+ }
219
+ if (/etag|cors|bucket|multipart|manifest|SigV4|\b(?:D1|B2|SQLITE|SQL|R2)\b|HTTP \d{3}/i.test(raw)) {
220
+ return "Non è stato possibile completare l’operazione sui file. Riprova tra poco.";
221
+ }
222
+ if (/failed to fetch|load failed|networkerror|network request failed|fetch failed/i.test(raw)) {
223
+ return "Controlla la connessione e riprova.";
224
+ }
225
+ return raw;
226
+ }
@@ -0,0 +1,79 @@
1
+ import { type UploadControl } from './delivery-network.js';
2
+ export declare const PART_BATCH_ROLLOUT_ENABLED = false;
3
+ export interface PartReceipt {
4
+ partNumber: number;
5
+ size: number;
6
+ etag: string;
7
+ digest: string;
8
+ }
9
+ export interface PartBatchTransport {
10
+ presign(partNumbers: number[], control: UploadControl): Promise<{
11
+ parts: {
12
+ partNumber: number;
13
+ url: string;
14
+ }[];
15
+ expiresIn: number;
16
+ }>;
17
+ put(sign: () => Promise<string>, body: Uint8Array, control: UploadControl): Promise<string>;
18
+ record(parts: PartReceipt[], batchId: string, control: UploadControl): Promise<{
19
+ batchId: string;
20
+ parts: PartReceipt[];
21
+ }>;
22
+ }
23
+ /** Bounded PUT and receipt queues. Production construction stays disabled until
24
+ * capability negotiation and full-consumer budgets have been certified. */
25
+ export declare class DeliveryPartPipeline {
26
+ private uploadId;
27
+ private transport;
28
+ private onPut;
29
+ private onRegistered;
30
+ private batchSize;
31
+ private flushAfterMs;
32
+ private readonly controller;
33
+ private readonly control;
34
+ private readonly receiptControl;
35
+ private readonly active;
36
+ private readonly known;
37
+ private readonly signatures;
38
+ private signing;
39
+ private pending;
40
+ private recording;
41
+ private timer;
42
+ private failure;
43
+ private waiters;
44
+ private unconfirmed;
45
+ private retainedBytes;
46
+ private highestPart;
47
+ private transferredBytes;
48
+ private registeredBytes;
49
+ private contiguousPart;
50
+ private readonly verified;
51
+ private readonly abort;
52
+ constructor(uploadId: string, transport: PartBatchTransport, control: UploadControl, prior?: ReadonlyMap<number, {
53
+ size: number;
54
+ digest: string;
55
+ }>, onPut?: (bytes: number) => void, onRegistered?: (bytes: number, reused: boolean) => void, batchSize?: 1 | 2 | 4, flushAfterMs?: number);
56
+ private detach;
57
+ get stats(): {
58
+ activePuts: number;
59
+ unconfirmedParts: number;
60
+ retainedBytes: number;
61
+ transferredBytes: number;
62
+ registeredBytes: number;
63
+ cachedSignatures: number;
64
+ };
65
+ restorePrefix(through: number): void;
66
+ waitThrough(through: number): Promise<void>;
67
+ private verifyPart;
68
+ enqueue(partNumber: number, body: Uint8Array): Promise<void>;
69
+ private upload;
70
+ private signature;
71
+ private validateSignatures;
72
+ private flushRecords;
73
+ flush(): Promise<void>;
74
+ settle(): Promise<void>;
75
+ private check;
76
+ private fail;
77
+ private clearTimer;
78
+ private wake;
79
+ }