@voltro/client 0.89.1 → 0.90.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/dist/useUpload.js CHANGED
@@ -1,295 +1,213 @@
1
- import { rememberRpcErrorKind as e, rpcErrorKind as t } from "./rpcErrorKind.js";
2
- import { useFrameworkApi as n } from "./runtimeContext.js";
3
- import { resolveByTag as r } from "./tagWalk.js";
4
- import { runRpcPromise as i } from "./runRpc.js";
5
- import { awaitResolvedApi as a } from "./awaitResolvedApi.js";
6
- import { createUploadProgress as o } from "./uploadProgress.js";
7
- import { useCallback as s, useMemo as c, useRef as l, useState as u } from "react";
8
- import { pluginTag as d } from "@voltro/protocol";
1
+ import { useUploadClient as e } from "./uploadClient.js";
2
+ import { postBytes as t, postChunk as n, putBytesRaw as r, putPart as i } from "./uploadBytes.js";
3
+ import { useCallback as a, useMemo as o, useRef as s } from "react";
4
+ import { pluginTag as c } from "@voltro/protocol";
9
5
  // src/useUpload.ts
10
- var f = "@voltro/plugin-storage", p = (e) => d(f, e), m = (e, t, n, r) => new Promise((i, a) => {
11
- let o = new XMLHttpRequest();
12
- o.open("PUT", e), o.upload.onprogress = (e) => {
13
- e.lengthComputable && n(e.loaded / e.total);
14
- }, o.onload = () => {
15
- if (o.status >= 200 && o.status < 300) {
16
- let e = o.getResponseHeader("ETag") ?? o.getResponseHeader("etag");
17
- e ? i(e) : a(/* @__PURE__ */ Error("multipart part: response carried no ETag (the bucket CORS must expose the ETag header)"));
18
- } else a(Error(`multipart part failed (${o.status}): ${o.responseText || o.statusText}`.trim()));
19
- }, o.onerror = () => a(/* @__PURE__ */ Error("multipart part: network error")), o.onabort = () => a(new DOMException("upload aborted", "AbortError")), r.aborted ? o.abort() : (r.addEventListener("abort", () => o.abort(), { once: !0 }), o.send(t));
20
- }), h = (e, t, n, r, i, a) => new Promise((o, s) => {
21
- let c = new XMLHttpRequest();
22
- c.open("POST", e), c.setRequestHeader("content-type", t), c.upload.onprogress = (e) => {
23
- e.lengthComputable && r(e.loaded / e.total);
24
- }, c.onload = () => {
25
- if (c.status >= 200 && c.status < 300) {
26
- if (!a) return o(null);
27
- try {
28
- o(JSON.parse(c.responseText));
29
- } catch {
30
- s(/* @__PURE__ */ Error("resumable upload: malformed final response"));
31
- }
32
- } else s(Error(`resumable chunk failed (${c.status}): ${c.responseText || c.statusText}`.trim()));
33
- }, c.onerror = () => s(/* @__PURE__ */ Error("resumable chunk: network error")), c.onabort = () => s(new DOMException("upload aborted", "AbortError")), i.aborted ? c.abort() : (i.addEventListener("abort", () => c.abort(), { once: !0 }), c.send(n));
34
- }), g = (e, t, n, r, i) => new Promise((a, o) => {
35
- let s = new XMLHttpRequest();
36
- s.open("PUT", e), s.setRequestHeader("content-type", t), s.upload.onprogress = (e) => {
37
- e.lengthComputable && r(e.loaded / e.total);
38
- }, s.onload = () => {
39
- s.status >= 200 && s.status < 300 ? a() : o(Error(`direct upload failed (${s.status}): ${s.responseText || s.statusText}`.trim()));
40
- }, s.onerror = () => o(/* @__PURE__ */ Error("direct upload: network error")), s.onabort = () => o(new DOMException("upload aborted", "AbortError")), i.aborted ? s.abort() : (i.addEventListener("abort", () => s.abort(), { once: !0 }), s.send(n));
41
- }), _ = (e, t, n, r, i) => new Promise((a, o) => {
42
- let s = new XMLHttpRequest();
43
- s.open("POST", e), s.setRequestHeader("content-type", t), s.upload.onprogress = (e) => {
44
- e.lengthComputable && r(e.loaded / e.total);
45
- }, s.onload = () => {
46
- if (s.status >= 200 && s.status < 300) try {
47
- a(JSON.parse(s.responseText));
48
- } catch {
49
- o(/* @__PURE__ */ Error("storage upload: malformed response"));
50
- }
51
- else o(Error(`storage upload failed (${s.status}): ${s.responseText || s.statusText}`.trim()));
52
- }, s.onerror = () => o(/* @__PURE__ */ Error("storage upload: network error")), s.onabort = () => o(new DOMException("upload aborted", "AbortError")), i.aborted ? s.abort() : (i.addEventListener("abort", () => s.abort(), { once: !0 }), s.send(n));
53
- }), v = (d, f = {}) => {
54
- let v = n(d), { inspectBaseUrl: y } = v, b = l(v);
55
- b.current = v;
56
- let [x, S] = u(0), [C, w] = u("idle"), [T, E] = u(void 0), D = l(null), O = s(() => {
57
- S(0), w("idle"), E(void 0);
58
- }, []), k = s(() => {
59
- D.current?.abort();
60
- }, []), A = s((e) => /^https?:\/\//.test(e) ? e : `${y}${e}`, [y]), j = s(async (t, n, o, s) => {
61
- let { runtime: c, client: l } = await a(b, d, "storage.upload").catch((t) => {
62
- throw e(t, "client");
63
- }), u = Math.max(0, n.retries ?? f.retries ?? 1), v = (t instanceof File, t.type || "application/octet-stream"), y = t instanceof File ? t.name : "blob", x = n.visibility ?? f.visibility, S = n.access ?? f.access, C = n.key ?? f.key, w = n.folder ?? f.folder, T = n.tags ?? f.tags, E = {
64
- ...x ? { visibility: x } : {},
65
- ...S === void 0 ? {} : { access: S },
66
- ...w ? { folder: w } : {},
67
- ...T ? { tags: T } : {},
68
- ...n.alt ? { alt: n.alt } : {},
69
- ...n.caption ? { caption: n.caption } : {}
70
- }, D = (e) => ({
6
+ var l = "@voltro/plugin-storage", u = (e) => c(l, e), d = (c, l = {}) => {
7
+ let d = s(l);
8
+ d.current = l;
9
+ let { execute: f, assertCurrent: p, cancel: m, reset: h, status: g, progress: _, error: v } = e(c), y = a((e) => {
10
+ let t = {
11
+ ...d.current,
12
+ ...Object.fromEntries(Object.entries(e).filter(([, e]) => e != null))
13
+ };
14
+ return {
15
+ ...t,
16
+ ...t.tags === void 0 ? {} : { tags: [...t.tags] },
17
+ ...t.access === void 0 ? {} : { access: t.access.map((e) => ({
18
+ ...e,
19
+ ...e.roles === void 0 ? {} : { roles: [...e.roles] },
20
+ ...e.groups === void 0 ? {} : { groups: [...e.groups] },
21
+ ...e.scopes === void 0 ? {} : { scopes: [...e.scopes] }
22
+ })) },
23
+ mintTag: t.mintTag ?? u("mintUploadTicket"),
24
+ presignMintTag: t.presignMintTag ?? u("mintPresignedUpload"),
25
+ finalizeTag: t.finalizeTag ?? u("finalizeUpload"),
26
+ beginResumableTag: t.beginResumableTag ?? u("beginResumableUpload"),
27
+ multipartBeginTag: t.multipartBeginTag ?? u("beginMultipartUpload"),
28
+ multipartSignTag: t.multipartSignTag ?? u("signMultipartPart"),
29
+ multipartCompleteTag: t.multipartCompleteTag ?? u("completeMultipartUpload"),
30
+ multipartAbortTag: t.multipartAbortTag ?? u("abortMultipartUpload")
31
+ };
32
+ }, []), b = a(async (e, a, o, s) => {
33
+ let c = o.signal, l = o.url;
34
+ o.assertCurrent();
35
+ let d = Math.max(0, a.retries ?? 1), f = (e instanceof File, e.type || "application/octet-stream"), p = e instanceof File ? e.name : "blob", m = a.visibility, h = a.access, g = a.key, _ = a.folder, v = a.tags, y = {
36
+ ...m ? { visibility: m } : {},
37
+ ...h === void 0 ? {} : { access: h },
38
+ ..._ ? { folder: _ } : {},
39
+ ...v ? { tags: v } : {},
40
+ ...a.alt ? { alt: a.alt } : {},
41
+ ...a.caption ? { caption: a.caption } : {}
42
+ }, b = (e) => ({
71
43
  id: e.id,
72
- url: A(e.url),
73
- name: y,
44
+ url: l(e.url),
45
+ name: p,
74
46
  mime: e.contentType,
75
47
  size: e.size,
76
48
  ...e.width === void 0 ? {} : { width: e.width },
77
49
  ...e.height === void 0 ? {} : { height: e.height }
78
- }), O = n.operationId ?? f.operationId, k = async () => {
79
- let e = n.mintTag ?? f.mintTag ?? p("mintUploadTicket"), a = r(l, e), u = await i(c, a({
80
- contentType: v,
81
- ...E,
82
- ...C ? { key: C } : {},
83
- ...O === void 0 ? {} : { operationId: O }
84
- }));
85
- O = u.operationId ?? O;
86
- let d = await _(A(u.uploadUrl), v, t, s, o);
87
- return D(d);
88
- }, j = async () => {
89
- let e = n.presignMintTag ?? f.presignMintTag ?? p("mintPresignedUpload"), a = n.finalizeTag ?? f.finalizeTag ?? p("finalizeUpload"), u;
50
+ }), x = a.operationId, S = async () => {
51
+ let n = a.mintTag ?? u("mintUploadTicket"), r = await o.rpc(n, {
52
+ contentType: f,
53
+ ...y,
54
+ ...g ? { key: g } : {},
55
+ ...x === void 0 ? {} : { operationId: x }
56
+ });
57
+ if (x !== void 0 && r.operationId !== void 0 && r.operationId !== x) throw Error("storage upload: the ticket returned a different operation identity");
58
+ x = r.operationId ?? x;
59
+ let i = await t(l(r.uploadUrl), f, e, s, c);
60
+ return b(i);
61
+ }, C = async () => {
62
+ let t = a.presignMintTag ?? u("mintPresignedUpload"), n = a.finalizeTag ?? u("finalizeUpload"), i;
90
63
  try {
91
- let t = r(l, e);
92
- u = await i(c, t({
93
- contentType: v,
94
- ...E
95
- }));
64
+ i = await o.rpc(t, {
65
+ contentType: f,
66
+ ...y
67
+ });
96
68
  } catch {
97
- return null;
69
+ return o.assertCurrent(), null;
98
70
  }
99
- await g(u.uploadUrl, v, t, s, o);
100
- let d = r(l, a), m = await i(c, d({ finalizeToken: u.finalizeToken }));
101
- return D(m);
102
- }, M = async () => {
103
- let e = n.beginResumableTag ?? f.beginResumableTag ?? p("beginResumableUpload"), a = r(l, e), u = t.size, d = n.chunkSize ?? f.chunkSize, m = await i(c, a({
104
- contentType: v,
105
- size: u,
106
- ...E,
107
- ...d ? { chunkSize: d } : {}
108
- })), g = A(m.uploadUrl), _ = Math.max(1, m.chunkSize), y = Math.max(1, Math.ceil(u / _)), b = Math.max(0, n.retries ?? f.retries ?? 1), x = 0, S = null;
109
- for (let e = 0; e < y; e++) {
110
- let n = e * _, r = Math.min(u, n + _), i = t.slice(n, r), a = e === y - 1, c = r - n, l = 0;
71
+ await r(i.uploadUrl, f, e, s, c);
72
+ let l = await o.rpc(n, { finalizeToken: i.finalizeToken });
73
+ return b(l);
74
+ }, w = async () => {
75
+ let t = a.beginResumableTag ?? u("beginResumableUpload"), r = e.size, i = a.chunkSize, d = await o.rpc(t, {
76
+ contentType: f,
77
+ size: r,
78
+ ...y,
79
+ ...i ? { chunkSize: i } : {}
80
+ }), p = l(d.uploadUrl), m = Math.max(1, d.chunkSize), h = Math.max(1, Math.ceil(r / m)), g = Math.max(0, a.retries ?? 1), _ = 0, v = null;
81
+ for (let t = 0; t < h; t++) {
82
+ let i = t * m, a = Math.min(r, i + m), l = e.slice(i, a), u = t === h - 1, y = a - i, b = 0;
111
83
  for (;;) {
112
- if (o.aborted) throw new DOMException("upload aborted", "AbortError");
84
+ o.assertCurrent();
113
85
  try {
114
- let t = await h(`${g}?${`token=${encodeURIComponent(m.resumableToken)}&index=${e}${a ? "&final=1" : ""}`}`, v, i, (e) => s((x + e * c) / u), o, a);
115
- a && (S = t);
86
+ let e = `token=${encodeURIComponent(d.resumableToken)}&index=${t}${u ? "&final=1" : ""}`, i = await n(`${p}?${e}`, f, l, (e) => s((_ + e * y) / r), c, u);
87
+ u && (v = i);
116
88
  break;
117
89
  } catch (e) {
118
- if (e instanceof DOMException && e.name === "AbortError" || l++ >= b) throw e;
90
+ if (o.assertCurrent(), e instanceof DOMException && e.name === "AbortError" || b++ >= g) throw e;
119
91
  }
120
92
  }
121
- x += c, s(x / u);
93
+ _ += y, s(_ / r);
122
94
  }
123
- if (!S) throw Error("resumable upload produced no final reply");
124
- return D(S);
125
- }, N = async () => {
126
- let e = n.multipartBeginTag ?? f.multipartBeginTag ?? p("beginMultipartUpload"), a = n.multipartSignTag ?? f.multipartSignTag ?? p("signMultipartPart"), u = n.multipartCompleteTag ?? f.multipartCompleteTag ?? p("completeMultipartUpload"), d = n.multipartAbortTag ?? f.multipartAbortTag ?? p("abortMultipartUpload"), h = t.size, g = n.chunkSize ?? f.chunkSize, _;
95
+ if (!v) throw Error("resumable upload produced no final reply");
96
+ return b(v);
97
+ }, T = async () => {
98
+ let t = a.multipartBeginTag ?? u("beginMultipartUpload"), n = a.multipartSignTag ?? u("signMultipartPart"), r = a.multipartCompleteTag ?? u("completeMultipartUpload"), d = a.multipartAbortTag ?? u("abortMultipartUpload"), m = e.size, h = a.chunkSize, g;
127
99
  try {
128
- let t = r(l, e);
129
- _ = await i(c, t({
130
- contentType: v,
131
- size: h,
132
- ...E,
133
- ...g ? { partSize: g } : {}
134
- }));
100
+ g = await o.rpc(t, {
101
+ contentType: f,
102
+ size: m,
103
+ ...y,
104
+ ...h ? { partSize: h } : {}
105
+ });
135
106
  } catch {
136
- return null;
107
+ return o.assertCurrent(), null;
137
108
  }
138
- let b = r(l, a), x = r(l, u), S = r(l, d), C = Math.max(1, _.partSize), w = Math.max(1, Math.ceil(h / C)), T = Math.max(0, n.retries ?? f.retries ?? 1), D = [], O = 0;
109
+ let _ = Math.max(1, g.partSize), v = Math.max(1, Math.ceil(m / _)), b = Math.max(0, a.retries ?? 1), x = [], S = 0;
139
110
  try {
140
- for (let e = 0; e < w; e++) {
141
- let n = e * C, r = Math.min(h, n + C), a = t.slice(n, r), l = e + 1, u = r - n, d = 0;
111
+ for (let t = 0; t < v; t++) {
112
+ let r = t * _, a = Math.min(m, r + _), l = e.slice(r, a), u = t + 1, d = a - r, f = 0;
142
113
  for (;;) {
143
- if (o.aborted) throw new DOMException("upload aborted", "AbortError");
114
+ o.assertCurrent();
144
115
  try {
145
- let { url: e } = await i(c, b({
146
- multipartToken: _.multipartToken,
147
- partNumber: l
148
- })), t = await m(e, a, (e) => s((O + e * u) / h), o);
149
- D.push({
150
- partNumber: l,
116
+ let { url: e } = await o.rpc(n, {
117
+ multipartToken: g.multipartToken,
118
+ partNumber: u
119
+ }), t = await i(e, l, (e) => s((S + e * d) / m), c);
120
+ x.push({
121
+ partNumber: u,
151
122
  etag: t
152
123
  });
153
124
  break;
154
125
  } catch (e) {
155
- if (e instanceof DOMException && e.name === "AbortError" || d++ >= T) throw e;
126
+ if (o.assertCurrent(), e instanceof DOMException && e.name === "AbortError" || f++ >= b) throw e;
156
127
  }
157
128
  }
158
- O += u, s(O / h);
129
+ S += d, s(S / m);
159
130
  }
160
- let e = await i(c, x({
161
- multipartToken: _.multipartToken,
162
- parts: D
163
- }));
131
+ let t = await o.rpc(r, {
132
+ multipartToken: g.multipartToken,
133
+ parts: x
134
+ });
164
135
  return {
165
- id: e.id,
166
- url: A(e.url),
167
- name: y,
168
- mime: v,
169
- size: e.size
136
+ id: t.id,
137
+ url: l(t.url),
138
+ name: p,
139
+ mime: f,
140
+ size: t.size
170
141
  };
171
142
  } catch (e) {
172
143
  try {
173
- await i(c, S({ multipartToken: _.multipartToken }));
144
+ await o.cleanup(d, { multipartToken: g.multipartToken });
174
145
  } catch {}
175
146
  throw e;
176
147
  }
177
148
  };
178
- if ((n.prefer ?? f.prefer) === "multipart") return await N() || await M();
179
- if ((n.prefer ?? f.prefer) === "resumable") return await M();
180
- let P = (n.prefer ?? f.prefer) === "presign", F;
181
- for (let e = 0; e <= u; e++) {
182
- if (o.aborted) throw new DOMException("upload aborted", "AbortError");
149
+ if (a.prefer === "multipart") return await T() || await w();
150
+ if (a.prefer === "resumable") return await w();
151
+ let E = a.prefer === "presign", D;
152
+ for (let e = 0; e <= d; e++) {
153
+ o.assertCurrent();
183
154
  try {
184
- if (P) {
185
- let e = await j();
155
+ if (E) {
156
+ let e = await C();
186
157
  if (e) return e;
187
158
  }
188
- return await k();
159
+ return await S();
189
160
  } catch (t) {
190
- if (t instanceof DOMException && t.name === "AbortError" || (F = t, e === u)) throw t;
161
+ if (o.assertCurrent(), t instanceof DOMException && t.name === "AbortError" || (D = t, e === d)) throw t;
191
162
  }
192
163
  }
193
- throw F;
194
- }, [
195
- d,
196
- A,
197
- f.operationId,
198
- f.mintTag,
199
- f.presignMintTag,
200
- f.finalizeTag,
201
- f.beginResumableTag,
202
- f.multipartBeginTag,
203
- f.multipartSignTag,
204
- f.multipartCompleteTag,
205
- f.multipartAbortTag,
206
- f.chunkSize,
207
- f.prefer,
208
- f.visibility,
209
- f.key,
210
- f.folder,
211
- f.tags,
212
- f.retries
213
- ]), M = s(async (e, n = {}) => {
214
- let r = new AbortController();
215
- D.current = r, w("uploading"), E(void 0), S(0);
216
- try {
217
- let t = await j(e, n, r.signal, S);
218
- return S(1), w("success"), t;
219
- } catch (e) {
220
- throw w("error"), E(e), e instanceof DOMException && e.name === "AbortError" || b.current.errorBus.emit({
221
- source: "action",
222
- tag: n.mintTag ?? f.mintTag ?? p("mintUploadTicket"),
223
- error: e,
224
- kind: t(e, "unknown"),
225
- outcome: t(e, "unknown") === "transport" ? "unknown" : "not-applicable"
226
- }), e;
227
- }
228
- }, [j, f.mintTag]), N = s(async (e, n = {}) => {
229
- if (e.length === 0) return [];
230
- if (e.length > 1 && (n.operationId ?? f.operationId) !== void 0) throw Error("useUpload: one operationId identifies one file; upload files with separate operation identities.");
231
- let r = new AbortController();
232
- D.current = r, w("uploading"), E(void 0), S(0);
233
- let i = Math.max(1, n.concurrency ?? f.concurrency ?? 3), a = Array(e.length), s = o(e.length), c = 0, l = async () => {
234
- for (;;) {
235
- let t = c++;
236
- if (t >= e.length) return;
237
- a[t] = await j(e[t], n, r.signal, (n) => {
238
- S(s(t, n, e.length));
239
- }), S(s(t, 1, e.length));
240
- }
241
- };
242
- try {
243
- return await Promise.all(Array.from({ length: Math.min(i, e.length) }, () => l())), S(1), w("success"), a;
244
- } catch (e) {
245
- throw r.abort(), w("error"), E(e), e instanceof DOMException && e.name === "AbortError" || b.current.errorBus.emit({
246
- source: "action",
247
- tag: n.mintTag ?? f.mintTag ?? p("mintUploadTicket"),
248
- error: e,
249
- kind: t(e, "unknown"),
250
- outcome: t(e, "unknown") === "transport" ? "unknown" : "not-applicable"
251
- }), e;
252
- }
253
- }, [
254
- j,
255
- f.concurrency,
256
- f.mintTag,
257
- f.operationId
258
- ]), P = s((e, t = {}) => {
259
- e.preventDefault();
164
+ throw D;
165
+ }, []), x = a(async (e, t = {}) => (p(), (await f([e], y(t), b))[0]), [
166
+ p,
167
+ f,
168
+ y,
169
+ b
170
+ ]), S = a(async (e, t = {}) => (p(), f([...e], y(t), b)), [
171
+ p,
172
+ f,
173
+ y,
174
+ b
175
+ ]), C = a(async (e, t = {}) => {
176
+ p(), e.preventDefault();
260
177
  let n = e.dataTransfer ? Array.from(e.dataTransfer.files) : [];
261
- return n.length ? N(n, t) : Promise.resolve([]);
262
- }, [N]), F = s((e, t = {}) => {
178
+ return n.length ? S(n, t) : Promise.resolve([]);
179
+ }, [p, S]), w = a(async (e, t = {}) => {
180
+ p();
263
181
  let n = e.clipboardData ? Array.from(e.clipboardData.files) : [];
264
- return n.length ? N(n, t) : Promise.resolve([]);
265
- }, [N]), I = c(() => ({
182
+ return n.length ? S(n, t) : Promise.resolve([]);
183
+ }, [p, S]), T = o(() => ({
266
184
  onDragOver: (e) => e.preventDefault(),
267
185
  onDrop: (e) => {
268
- P(e);
186
+ C(e).catch(() => void 0);
269
187
  }
270
- }), [P]);
271
- return c(() => ({
272
- upload: M,
273
- uploadMany: N,
274
- progress: x,
275
- status: C,
276
- error: T,
277
- cancel: k,
278
- reset: O,
279
- onDrop: P,
280
- onPaste: F,
281
- dropzoneProps: I
188
+ }), [C]);
189
+ return o(() => ({
190
+ upload: x,
191
+ uploadMany: S,
192
+ progress: _,
193
+ status: g,
194
+ error: v,
195
+ cancel: m,
196
+ reset: h,
197
+ onDrop: C,
198
+ onPaste: w,
199
+ dropzoneProps: T
282
200
  }), [
283
- M,
284
- N,
285
201
  x,
202
+ S,
203
+ _,
204
+ g,
205
+ v,
206
+ m,
207
+ h,
286
208
  C,
287
- T,
288
- k,
289
- O,
290
- P,
291
- F,
292
- I
209
+ w,
210
+ T
293
211
  ]);
294
212
  };
295
- export { v as useUpload };
213
+ export { d as useUpload };