tempest-react-sdk 0.76.0 → 0.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/create-tempest-app.e2e.test.mjs +112 -0
- package/bin/create-tempest-app.mjs +69 -28
- package/bin/lib/alias/collect.mjs +20 -3
- package/bin/lib/alias/index.mjs +12 -1
- package/bin/lib/alias/index.test.mjs +24 -0
- package/bin/lib/component/generate.mjs +191 -0
- package/bin/lib/component/generate.test.mjs +336 -0
- package/bin/lib/css/analyze.test.mjs +21 -1
- package/bin/lib/css/collect.mjs +14 -0
- package/bin/lib/css/extract.mjs +63 -5
- package/bin/lib/css/extract.test.mjs +110 -1
- package/bin/lib/css/fix.e2e.test.mjs +50 -0
- package/bin/lib/css/index.mjs +6 -1
- package/bin/lib/fs/contain.mjs +50 -0
- package/bin/lib/icons/generate.mjs +28 -3
- package/bin/lib/icons/generate.test.mjs +57 -1
- package/bin/lib/openapi/escape.mjs +224 -0
- package/bin/lib/openapi/generate.encode.test.mjs +120 -0
- package/bin/lib/openapi/generate.hostile.test.mjs +621 -0
- package/bin/lib/openapi/generate.mjs +129 -18
- package/bin/lib/openapi/generate.test.mjs +7 -2
- package/bin/lib/openapi/schema-to-zod.mjs +43 -4
- package/bin/tempest-gen.test.mjs +188 -0
- package/bin/tempest.mjs +263 -6
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +203 -58
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/refresh-queue.cjs +1 -1
- package/dist/auth/refresh-queue.cjs.map +1 -1
- package/dist/auth/refresh-queue.js +13 -6
- package/dist/auth/refresh-queue.js.map +1 -1
- package/dist/br/pix.cjs +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js +85 -72
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +19 -4
- package/dist/components/Chat/ChatAttachments.cjs +1 -1
- package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
- package/dist/components/Chat/ChatAttachments.js +46 -38
- package/dist/components/Chat/ChatAttachments.js.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/CodeBlock/tokenize.cjs +1 -1
- package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
- package/dist/components/CodeBlock/tokenize.js +54 -25
- package/dist/components/CodeBlock/tokenize.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +7 -5
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +171 -90
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Toast/Toast.module.cjs +1 -1
- package/dist/components/Toast/Toast.module.cjs.map +1 -1
- package/dist/components/Toast/Toast.module.js +7 -3
- package/dist/components/Toast/Toast.module.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js +77 -51
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/data/create-data-provider.cjs +1 -1
- package/dist/data/create-data-provider.cjs.map +1 -1
- package/dist/data/create-data-provider.js +32 -21
- package/dist/data/create-data-provider.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +81 -73
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +39 -35
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +141 -105
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +5 -6
- package/dist/http/retry.js.map +1 -1
- package/dist/oauth/callback.cjs +2 -0
- package/dist/oauth/callback.cjs.map +1 -0
- package/dist/oauth/callback.js +42 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/use-oauth-callback.cjs +1 -1
- package/dist/oauth/use-oauth-callback.cjs.map +1 -1
- package/dist/oauth/use-oauth-callback.js +13 -20
- package/dist/oauth/use-oauth-callback.js.map +1 -1
- package/dist/push/use-push-subscription.cjs +1 -1
- package/dist/push/use-push-subscription.cjs.map +1 -1
- package/dist/push/use-push-subscription.js +42 -42
- package/dist/push/use-push-subscription.js.map +1 -1
- package/dist/push/web-push-client.cjs +1 -1
- package/dist/push/web-push-client.cjs.map +1 -1
- package/dist/push/web-push-client.js +23 -3
- package/dist/push/web-push-client.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +68 -23
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/styles/component/Toast.css +6 -1
- package/dist/styles/feedback.css +6 -1
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +272 -60
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache-inspect.cjs.map +1 -1
- package/dist/sw/cache-inspect.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +91 -64
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw/credential-headers.cjs +2 -0
- package/dist/sw/credential-headers.cjs.map +1 -0
- package/dist/sw/credential-headers.js +17 -0
- package/dist/sw/credential-headers.js.map +1 -0
- package/dist/sw/session-data.cjs +2 -0
- package/dist/sw/session-data.cjs.map +1 -0
- package/dist/sw/session-data.js +17 -0
- package/dist/sw/session-data.js.map +1 -0
- package/dist/sw.cjs +1 -1
- package/dist/sw.d.ts +309 -23
- package/dist/sw.js +7 -5
- package/dist/telemetry/app-error-queue.cjs +1 -1
- package/dist/telemetry/app-error-queue.cjs.map +1 -1
- package/dist/telemetry/app-error-queue.js +19 -14
- package/dist/telemetry/app-error-queue.js.map +1 -1
- package/dist/telemetry/app-error-reporter.cjs +1 -1
- package/dist/telemetry/app-error-reporter.cjs.map +1 -1
- package/dist/telemetry/app-error-reporter.js +75 -34
- package/dist/telemetry/app-error-reporter.js.map +1 -1
- package/dist/telemetry/app-error-transport.cjs +1 -1
- package/dist/telemetry/app-error-transport.cjs.map +1 -1
- package/dist/telemetry/app-error-transport.js +16 -3
- package/dist/telemetry/app-error-transport.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +1183 -64
- package/dist/tempest-react-sdk.js +160 -156
- package/dist/utils/csv.cjs +3 -3
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js +18 -14
- package/dist/utils/csv.js.map +1 -1
- package/dist/utils/owner-fingerprint.cjs +2 -0
- package/dist/utils/owner-fingerprint.cjs.map +1 -0
- package/dist/utils/owner-fingerprint.js +18 -0
- package/dist/utils/owner-fingerprint.js.map +1 -0
- package/dist/utils/safe-url.cjs +2 -0
- package/dist/utils/safe-url.cjs.map +1 -0
- package/dist/utils/safe-url.js +39 -0
- package/dist/utils/safe-url.js.map +1 -0
- package/dist/vite/tempest-csp.cjs +2 -2
- package/dist/vite/tempest-csp.cjs.map +1 -1
- package/dist/vite/tempest-csp.js +130 -64
- package/dist/vite/tempest-csp.js.map +1 -1
- package/dist/vite.d.ts +23 -5
- package/dist/webrtc/peer-link.cjs +1 -1
- package/dist/webrtc/peer-link.cjs.map +1 -1
- package/dist/webrtc/peer-link.js +2 -10
- package/dist/webrtc/peer-link.js.map +1 -1
- package/dist/webrtc/peer-mesh.cjs +1 -1
- package/dist/webrtc/peer-mesh.cjs.map +1 -1
- package/dist/webrtc/peer-mesh.js +110 -72
- package/dist/webrtc/peer-mesh.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/src/pwa.tsx +22 -0
- package/template-pwa/src/sw.ts +27 -14
- package/dist/components/Markdown/markdown-url.cjs +0 -2
- package/dist/components/Markdown/markdown-url.cjs.map +0 -1
- package/dist/components/Markdown/markdown-url.js +0 -28
- package/dist/components/Markdown/markdown-url.js.map +0 -1
|
@@ -3,22 +3,37 @@ import { isTrustedCredentialTarget as t, reportSuppressedCredential as n } from
|
|
|
3
3
|
import { csrfHeaders as r } from "./csrf.js";
|
|
4
4
|
import { TempestApiError as i, buildApiError as a, isApiError as o, isRetriableStatus as s } from "./errors.js";
|
|
5
5
|
import { retry as c } from "./retry.js";
|
|
6
|
-
import {
|
|
6
|
+
import { ownerFingerprint as l } from "../utils/owner-fingerprint.js";
|
|
7
|
+
import { generateIdempotencyKey as ee } from "./idempotency.js";
|
|
7
8
|
//#region src/http/resumable-upload.ts
|
|
8
|
-
var u = "1.0.0", d = 5242880
|
|
9
|
-
|
|
9
|
+
var u = "1.0.0", d = 5242880, f = class extends Error {
|
|
10
|
+
reason;
|
|
11
|
+
constructor(e) {
|
|
12
|
+
super(e === "principal" ? "O usuário mudou durante o upload resumível." : "Os registros de upload resumível foram limpos durante o upload."), this.name = "ResumableUploadSupersededError", this.reason = e;
|
|
13
|
+
}
|
|
14
|
+
}, p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new WeakMap();
|
|
15
|
+
function h(e) {
|
|
16
|
+
if (!e) return !1;
|
|
17
|
+
try {
|
|
18
|
+
let t = JSON.parse(e);
|
|
19
|
+
return typeof t == "object" && !!t && typeof t.url == "string" && typeof t.offset == "number" && typeof t.size == "number" && typeof t.idempotencyKey == "string";
|
|
20
|
+
} catch {
|
|
21
|
+
return !1;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function g(t) {
|
|
10
25
|
return e(new TextEncoder().encode(t));
|
|
11
26
|
}
|
|
12
|
-
function
|
|
27
|
+
function _(e) {
|
|
13
28
|
if (!e) return null;
|
|
14
|
-
let t = Object.entries(e).map(([e, t]) => `${e} ${
|
|
29
|
+
let t = Object.entries(e).map(([e, t]) => `${e} ${g(t)}`);
|
|
15
30
|
return t.length > 0 ? t.join(",") : null;
|
|
16
31
|
}
|
|
17
|
-
function
|
|
32
|
+
function v(e, t) {
|
|
18
33
|
let n = t, r = typeof n.name == "string" ? n.name : "blob", i = typeof n.lastModified == "number" ? n.lastModified : 0;
|
|
19
34
|
return `${e}|${r}|${t.size}|${t.type}|${i}`;
|
|
20
35
|
}
|
|
21
|
-
function
|
|
36
|
+
function y(e = "tempest-upload:") {
|
|
22
37
|
function t() {
|
|
23
38
|
try {
|
|
24
39
|
return typeof localStorage > "u" ? null : localStorage;
|
|
@@ -26,7 +41,7 @@ function h(e = "tempest-upload:") {
|
|
|
26
41
|
return null;
|
|
27
42
|
}
|
|
28
43
|
}
|
|
29
|
-
|
|
44
|
+
let n = {
|
|
30
45
|
get(n) {
|
|
31
46
|
let r = t()?.getItem(e + n);
|
|
32
47
|
if (!r) return null;
|
|
@@ -41,10 +56,22 @@ function h(e = "tempest-upload:") {
|
|
|
41
56
|
},
|
|
42
57
|
delete(n) {
|
|
43
58
|
t()?.removeItem(e + n);
|
|
59
|
+
},
|
|
60
|
+
clear() {
|
|
61
|
+
p.set(e, (p.get(e) ?? 0) + 1);
|
|
62
|
+
let n = t();
|
|
63
|
+
if (!n) return;
|
|
64
|
+
let r = [];
|
|
65
|
+
for (let t = 0; t < n.length; t += 1) {
|
|
66
|
+
let i = n.key(t);
|
|
67
|
+
i?.startsWith(e) && h(n.getItem(i)) && r.push(i);
|
|
68
|
+
}
|
|
69
|
+
for (let e of r) n.removeItem(e);
|
|
44
70
|
}
|
|
45
71
|
};
|
|
72
|
+
return m.set(n, () => p.get(e) ?? 0), n;
|
|
46
73
|
}
|
|
47
|
-
function
|
|
74
|
+
function b(e) {
|
|
48
75
|
return new Promise((t, n) => {
|
|
49
76
|
let r = new XMLHttpRequest();
|
|
50
77
|
r.open(e.method, e.url), r.withCredentials = e.withCredentials;
|
|
@@ -63,13 +90,13 @@ function g(e) {
|
|
|
63
90
|
})), r.onabort = () => n(new DOMException("Aborted", "AbortError")), e.register(r), r.send(e.body);
|
|
64
91
|
});
|
|
65
92
|
}
|
|
66
|
-
function
|
|
93
|
+
function x(e) {
|
|
67
94
|
let t = e.header("Upload-Offset");
|
|
68
95
|
if (t === null) return null;
|
|
69
96
|
let n = Number(t);
|
|
70
97
|
return Number.isFinite(n) && n >= 0 ? n : null;
|
|
71
98
|
}
|
|
72
|
-
function
|
|
99
|
+
function S(e) {
|
|
73
100
|
if (!e) return null;
|
|
74
101
|
try {
|
|
75
102
|
return JSON.parse(e);
|
|
@@ -77,18 +104,18 @@ function v(e) {
|
|
|
77
104
|
return e;
|
|
78
105
|
}
|
|
79
106
|
}
|
|
80
|
-
var
|
|
81
|
-
function
|
|
82
|
-
return !o(e) ||
|
|
107
|
+
var C = /* @__PURE__ */ new Set([409, 412]);
|
|
108
|
+
function w(e) {
|
|
109
|
+
return !o(e) || C.has(e.status) ? !0 : s(e.status);
|
|
83
110
|
}
|
|
84
|
-
function
|
|
85
|
-
let n =
|
|
111
|
+
function T(e, t) {
|
|
112
|
+
let n = S(e.text), r = a(e.status, n, { get: e.header }), o = typeof n == "object" && !!n && ("detail" in n || "message" in n);
|
|
86
113
|
return new i({
|
|
87
114
|
...r,
|
|
88
115
|
detail: o ? r.detail : t
|
|
89
116
|
});
|
|
90
117
|
}
|
|
91
|
-
function
|
|
118
|
+
function E(e) {
|
|
92
119
|
let t = typeof window > "u" ? void 0 : window.location.href;
|
|
93
120
|
try {
|
|
94
121
|
return new URL(e, t).href;
|
|
@@ -96,170 +123,179 @@ function S(e) {
|
|
|
96
123
|
return e;
|
|
97
124
|
}
|
|
98
125
|
}
|
|
99
|
-
function
|
|
100
|
-
let { endpoint: a, file: o, chunkSize: s = d, metadata:
|
|
101
|
-
function
|
|
102
|
-
|
|
126
|
+
function D(e) {
|
|
127
|
+
let { endpoint: a, file: o, chunkSize: s = d, metadata: p, headers: h = {}, getToken: g, getPrincipal: S, trustedOrigins: C, withCredentials: D = !1, csrf: O, key: k = v(a, o), storage: A = y(), retry: j, onProgress: M, onStateChange: N } = e, P = "idle", F = 0, I = null, L = null, R, z = !1, B = A ? m.get(A) : void 0, V = B?.() ?? 0;
|
|
128
|
+
function H() {
|
|
129
|
+
if (S && l("p", S()) !== R) throw new f("principal");
|
|
130
|
+
if (B && B() !== V) throw new f("cleared");
|
|
103
131
|
}
|
|
104
|
-
|
|
105
|
-
|
|
132
|
+
let U = null, W = null, G = 0;
|
|
133
|
+
function K(e) {
|
|
134
|
+
P !== e && (P = e, N?.(e));
|
|
135
|
+
}
|
|
136
|
+
function q(e) {
|
|
137
|
+
M?.({
|
|
106
138
|
loaded: e,
|
|
107
139
|
total: o.size,
|
|
108
140
|
fraction: o.size === 0 ? 1 : e / o.size,
|
|
109
|
-
resumedFrom:
|
|
141
|
+
resumedFrom: G
|
|
110
142
|
});
|
|
111
143
|
}
|
|
112
|
-
function
|
|
144
|
+
function J(e, i) {
|
|
113
145
|
let o = {
|
|
114
|
-
...
|
|
146
|
+
...h,
|
|
115
147
|
"Tus-Resumable": u
|
|
116
|
-
}, s =
|
|
148
|
+
}, s = g?.();
|
|
117
149
|
return s && !("Authorization" in o) && (t(e, a, C) ? o.Authorization = `Bearer ${s}` : n(e, a)), Object.assign(o, r({
|
|
118
150
|
method: i,
|
|
119
151
|
url: e,
|
|
120
152
|
reference: a,
|
|
121
|
-
csrf:
|
|
153
|
+
csrf: O,
|
|
122
154
|
trustedOrigins: C,
|
|
123
|
-
headers:
|
|
155
|
+
headers: h
|
|
124
156
|
})), o;
|
|
125
157
|
}
|
|
126
|
-
function
|
|
127
|
-
|
|
158
|
+
function Y(e) {
|
|
159
|
+
W = e;
|
|
128
160
|
}
|
|
129
|
-
async function
|
|
130
|
-
|
|
131
|
-
url:
|
|
132
|
-
offset:
|
|
161
|
+
async function X() {
|
|
162
|
+
A && I && L && (H(), await A.set(k, {
|
|
163
|
+
url: I,
|
|
164
|
+
offset: F,
|
|
133
165
|
size: o.size,
|
|
134
|
-
idempotencyKey:
|
|
135
|
-
updatedAt: Date.now()
|
|
136
|
-
|
|
166
|
+
idempotencyKey: L,
|
|
167
|
+
updatedAt: Date.now(),
|
|
168
|
+
...R === void 0 ? {} : { owner: R }
|
|
169
|
+
}));
|
|
137
170
|
}
|
|
138
|
-
async function
|
|
139
|
-
let t = await
|
|
171
|
+
async function Z(e) {
|
|
172
|
+
let t = await b({
|
|
140
173
|
method: "HEAD",
|
|
141
174
|
url: e,
|
|
142
|
-
headers:
|
|
143
|
-
withCredentials:
|
|
144
|
-
register:
|
|
175
|
+
headers: J(e, "HEAD"),
|
|
176
|
+
withCredentials: D,
|
|
177
|
+
register: Y
|
|
145
178
|
});
|
|
146
179
|
if (t.status === 404 || t.status === 410) throw new i({
|
|
147
180
|
status: t.status,
|
|
148
181
|
detail: "O upload expirou no servidor. Comece de novo."
|
|
149
182
|
});
|
|
150
|
-
let n =
|
|
151
|
-
if (n === null) throw
|
|
183
|
+
let n = x(t);
|
|
184
|
+
if (n === null) throw T(t, "HEAD sem Upload-Offset.");
|
|
152
185
|
return n;
|
|
153
186
|
}
|
|
154
|
-
async function
|
|
155
|
-
let e =
|
|
156
|
-
|
|
157
|
-
|
|
187
|
+
async function te() {
|
|
188
|
+
let e = S ? l("p", S()) : void 0;
|
|
189
|
+
z && e !== R && (L = null), R = e, z = !0, V = B?.() ?? 0;
|
|
190
|
+
let t = A ? await A.get(k) : null;
|
|
191
|
+
if (t && R !== void 0 && t.owner !== R && (await A?.delete(k), t = null), t && t.size === o.size && (L = t.idempotencyKey, t.url)) try {
|
|
192
|
+
return F = await Z(t.url), I = t.url, t.url;
|
|
158
193
|
} catch {
|
|
159
|
-
|
|
194
|
+
F = 0;
|
|
160
195
|
}
|
|
161
|
-
|
|
196
|
+
K("creating"), L ??= ee(), I = null, F = 0, A && await A.set(k, {
|
|
162
197
|
url: "",
|
|
163
198
|
offset: 0,
|
|
164
199
|
size: o.size,
|
|
165
|
-
idempotencyKey:
|
|
166
|
-
updatedAt: Date.now()
|
|
200
|
+
idempotencyKey: L,
|
|
201
|
+
updatedAt: Date.now(),
|
|
202
|
+
...R === void 0 ? {} : { owner: R }
|
|
167
203
|
});
|
|
168
|
-
let
|
|
169
|
-
...
|
|
204
|
+
let n = {
|
|
205
|
+
...J(a, "POST"),
|
|
170
206
|
"Upload-Length": String(o.size),
|
|
171
|
-
"Idempotency-Key":
|
|
172
|
-
},
|
|
173
|
-
|
|
174
|
-
let
|
|
207
|
+
"Idempotency-Key": L
|
|
208
|
+
}, r = _(p);
|
|
209
|
+
r && (n["Upload-Metadata"] = r);
|
|
210
|
+
let i = await b({
|
|
175
211
|
method: "POST",
|
|
176
212
|
url: a,
|
|
177
|
-
headers:
|
|
178
|
-
withCredentials:
|
|
179
|
-
register:
|
|
213
|
+
headers: n,
|
|
214
|
+
withCredentials: D,
|
|
215
|
+
register: Y
|
|
180
216
|
});
|
|
181
|
-
if (
|
|
182
|
-
let
|
|
183
|
-
if (!
|
|
184
|
-
return
|
|
217
|
+
if (i.status !== 201) throw T(i, "Criação do upload recusada.");
|
|
218
|
+
let s = i.header("Location");
|
|
219
|
+
if (!s) throw T(i, "Criação do upload sem cabeçalho Location.");
|
|
220
|
+
return I = E(s), await X(), I;
|
|
185
221
|
}
|
|
186
|
-
async function
|
|
187
|
-
if (t.needed && (
|
|
188
|
-
let n = Math.min(
|
|
222
|
+
async function ne(e, t) {
|
|
223
|
+
if (H(), t.needed && (F = await Z(e), t.needed = !1, q(F), await X(), F >= o.size)) return;
|
|
224
|
+
let n = Math.min(F + s, o.size), r = F, i = await b({
|
|
189
225
|
method: "PATCH",
|
|
190
226
|
url: e,
|
|
191
227
|
headers: {
|
|
192
|
-
...
|
|
228
|
+
...J(e, "PATCH"),
|
|
193
229
|
"Content-Type": "application/offset+octet-stream",
|
|
194
230
|
"Upload-Offset": String(r)
|
|
195
231
|
},
|
|
196
232
|
body: o.slice(r, n),
|
|
197
|
-
withCredentials:
|
|
198
|
-
onProgress: (e) =>
|
|
199
|
-
register:
|
|
233
|
+
withCredentials: D,
|
|
234
|
+
onProgress: (e) => q(Math.min(r + e, o.size)),
|
|
235
|
+
register: Y
|
|
200
236
|
});
|
|
201
|
-
if (i.status === 409 || i.status === 412) throw t.needed = !0,
|
|
202
|
-
if (i.status !== 204 && i.status !== 200) throw
|
|
203
|
-
|
|
237
|
+
if (i.status === 409 || i.status === 412) throw t.needed = !0, T(i, "Offset divergente — o servidor já tinha esses bytes.");
|
|
238
|
+
if (i.status !== 204 && i.status !== 200) throw T(i, "Chunk recusado pelo servidor.");
|
|
239
|
+
F = x(i) ?? n, q(F), await X();
|
|
204
240
|
}
|
|
205
|
-
async function
|
|
206
|
-
|
|
207
|
-
let e = await
|
|
208
|
-
|
|
241
|
+
async function re() {
|
|
242
|
+
U = null;
|
|
243
|
+
let e = await te();
|
|
244
|
+
G = F, K("uploading"), q(F);
|
|
209
245
|
let t = { needed: !1 };
|
|
210
|
-
for (;
|
|
246
|
+
for (; F < o.size && !U;) await c(() => ne(e, t), {
|
|
211
247
|
retries: 5,
|
|
212
|
-
...
|
|
248
|
+
...j,
|
|
213
249
|
shouldRetry: (e, n) => {
|
|
214
|
-
if (
|
|
215
|
-
let r =
|
|
250
|
+
if (U || e instanceof f || e instanceof DOMException && e.name === "AbortError") return !1;
|
|
251
|
+
let r = j?.shouldRetry?.(e, n) ?? w(e);
|
|
216
252
|
return r && (t.needed = !0), r;
|
|
217
253
|
}
|
|
218
254
|
});
|
|
219
|
-
return
|
|
255
|
+
return U === "pause" ? (K("paused"), null) : U === "abort" ? (K("aborted"), null) : (K("done"), A && await A.delete(k), {
|
|
220
256
|
url: e,
|
|
221
257
|
size: o.size
|
|
222
258
|
});
|
|
223
259
|
}
|
|
224
|
-
async function
|
|
260
|
+
async function Q() {
|
|
225
261
|
try {
|
|
226
|
-
return await
|
|
262
|
+
return await re();
|
|
227
263
|
} catch (e) {
|
|
228
|
-
if (
|
|
229
|
-
throw
|
|
264
|
+
if (U !== null || e instanceof DOMException && e.name === "AbortError") return K(U === "abort" ? "aborted" : "paused"), null;
|
|
265
|
+
throw K("error"), e;
|
|
230
266
|
} finally {
|
|
231
|
-
|
|
267
|
+
W = null;
|
|
232
268
|
}
|
|
233
269
|
}
|
|
234
|
-
function
|
|
235
|
-
|
|
270
|
+
function $(e) {
|
|
271
|
+
U = e, W?.abort(), W = null;
|
|
236
272
|
}
|
|
237
273
|
return {
|
|
238
|
-
start:
|
|
239
|
-
resume:
|
|
240
|
-
pause: () =>
|
|
274
|
+
start: Q,
|
|
275
|
+
resume: Q,
|
|
276
|
+
pause: () => $("pause"),
|
|
241
277
|
abort: async ({ discard: e = !1 } = {}) => {
|
|
242
|
-
|
|
278
|
+
$("abort"), K("aborted"), e && (I && await b({
|
|
243
279
|
method: "DELETE",
|
|
244
|
-
url:
|
|
245
|
-
headers:
|
|
246
|
-
withCredentials:
|
|
280
|
+
url: I,
|
|
281
|
+
headers: J(I, "DELETE"),
|
|
282
|
+
withCredentials: D,
|
|
247
283
|
register: () => void 0
|
|
248
|
-
}).catch(() => void 0),
|
|
284
|
+
}).catch(() => void 0), A && await A.delete(k));
|
|
249
285
|
},
|
|
250
286
|
get state() {
|
|
251
|
-
return
|
|
287
|
+
return P;
|
|
252
288
|
},
|
|
253
289
|
get offset() {
|
|
254
|
-
return
|
|
290
|
+
return F;
|
|
255
291
|
},
|
|
256
292
|
get url() {
|
|
257
|
-
return
|
|
293
|
+
return I;
|
|
258
294
|
},
|
|
259
|
-
key:
|
|
295
|
+
key: k
|
|
260
296
|
};
|
|
261
297
|
}
|
|
262
298
|
//#endregion
|
|
263
|
-
export { d as DEFAULT_CHUNK_SIZE, u as TUS_VERSION,
|
|
299
|
+
export { d as DEFAULT_CHUNK_SIZE, f as ResumableUploadSupersededError, u as TUS_VERSION, y as createLocalUploadStorage, D as createResumableUpload, v as uploadFingerprint };
|
|
264
300
|
|
|
265
301
|
//# sourceMappingURL=resumable-upload.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport type { CsrfOptions } from \"./csrf\";\nimport { buildApiError, isApiError, isRetriableStatus, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /**\n * Origins besides `endpoint`'s that may receive the `getToken` credential.\n *\n * Since 0.66.0 the bearer token is scoped to the origin of `endpoint`, and\n * the creation response's `Location` no longer decides where it goes. A\n * server that hands the upload to object storage on another host still\n * works — the `PATCH` requests simply carry no `Authorization`, which is\n * what a presigned storage URL expects anyway.\n *\n * List the storage origin here when it does need the API's token.\n */\n trustedOrigins?: readonly string[];\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Send a CSRF token on the creation `POST`, every chunk `PATCH` and the\n * discarding `DELETE` — never on the offset `HEAD`. Off by default; `true`\n * reads the `csrf_token` cookie into `X-CSRF-Token`, as `createApiClient`\n * does.\n *\n * Scoped like the bearer token, to `endpoint`'s origin plus\n * {@link trustedOrigins}: a `Location` pointing at object storage on\n * another host gets neither.\n */\n csrf?: boolean | CsrfOptions;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): ResumableUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n return {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n };\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\n/**\n * The two statuses a chunk retry fixes that the shared policy cannot know about.\n *\n * `409` and `412` are the offset-divergence answers, and they are the entire\n * reason `resync` exists: the next attempt re-reads the server's offset with\n * `HEAD` and writes from there. They are 4xx refusals a replay genuinely fixes,\n * which is the one thing {@link isRetriableStatus} has no way to tell — from\n * outside this protocol they look like any other deliberate rejection.\n */\nconst RESYNCABLE_STATUSES: ReadonlySet<number> = new Set([409, 412]);\n\n/**\n * Whether a chunk failure is worth another attempt.\n *\n * The default used to be `true` for everything, which cost five round trips\n * before surfacing an answer the first one already gave. Two groups matter here\n * and both are specific to the resume protocol:\n *\n * - **`409`/`412` retry**, even though the shared policy rejects 4xx: they mean\n * \"your offset is wrong\", and `resync` is how the next attempt fixes it.\n * - **`404`/`410` do not**, even though a lost resource can look transient.\n * `probe()` turns them into \"O upload expirou no servidor. Comece de novo.\" and\n * recreating the upload only happens in `ensureUpload`, at attach time — never\n * inside the chunk loop. So a retry here re-runs `HEAD` against a resource that\n * is gone, five times, and then reports the same thing with the backoff added\n * on top.\n *\n * Anything with no API shape still retries: a transport failure has no status to\n * judge, and losing a large upload to one dropped connection is the outcome this\n * whole module exists to avoid.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the chunk loop should try again.\n */\nfunction isRetriableChunkFailure(error: unknown): boolean {\n if (!isApiError(error)) return true;\n if (RESYNCABLE_STATUSES.has(error.status)) return true;\n return isRetriableStatus(error.status);\n}\n\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n trustedOrigins,\n withCredentials = false,\n csrf,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n /**\n * Headers every tus request carries, with the credential scoped to the\n * endpoint's origin.\n *\n * The target is a parameter because after creation it is not ours: tus\n * answers `POST {endpoint}` with a `Location` the server chooses, and the\n * spec allows an absolute URL on another host — handing the upload to\n * object storage is the ordinary deployment, not an attack. Before 0.66.0\n * the bearer token followed that header wherever it pointed, along with the\n * file bytes.\n *\n * The CSRF token follows the same scope, and only on the methods that\n * write — which is why the method is a parameter too.\n *\n * @param target - The URL this particular request goes to.\n * @param method - The HTTP method of this request.\n * @returns The headers to send.\n */\n function baseHeaders(target: string, method: string): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) {\n if (isTrustedCredentialTarget(target, endpoint, trustedOrigins)) {\n result.Authorization = `Bearer ${token}`;\n } else {\n reportSuppressedCredential(target, endpoint);\n }\n }\n Object.assign(\n result,\n csrfHeaders({\n method,\n url: target,\n reference: endpoint,\n csrf,\n trustedOrigins,\n headers,\n }),\n );\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(target, \"HEAD\"),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n */\n async function ensureUpload(): Promise<string> {\n const stored = storage ? await storage.get(key) : null;\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(endpoint, \"POST\"),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(target, \"PATCH\"),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * `resync` is armed only when the attempt is actually going to happen. A\n * caller's own `shouldRetry` still wins the decision, and still arms the\n * resync when it says yes — the flag describes what the *next* attempt must\n * do, so setting it for an attempt that never comes describes nothing.\n * {@link isRetriableChunkFailure} is the default, and it is where `409`/`412`\n * earn a retry the shared policy would refuse and `404`/`410` lose one it\n * would have granted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n const again =\n retryOptions?.shouldRetry?.(error, attempt) ??\n isRetriableChunkFailure(error);\n if (again) resync.needed = true;\n return again;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(url, \"DELETE\"),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset() {\n return offset;\n },\n get url() {\n return url;\n },\n key,\n };\n}\n"],"mappings":";;;;;;;AAgBA,IAAa,IAAc,SAGd,IAAqB;AAsKlC,SAAS,EAAW,GAAuB;CACvC,OAAO,EAAc,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC;AACxD;AAQA,SAAS,EAAe,GAA6D;CACjF,IAAI,CAAC,GAAU,OAAO;CACtB,IAAM,IAAQ,OAAO,QAAQ,CAAQ,CAAC,CAAC,KAAK,CAAC,GAAM,OAAW,GAAG,EAAK,GAAG,EAAW,CAAK,GAAG;CAC5F,OAAO,EAAM,SAAS,IAAI,EAAM,KAAK,GAAG,IAAI;AAChD;AAcA,SAAgB,EAAkB,GAAkB,GAA2B;CAC3E,IAAM,IAAQ,GACR,IAAO,OAAO,EAAM,QAAS,WAAW,EAAM,OAAO,QACrD,IAAW,OAAO,EAAM,gBAAiB,WAAW,EAAM,eAAe;CAC/E,OAAO,GAAG,EAAS,GAAG,EAAK,GAAG,EAAK,KAAK,GAAG,EAAK,KAAK,GAAG;AAC5D;AAcA,SAAgB,EAAyB,IAAS,mBAA2C;CACzF,SAAS,IAA0B;EAC/B,IAAI;GACA,OAAO,OAAO,eAAiB,MAAc,OAAO;EACxD,QAAQ;GACJ,OAAO;EACX;CACJ;CAEA,OAAO;EACH,IAAI,GAAK;GACL,IAAM,IAAM,EAAQ,CAAC,EAAE,QAAQ,IAAS,CAAG;GAC3C,IAAI,CAAC,GAAK,OAAO;GACjB,IAAI;IACA,OAAO,KAAK,MAAM,CAAG;GACzB,QAAQ;IACJ,OAAO;GACX;EACJ;EAC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,MAAM;GACN,OAAO;EACX;EACA;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { ownerFingerprint } from \"@/utils/owner-fingerprint\";\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport type { CsrfOptions } from \"./csrf\";\nimport { buildApiError, isApiError, isRetriableStatus, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Thrown by `start()`/`resume()` when the run can no longer go on as the\n * account that started it.\n *\n * - `\"principal\"` — `getPrincipal` names someone else than when the run\n * attached: the next chunk would carry the new account's token to the\n * previous account's upload URL, and the record would be stamped for the\n * wrong owner.\n * - `\"cleared\"` — `createLocalUploadStorage().clear()` ran for this storage's\n * prefix (typically in `onSessionEnd`): writing the record back would undo\n * the clear.\n *\n * Not a pause: the run cannot be resumed as the new account. The state moves\n * to `\"error\"`, and the previous owner's record is left as it was.\n */\nexport class ResumableUploadSupersededError extends Error {\n /** Why the run stopped. */\n readonly reason: \"principal\" | \"cleared\";\n\n /**\n * @param reason - Why the run stopped.\n */\n constructor(reason: \"principal\" | \"cleared\") {\n super(\n reason === \"principal\"\n ? \"O usuário mudou durante o upload resumível.\"\n : \"Os registros de upload resumível foram limpos durante o upload.\",\n );\n this.name = \"ResumableUploadSupersededError\";\n this.reason = reason;\n }\n}\n\n/**\n * How many times `clear()` ran per local-storage prefix, so a run can tell its\n * record was cleared under it — even through another\n * `createLocalUploadStorage()` object with the same prefix, which is what an\n * `onSessionEnd` builds.\n */\nconst clearGenerations = new Map<string, number>();\n\n/**\n * The clear generation reader of each storage built by\n * `createLocalUploadStorage`. A custom storage has none, and its runs only\n * stop on a principal change.\n */\nconst localGenerations = new WeakMap<ResumableUploadStorage, () => number>();\n\n/**\n * Whether a stored value has the shape of a {@link ResumableUploadRecord}.\n *\n * `clear()` matches keys by prefix, and a prefix with no delimiter (`\"app\"`)\n * also matches an app's own keys (`\"appSettings\"`). Changing how keys are\n * built would orphan every record already stored under a custom prefix, so\n * `clear()` removes only values this storage could have written.\n *\n * @param raw - The stored string.\n * @returns Whether it parses as a record.\n */\nfunction isUploadRecord(raw: string | null): boolean {\n if (!raw) return false;\n try {\n const value = JSON.parse(raw) as Partial<ResumableUploadRecord> | null;\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof value.url === \"string\" &&\n typeof value.offset === \"number\" &&\n typeof value.size === \"number\" &&\n typeof value.idempotencyKey === \"string\"\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n /**\n * One-way fingerprint of the principal that created the upload (`\"p:<hex>\"`),\n * `null` for an anonymous one. Absent when the upload ran without\n * {@link ResumableUploadOptions.getPrincipal}, and on records written before\n * 0.78.0.\n */\n owner?: string | null;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/**\n * The default `localStorage` storage, which can also forget every record it\n * holds.\n */\nexport interface LocalUploadStorage extends ResumableUploadStorage {\n /**\n * Forget every record under this storage's prefix — the call for\n * `onSessionEnd`, so the next account on the browser does not find the\n * previous one's upload URLs. Synchronous; a no-op without `localStorage`.\n *\n * Only values shaped like a record are removed, so a prefix without a\n * delimiter does not take the app's own keys with it. A run still going on\n * this prefix stops before its next chunk with\n * {@link ResumableUploadSupersededError} (`\"cleared\"`) instead of writing\n * its record back.\n */\n clear(): void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /**\n * Who is signed in — a user id, or `null`/`undefined` for nobody — read when\n * `start()`/`resume()` attaches to the upload. The same getter the error\n * reporter and `provideBackgroundSyncCredentials` take.\n *\n * The resume record is stamped with a one-way fingerprint of it, and a\n * record stamped by anyone else — another user, nobody, or no stamp at all\n * — is deleted instead of resumed: its upload URL is not probed, and its\n * `Idempotency-Key` is never replayed. Without it, the record is bound to\n * the file alone (endpoint, name, size, type, mtime), so after user A\n * signed out leaving an upload half-done, user B picking an identical file\n * sent `HEAD`/`PATCH` to A's upload URL with B's token, and on refusal\n * replayed A's `Idempotency-Key` with B's token (#479). Pass it on every\n * app with more than one account per browser, and also clear the storage\n * at session end (`createLocalUploadStorage().clear()` in `onSessionEnd`).\n *\n * It is read again before every chunk and every record write: when it\n * names someone else mid-run, the run stops with\n * {@link ResumableUploadSupersededError} (`\"principal\"`) before the new\n * account's token reaches the previous one's upload URL. Without it, call\n * `abort()` on the uploads in progress from `onSessionEnd`.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * Origins besides `endpoint`'s that may receive the `getToken` credential.\n *\n * Since 0.66.0 the bearer token is scoped to the origin of `endpoint`, and\n * the creation response's `Location` no longer decides where it goes. A\n * server that hands the upload to object storage on another host still\n * works — the `PATCH` requests simply carry no `Authorization`, which is\n * what a presigned storage URL expects anyway.\n *\n * List the storage origin here when it does need the API's token.\n */\n trustedOrigins?: readonly string[];\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Send a CSRF token on the creation `POST`, every chunk `PATCH` and the\n * discarding `DELETE` — never on the offset `HEAD`. Off by default; `true`\n * reads the `csrf_token` cookie into `X-CSRF-Token`, as `createApiClient`\n * does.\n *\n * Scoped like the bearer token, to `endpoint`'s origin plus\n * {@link trustedOrigins}: a `Location` pointing at object storage on\n * another host gets neither.\n */\n csrf?: boolean | CsrfOptions;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * `clear()` forgets every record under the prefix. Call it from\n * `onSessionEnd`: a record outlives the session that wrote it, and only\n * completing the upload or `abort({ discard: true })` removes it otherwise.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): LocalUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n const storage: LocalUploadStorage = {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n clear() {\n clearGenerations.set(prefix, (clearGenerations.get(prefix) ?? 0) + 1);\n const store = backend();\n if (!store) return;\n const owned: string[] = [];\n for (let index = 0; index < store.length; index += 1) {\n const name = store.key(index);\n if (name?.startsWith(prefix) && isUploadRecord(store.getItem(name))) {\n owned.push(name);\n }\n }\n for (const name of owned) store.removeItem(name);\n },\n };\n localGenerations.set(storage, () => clearGenerations.get(prefix) ?? 0);\n return storage;\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\n/**\n * The two statuses a chunk retry fixes that the shared policy cannot know about.\n *\n * `409` and `412` are the offset-divergence answers, and they are the entire\n * reason `resync` exists: the next attempt re-reads the server's offset with\n * `HEAD` and writes from there. They are 4xx refusals a replay genuinely fixes,\n * which is the one thing {@link isRetriableStatus} has no way to tell — from\n * outside this protocol they look like any other deliberate rejection.\n */\nconst RESYNCABLE_STATUSES: ReadonlySet<number> = new Set([409, 412]);\n\n/**\n * Whether a chunk failure is worth another attempt.\n *\n * The default used to be `true` for everything, which cost five round trips\n * before surfacing an answer the first one already gave. Two groups matter here\n * and both are specific to the resume protocol:\n *\n * - **`409`/`412` retry**, even though the shared policy rejects 4xx: they mean\n * \"your offset is wrong\", and `resync` is how the next attempt fixes it.\n * - **`404`/`410` do not**, even though a lost resource can look transient.\n * `probe()` turns them into \"O upload expirou no servidor. Comece de novo.\" and\n * recreating the upload only happens in `ensureUpload`, at attach time — never\n * inside the chunk loop. So a retry here re-runs `HEAD` against a resource that\n * is gone, five times, and then reports the same thing with the backoff added\n * on top.\n *\n * Anything with no API shape still retries: a transport failure has no status to\n * judge, and losing a large upload to one dropped connection is the outcome this\n * whole module exists to avoid.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the chunk loop should try again.\n */\nfunction isRetriableChunkFailure(error: unknown): boolean {\n if (!isApiError(error)) return true;\n if (RESYNCABLE_STATUSES.has(error.status)) return true;\n return isRetriableStatus(error.status);\n}\n\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n getPrincipal,\n trustedOrigins,\n withCredentials = false,\n csrf,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let owner: string | null | undefined;\n let attached = false;\n const generationOf = storage ? localGenerations.get(storage) : undefined;\n let generation = generationOf?.() ?? 0;\n\n /**\n * Throw when the run can no longer go on as the account that attached it:\n * the principal changed, or the local storage was cleared under it.\n *\n * @throws {ResumableUploadSupersededError} In either case.\n */\n function assertCurrentOwner(): void {\n if (getPrincipal && ownerFingerprint(\"p\", getPrincipal()) !== owner) {\n throw new ResumableUploadSupersededError(\"principal\");\n }\n if (generationOf && generationOf() !== generation) {\n throw new ResumableUploadSupersededError(\"cleared\");\n }\n }\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n /**\n * Headers every tus request carries, with the credential scoped to the\n * endpoint's origin.\n *\n * The target is a parameter because after creation it is not ours: tus\n * answers `POST {endpoint}` with a `Location` the server chooses, and the\n * spec allows an absolute URL on another host — handing the upload to\n * object storage is the ordinary deployment, not an attack. Before 0.66.0\n * the bearer token followed that header wherever it pointed, along with the\n * file bytes.\n *\n * The CSRF token follows the same scope, and only on the methods that\n * write — which is why the method is a parameter too.\n *\n * @param target - The URL this particular request goes to.\n * @param method - The HTTP method of this request.\n * @returns The headers to send.\n */\n function baseHeaders(target: string, method: string): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) {\n if (isTrustedCredentialTarget(target, endpoint, trustedOrigins)) {\n result.Authorization = `Bearer ${token}`;\n } else {\n reportSuppressedCredential(target, endpoint);\n }\n }\n Object.assign(\n result,\n csrfHeaders({\n method,\n url: target,\n reference: endpoint,\n csrf,\n trustedOrigins,\n headers,\n }),\n );\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n assertCurrentOwner();\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n ...(owner === undefined ? {} : { owner }),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(target, \"HEAD\"),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n *\n * With `getPrincipal`, it is also only trusted when it carries the current\n * principal's fingerprint; anyone else's is deleted, and the creation that\n * follows gets a fresh `Idempotency-Key`. The key this handle kept in memory\n * from an earlier run is reused only while the principal is the same, which\n * is what keeps creation idempotent across `resume()` without storage.\n */\n async function ensureUpload(): Promise<string> {\n const current = getPrincipal ? ownerFingerprint(\"p\", getPrincipal()) : undefined;\n if (attached && current !== owner) idempotencyKey = null;\n owner = current;\n attached = true;\n generation = generationOf?.() ?? 0;\n let stored = storage ? await storage.get(key) : null;\n if (stored && owner !== undefined && stored.owner !== owner) {\n await storage?.delete(key);\n stored = null;\n }\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n ...(owner === undefined ? {} : { owner }),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(endpoint, \"POST\"),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n assertCurrentOwner();\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(target, \"PATCH\"),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * `resync` is armed only when the attempt is actually going to happen. A\n * caller's own `shouldRetry` still wins the decision, and still arms the\n * resync when it says yes — the flag describes what the *next* attempt must\n * do, so setting it for an attempt that never comes describes nothing.\n * {@link isRetriableChunkFailure} is the default, and it is where `409`/`412`\n * earn a retry the shared policy would refuse and `404`/`410` lose one it\n * would have granted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof ResumableUploadSupersededError) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n const again =\n retryOptions?.shouldRetry?.(error, attempt) ??\n isRetriableChunkFailure(error);\n if (again) resync.needed = true;\n return again;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(url, \"DELETE\"),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset()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KAAA,CAAS,GAExB,KAAS,MAAM,EAAQ,OAAO,CAAG;EACzC;EACA,IAAI,QAAQ;GACR,OAAO;EACX;EACA,IAAI,SAAS;GACT,OAAO;EACX;EACA,IAAI,MAAM;GACN,OAAO;EACX;EACA;CACJ;AACJ"}
|
package/dist/http/retry.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");function t(t){return!e.isApiError(t)||e.isRetriableStatus(t.status)}function n(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})})}async function r(e,r={}){let{retries:i=3,initialDelay:a=300,maxDelay:o=1e4,respectRetryAfter:s=!0,shouldRetry:c=t,onRetry:l,signal:u}=r,d=
|
|
1
|
+
const e=require("./errors.cjs");function t(t){return!e.isApiError(t)||e.isRetriableStatus(t.status)}function n(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})})}async function r(e,r={}){let{retries:i=3,initialDelay:a=300,maxDelay:o=1e4,respectRetryAfter:s=!0,shouldRetry:c=t,onRetry:l,signal:u}=r,d=Number.isNaN(i)?3:Math.max(1,Math.floor(i)),f=0;for(;;){if(u?.aborted)throw new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(f+=1,f>=d||!c(e,f))throw e;let t=s&&typeof e?.retryAfter==`number`?e.retryAfter*1e3:null,r=Math.min(t===null?a*2**(f-1):t,o);l?.({attempt:f,delay:r,error:e}),await n(r,u)}}}exports.retry=r;
|
|
2
2
|
//# sourceMappingURL=retry.cjs.map
|
package/dist/http/retry.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.cjs","names":[],"sources":["../../src/http/retry.ts"],"sourcesContent":["import { isApiError, isRetriableStatus } from \"./errors\";\n\nexport interface RetryOptions {\n
|
|
1
|
+
{"version":3,"file":"retry.cjs","names":[],"sources":["../../src/http/retry.ts"],"sourcesContent":["import { isApiError, isRetriableStatus } from \"./errors\";\n\nexport interface RetryOptions {\n /**\n * Total attempts, the first one included. Default: 3 — one call plus two\n * replays.\n *\n * The first attempt always runs: `0`, a negative number or a fraction below\n * one all mean \"a single attempt, no replay\", and that attempt's error is the\n * one the promise rejects with. A fraction is rounded down; `NaN` falls back\n * to the default.\n *\n * The name reads like \"replays after the first\", but every surface that\n * forwards it has always counted totals — {@link createApiClient}'s `retry`,\n * `createResumableUpload` (\"5 attempts\"), and `lazyWithRetry`'s own\n * `retries`. Switching to \"replays\" would add one request to every caller\n * that passes a number, which no change of default can hide, so the count\n * stays a total and only the values that ran nothing were fixed (#486).\n */\n retries?: number;\n /** Initial backoff in ms. Doubles each attempt, capped at `maxDelay`. Default: 300. */\n initialDelay?: number;\n /** Maximum delay between attempts. Default: 10_000. */\n maxDelay?: number;\n /**\n * Honor a `Retry-After` hint on the thrown error (`error.retryAfter`, in\n * seconds — populated by {@link createApiClient} on `429`/`503`). When\n * present it overrides the exponential backoff for that attempt. The value\n * is capped at `maxDelay`. Default: true.\n */\n respectRetryAfter?: boolean;\n /**\n * Return false to stop retrying for a specific error.\n *\n * Default: replay anything that is not a recognisable API error — a\n * transport failure has no status to judge — and, for one that is, only the\n * statuses {@link isRetriableStatus} accepts. A `403` on an admin-only\n * endpoint and a `404` for a deleted record are the server's final answer;\n * repeating them spends the caller's time to show the same error twice.\n */\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n /** Called before each retry with the upcoming delay. */\n onRetry?: (info: { attempt: number; delay: number; error: unknown }) => void;\n /** Cancel pending retries. */\n signal?: AbortSignal;\n}\n\n/**\n * The default {@link RetryOptions.shouldRetry}.\n *\n * Permissive about what it cannot classify and strict about what it can: an\n * error with no API shape may well be a transport failure, while an API error\n * carrying a deliberate refusal will answer the same on every attempt.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the helper should try again.\n */\nfunction defaultShouldRetry(error: unknown): boolean {\n return !isApiError(error) || isRetriableStatus(error.status);\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n },\n { once: true },\n );\n });\n}\n\n/**\n * Run `factory()` with exponential backoff. Each attempt awaits an\n * increasing delay capped at `maxDelay`. Throws the last error if every\n * attempt fails.\n *\n * `retries` is the **total** number of attempts, never fewer than one — see\n * {@link RetryOptions.retries}. `retries: 5` means one call plus four replays.\n *\n * @param factory - Starts one attempt; called again for every replay.\n * @param options - Attempt count, backoff and the retry predicate.\n * @returns What the first successful attempt resolved with.\n * @throws The error of the last attempt, or an `AbortError` once `signal` aborts.\n *\n * @example\n * const data = await retry(() => api.get(\"/flaky\"), { retries: 5 });\n */\nexport async function retry<T>(factory: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const {\n retries = 3,\n initialDelay = 300,\n maxDelay = 10_000,\n respectRetryAfter = true,\n shouldRetry = defaultShouldRetry,\n onRetry,\n signal,\n } = options;\n\n const attempts = Number.isNaN(retries) ? 3 : Math.max(1, Math.floor(retries));\n let attempt = 0;\n\n for (;;) {\n if (signal?.aborted) throw new DOMException(\"Aborted\", \"AbortError\");\n try {\n return await factory();\n } catch (error) {\n attempt += 1;\n if (attempt >= attempts || !shouldRetry(error, attempt)) {\n throw error;\n }\n const retryAfter =\n respectRetryAfter &&\n typeof (error as { retryAfter?: unknown })?.retryAfter === \"number\"\n ? (error as { retryAfter: number }).retryAfter * 1000\n : null;\n const delay =\n retryAfter !== null\n ? Math.min(retryAfter, maxDelay)\n : Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n onRetry?.({ attempt, delay, error });\n await wait(delay, signal);\n }\n }\n}\n"],"mappings":"gCAyDA,SAAS,EAAmB,EAAyB,CACjD,MAAO,CAAC,EAAA,WAAW,CAAK,GAAK,EAAA,kBAAkB,EAAM,MAAM,CAC/D,CAEA,SAAS,EAAK,EAAY,EAAqC,CAC3D,OAAO,IAAI,SAAe,EAAS,IAAW,CAC1C,GAAI,GAAQ,QAAS,CACjB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,MACJ,CACA,IAAM,EAAQ,WAAW,EAAS,CAAE,EACpC,GAAQ,iBACJ,YACM,CACF,aAAa,CAAK,EAClB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,CACpD,EACA,CAAE,KAAM,EAAK,CACjB,CACJ,CAAC,CACL,CAkBA,eAAsB,EAAS,EAA2B,EAAwB,CAAC,EAAe,CAC9F,GAAM,CACF,UAAU,EACV,eAAe,IACf,WAAW,IACX,oBAAoB,GACpB,cAAc,EACd,UACA,UACA,EAEE,EAAW,OAAO,MAAM,CAAO,EAAI,EAAI,KAAK,IAAI,EAAG,KAAK,MAAM,CAAO,CAAC,EACxE,EAAU,EAEd,OAAS,CACL,GAAI,GAAQ,QAAS,MAAM,IAAI,aAAa,UAAW,YAAY,EACnE,GAAI,CACA,OAAO,MAAM,EAAQ,CACzB,OAAS,EAAO,CAEZ,GADA,GAAW,EACP,GAAW,GAAY,CAAC,EAAY,EAAO,CAAO,EAClD,MAAM,EAEV,IAAM,EACF,GACA,OAAQ,GAAoC,YAAe,SACpD,EAAiC,WAAa,IAC/C,KACJ,EAGI,KAAK,IAFX,IAAe,KAEA,EAAe,IAAM,EAAU,GAD/B,EACmC,CAAQ,EAC9D,IAAU,CAAE,UAAS,QAAO,OAAM,CAAC,EACnC,MAAM,EAAK,EAAO,CAAM,CAC5B,CACJ,CACJ"}
|