@gradio/client 2.3.1 → 2.5.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +4 -2
  3. package/dist/__vite-browser-external-Cgmn0awE.js +7 -0
  4. package/dist/browser.js +1949 -1963
  5. package/dist/client.d.ts +5 -0
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/constants.d.ts +4 -0
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/helpers/api_info.d.ts.map +1 -1
  10. package/dist/helpers/data.d.ts.map +1 -1
  11. package/dist/helpers/init_helpers.d.ts +11 -2
  12. package/dist/helpers/init_helpers.d.ts.map +1 -1
  13. package/dist/index.cjs +2584 -0
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2471 -2466
  17. package/dist/index.min.js +1962 -0
  18. package/dist/types.d.ts +29 -0
  19. package/dist/types.d.ts.map +1 -1
  20. package/dist/utils/duplicate.d.ts.map +1 -1
  21. package/dist/utils/predict.d.ts.map +1 -1
  22. package/dist/utils/run_history.d.ts +64 -0
  23. package/dist/utils/run_history.d.ts.map +1 -0
  24. package/dist/utils/stream.d.ts.map +1 -1
  25. package/dist/utils/submit.d.ts.map +1 -1
  26. package/package.json +11 -4
  27. package/scripts/verify_dist.mjs +46 -0
  28. package/src/client.ts +54 -5
  29. package/src/constants.ts +10 -0
  30. package/src/helpers/api_info.ts +46 -19
  31. package/src/helpers/data.ts +8 -3
  32. package/src/helpers/init_helpers.ts +54 -7
  33. package/src/index.ts +12 -0
  34. package/src/test/api_info.test.ts +77 -12
  35. package/src/test/data.test.ts +26 -3
  36. package/src/test/init.test.ts +21 -3
  37. package/src/test/init_helpers.test.ts +67 -1
  38. package/src/test/refresh.test.ts +31 -0
  39. package/src/test/run_history.test.ts +345 -0
  40. package/src/test/submit.test.ts +1 -3
  41. package/src/types.ts +29 -0
  42. package/src/utils/duplicate.ts +2 -0
  43. package/src/utils/predict.ts +14 -1
  44. package/src/utils/run_history.ts +520 -0
  45. package/src/utils/stream.ts +17 -4
  46. package/src/utils/submit.ts +105 -12
  47. package/vite.config.ts +20 -4
  48. package/dist/__vite-browser-external-DYxpcVy9.js +0 -4
package/dist/browser.js CHANGED
@@ -1,1971 +1,1957 @@
1
- const Ke = "host", xe = "queue/data", Ve = "queue/join", ye = "upload", Ye = "login", K = "config", Qe = "info", Xe = "runtime", et = "sleeptime", tt = "heartbeat", st = "component_server", nt = "reset", it = "cancel", ot = "app_id", De = "This application is currently busy. Please try again. ", N = "Connection errored out. ", L = "Could not resolve app config. ", rt = "Could not get space status. ", at = "Could not get API info. ", ue = "Space metadata could not be loaded. ", ct = "Invalid URL. A full URL path is required.", ut = "Not authorized to access this space. ", Le = "Invalid credentials. Could not login. ", lt = "Login credentials are required to access this space.", pt = "File system access is only available in Node.js environments", Ne = "Root URL not found in client config", dt = "Error uploading file";
2
- async function be(e, s, t) {
3
- try {
4
- return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, {
5
- headers: {
6
- Authorization: `Bearer ${s}`,
7
- ...t ? { Cookie: t } : {}
8
- }
9
- })).json()).token || !1;
10
- } catch {
11
- return !1;
12
- }
1
+ //#region \0rolldown/runtime.js
2
+ var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => {
3
+ if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, {
4
+ get: ((e) => i[e]).bind(null, d),
5
+ enumerable: !(s = n(i, d)) || s.enumerable
6
+ });
7
+ return e;
8
+ }, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", {
9
+ value: n,
10
+ enumerable: !0
11
+ }) : a, n)), l = "host", u = "queue/data", d = "queue/join", f = "upload", p = "login", m = "config", h = "info", g = "runtime", ee = "sleeptime", _ = "heartbeat", te = "component_server", ne = "reset", re = "cancel", v = "app_id", ie = "This application is currently busy. Please try again. ", y = "Connection errored out. ", b = "Could not resolve app config. ", x = "Could not get space status. ", S = "Could not get API info. ", C = "Space metadata could not be loaded. ", w = "Invalid URL. A full URL path is required.", T = "Not authorized to access this space. ", E = "Invalid credentials. Could not login. ", ae = "Login credentials are required to access this space.", D = "Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.", oe = (e, t) => `Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`, se = "No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ", ce = "This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.", le = "File system access is only available in Node.js environments", O = "Root URL not found in client config", ue = "Error uploading file";
12
+ //#endregion
13
+ //#region src/helpers/init_helpers.ts
14
+ async function de(e, t, n) {
15
+ try {
16
+ return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: {
17
+ Authorization: `Bearer ${t}`,
18
+ ...n ? { Cookie: n } : {}
19
+ } })).json()).token || !1;
20
+ } catch {
21
+ return !1;
22
+ }
13
23
  }
14
- function ht(e) {
15
- let s = {};
16
- return e.forEach(({ api_name: t, id: n }) => {
17
- t && (s[t] = n);
18
- }), s;
19
- }
20
- async function ft(e) {
21
- const s = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {};
22
- if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") {
23
- if (window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") {
24
- let t = ae(
25
- e,
26
- this.deep_link ? K + "?deep_link=" + this.deep_link : K
27
- );
28
- const n = await this.fetch(t, {
29
- headers: s,
30
- credentials: this.options.credentials ?? "same-origin"
31
- }), o = await ve(n, !!this.options.auth);
32
- o.root = e || o.root, window.gradio_config = {
33
- ...o,
34
- current_page: window.gradio_config.current_page
35
- };
36
- }
37
- return { ...window.gradio_config };
38
- } else if (e) {
39
- let t = ae(
40
- e,
41
- this.deep_link ? K + "?deep_link=" + this.deep_link : K
42
- );
43
- const n = await this.fetch(t, {
44
- headers: s,
45
- credentials: this.options.credentials ?? "same-origin"
46
- }), o = await ve(n, !!this.options.auth);
47
- return o.root || (o.root = e), o;
48
- }
49
- throw new Error(L);
50
- }
51
- async function ve(e, s) {
52
- if (e?.status === 401 && !s) {
53
- const n = (await e.json())?.detail?.auth_message;
54
- throw new Error(n || lt);
55
- } else if (e?.status === 401 && s)
56
- throw new Error(Le);
57
- if (e?.status === 200) {
58
- let t = await e.json();
59
- return t.dependencies?.forEach((n, o) => {
60
- n.id === void 0 && (n.id = o);
61
- }), t;
62
- } else if (e?.status === 401)
63
- throw new Error(ut);
64
- throw new Error(L);
65
- }
66
- async function _t() {
67
- const { http_protocol: e, host: s } = await pe(
68
- this.app_reference,
69
- this.options.token
70
- );
71
- try {
72
- if (this.options.auth) {
73
- const t = await Ce(
74
- e,
75
- s,
76
- this.options.auth,
77
- this.fetch,
78
- this.options.token,
79
- this.options.credentials
80
- );
81
- t && this.set_cookies(t);
82
- }
83
- } catch (t) {
84
- throw Error(t.message);
85
- }
86
- }
87
- async function Ce(e, s, t, n, o, r) {
88
- const i = new FormData();
89
- i.append("username", t?.[0]), i.append("password", t?.[1]);
90
- let a = {};
91
- o && (a.Authorization = `Bearer ${o}`);
92
- const u = await n(`${e}//${s}/${Ye}`, {
93
- headers: a,
94
- method: "POST",
95
- body: i,
96
- credentials: r ?? "same-origin"
97
- });
98
- if (u.status === 200)
99
- return u.headers.get("set-cookie");
100
- throw u.status === 401 ? new Error(Le) : new Error(ue);
101
- }
102
- function re(e) {
103
- if (e.startsWith("http")) {
104
- const { protocol: s, host: t, pathname: n } = new URL(e);
105
- return {
106
- ws_protocol: s === "https:" ? "wss" : "ws",
107
- http_protocol: s,
108
- host: t + (n !== "/" ? n : "")
109
- };
110
- }
111
- return {
112
- ws_protocol: "wss",
113
- http_protocol: "https:",
114
- host: new URL(e).host
115
- };
116
- }
117
- const Pe = (e) => {
118
- let s = [];
119
- return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((n) => {
120
- const [o, r] = n.split(";")[0].split("=");
121
- o && r && s.push(`${o.trim()}=${r.trim()}`);
122
- }), s;
123
- }, le = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, gt = /.*hf\.space\/{0,1}.*$/;
124
- async function pe(e, s) {
125
- const t = {};
126
- s && (t.Authorization = `Bearer ${s}`);
127
- const n = e.trim().replace(/\/$/, "");
128
- if (le.test(n))
129
- try {
130
- const r = (await (await fetch(
131
- `https://huggingface.co/api/spaces/${n}/${Ke}`,
132
- { headers: t }
133
- )).json()).host;
134
- return {
135
- space_id: e,
136
- ...re(r)
137
- };
138
- } catch {
139
- throw new Error(ue);
140
- }
141
- if (gt.test(n)) {
142
- const { ws_protocol: o, http_protocol: r, host: i } = re(n);
143
- return {
144
- space_id: i.split("/")[0].replace(".hf.space", ""),
145
- ws_protocol: o,
146
- http_protocol: r,
147
- host: i
148
- };
149
- }
150
- return {
151
- space_id: !1,
152
- ...re(n)
153
- };
154
- }
155
- const ae = (...e) => {
156
- try {
157
- return e.reduce((s, t) => (s = s.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, s + "/").toString()));
158
- } catch {
159
- throw new Error(ct);
160
- }
24
+ function k(e) {
25
+ e.hf_token && !e.token && (e.token = e.hf_token, console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client."));
26
+ }
27
+ function fe(e) {
28
+ let t = {};
29
+ return e.forEach(({ api_name: e, id: n }) => {
30
+ e && (t[e] = n);
31
+ }), t;
32
+ }
33
+ function A(e, t) {
34
+ let n = new URL(e, t), r = new URL(t);
35
+ return n.hostname === r.hostname ? (n.protocol = r.protocol, n.host = r.host, n.toString().replace(/\/$/, "")) : e;
36
+ }
37
+ async function j(e, t = !0) {
38
+ let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {};
39
+ if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") {
40
+ if (t && window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") {
41
+ let t = me(e, this.deep_link ? m + "?deep_link=" + this.deep_link : m), r = await M(await this.fetch(t, {
42
+ headers: n,
43
+ credentials: this.options.credentials ?? "same-origin"
44
+ }), !!this.options.auth);
45
+ r.root = e || r.root, window.gradio_config = {
46
+ ...r,
47
+ current_page: window.gradio_config.current_page
48
+ };
49
+ }
50
+ let r = { ...window.gradio_config };
51
+ return r.root = A(r.root, location.href), r;
52
+ } else if (e) {
53
+ let t = me(e, this.deep_link ? m + "?deep_link=" + this.deep_link : m), r = await M(await this.fetch(t, {
54
+ headers: n,
55
+ credentials: this.options.credentials ?? "same-origin"
56
+ }), !!this.options.auth);
57
+ return r.root ||= e, r;
58
+ }
59
+ throw Error(b);
60
+ }
61
+ async function M(e, t) {
62
+ if (e?.status === 401 && !t) {
63
+ let t = null;
64
+ try {
65
+ t = await e.json();
66
+ } catch {
67
+ throw Error(D);
68
+ }
69
+ let n = t?.detail?.auth_message;
70
+ throw Error(n || "Login credentials are required to access this space.");
71
+ } else if (e?.status === 401 && t) throw Error(E);
72
+ if (e?.status === 200) {
73
+ let t = await e.json();
74
+ return t.dependencies?.forEach((e, t) => {
75
+ e.id === void 0 && (e.id = t);
76
+ }), t;
77
+ } else if (e?.status === 401) throw Error(T);
78
+ throw Error(`${b}(received status ${e?.status} when fetching the app config)`);
79
+ }
80
+ async function N() {
81
+ let { http_protocol: e, host: t } = await R(this.app_reference, this.options.token);
82
+ try {
83
+ if (this.options.auth) {
84
+ let n = await P(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials);
85
+ n && this.set_cookies(n);
86
+ }
87
+ } catch (e) {
88
+ throw Error(e.message);
89
+ }
90
+ }
91
+ async function P(e, t, n, r, i, a) {
92
+ let o = new FormData();
93
+ o.append("username", n?.[0]), o.append("password", n?.[1]);
94
+ let s = {};
95
+ i && (s.Authorization = `Bearer ${i}`);
96
+ let c = await r(`${e}//${t}/${p}`, {
97
+ headers: s,
98
+ method: "POST",
99
+ body: o,
100
+ credentials: a ?? "same-origin"
101
+ });
102
+ if (c.status === 200) return c.headers.get("set-cookie");
103
+ throw c.status === 401 ? Error(E) : Error(C);
104
+ }
105
+ function F(e) {
106
+ if (e.startsWith("http")) {
107
+ let { protocol: t, host: n, pathname: r } = new URL(e);
108
+ return {
109
+ ws_protocol: t === "https:" ? "wss" : "ws",
110
+ http_protocol: t,
111
+ host: n + (r === "/" ? "" : r)
112
+ };
113
+ }
114
+ return {
115
+ ws_protocol: "wss",
116
+ http_protocol: "https:",
117
+ host: new URL(e).host
118
+ };
119
+ }
120
+ var I = (e) => {
121
+ let t = [];
122
+ return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e) => {
123
+ let [n, r] = e.split(";")[0].split("=");
124
+ n && r && t.push(`${n.trim()}=${r.trim()}`);
125
+ }), t;
126
+ }, L = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, pe = /.*hf\.space\/{0,1}.*$/;
127
+ async function R(e, t) {
128
+ let n = {};
129
+ t && (n.Authorization = `Bearer ${t}`);
130
+ let r = e.trim().replace(/\/$/, "");
131
+ if (L.test(r)) {
132
+ let e;
133
+ try {
134
+ e = await fetch(`https://huggingface.co/api/spaces/${r}/${l}`, { headers: n });
135
+ } catch {
136
+ throw Error(C);
137
+ }
138
+ if (e.status === 401 || e.status === 404) throw Error(oe(r, e.status));
139
+ let t;
140
+ try {
141
+ t = (await e.json()).host;
142
+ } catch {
143
+ throw Error(C);
144
+ }
145
+ if (!t) throw Error(C);
146
+ return {
147
+ space_id: r,
148
+ ...F(t)
149
+ };
150
+ }
151
+ if (pe.test(r)) {
152
+ let { ws_protocol: e, http_protocol: t, host: n } = F(r);
153
+ return {
154
+ space_id: n.split("/")[0].replace(".hf.space", ""),
155
+ ws_protocol: e,
156
+ http_protocol: t,
157
+ host: n
158
+ };
159
+ }
160
+ return {
161
+ space_id: !1,
162
+ ...F(r)
163
+ };
164
+ }
165
+ var me = (...e) => {
166
+ try {
167
+ return e.reduce((e, t) => (e = e.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, e + "/").toString()));
168
+ } catch {
169
+ throw Error(w);
170
+ }
161
171
  };
162
- function mt(e, s, t) {
163
- const n = {
164
- named_endpoints: {},
165
- unnamed_endpoints: {}
166
- };
167
- return Object.keys(e).forEach((o) => {
168
- (o === "named_endpoints" || o === "unnamed_endpoints") && (n[o] = {}, Object.entries(e[o]).forEach(
169
- ([r, { parameters: i, returns: a }]) => {
170
- const u = s.dependencies.find(
171
- (c) => c.api_name === r || c.api_name === r.replace("/", "")
172
- )?.id || t[r.replace("/", "")] || -1, l = u !== -1 ? s.dependencies.find((c) => c.id == u)?.types : { generator: !1, cancel: !1 };
173
- if (u !== -1 && s.dependencies.find((c) => c.id == u)?.inputs?.length !== i.length) {
174
- const c = s.dependencies.find((g) => g.id == u).inputs.map(
175
- (g) => s.components.find((w) => w.id === g)?.type
176
- );
177
- try {
178
- c.forEach((g, w) => {
179
- if (g === "state") {
180
- const C = {
181
- component: "state",
182
- example: null,
183
- parameter_default: null,
184
- parameter_has_default: !0,
185
- parameter_name: null,
186
- hidden: !0
187
- };
188
- i.splice(w, 0, C);
189
- }
190
- });
191
- } catch (g) {
192
- console.error(g);
193
- }
194
- }
195
- const p = (c, g, w, C) => ({
196
- ...c,
197
- description: yt(c?.type, w),
198
- type: wt(c?.type, g, w, C) || ""
199
- });
200
- n[o][r] = {
201
- parameters: i.map(
202
- (c) => p(c, c?.component, c?.serializer, "parameter")
203
- ),
204
- returns: a.map(
205
- (c) => p(c, c?.component, c?.serializer, "return")
206
- ),
207
- type: l
208
- };
209
- }
210
- ));
211
- }), n;
212
- }
213
- function wt(e, s, t, n) {
214
- if (s === "Api") return e.type;
215
- switch (e?.type) {
216
- case "string":
217
- return "string";
218
- case "boolean":
219
- return "boolean";
220
- case "number":
221
- return "number";
222
- }
223
- if (t === "JSONSerializable" || t === "StringSerializable")
224
- return "any";
225
- if (t === "ListStringSerializable")
226
- return "string[]";
227
- if (s === "Image")
228
- return n === "parameter" ? "Blob | File | Buffer" : "string";
229
- if (t === "FileSerializable")
230
- return e?.type === "array" ? n === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : n === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";
231
- if (t === "GallerySerializable")
232
- return n === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]";
233
- }
234
- function yt(e, s) {
235
- return s === "GallerySerializable" ? "array of [file, label] tuples" : s === "ListStringSerializable" ? "array of strings" : s === "FileSerializable" ? "array of files or single file" : e?.description;
236
- }
237
- function Ee(e, s) {
238
- switch (e.msg) {
239
- case "send_data":
240
- return { type: "data" };
241
- case "send_hash":
242
- return { type: "hash" };
243
- case "queue_full":
244
- return {
245
- type: "update",
246
- status: {
247
- queue: !0,
248
- message: De,
249
- stage: "error",
250
- code: e.code,
251
- success: e.success
252
- }
253
- };
254
- case "heartbeat":
255
- return {
256
- type: "heartbeat"
257
- };
258
- case "unexpected_error":
259
- return {
260
- type: "unexpected_error",
261
- status: {
262
- queue: !0,
263
- message: e.message,
264
- session_not_found: e.session_not_found,
265
- stage: "error",
266
- success: !1
267
- }
268
- };
269
- case "broken_connection":
270
- return {
271
- type: "broken_connection",
272
- status: {
273
- queue: !0,
274
- message: e.message,
275
- stage: "error",
276
- success: !1
277
- }
278
- };
279
- case "estimation":
280
- return {
281
- type: "update",
282
- status: {
283
- queue: !0,
284
- stage: s || "pending",
285
- code: e.code,
286
- size: e.queue_size,
287
- position: e.rank,
288
- eta: e.rank_eta,
289
- success: e.success
290
- }
291
- };
292
- case "progress":
293
- return {
294
- type: "update",
295
- status: {
296
- queue: !0,
297
- stage: "pending",
298
- code: e.code,
299
- progress_data: e.progress_data,
300
- success: e.success
301
- }
302
- };
303
- case "log":
304
- return { type: "log", data: e };
305
- case "process_generating":
306
- return {
307
- type: "generating",
308
- status: {
309
- queue: !0,
310
- message: e.success ? null : e.output.error,
311
- stage: e.success ? "generating" : "error",
312
- code: e.code,
313
- progress_data: e.progress_data,
314
- eta: e.average_duration,
315
- changed_state_ids: e.success ? e.output.changed_state_ids : void 0
316
- },
317
- data: e.success ? e.output : null
318
- };
319
- case "process_streaming":
320
- return {
321
- type: "streaming",
322
- status: {
323
- queue: !0,
324
- message: e.output.error,
325
- stage: "streaming",
326
- time_limit: e.time_limit,
327
- code: e.code,
328
- progress_data: e.progress_data,
329
- changed_state_ids: e.output.changed_state_ids,
330
- eta: e.eta
331
- },
332
- data: e.output
333
- };
334
- case "process_completed":
335
- return "error" in e.output ? {
336
- type: "update",
337
- status: {
338
- queue: !0,
339
- title: e.output.title ?? "Error",
340
- message: e.output.error ?? "An error occurred",
341
- visible: e.output.visible,
342
- duration: e.output.duration,
343
- stage: "error",
344
- code: e.code,
345
- success: e.success
346
- }
347
- } : {
348
- type: "complete",
349
- status: {
350
- queue: !0,
351
- message: e.success ? void 0 : e.output.error,
352
- stage: e.success ? "complete" : "error",
353
- code: e.code,
354
- progress_data: e.progress_data,
355
- changed_state_ids: e.success ? e.output.changed_state_ids : void 0,
356
- used_cache: e.used_cache,
357
- cache_duration: e.cache_duration,
358
- avg_time: e.avg_time
359
- },
360
- data: e.success ? e.output : null
361
- };
362
- case "process_starts":
363
- return {
364
- type: "update",
365
- status: {
366
- queue: !0,
367
- stage: "pending",
368
- code: e.code,
369
- size: e.rank,
370
- position: 0,
371
- success: e.success,
372
- eta: e.eta
373
- },
374
- original_msg: "process_starts"
375
- };
376
- }
377
- return { type: "none", status: { stage: "error", queue: !0 } };
378
- }
379
- const bt = (e = [], s) => {
380
- const t = s ? s.parameters : [];
381
- if (Array.isArray(e))
382
- return s && t.length > 0 && e.length > t.length && console.warn("Too many arguments provided for the endpoint."), e;
383
- const n = [], o = Object.keys(e);
384
- return t.forEach((r, i) => {
385
- if (e.hasOwnProperty(r.parameter_name))
386
- n[i] = e[r.parameter_name];
387
- else if (r.parameter_has_default)
388
- n[i] = r.parameter_default;
389
- else
390
- throw new Error(
391
- `No value provided for required parameter: ${r.parameter_name}`
392
- );
393
- }), o.forEach((r) => {
394
- if (!t.some((i) => i.parameter_name === r))
395
- throw new Error(
396
- `Parameter \`${r}\` is not a valid keyword argument. Please refer to the API for usage.`
397
- );
398
- }), n.forEach((r, i) => {
399
- if (r === void 0 && !t[i].parameter_has_default)
400
- throw new Error(
401
- `No value provided for required parameter: ${t[i].parameter_name}`
402
- );
403
- }), n;
172
+ function he(e, t, n) {
173
+ let r = {
174
+ named_endpoints: {},
175
+ unnamed_endpoints: {}
176
+ };
177
+ return Object.keys(e).forEach((i) => {
178
+ (i === "named_endpoints" || i === "unnamed_endpoints") && (r[i] = {}, Object.entries(e[i]).forEach(([e, a]) => {
179
+ let o = a?.parameters ?? [], s = a?.returns ?? [], c = t.dependencies.find((t) => t.api_name === e || t.api_name === e.replace("/", ""))?.id || n[e.replace("/", "")] || -1, l = c === -1 ? void 0 : t.dependencies.find((e) => e.id == c), u = c === -1 ? {
180
+ generator: !1,
181
+ cancel: !1
182
+ } : l?.types;
183
+ if (l && Array.isArray(l.inputs) && l.inputs.length !== o.length) {
184
+ let e = l.inputs.map((e) => t.components.find((t) => t.id === e)?.type);
185
+ try {
186
+ e.forEach((e, t) => {
187
+ e === "state" && o.splice(t, 0, {
188
+ component: "state",
189
+ example: null,
190
+ parameter_default: null,
191
+ parameter_has_default: !0,
192
+ parameter_name: null,
193
+ hidden: !0
194
+ });
195
+ });
196
+ } catch (e) {
197
+ console.error(e);
198
+ }
199
+ }
200
+ let d = (e, t, n, r) => ({
201
+ ...e,
202
+ description: _e(e?.type, n),
203
+ type: ge(e?.type, t, n, r) || ""
204
+ });
205
+ r[i][e] = {
206
+ parameters: o.map((e) => d(e, e?.component, e?.serializer, "parameter")),
207
+ returns: s.map((e) => d(e, e?.component, e?.serializer, "return")),
208
+ type: u,
209
+ ...a?.oauth_token ? { oauth_token: a.oauth_token } : {}
210
+ };
211
+ }));
212
+ }), r;
213
+ }
214
+ function ge(e, t, n, r) {
215
+ if (t === "Api") return e.type;
216
+ switch (e?.type) {
217
+ case "string": return "string";
218
+ case "boolean": return "boolean";
219
+ case "number": return "number";
220
+ }
221
+ if (n === "JSONSerializable" || n === "StringSerializable") return "any";
222
+ if (n === "ListStringSerializable") return "string[]";
223
+ if (t === "Image") return r === "parameter" ? "Blob | File | Buffer" : "string";
224
+ if (n === "FileSerializable") return e?.type === "array" ? r === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : r === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";
225
+ if (n === "GallerySerializable") return r === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]";
226
+ }
227
+ function _e(e, t) {
228
+ return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e?.description;
229
+ }
230
+ function ve(e, t) {
231
+ switch (e.msg) {
232
+ case "send_data": return { type: "data" };
233
+ case "send_hash": return { type: "hash" };
234
+ case "queue_full": return {
235
+ type: "update",
236
+ status: {
237
+ queue: !0,
238
+ message: ie,
239
+ stage: "error",
240
+ code: e.code,
241
+ success: e.success
242
+ }
243
+ };
244
+ case "heartbeat": return { type: "heartbeat" };
245
+ case "unexpected_error": return {
246
+ type: "unexpected_error",
247
+ status: {
248
+ queue: !0,
249
+ message: e.message,
250
+ session_not_found: e.session_not_found,
251
+ stage: "error",
252
+ success: !1
253
+ }
254
+ };
255
+ case "broken_connection": return {
256
+ type: "broken_connection",
257
+ status: {
258
+ queue: !0,
259
+ message: e.message,
260
+ stage: "error",
261
+ success: !1
262
+ }
263
+ };
264
+ case "estimation": return {
265
+ type: "update",
266
+ status: {
267
+ queue: !0,
268
+ stage: t || "pending",
269
+ code: e.code,
270
+ size: e.queue_size,
271
+ position: e.rank,
272
+ eta: e.rank_eta,
273
+ success: e.success
274
+ }
275
+ };
276
+ case "progress": return {
277
+ type: "update",
278
+ status: {
279
+ queue: !0,
280
+ stage: "pending",
281
+ code: e.code,
282
+ progress_data: e.progress_data,
283
+ success: e.success
284
+ }
285
+ };
286
+ case "log": return {
287
+ type: "log",
288
+ data: e
289
+ };
290
+ case "process_generating": return {
291
+ type: "generating",
292
+ status: {
293
+ queue: !0,
294
+ message: e.success ? null : e.output.error,
295
+ stage: e.success ? "generating" : "error",
296
+ code: e.code,
297
+ progress_data: e.progress_data,
298
+ eta: e.average_duration,
299
+ changed_state_ids: e.success ? e.output.changed_state_ids : void 0
300
+ },
301
+ data: e.success ? e.output : null
302
+ };
303
+ case "process_streaming": return {
304
+ type: "streaming",
305
+ status: {
306
+ queue: !0,
307
+ message: e.output.error,
308
+ stage: "streaming",
309
+ time_limit: e.time_limit,
310
+ code: e.code,
311
+ progress_data: e.progress_data,
312
+ changed_state_ids: e.output.changed_state_ids,
313
+ eta: e.eta
314
+ },
315
+ data: e.output
316
+ };
317
+ case "process_completed": return "error" in e.output ? {
318
+ type: "update",
319
+ status: {
320
+ queue: !0,
321
+ title: e.output.title ?? "Error",
322
+ message: e.output.error ?? "An error occurred",
323
+ visible: e.output.visible,
324
+ duration: e.output.duration,
325
+ stage: "error",
326
+ code: e.code,
327
+ success: e.success
328
+ }
329
+ } : {
330
+ type: "complete",
331
+ status: {
332
+ queue: !0,
333
+ message: e.success ? void 0 : e.output.error,
334
+ stage: e.success ? "complete" : "error",
335
+ code: e.code,
336
+ progress_data: e.progress_data,
337
+ changed_state_ids: e.success ? e.output.changed_state_ids : void 0,
338
+ used_cache: e.used_cache,
339
+ cache_duration: e.cache_duration,
340
+ avg_time: e.avg_time
341
+ },
342
+ data: e.success ? e.output : null
343
+ };
344
+ case "process_starts": return {
345
+ type: "update",
346
+ status: {
347
+ queue: !0,
348
+ stage: "pending",
349
+ code: e.code,
350
+ size: e.rank,
351
+ position: 0,
352
+ success: e.success,
353
+ eta: e.eta
354
+ },
355
+ original_msg: "process_starts"
356
+ };
357
+ }
358
+ return {
359
+ type: "none",
360
+ status: {
361
+ stage: "error",
362
+ queue: !0
363
+ }
364
+ };
365
+ }
366
+ var ye = (e = [], t) => {
367
+ let n = t ? t.parameters : [];
368
+ if (Array.isArray(e)) return t && n.length > 0 && e.length > n.length && console.warn("Too many arguments provided for the endpoint."), e;
369
+ let r = [], i = Object.keys(e);
370
+ return n.forEach((t, n) => {
371
+ if (e.hasOwnProperty(t.parameter_name)) r[n] = e[t.parameter_name];
372
+ else if (t.parameter_has_default) r[n] = t.parameter_default;
373
+ else throw Error(`No value provided for required parameter: ${t.parameter_name}`);
374
+ }), i.forEach((e) => {
375
+ if (!n.some((t) => t.parameter_name === e)) throw Error(`Parameter \`${e}\` is not a valid keyword argument. Please refer to the API for usage.`);
376
+ }), r.forEach((e, t) => {
377
+ if (e === void 0 && !n[t].parameter_has_default) throw Error(`No value provided for required parameter: ${n[t].parameter_name}`);
378
+ }), r;
404
379
  };
405
- async function vt() {
406
- if (this.api_info) return this.api_info;
407
- const { token: e } = this.options, { config: s } = this, t = {};
408
- if (e && (t.Authorization = `Bearer ${e}`), !!s)
409
- try {
410
- let n, o;
411
- if (typeof window < "u" && window.gradio_api_info)
412
- o = window.gradio_api_info;
413
- else {
414
- const r = ae(s.root, this.api_prefix, Qe);
415
- if (n = await this.fetch(r, {
416
- headers: t,
417
- credentials: this.options.credentials ?? "same-origin"
418
- }), !n.ok)
419
- throw new Error(N);
420
- o = await n.json();
421
- }
422
- return "api" in o && (o = o.api), o.named_endpoints["/predict"] && !o.unnamed_endpoints[0] && (o.unnamed_endpoints[0] = o.named_endpoints["/predict"]), mt(o, s, this.api_map);
423
- } catch (n) {
424
- throw new Error("Could not get API info. " + n.message);
425
- }
426
- }
427
- async function Et(e, s, t) {
428
- const n = {};
429
- this?.options?.token && (n.Authorization = `Bearer ${this.options.token}`);
430
- const o = 1e3, r = [];
431
- let i;
432
- for (let a = 0; a < s.length; a += o) {
433
- const u = s.slice(a, a + o), l = new FormData();
434
- u.forEach((c) => {
435
- l.append("files", c);
436
- });
437
- try {
438
- const c = t ? `${e}${this.api_prefix}/${ye}?upload_id=${t}` : `${e}${this.api_prefix}/${ye}`;
439
- i = await this.fetch(c, {
440
- method: "POST",
441
- body: l,
442
- headers: n,
443
- credentials: this.options.credentials ?? "same-origin"
444
- });
445
- } catch (c) {
446
- throw new Error(N + c.message);
447
- }
448
- if (!i.ok) {
449
- const c = await i.text();
450
- return { error: `HTTP ${i.status}: ${c}` };
451
- }
452
- const p = await i.json();
453
- p && r.push(...p);
454
- }
455
- return { files: r };
456
- }
457
- const St = {
458
- radix: 1e3,
459
- unit: ["b", "kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"]
460
- }, $t = {
461
- radix: 1024,
462
- unit: ["b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"]
463
- }, kt = {
464
- radix: 1024,
465
- unit: ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"]
466
- }, Se = {
467
- si: St,
468
- iec: $t,
469
- jedec: kt
380
+ //#endregion
381
+ //#region src/utils/view_api.ts
382
+ async function be() {
383
+ if (this.api_info) return this.api_info;
384
+ let { token: e } = this.options, { config: t } = this, n = {};
385
+ if (e && (n.Authorization = `Bearer ${e}`), t) try {
386
+ let e, r;
387
+ if (typeof window < "u" && window.gradio_api_info) r = window.gradio_api_info;
388
+ else {
389
+ let i = me(t.root, this.api_prefix, h);
390
+ if (e = await this.fetch(i, {
391
+ headers: n,
392
+ credentials: this.options.credentials ?? "same-origin"
393
+ }), !e.ok) throw Error(y);
394
+ r = await e.json();
395
+ }
396
+ return "api" in r && (r = r.api), r.named_endpoints["/predict"] && !r.unnamed_endpoints[0] && (r.unnamed_endpoints[0] = r.named_endpoints["/predict"]), he(r, t, this.api_map);
397
+ } catch (e) {
398
+ throw Error("Could not get API info. " + e.message);
399
+ }
400
+ }
401
+ //#endregion
402
+ //#region src/utils/upload_files.ts
403
+ async function z(e, t, n) {
404
+ let r = {};
405
+ this?.options?.token && (r.Authorization = `Bearer ${this.options.token}`);
406
+ let i = 1e3, a = [], o;
407
+ for (let s = 0; s < t.length; s += i) {
408
+ let c = t.slice(s, s + i), l = new FormData();
409
+ c.forEach((e) => {
410
+ l.append("files", e);
411
+ });
412
+ try {
413
+ let t = n ? `${e}${this.api_prefix}/${f}?upload_id=${n}` : `${e}${this.api_prefix}/${f}`;
414
+ o = await this.fetch(t, {
415
+ method: "POST",
416
+ body: l,
417
+ headers: r,
418
+ credentials: this.options.credentials ?? "same-origin"
419
+ });
420
+ } catch (e) {
421
+ throw Error(y + e.message);
422
+ }
423
+ if (!o.ok) {
424
+ let e = await o.text();
425
+ return { error: `HTTP ${o.status}: ${e}` };
426
+ }
427
+ let u = await o.json();
428
+ u && a.push(...u);
429
+ }
430
+ return { files: a };
431
+ }
432
+ var B = {
433
+ si: {
434
+ radix: 1e3,
435
+ unit: [
436
+ "b",
437
+ "kb",
438
+ "Mb",
439
+ "Gb",
440
+ "Tb",
441
+ "Pb",
442
+ "Eb",
443
+ "Zb",
444
+ "Yb"
445
+ ]
446
+ },
447
+ iec: {
448
+ radix: 1024,
449
+ unit: [
450
+ "b",
451
+ "Kib",
452
+ "Mib",
453
+ "Gib",
454
+ "Tib",
455
+ "Pib",
456
+ "Eib",
457
+ "Zib",
458
+ "Yib"
459
+ ]
460
+ },
461
+ jedec: {
462
+ radix: 1024,
463
+ unit: [
464
+ "b",
465
+ "Kb",
466
+ "Mb",
467
+ "Gb",
468
+ "Tb",
469
+ "Pb",
470
+ "Eb",
471
+ "Zb",
472
+ "Yb"
473
+ ]
474
+ }
470
475
  };
471
- function Rt(e, s = 1, t = "jedec") {
472
- e = Math.abs(e);
473
- const { radix: n, unit: o } = Se[t] || Se.jedec;
474
- let r = 0;
475
- for (; e >= n; )
476
- e /= n, ++r;
477
- return `${e.toFixed(s)} ${o[r]}`;
478
- }
479
- async function Ot(e, s, t, n) {
480
- let o = (Array.isArray(e) ? e : [e]).map(
481
- (i) => i.blob
482
- );
483
- const r = o.filter(
484
- (i) => i.size > (n ?? 1 / 0)
485
- );
486
- if (r.length)
487
- throw new Error(
488
- `File(s) exceed the maximum allowed size of ${Rt(n || 1 / 0)}: ${r.map((i) => `"${i.name}"`).join(", ")}`
489
- );
490
- return await Promise.all(
491
- await this.upload_files(s, o, t).then(
492
- async (i) => {
493
- if (i.error)
494
- throw new Error(i.error);
495
- return i.files ? i.files.map((a, u) => new Q({
496
- ...e[u],
497
- path: a,
498
- url: `${s}${this.api_prefix}/file=${a}`
499
- })) : [];
500
- }
501
- )
502
- );
503
- }
504
- async function ns(e, s) {
505
- return e.map(
506
- (t) => new Q({
507
- path: t.name,
508
- orig_name: t.name,
509
- blob: t,
510
- size: t.size,
511
- mime_type: t.type,
512
- is_stream: s
513
- })
514
- );
515
- }
516
- class Q {
517
- path;
518
- url;
519
- orig_name;
520
- size;
521
- blob;
522
- is_stream;
523
- mime_type;
524
- alt_text;
525
- b64;
526
- meta = { _type: "gradio.FileData" };
527
- constructor({
528
- path: s,
529
- url: t,
530
- orig_name: n,
531
- size: o,
532
- blob: r,
533
- is_stream: i,
534
- mime_type: a,
535
- alt_text: u,
536
- b64: l
537
- }) {
538
- this.path = s, this.url = t, this.orig_name = n, this.size = o, this.blob = t ? void 0 : r, this.is_stream = i, this.mime_type = a, this.alt_text = u, this.b64 = l;
539
- }
540
- }
541
- class Ie {
542
- type;
543
- command;
544
- meta;
545
- fileData;
546
- constructor(s, t) {
547
- this.type = "command", this.command = s, this.meta = t;
548
- }
549
- }
550
- const At = typeof process < "u" && process.versions && process.versions.node;
551
- function $e(e, s, t) {
552
- for (; t.length > 1; ) {
553
- const o = t.shift();
554
- if (typeof o == "string" || typeof o == "number")
555
- e = e[o];
556
- else
557
- throw new Error("Invalid key type");
558
- }
559
- const n = t.shift();
560
- if (typeof n == "string" || typeof n == "number")
561
- e[n] = s;
562
- else
563
- throw new Error("Invalid key type");
564
- }
565
- async function ce(e, s = void 0, t = [], n = !1, o = void 0) {
566
- if (Array.isArray(e)) {
567
- let r = [];
568
- return await Promise.all(
569
- e.map(async (i, a) => {
570
- let u = t.slice();
571
- u.push(String(a));
572
- const l = await ce(
573
- e[a],
574
- n ? o?.parameters[a]?.component || void 0 : s,
575
- u,
576
- !1,
577
- o
578
- );
579
- r = r.concat(l);
580
- })
581
- ), r;
582
- } else {
583
- if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob)
584
- return [
585
- {
586
- path: t,
587
- blob: new Blob([e]),
588
- type: s
589
- }
590
- ];
591
- if (typeof e == "object" && e !== null) {
592
- let r = [];
593
- for (const i of Object.keys(e)) {
594
- const a = [...t, i], u = e[i];
595
- r = r.concat(
596
- await ce(
597
- u,
598
- void 0,
599
- a,
600
- !1,
601
- o
602
- )
603
- );
604
- }
605
- return r;
606
- }
607
- }
608
- return [];
609
- }
610
- function Tt(e, s) {
611
- let t = s?.dependencies?.find((n) => n.id == e)?.queue;
612
- return t != null ? !t : !s.enable_queue;
613
- }
614
- function xt(e, s) {
615
- return new Promise((t, n) => {
616
- const o = new MessageChannel();
617
- o.port1.onmessage = (({ data: r }) => {
618
- o.port1.close(), t(r);
619
- }), window.parent.postMessage(e, s, [o.port2]);
620
- });
621
- }
622
- function is(e) {
623
- if (typeof e == "string") {
624
- if (e.startsWith("http://") || e.startsWith("https://"))
625
- return {
626
- path: e,
627
- url: e,
628
- orig_name: e.split("/").pop() ?? "unknown",
629
- meta: { _type: "gradio.FileData" }
630
- };
631
- if (At)
632
- return new Ie("upload_file", {
633
- path: e,
634
- name: e,
635
- orig_path: e
636
- });
637
- } else {
638
- if (typeof File < "u" && e instanceof File)
639
- return new Blob([e]);
640
- if (e instanceof Buffer)
641
- return new Blob([e]);
642
- if (e instanceof Blob)
643
- return e;
644
- }
645
- throw new Error(
646
- "Invalid input: must be a URL, File, Blob, or Buffer object."
647
- );
648
- }
649
- function V(e, s, t, n, o = !1) {
650
- if (n === "input" && !o)
651
- throw new Error("Invalid code path. Cannot skip state inputs for input.");
652
- if (n === "output" && o)
653
- return e;
654
- let r = [], i = 0;
655
- const a = n === "input" ? s.inputs : s.outputs;
656
- for (let u = 0; u < a.length; u++) {
657
- const l = a[u];
658
- if (t.find((c) => c.id === l)?.type === "state") {
659
- if (o)
660
- if (e.length === a.length) {
661
- const c = e[i];
662
- r.push(c), i++;
663
- } else
664
- r.push(null);
665
- else {
666
- i++;
667
- continue;
668
- }
669
- continue;
670
- } else {
671
- const c = e[i];
672
- r.push(c), i++;
673
- }
674
- }
675
- return r;
676
- }
677
- async function Dt(e, s, t) {
678
- const n = this;
679
- await Lt(n, s);
680
- const o = await ce(
681
- s,
682
- void 0,
683
- [],
684
- !0,
685
- t
686
- );
687
- return (await Promise.all(
688
- o.map(async ({ path: i, blob: a, type: u }) => {
689
- if (!a) return { path: i, type: u };
690
- const l = await n.upload_files(e, [a]), p = l.files && l.files[0];
691
- return {
692
- path: i,
693
- file_url: p,
694
- type: u,
695
- name: typeof File < "u" && a instanceof File ? a?.name : void 0
696
- };
697
- })
698
- )).forEach(({ path: i, file_url: a, type: u, name: l }) => {
699
- if (u === "Gallery")
700
- $e(s, a, i);
701
- else if (a) {
702
- const p = new Q({ path: a, orig_name: l });
703
- $e(s, p, i);
704
- }
705
- }), s;
706
- }
707
- async function Lt(e, s) {
708
- if (!(e.config?.root || e.config?.root_url))
709
- throw new Error(Ne);
710
- await Ue(e, s);
711
- }
712
- async function Ue(e, s, t = []) {
713
- for (const n in s)
714
- s[n] instanceof Ie ? await Nt(e, s, n) : typeof s[n] == "object" && s[n] !== null && await Ue(e, s[n], [...t, n]);
715
- }
716
- async function Nt(e, s, t) {
717
- let n = s[t];
718
- const o = e.config?.root || e.config?.root_url;
719
- if (!o)
720
- throw new Error(Ne);
721
- try {
722
- let r, i;
723
- if (typeof process < "u" && process.versions && process.versions.node) {
724
- const p = await import("./__vite-browser-external-DYxpcVy9.js");
725
- i = (await import("./__vite-browser-external-DYxpcVy9.js")).resolve(process.cwd(), n.meta.path), r = await p.readFile(i);
726
- } else
727
- throw new Error(pt);
728
- const a = new Blob([r], {
729
- type: "application/octet-stream"
730
- }), u = await e.upload_files(o, [a]), l = u.files && u.files[0];
731
- if (l) {
732
- const p = new Q({
733
- path: l,
734
- orig_name: n.meta.name || ""
735
- });
736
- s[t] = p;
737
- }
738
- } catch (r) {
739
- console.error(dt, r);
740
- }
741
- }
742
- async function Ct(e, s, t) {
743
- const n = { "Content-Type": "application/json" };
744
- this.options.token && (n.Authorization = `Bearer ${this.options.token}`);
745
- try {
746
- var o = await this.fetch(e, {
747
- method: "POST",
748
- body: JSON.stringify(s),
749
- headers: { ...n, ...t },
750
- credentials: this.options.credentials ?? "same-origin"
751
- });
752
- } catch {
753
- return [{ error: N }, 500];
754
- }
755
- let r, i;
756
- try {
757
- r = await o.json(), i = o.status;
758
- } catch (a) {
759
- r = { error: `Could not parse server response: ${a}` }, i = 500;
760
- }
761
- return [r, i];
762
- }
763
- async function Pt(e, s = {}) {
764
- let t = !1, n = !1;
765
- if (!this.config)
766
- throw new Error("Could not resolve app config");
767
- if (typeof e == "number")
768
- this.config.dependencies.find((i) => i.id == e);
769
- else {
770
- const i = e.replace(/^\//, "");
771
- this.config.dependencies.find(
772
- (a) => a.id == this.api_map[i]
773
- );
774
- }
775
- const o = this.submit(e, s, null, null, !0);
776
- let r;
777
- for await (const i of o) {
778
- if (i.type === "data" && (t = !0, r = i, n))
779
- return r;
780
- if (i.type === "status") {
781
- if (i.stage === "error")
782
- throw i;
783
- if (i.stage === "complete" && (n = !0, t))
784
- return r;
785
- }
786
- }
787
- return r;
788
- }
789
- async function F(e, s, t) {
790
- let n = s === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, o, r;
791
- try {
792
- if (o = await fetch(n), r = o.status, r !== 200)
793
- throw new Error();
794
- o = await o.json();
795
- } catch {
796
- t({
797
- status: "error",
798
- load_status: "error",
799
- message: rt,
800
- detail: "NOT_FOUND"
801
- });
802
- return;
803
- }
804
- if (!o || r !== 200) return;
805
- const {
806
- runtime: { stage: i },
807
- id: a
808
- } = o;
809
- switch (i) {
810
- case "STOPPED":
811
- case "SLEEPING":
812
- t({
813
- status: "sleeping",
814
- load_status: "pending",
815
- message: "Space is asleep. Waking it up...",
816
- detail: i
817
- }), setTimeout(() => {
818
- F(e, s, t);
819
- }, 1e3);
820
- break;
821
- case "PAUSED":
822
- t({
823
- status: "paused",
824
- load_status: "error",
825
- message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
826
- detail: i,
827
- discussions_enabled: await ke(a)
828
- });
829
- break;
830
- case "RUNNING":
831
- case "RUNNING_BUILDING":
832
- t({
833
- status: "running",
834
- load_status: "complete",
835
- message: "Space is running.",
836
- detail: i
837
- });
838
- break;
839
- case "BUILDING":
840
- t({
841
- status: "building",
842
- load_status: "pending",
843
- message: "Space is building...",
844
- detail: i
845
- }), setTimeout(() => {
846
- F(e, s, t);
847
- }, 1e3);
848
- break;
849
- case "APP_STARTING":
850
- t({
851
- status: "starting",
852
- load_status: "pending",
853
- message: "Space is starting...",
854
- detail: i
855
- }), setTimeout(() => {
856
- F(e, s, t);
857
- }, 1e3);
858
- break;
859
- default:
860
- t({
861
- status: "space_error",
862
- load_status: "error",
863
- message: "This space is experiencing an issue.",
864
- detail: i,
865
- discussions_enabled: await ke(a)
866
- });
867
- break;
868
- }
869
- }
870
- const je = async (e, s) => {
871
- let t = 0;
872
- const n = 12, o = 5e3;
873
- return new Promise((r) => {
874
- F(
875
- e,
876
- le.test(e) ? "space_name" : "subdomain",
877
- (i) => {
878
- s(i), i.status === "running" || i.status === "error" || i.status === "paused" || i.status === "space_error" ? r() : (i.status === "sleeping" || i.status === "building") && (t < n ? (t++, setTimeout(() => {
879
- je(e, s).then(r);
880
- }, o)) : r());
881
- }
882
- );
883
- });
884
- }, It = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
885
- async function ke(e) {
886
- try {
887
- const s = await fetch(
888
- `https://huggingface.co/api/spaces/${e}/discussions`,
889
- {
890
- method: "HEAD"
891
- }
892
- ), t = s.headers.get("x-error-message");
893
- return !(!s.ok || t && It.test(t));
894
- } catch {
895
- return !1;
896
- }
897
- }
898
- async function Ut(e, s) {
899
- const t = {};
900
- s && (t.Authorization = `Bearer ${s}`);
901
- try {
902
- const n = await fetch(
903
- `https://huggingface.co/api/spaces/${e}/${Xe}`,
904
- { headers: t }
905
- );
906
- if (n.status !== 200)
907
- throw new Error("Space hardware could not be obtained.");
908
- const { hardware: o } = await n.json();
909
- return o.current;
910
- } catch (n) {
911
- throw new Error(n.message);
912
- }
913
- }
914
- async function jt(e, s, t) {
915
- const n = {};
916
- t && (n.Authorization = `Bearer ${t}`);
917
- const o = {
918
- seconds: s
919
- };
920
- try {
921
- const r = await fetch(
922
- `https://huggingface.co/api/spaces/${e}/${et}`,
923
- {
924
- method: "POST",
925
- headers: { "Content-Type": "application/json", ...n },
926
- body: JSON.stringify(o)
927
- }
928
- );
929
- if (r.status !== 200)
930
- throw new Error(
931
- "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."
932
- );
933
- return await r.json();
934
- } catch (r) {
935
- throw new Error(r.message);
936
- }
937
- }
938
- const Re = [
939
- "cpu-basic",
940
- "cpu-upgrade",
941
- "cpu-xl",
942
- "t4-small",
943
- "t4-medium",
944
- "a10g-small",
945
- "a10g-large",
946
- "a10g-largex2",
947
- "a10g-largex4",
948
- "a100-large",
949
- "zero-a10g",
950
- "h100",
951
- "h100x8"
476
+ function V(e, t = 1, n = "jedec") {
477
+ e = Math.abs(e);
478
+ let { radix: r, unit: i } = B[n] || B.jedec, a = 0;
479
+ for (; e >= r;) e /= r, ++a;
480
+ return `${e.toFixed(t)} ${i[a]}`;
481
+ }
482
+ //#endregion
483
+ //#region src/upload.ts
484
+ async function H(e, t, n, r) {
485
+ let i = (Array.isArray(e) ? e : [e]).map((e) => e.blob), a = i.filter((e) => e.size > (r ?? Infinity));
486
+ if (a.length) throw Error(`File(s) exceed the maximum allowed size of ${V(r || Infinity)}: ${a.map((e) => `"${e.name}"`).join(", ")}`);
487
+ return await Promise.all(await this.upload_files(t, i, n).then(async (n) => {
488
+ if (n.error) throw Error(n.error);
489
+ return n.files ? n.files.map((n, r) => new U({
490
+ ...e[r],
491
+ path: n,
492
+ url: `${t}${this.api_prefix}/file=${n}`
493
+ })) : [];
494
+ }));
495
+ }
496
+ async function xe(e, t) {
497
+ return e.map((e) => new U({
498
+ path: e.name,
499
+ orig_name: e.name,
500
+ blob: e,
501
+ size: e.size,
502
+ mime_type: e.type,
503
+ is_stream: t
504
+ }));
505
+ }
506
+ var U = class {
507
+ path;
508
+ url;
509
+ orig_name;
510
+ size;
511
+ blob;
512
+ is_stream;
513
+ mime_type;
514
+ alt_text;
515
+ b64;
516
+ meta = { _type: "gradio.FileData" };
517
+ constructor({ path: e, url: t, orig_name: n, size: r, blob: i, is_stream: a, mime_type: o, alt_text: s, b64: c }) {
518
+ this.path = e, this.url = t, this.orig_name = n, this.size = r, this.blob = t ? void 0 : i, this.is_stream = a, this.mime_type = o, this.alt_text = s, this.b64 = c;
519
+ }
520
+ }, W = class {
521
+ type;
522
+ command;
523
+ meta;
524
+ fileData;
525
+ constructor(e, t) {
526
+ this.type = "command", this.command = e, this.meta = t;
527
+ }
528
+ }, Se = typeof process < "u" && process.versions && process.versions.node;
529
+ function Ce(e, t, n) {
530
+ for (; n.length > 1;) {
531
+ let t = n.shift();
532
+ if (typeof t == "string" || typeof t == "number") e = e[t];
533
+ else throw Error("Invalid key type");
534
+ }
535
+ let r = n.shift();
536
+ if (typeof r == "string" || typeof r == "number") e[r] = t;
537
+ else throw Error("Invalid key type");
538
+ }
539
+ async function we(e, t = void 0, n = [], r = !1, i = void 0) {
540
+ if (Array.isArray(e)) {
541
+ let a = [];
542
+ return await Promise.all(e.map(async (o, s) => {
543
+ let c = n.slice();
544
+ c.push(String(s));
545
+ let l = await we(e[s], r ? i?.parameters[s]?.component || void 0 : t, c, !1, i);
546
+ a = a.concat(l);
547
+ })), a;
548
+ } else if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob) return [{
549
+ path: n,
550
+ blob: e instanceof Blob ? e : new Blob([e]),
551
+ type: t
552
+ }];
553
+ else if (typeof e == "object" && e) {
554
+ let t = [];
555
+ for (let r of Object.keys(e)) {
556
+ let a = [...n, r], o = e[r];
557
+ t = t.concat(await we(o, void 0, a, !1, i));
558
+ }
559
+ return t;
560
+ }
561
+ return [];
562
+ }
563
+ function Te(e, t) {
564
+ let n = t?.dependencies?.find((t) => t.id == e)?.queue;
565
+ return n == null ? !t.enable_queue : !n;
566
+ }
567
+ function Ee(e, t) {
568
+ return new Promise((n, r) => {
569
+ let i = new MessageChannel();
570
+ i.port1.onmessage = (({ data: e }) => {
571
+ i.port1.close(), n(e);
572
+ }), window.parent.postMessage(e, t, [i.port2]);
573
+ });
574
+ }
575
+ function De(e) {
576
+ if (typeof e == "string") {
577
+ if (e.startsWith("http://") || e.startsWith("https://")) return {
578
+ path: e,
579
+ url: e,
580
+ orig_name: e.split("/").pop() ?? "unknown",
581
+ meta: { _type: "gradio.FileData" }
582
+ };
583
+ if (Se) return new W("upload_file", {
584
+ path: e,
585
+ name: e,
586
+ orig_path: e
587
+ });
588
+ } else if (typeof File < "u" && e instanceof File) return e;
589
+ else if (globalThis.Buffer && e instanceof globalThis.Buffer) return new Blob([e]);
590
+ else if (e instanceof Blob) return e;
591
+ throw Error("Invalid input: must be a URL, File, Blob, or Buffer object.");
592
+ }
593
+ function G(e, t, n, r, i = !1) {
594
+ if (r === "input" && !i) throw Error("Invalid code path. Cannot skip state inputs for input.");
595
+ if (r === "output" && i) return e;
596
+ let a = [], o = 0, s = r === "input" ? t.inputs : t.outputs;
597
+ for (let t = 0; t < s.length; t++) {
598
+ let r = s[t];
599
+ if (n.find((e) => e.id === r)?.type === "state") {
600
+ if (i) if (e.length === s.length) {
601
+ let t = e[o];
602
+ a.push(t), o++;
603
+ } else a.push(null);
604
+ else {
605
+ o++;
606
+ continue;
607
+ }
608
+ continue;
609
+ } else {
610
+ let t = e[o];
611
+ a.push(t), o++;
612
+ }
613
+ }
614
+ return a;
615
+ }
616
+ //#endregion
617
+ //#region src/utils/handle_blob.ts
618
+ async function Oe(e, t, n) {
619
+ let r = this;
620
+ await ke(r, t);
621
+ let i = await we(t, void 0, [], !0, n);
622
+ return (await Promise.all(i.map(async ({ path: t, blob: n, type: i }) => {
623
+ if (!n) return {
624
+ path: t,
625
+ type: i
626
+ };
627
+ let a = await r.upload_files(e, [n]);
628
+ return {
629
+ path: t,
630
+ file_url: a.files && a.files[0],
631
+ type: i,
632
+ name: typeof File < "u" && n instanceof File ? n?.name : void 0
633
+ };
634
+ }))).forEach(({ path: e, file_url: n, type: r, name: i }) => {
635
+ r === "Gallery" ? Ce(t, n, e) : n && Ce(t, new U({
636
+ path: n,
637
+ orig_name: i
638
+ }), e);
639
+ }), t;
640
+ }
641
+ async function ke(e, t) {
642
+ if (!(e.config?.root || e.config?.root_url)) throw Error(O);
643
+ await Ae(e, t);
644
+ }
645
+ async function Ae(e, t, n = []) {
646
+ for (let r in t) t[r] instanceof W ? await je(e, t, r) : typeof t[r] == "object" && t[r] !== null && await Ae(e, t[r], [...n, r]);
647
+ }
648
+ async function je(e, t, n) {
649
+ let r = t[n], i = e.config?.root || e.config?.root_url;
650
+ if (!i) throw Error(O);
651
+ try {
652
+ let a, o;
653
+ if (typeof process < "u" && process.versions && process.versions.node) {
654
+ let e = await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1));
655
+ o = (await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1))).resolve(process.cwd(), r.meta.path), a = await e.readFile(o);
656
+ } else throw Error(le);
657
+ let s = new Blob([a], { type: "application/octet-stream" }), l = await e.upload_files(i, [s]), u = l.files && l.files[0];
658
+ u && (t[n] = new U({
659
+ path: u,
660
+ orig_name: r.meta.name || ""
661
+ }));
662
+ } catch (e) {
663
+ console.error(ue, e);
664
+ }
665
+ }
666
+ //#endregion
667
+ //#region src/utils/post_data.ts
668
+ async function Me(e, t, n) {
669
+ let r = { "Content-Type": "application/json" };
670
+ this.options.token && (r.Authorization = `Bearer ${this.options.token}`);
671
+ try {
672
+ var i = await this.fetch(e, {
673
+ method: "POST",
674
+ body: JSON.stringify(t),
675
+ headers: {
676
+ ...r,
677
+ ...n
678
+ },
679
+ credentials: this.options.credentials ?? "same-origin"
680
+ });
681
+ } catch {
682
+ return [{ error: y }, 500];
683
+ }
684
+ let a, o;
685
+ try {
686
+ a = await i.json(), o = i.status;
687
+ } catch (e) {
688
+ a = { error: `Could not parse server response: ${e}` }, o = 500;
689
+ }
690
+ return [a, o];
691
+ }
692
+ //#endregion
693
+ //#region src/utils/predict.ts
694
+ async function Ne(e, t = {}) {
695
+ let n = !1, r = !1;
696
+ if (!this.config) throw Error("Could not resolve app config");
697
+ if (typeof e == "number") this.config.dependencies.find((t) => t.id == e);
698
+ else {
699
+ let t = e.replace(/^\//, "");
700
+ this.config.dependencies.find((e) => e.id == this.api_map[t]);
701
+ }
702
+ let i = this.submit(e, t, null, null, !0), a;
703
+ for await (let e of i) {
704
+ if (e.type === "data" && (n = !0, a = e, r)) return a;
705
+ if (e.type === "status") {
706
+ if (e.stage === "error") {
707
+ let { message: t, ...n } = e, r = Error((typeof t == "string" ? t : t && JSON.stringify(t)) || "An unknown error occurred while making a prediction.");
708
+ throw Object.assign(r, n), r;
709
+ }
710
+ if (e.stage === "complete" && (r = !0, n)) return a;
711
+ }
712
+ }
713
+ return a;
714
+ }
715
+ //#endregion
716
+ //#region src/helpers/spaces.ts
717
+ async function K(e, t, n) {
718
+ let r = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, a;
719
+ try {
720
+ if (i = await fetch(r), a = i.status, a !== 200) throw Error();
721
+ i = await i.json();
722
+ } catch {
723
+ n({
724
+ status: "error",
725
+ load_status: "error",
726
+ message: x,
727
+ detail: "NOT_FOUND"
728
+ });
729
+ return;
730
+ }
731
+ if (!i || a !== 200) return;
732
+ let { runtime: { stage: o }, id: s } = i;
733
+ switch (o) {
734
+ case "STOPPED":
735
+ case "SLEEPING":
736
+ n({
737
+ status: "sleeping",
738
+ load_status: "pending",
739
+ message: "Space is asleep. Waking it up...",
740
+ detail: o
741
+ }), setTimeout(() => {
742
+ K(e, t, n);
743
+ }, 1e3);
744
+ break;
745
+ case "PAUSED":
746
+ n({
747
+ status: "paused",
748
+ load_status: "error",
749
+ message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
750
+ detail: o,
751
+ discussions_enabled: await Ie(s)
752
+ });
753
+ break;
754
+ case "RUNNING":
755
+ case "RUNNING_BUILDING":
756
+ n({
757
+ status: "running",
758
+ load_status: "complete",
759
+ message: "Space is running.",
760
+ detail: o
761
+ });
762
+ break;
763
+ case "BUILDING":
764
+ n({
765
+ status: "building",
766
+ load_status: "pending",
767
+ message: "Space is building...",
768
+ detail: o
769
+ }), setTimeout(() => {
770
+ K(e, t, n);
771
+ }, 1e3);
772
+ break;
773
+ case "APP_STARTING":
774
+ n({
775
+ status: "starting",
776
+ load_status: "pending",
777
+ message: "Space is starting...",
778
+ detail: o
779
+ }), setTimeout(() => {
780
+ K(e, t, n);
781
+ }, 1e3);
782
+ break;
783
+ default:
784
+ n({
785
+ status: "space_error",
786
+ load_status: "error",
787
+ message: "This space is experiencing an issue.",
788
+ detail: o,
789
+ discussions_enabled: await Ie(s)
790
+ });
791
+ break;
792
+ }
793
+ }
794
+ var Pe = async (e, t) => {
795
+ let n = 0;
796
+ return new Promise((r) => {
797
+ K(e, L.test(e) ? "space_name" : "subdomain", (i) => {
798
+ t(i), i.status === "running" || i.status === "error" || i.status === "paused" || i.status === "space_error" ? r() : (i.status === "sleeping" || i.status === "building") && (n < 12 ? (n++, setTimeout(() => {
799
+ Pe(e, t).then(r);
800
+ }, 5e3)) : r());
801
+ });
802
+ });
803
+ }, Fe = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
804
+ async function Ie(e) {
805
+ try {
806
+ let t = await fetch(`https://huggingface.co/api/spaces/${e}/discussions`, { method: "HEAD" }), n = t.headers.get("x-error-message");
807
+ return !(!t.ok || n && Fe.test(n));
808
+ } catch {
809
+ return !1;
810
+ }
811
+ }
812
+ async function Le(e, t) {
813
+ let n = {};
814
+ t && (n.Authorization = `Bearer ${t}`);
815
+ try {
816
+ let t = await fetch(`https://huggingface.co/api/spaces/${e}/${g}`, { headers: n });
817
+ if (t.status !== 200) throw Error("Space hardware could not be obtained.");
818
+ let { hardware: r } = await t.json();
819
+ return r.current;
820
+ } catch (e) {
821
+ throw Error(e.message);
822
+ }
823
+ }
824
+ async function Re(e, t, n) {
825
+ let r = {};
826
+ n && (r.Authorization = `Bearer ${n}`);
827
+ let i = { seconds: t };
828
+ try {
829
+ let t = await fetch(`https://huggingface.co/api/spaces/${e}/${ee}`, {
830
+ method: "POST",
831
+ headers: {
832
+ "Content-Type": "application/json",
833
+ ...r
834
+ },
835
+ body: JSON.stringify(i)
836
+ });
837
+ if (t.status !== 200) throw Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges.");
838
+ return await t.json();
839
+ } catch (e) {
840
+ throw Error(e.message);
841
+ }
842
+ }
843
+ var ze = [
844
+ "cpu-basic",
845
+ "cpu-upgrade",
846
+ "cpu-xl",
847
+ "t4-small",
848
+ "t4-medium",
849
+ "a10g-small",
850
+ "a10g-large",
851
+ "a10g-largex2",
852
+ "a10g-largex4",
853
+ "a100-large",
854
+ "zero-a10g",
855
+ "h100",
856
+ "h100x8"
952
857
  ];
953
- async function qt(e, s) {
954
- const { token: t, private: n, hardware: o, timeout: r, auth: i } = s;
955
- if (o && !Re.includes(o))
956
- throw new Error(
957
- `Invalid hardware type provided. Valid types are: ${Re.map((m) => `"${m}"`).join(",")}.`
958
- );
959
- const { http_protocol: a, host: u } = await pe(e, t);
960
- let l = null;
961
- if (i) {
962
- const m = await Ce(
963
- a,
964
- u,
965
- i,
966
- fetch,
967
- void 0,
968
- s.credentials
969
- );
970
- m && (l = Pe(m));
971
- }
972
- const p = {
973
- Authorization: `Bearer ${t}`,
974
- "Content-Type": "application/json",
975
- ...l ? { Cookie: l.join("; ") } : {}
976
- }, c = (await (await fetch("https://huggingface.co/api/whoami-v2", {
977
- headers: p
978
- })).json()).name, g = e.split("/")[1], w = {
979
- repository: `${c}/${g}`
980
- };
981
- n && (w.private = !0);
982
- let C;
983
- try {
984
- o || (C = await Ut(e, t));
985
- } catch (m) {
986
- throw Error(ue + m.message);
987
- }
988
- const f = o || C || "cpu-basic";
989
- w.hardware = f;
990
- try {
991
- const m = await fetch(
992
- `https://huggingface.co/api/spaces/${e}/duplicate`,
993
- {
994
- method: "POST",
995
- headers: p,
996
- body: JSON.stringify(w)
997
- }
998
- );
999
- if (m.status === 409)
1000
- try {
1001
- return await Y.connect(`${c}/${g}`, s);
1002
- } catch (z) {
1003
- throw console.error("Failed to connect Client instance:", z), z;
1004
- }
1005
- else if (m.status !== 200)
1006
- throw new Error(m.statusText);
1007
- const H = await m.json();
1008
- return await jt(`${c}/${g}`, r || 300, t), await Y.connect(
1009
- zt(H.url),
1010
- s
1011
- );
1012
- } catch (m) {
1013
- throw new Error(m);
1014
- }
858
+ //#endregion
859
+ //#region src/utils/duplicate.ts
860
+ async function Be(e, t) {
861
+ k(t);
862
+ let { token: n, private: r, hardware: i, timeout: a, auth: o } = t;
863
+ if (i && !ze.includes(i)) throw Error(`Invalid hardware type provided. Valid types are: ${ze.map((e) => `"${e}"`).join(",")}.`);
864
+ let { http_protocol: s, host: c } = await R(e, n), l = null;
865
+ if (o) {
866
+ let e = await P(s, c, o, fetch, void 0, t.credentials);
867
+ e && (l = I(e));
868
+ }
869
+ let u = {
870
+ Authorization: `Bearer ${n}`,
871
+ "Content-Type": "application/json",
872
+ ...l ? { Cookie: l.join("; ") } : {}
873
+ }, d = (await (await fetch("https://huggingface.co/api/whoami-v2", { headers: u })).json()).name, f = e.split("/")[1], p = { repository: `${d}/${f}` };
874
+ r && (p.private = !0);
875
+ let m;
876
+ try {
877
+ i || (m = await Le(e, n));
878
+ } catch (e) {
879
+ throw Error(C + e.message);
880
+ }
881
+ p.hardware = i || m || "cpu-basic";
882
+ try {
883
+ let r = await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`, {
884
+ method: "POST",
885
+ headers: u,
886
+ body: JSON.stringify(p)
887
+ });
888
+ if (r.status === 409) try {
889
+ return await $.connect(`${d}/${f}`, t);
890
+ } catch (e) {
891
+ throw console.error("Failed to connect Client instance:", e), e;
892
+ }
893
+ else if (r.status !== 200) throw Error(r.statusText);
894
+ let i = await r.json();
895
+ return await Re(`${d}/${f}`, a || 300, n), await $.connect(Ve(i.url), t);
896
+ } catch (e) {
897
+ throw Error(e);
898
+ }
899
+ }
900
+ function Ve(e) {
901
+ let t = e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/);
902
+ if (t) return t[1];
903
+ }
904
+ //#endregion
905
+ //#region src/helpers/zerogpu.ts
906
+ var He = "supports-zerogpu-headers", Ue = !1;
907
+ function We() {
908
+ return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function";
909
+ }
910
+ function Ge(e) {
911
+ return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null;
912
+ }
913
+ function Ke() {
914
+ if (!We() || Ue) return;
915
+ window.addEventListener("message", (e) => {
916
+ e.data === He && (window.supports_zerogpu_headers = !0);
917
+ }), Ue = !0;
918
+ let e = Ge(window.location.hostname);
919
+ e && window.parent !== window && window.parent.postMessage(He, e);
920
+ }
921
+ //#endregion
922
+ //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/deps/jsr.io/@std/streams/0.221.0/text_line_stream.js
923
+ var qe = class extends TransformStream {
924
+ #e = "";
925
+ constructor(e = { allowCR: !1 }) {
926
+ super({
927
+ transform: (t, n) => {
928
+ for (t = this.#e + t;;) {
929
+ let r = t.indexOf("\n"), i = e.allowCR ? t.indexOf("\r") : -1;
930
+ if (i !== -1 && i !== t.length - 1 && (r === -1 || r - 1 > i)) {
931
+ n.enqueue(t.slice(0, i)), t = t.slice(i + 1);
932
+ continue;
933
+ }
934
+ if (r === -1) break;
935
+ let a = t[r - 1] === "\r" ? r - 1 : r;
936
+ n.enqueue(t.slice(0, a)), t = t.slice(r + 1);
937
+ }
938
+ this.#e = t;
939
+ },
940
+ flush: (t) => {
941
+ if (this.#e === "") return;
942
+ let n = e.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e;
943
+ t.enqueue(n);
944
+ }
945
+ });
946
+ }
947
+ };
948
+ //#endregion
949
+ //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/utils.js
950
+ function Je(e) {
951
+ let t = new TextDecoderStream(), n = new qe({ allowCR: !0 });
952
+ return e.pipeThrough(t).pipeThrough(n);
953
+ }
954
+ function Ye(e) {
955
+ let t = /[:]\s*/.exec(e), n = t && t.index;
956
+ if (n) return [e.substring(0, n), e.substring(n + t[0].length)];
957
+ }
958
+ function Xe(e, t, n) {
959
+ e.get(t) || e.set(t, n);
960
+ }
961
+ //#endregion
962
+ //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/mod.js
963
+ async function* Ze(e, t) {
964
+ if (!e.body) return;
965
+ let n = Je(e.body), r, i = n.getReader(), a;
966
+ for (;;) {
967
+ if (t && t.aborted) return i.cancel();
968
+ if (r = await i.read(), r.done) return;
969
+ if (!r.value) {
970
+ a && (yield a), a = void 0;
971
+ continue;
972
+ }
973
+ let [e, n] = Ye(r.value) || [];
974
+ e === "data" ? (a ||= {}, a[e] = a[e] ? a[e] + "\n" + n : n) : e === "event" ? (a ||= {}, a[e] = n) : e === "id" ? (a ||= {}, a[e] = String(+n) === n ? +n : n) : e === "retry" && (a ||= {}, a[e] = +n || void 0);
975
+ }
976
+ }
977
+ async function Qe(e, t) {
978
+ let n = new Request(e, t);
979
+ Xe(n.headers, "Accept", "text/event-stream"), Xe(n.headers, "Content-Type", "application/json");
980
+ let r = await fetch(n);
981
+ if (!r.ok) throw r;
982
+ return Ze(r, n.signal);
983
+ }
984
+ //#endregion
985
+ //#region src/utils/stream.ts
986
+ async function $e() {
987
+ let { event_callbacks: e, unclosed_events: t, pending_stream_messages: n, stream_status: r, config: i, jwt: a } = this, o = this;
988
+ if (!i) throw Error("Could not resolve app config");
989
+ r.open = !0;
990
+ let s = null, c = new URLSearchParams({ session_hash: this.session_hash }).toString(), l = new URL(`${i.root}${this.api_prefix}/${u}?${c}`);
991
+ if (a && l.searchParams.set("__sign", a), s = this.stream(l), !s) {
992
+ console.warn("Cannot connect to SSE endpoint: " + l.toString());
993
+ return;
994
+ }
995
+ s.onmessage = async function(a) {
996
+ let s = JSON.parse(a.data);
997
+ if (s.msg === "close_stream") {
998
+ et(r, o.abort_controller);
999
+ return;
1000
+ }
1001
+ let c = s.event_id;
1002
+ if (!c) await Promise.all(Object.keys(e).map((t) => e[t](s)));
1003
+ else if (e[c] && i) {
1004
+ s.msg === "process_completed" && [
1005
+ "sse",
1006
+ "sse_v1",
1007
+ "sse_v2",
1008
+ "sse_v2.1",
1009
+ "sse_v3"
1010
+ ].includes(i.protocol) && t.delete(c);
1011
+ let n = e[c];
1012
+ typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(n, 0, s) : n(s);
1013
+ } else n[c] || (n[c] = []), n[c].push(s);
1014
+ }, s.onerror = async function(t) {
1015
+ console.error(t), await Promise.all(Object.keys(e).map((t) => e[t]({
1016
+ msg: "broken_connection",
1017
+ message: y
1018
+ })));
1019
+ };
1020
+ }
1021
+ function et(e, t) {
1022
+ e && (e.open = !1, t?.abort());
1023
+ }
1024
+ function tt(e, t, n) {
1025
+ e[t] ? n.data.forEach((r, i) => {
1026
+ let a = nt(i < e[t].length ? e[t][i] : null, r);
1027
+ e[t][i] = a, n.data[i] = a;
1028
+ }) : (e[t] = [], n.data.forEach((n, r) => {
1029
+ e[t][r] = n;
1030
+ }));
1031
+ }
1032
+ function nt(e, t) {
1033
+ return t.forEach(([t, n, r]) => {
1034
+ e = rt(e, n, t, r);
1035
+ }), e;
1036
+ }
1037
+ function rt(e, t, n, r) {
1038
+ if (t.length === 0) {
1039
+ if (n === "replace") return r;
1040
+ if (n === "append") return e + r;
1041
+ throw Error(`Unsupported action: ${n}`);
1042
+ }
1043
+ let i = e;
1044
+ for (let e = 0; e < t.length - 1; e++) i = i[t[e]];
1045
+ let a = t[t.length - 1];
1046
+ switch (n) {
1047
+ case "replace":
1048
+ i[a] = r;
1049
+ break;
1050
+ case "append":
1051
+ i[a] += r;
1052
+ break;
1053
+ case "add":
1054
+ Array.isArray(i) ? i.splice(Number(a), 0, r) : i[a] = r;
1055
+ break;
1056
+ case "delete":
1057
+ Array.isArray(i) ? i.splice(Number(a), 1) : delete i[a];
1058
+ break;
1059
+ default: throw Error(`Unknown action: ${n}`);
1060
+ }
1061
+ return e;
1062
+ }
1063
+ function it(e, t = {}) {
1064
+ let n = {
1065
+ close: () => {
1066
+ console.warn("Method not implemented.");
1067
+ },
1068
+ onerror: null,
1069
+ onmessage: null,
1070
+ onopen: null,
1071
+ readyState: 0,
1072
+ url: e.toString(),
1073
+ withCredentials: !1,
1074
+ CONNECTING: 0,
1075
+ OPEN: 1,
1076
+ CLOSED: 2,
1077
+ addEventListener: () => {
1078
+ throw Error("Method not implemented.");
1079
+ },
1080
+ dispatchEvent: () => {
1081
+ throw Error("Method not implemented.");
1082
+ },
1083
+ removeEventListener: () => {
1084
+ throw Error("Method not implemented.");
1085
+ }
1086
+ };
1087
+ return Qe(e, t).then(async (e) => {
1088
+ n.readyState = n.OPEN;
1089
+ try {
1090
+ for await (let t of e) n.onmessage && n.onmessage(t);
1091
+ n.readyState = n.CLOSED;
1092
+ } catch (e) {
1093
+ n.onerror && n.onerror(e), n.readyState = n.CLOSED;
1094
+ }
1095
+ }).catch((e) => {
1096
+ console.error(e), n.onerror && n.onerror(e), n.readyState = n.CLOSED;
1097
+ }), n;
1098
+ }
1099
+ //#endregion
1100
+ //#region src/utils/run_history.ts
1101
+ var at = "gradio:run-history:", q = `${at}v2:`, ot = `${at}replay:v2:`, st = 100, ct = 8;
1102
+ function J(e, t) {
1103
+ try {
1104
+ return e();
1105
+ } catch (e) {
1106
+ return console.warn("Could not update the run history.", e), t;
1107
+ }
1108
+ }
1109
+ function lt(e, t = "/gradio_api") {
1110
+ return `${e.replace(/\/+$/, "")}${t}/runs`;
1111
+ }
1112
+ function Y(e) {
1113
+ if (typeof window > "u") return null;
1114
+ let t = e?.app_id;
1115
+ if (t == null || t === "") return null;
1116
+ try {
1117
+ return window.localStorage ? `${q}${t}${e?.username ? `:user:${encodeURIComponent(e.username)}` : ""}` : null;
1118
+ } catch {
1119
+ return null;
1120
+ }
1121
+ }
1122
+ function ut(e) {
1123
+ let t = Y(e);
1124
+ return t ? t.replace(q, ot) : null;
1125
+ }
1126
+ function dt(e) {
1127
+ try {
1128
+ let t = JSON.parse(window.localStorage.getItem(e) || "[]");
1129
+ return Array.isArray(t) && t.length && Date.parse(t[0]?.started_at) || 0;
1130
+ } catch {
1131
+ return 0;
1132
+ }
1133
+ }
1134
+ function ft(e) {
1135
+ let t = Object.keys(window.localStorage).filter((e) => e.startsWith(at)), n = [...t.filter((e) => !e.startsWith(q) && !e.startsWith(ot)), ...t.filter((t) => t.startsWith(q) && t !== e).sort((e, t) => dt(t) - dt(e)).slice(ct - 1)];
1136
+ for (let e of n) try {
1137
+ window.localStorage.removeItem(e), window.sessionStorage.removeItem(e.replace(q, ot));
1138
+ } catch {}
1139
+ }
1140
+ function pt() {
1141
+ return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
1142
+ }
1143
+ function X(e) {
1144
+ let t = /* @__PURE__ */ new WeakSet();
1145
+ try {
1146
+ return JSON.parse(JSON.stringify(e, (e, n) => {
1147
+ if (typeof n == "bigint") return n.toString();
1148
+ if (typeof n == "object" && n) {
1149
+ if (t.has(n)) return "[Circular]";
1150
+ t.add(n);
1151
+ }
1152
+ return n;
1153
+ }));
1154
+ } catch {
1155
+ return "[Unserializable value]";
1156
+ }
1157
+ }
1158
+ function Z(e) {
1159
+ let t = Y(e);
1160
+ if (!t) return [];
1161
+ try {
1162
+ let e = JSON.parse(window.localStorage.getItem(t) || "[]");
1163
+ return Array.isArray(e) ? e : [];
1164
+ } catch {
1165
+ return [];
1166
+ }
1167
+ }
1168
+ function mt(e, t) {
1169
+ let n = Y(e);
1170
+ if (!n) return;
1171
+ let r = t.slice(0, st), i = !1;
1172
+ for (; r.length > 0;) try {
1173
+ window.localStorage.setItem(n, JSON.stringify(r));
1174
+ return;
1175
+ } catch {
1176
+ if (!i) {
1177
+ i = !0, ft(n);
1178
+ continue;
1179
+ }
1180
+ r = r.slice(0, -1);
1181
+ }
1182
+ try {
1183
+ window.localStorage.removeItem(n);
1184
+ } catch {}
1185
+ }
1186
+ function ht(e) {
1187
+ let t = Y(e);
1188
+ if (t) {
1189
+ try {
1190
+ window.localStorage.removeItem(t);
1191
+ } catch {}
1192
+ vt();
1193
+ }
1194
+ }
1195
+ function gt(e, t) {
1196
+ mt(e, Z(e).filter((e) => e.id !== t)), vt();
1197
+ }
1198
+ var _t = "gradio:run-history-change";
1199
+ function vt() {
1200
+ if (!(typeof window > "u")) try {
1201
+ window.dispatchEvent(new Event(_t));
1202
+ } catch {}
1203
+ }
1204
+ function yt(e) {
1205
+ return typeof window > "u" ? () => {} : (window.addEventListener(_t, e), window.addEventListener("storage", e), () => {
1206
+ window.removeEventListener(_t, e), window.removeEventListener("storage", e);
1207
+ });
1208
+ }
1209
+ function bt(e, t) {
1210
+ let n = ut(e);
1211
+ if (n) try {
1212
+ window.sessionStorage.setItem(n, JSON.stringify(t));
1213
+ } catch {}
1214
+ }
1215
+ function xt(e) {
1216
+ let t = ut(e);
1217
+ if (!t) return null;
1218
+ try {
1219
+ let e = window.sessionStorage.getItem(t);
1220
+ return window.sessionStorage.removeItem(t), e ? JSON.parse(e) : null;
1221
+ } catch {
1222
+ return null;
1223
+ }
1224
+ }
1225
+ function St(e) {
1226
+ let t = Y(e);
1227
+ if (!t) return null;
1228
+ ft(t);
1229
+ let n = {
1230
+ id: pt(),
1231
+ endpoint: e.endpoint,
1232
+ api_name: e.api_name,
1233
+ fn_index: e.fn_index,
1234
+ page: `${window.location.pathname}${window.location.search}`,
1235
+ inputs: X(e.inputs),
1236
+ outputs: null,
1237
+ ...e.input_components ? { input_components: X(e.input_components) } : {},
1238
+ ...e.output_components ? { output_components: X(e.output_components) } : {},
1239
+ status: "running",
1240
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
1241
+ };
1242
+ return mt(e, [n, ...Z(e)]), vt(), n.id;
1243
+ }
1244
+ function Ct(e, t, n) {
1245
+ if (!t) return;
1246
+ let r = Z(e), i = r.find((e) => e.id === t);
1247
+ i && (i.inputs = X(n), mt(e, r));
1248
+ }
1249
+ function wt(e, t, n) {
1250
+ if (!t) return;
1251
+ let r = Z(e), i = r.find((e) => e.id === t);
1252
+ if (!i) return;
1253
+ let a = !1;
1254
+ if (n.type === "data") i.outputs = X(n.data), Q.set(t, i.outputs);
1255
+ else if (n.type === "status" && n.original_msg === "process_starts") Dt(i, n.time);
1256
+ else if (n.type === "status" && (n.stage === "generating" || n.stage === "streaming")) i.streamed = !0;
1257
+ else if (n.type === "status" && n.stage === "complete") i.status = "completed", Ot(i, n), a = !0;
1258
+ else if (n.type === "status" && n.stage === "error") i.status = "failed", i.error = typeof n.message == "string" ? n.message : JSON.stringify(n.message || "Unknown error"), Ot(i, n), a = !0;
1259
+ else return;
1260
+ if (a) Q.has(t) && (i.outputs = Q.get(t)), Q.delete(t), Et.delete(t);
1261
+ else if (i.streamed) {
1262
+ if (Date.now() - (Et.get(t) ?? 0) < Tt) return;
1263
+ Et.set(t, Date.now()), Q.delete(t);
1264
+ }
1265
+ mt(e, r);
1266
+ }
1267
+ var Tt = 500, Et = /* @__PURE__ */ new Map(), Q = /* @__PURE__ */ new Map();
1268
+ function Dt(e, t) {
1269
+ if (e.process_started_at) return;
1270
+ let n = t || /* @__PURE__ */ new Date();
1271
+ e.process_started_at = n.toISOString(), e.queued_ms = Math.max(0, n.getTime() - Date.parse(e.started_at));
1272
+ }
1273
+ function Ot(e, t) {
1274
+ let n = t.time || /* @__PURE__ */ new Date();
1275
+ e.completed_at = n.toISOString(), e.duration_ms = (!e.streamed && typeof t.cache_duration == "number" && t.cache_duration >= 0 ? t.cache_duration * 1e3 : null) ?? Math.max(0, n.getTime() - Date.parse(e.process_started_at || e.started_at));
1276
+ }
1277
+ function kt(e) {
1278
+ return J(() => Z(e), []);
1279
+ }
1280
+ function At(e) {
1281
+ J(() => ht(e), void 0);
1282
+ }
1283
+ function jt(e, t) {
1284
+ J(() => gt(e, t), void 0);
1285
+ }
1286
+ function Mt(e, t) {
1287
+ J(() => bt(e, t), void 0);
1288
+ }
1289
+ function Nt(e) {
1290
+ return J(() => xt(e), null);
1291
+ }
1292
+ function Pt(e) {
1293
+ return J(() => St(e), null);
1294
+ }
1295
+ function Ft(e, t, n) {
1296
+ J(() => Ct(e, t, n), void 0);
1297
+ }
1298
+ function It(e, t, n) {
1299
+ J(() => wt(e, t, n), void 0);
1300
+ }
1301
+ function Lt(e) {
1302
+ return J(() => yt(() => J(e, void 0)), () => {});
1303
+ }
1304
+ //#endregion
1305
+ //#region src/utils/submit.ts
1306
+ function Rt(e, t = {}, n, r, i, a) {
1307
+ try {
1308
+ let { token: o } = this.options, { fetch: s, app_reference: c, config: l, session_hash: f, api_info: p, api_map: m, stream_status: h, pending_stream_messages: g, pending_diff_streams: ee, event_callbacks: _, unclosed_events: te, post_data: v, options: b, api_prefix: x } = this, S = a || { "x-gradio-user": "api" }, C = this;
1309
+ if (!p) throw Error(se);
1310
+ if (!l) throw Error("Could not resolve app config");
1311
+ let { fn_index: w, endpoint_info: T, dependency: E } = Bt(p, e, m, l), ae = ye(t, T), D = l.protocol ?? "ws";
1312
+ if (D === "ws") throw Error(ce);
1313
+ let oe = typeof E.api_name == "string" ? `/${E.api_name}` : e, le = typeof E.api_name == "string" ? `/${E.api_name}` : `Function ${w}`, O = (e) => {
1314
+ let t = l.components.find((t) => t.id === e);
1315
+ return t ? {
1316
+ type: t.type,
1317
+ component_class_id: t.component_class_id,
1318
+ props: t.props
1319
+ } : null;
1320
+ }, ue = E.api_visibility === "public", de = l.run_history !== !1 && this.options.record_history !== !1, k = {
1321
+ app_id: l.app_id,
1322
+ username: l.username
1323
+ }, fe = !de || !ue ? null : Pt({
1324
+ ...k,
1325
+ endpoint: oe,
1326
+ api_name: le,
1327
+ fn_index: w,
1328
+ inputs: G(ae, E, l.components, "input", !0),
1329
+ input_components: E.inputs.map(O),
1330
+ output_components: E.outputs.map(O)
1331
+ }), A, j = "", M = typeof e == "number" ? "/predict" : e, N, P = null, F = !1, I = {}, L = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "", pe = b?.events?.reduce((e, t) => (e[t] = !0, e), {}) || {};
1332
+ function R(e) {
1333
+ It(k, fe, e), (i || pe[e.type]) && U(e);
1334
+ }
1335
+ async function me() {
1336
+ let e = {}, t = {};
1337
+ e = { event_id: P }, t = {
1338
+ event_id: P,
1339
+ session_hash: f,
1340
+ fn_index: w
1341
+ };
1342
+ try {
1343
+ if (!l) throw Error("Could not resolve app config");
1344
+ "event_id" in t && await s(`${l.root}${x}/${re}`, {
1345
+ headers: { "Content-Type": "application/json" },
1346
+ method: "POST",
1347
+ body: JSON.stringify(t)
1348
+ }), await s(`${l.root}${x}/${ne}`, {
1349
+ headers: { "Content-Type": "application/json" },
1350
+ method: "POST",
1351
+ body: JSON.stringify(e)
1352
+ });
1353
+ } catch {
1354
+ console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.");
1355
+ }
1356
+ }
1357
+ let he = async (e) => {
1358
+ await this._resolve_heartbeat(e);
1359
+ };
1360
+ async function ge(e) {
1361
+ if (!l) return;
1362
+ let t = e.render_id;
1363
+ l.components = [...l.components.filter((e) => e.props.rendered_in !== t), ...e.components], l.dependencies = [...l.dependencies.filter((e) => e.rendered_in !== t), ...e.dependencies];
1364
+ let n = l.components.some((e) => e.type === "state"), r = l.dependencies.some((e) => e.targets.some((e) => e[1] === "unload"));
1365
+ l.connect_heartbeat = n || r, await he(l), R({
1366
+ type: "render",
1367
+ data: e,
1368
+ endpoint: M,
1369
+ fn_index: w
1370
+ });
1371
+ }
1372
+ let _e = this.handle_blob(l.root, ae, T).then(async (e) => {
1373
+ let t = G(e, E, l.components, "input", !0);
1374
+ if (Ft(k, fe, t || []), N = {
1375
+ data: t || [],
1376
+ event_data: n,
1377
+ fn_index: w,
1378
+ trigger_id: r,
1379
+ ...b.oauth_token && T?.oauth_token ? { oauth_token: b.oauth_token } : {}
1380
+ }, Te(w, l)) R({
1381
+ type: "status",
1382
+ endpoint: M,
1383
+ stage: "pending",
1384
+ queue: !1,
1385
+ fn_index: w,
1386
+ time: /* @__PURE__ */ new Date()
1387
+ }), v(`${l.root}${x}/run${M.startsWith("/") ? M : `/${M}`}${L ? "?" + L : ""}`, {
1388
+ ...N,
1389
+ session_hash: f
1390
+ }, S).then(async ([e, t]) => {
1391
+ let i = e.data;
1392
+ if (t == 200) R({
1393
+ type: "data",
1394
+ endpoint: M,
1395
+ fn_index: w,
1396
+ data: G(i, E, l.components, "output", b.with_null_state),
1397
+ time: /* @__PURE__ */ new Date(),
1398
+ event_data: n,
1399
+ trigger_id: r
1400
+ }), e.render_config && await ge(e.render_config), R({
1401
+ type: "status",
1402
+ endpoint: M,
1403
+ fn_index: w,
1404
+ stage: "complete",
1405
+ eta: e.average_duration,
1406
+ queue: !1,
1407
+ time: /* @__PURE__ */ new Date()
1408
+ });
1409
+ else {
1410
+ let t = e?.error === y;
1411
+ R({
1412
+ type: "status",
1413
+ stage: "error",
1414
+ endpoint: M,
1415
+ fn_index: w,
1416
+ message: e.error,
1417
+ broken: t,
1418
+ queue: !1,
1419
+ time: /* @__PURE__ */ new Date()
1420
+ });
1421
+ }
1422
+ }).catch((e) => {
1423
+ R({
1424
+ type: "status",
1425
+ stage: "error",
1426
+ message: e.message,
1427
+ endpoint: M,
1428
+ fn_index: w,
1429
+ queue: !1,
1430
+ time: /* @__PURE__ */ new Date()
1431
+ });
1432
+ });
1433
+ else if (D == "sse") {
1434
+ R({
1435
+ type: "status",
1436
+ stage: "pending",
1437
+ queue: !0,
1438
+ endpoint: M,
1439
+ fn_index: w,
1440
+ time: /* @__PURE__ */ new Date()
1441
+ });
1442
+ var i = new URLSearchParams({
1443
+ fn_index: w.toString(),
1444
+ session_hash: f
1445
+ }).toString();
1446
+ let e = new URL(`${l.root}${x}/${u}?${L ? L + "&" : ""}${i}`);
1447
+ if (this.jwt && e.searchParams.set("__sign", this.jwt), A = this.stream(e), !A) return Promise.reject(/* @__PURE__ */ Error("Cannot connect to SSE endpoint: " + e.toString()));
1448
+ A.onmessage = async function(e) {
1449
+ let { type: t, status: i, data: a } = ve(JSON.parse(e.data), I[w]);
1450
+ if (t === "update" && i && !F) R({
1451
+ type: "status",
1452
+ endpoint: M,
1453
+ fn_index: w,
1454
+ time: /* @__PURE__ */ new Date(),
1455
+ ...i
1456
+ }), i.stage === "error" && (A?.close(), V());
1457
+ else if (t === "data") {
1458
+ let [e, t] = await v(`${l.root}${x}/queue/data`, {
1459
+ ...N,
1460
+ session_hash: f,
1461
+ event_id: P
1462
+ });
1463
+ t !== 200 && (R({
1464
+ type: "status",
1465
+ stage: "error",
1466
+ message: y,
1467
+ queue: !0,
1468
+ endpoint: M,
1469
+ fn_index: w,
1470
+ time: /* @__PURE__ */ new Date()
1471
+ }), A?.close(), V());
1472
+ } else t === "complete" ? F = i : t === "log" ? R({
1473
+ type: "log",
1474
+ title: a.title,
1475
+ log: a.log,
1476
+ level: a.level,
1477
+ endpoint: M,
1478
+ duration: a.duration,
1479
+ visible: a.visible,
1480
+ fn_index: w
1481
+ }) : (t === "generating" || t === "streaming") && R({
1482
+ type: "status",
1483
+ time: /* @__PURE__ */ new Date(),
1484
+ ...i,
1485
+ stage: i?.stage,
1486
+ queue: !0,
1487
+ endpoint: M,
1488
+ fn_index: w
1489
+ });
1490
+ a && (R({
1491
+ type: "data",
1492
+ time: /* @__PURE__ */ new Date(),
1493
+ data: G(a.data, E, l.components, "output", b.with_null_state),
1494
+ endpoint: M,
1495
+ fn_index: w,
1496
+ event_data: n,
1497
+ trigger_id: r
1498
+ }), F && (R({
1499
+ type: "status",
1500
+ time: /* @__PURE__ */ new Date(),
1501
+ ...F,
1502
+ stage: i?.stage,
1503
+ queue: !0,
1504
+ endpoint: M,
1505
+ fn_index: w
1506
+ }), A?.close(), V()));
1507
+ };
1508
+ } else if (D == "sse_v1" || D == "sse_v2" || D == "sse_v2.1" || D == "sse_v3") {
1509
+ R({
1510
+ type: "status",
1511
+ stage: "pending",
1512
+ queue: !0,
1513
+ endpoint: M,
1514
+ fn_index: w,
1515
+ time: /* @__PURE__ */ new Date()
1516
+ });
1517
+ let e = "";
1518
+ typeof window < "u" && typeof document < "u" && (e = window?.location?.hostname);
1519
+ let t = Ge(e);
1520
+ return (typeof window < "u" && typeof document < "u" && window.parent != window && t && window.supports_zerogpu_headers ? Ee("zerogpu-headers", t) : Promise.resolve(null)).then((e) => {
1521
+ let t = {
1522
+ ...S,
1523
+ ...e || {}
1524
+ };
1525
+ return v(`${l.root}${x}/${d}?${L}`, {
1526
+ ...N,
1527
+ session_hash: f
1528
+ }, t);
1529
+ }).then(async ([e, t]) => {
1530
+ if (e.event_id && (j = e.event_id), t === 503) R({
1531
+ type: "status",
1532
+ stage: "error",
1533
+ message: ie,
1534
+ queue: !0,
1535
+ endpoint: M,
1536
+ fn_index: w,
1537
+ time: /* @__PURE__ */ new Date(),
1538
+ visible: !0
1539
+ }), V();
1540
+ else if (t === 422) R({
1541
+ type: "status",
1542
+ stage: "error",
1543
+ message: e.detail,
1544
+ queue: !0,
1545
+ endpoint: M,
1546
+ fn_index: w,
1547
+ code: "validation_error",
1548
+ time: /* @__PURE__ */ new Date(),
1549
+ visible: !0
1550
+ }), V();
1551
+ else if (t !== 200) {
1552
+ let t = e?.error === y;
1553
+ R({
1554
+ type: "status",
1555
+ stage: "error",
1556
+ broken: t,
1557
+ message: t ? y : e.detail || e.error,
1558
+ queue: !0,
1559
+ endpoint: M,
1560
+ fn_index: w,
1561
+ time: /* @__PURE__ */ new Date(),
1562
+ visible: !0
1563
+ }), V();
1564
+ } else {
1565
+ P = e.event_id, j = P;
1566
+ let t = async function(e) {
1567
+ try {
1568
+ let { type: t, status: n, data: r, original_msg: i } = ve(e, I[w]);
1569
+ if (t == "heartbeat") return;
1570
+ if (t === "update" && n && !F) R({
1571
+ type: "status",
1572
+ endpoint: M,
1573
+ fn_index: w,
1574
+ time: /* @__PURE__ */ new Date(),
1575
+ original_msg: i,
1576
+ ...n
1577
+ });
1578
+ else if (t === "complete") F = n;
1579
+ else if (t == "unexpected_error" || t == "broken_connection") {
1580
+ console.error("Unexpected error", n?.message);
1581
+ let e = t === "broken_connection";
1582
+ R({
1583
+ type: "status",
1584
+ stage: "error",
1585
+ message: n?.message || "An Unexpected Error Occurred!",
1586
+ queue: !0,
1587
+ endpoint: M,
1588
+ broken: e,
1589
+ session_not_found: n?.session_not_found,
1590
+ fn_index: w,
1591
+ time: /* @__PURE__ */ new Date()
1592
+ });
1593
+ } else if (t === "log") {
1594
+ R({
1595
+ type: "log",
1596
+ title: r.title,
1597
+ log: r.log,
1598
+ level: r.level,
1599
+ endpoint: M,
1600
+ duration: r.duration,
1601
+ visible: r.visible,
1602
+ fn_index: w
1603
+ });
1604
+ return;
1605
+ } else (t === "generating" || t === "streaming") && (R({
1606
+ type: "status",
1607
+ time: /* @__PURE__ */ new Date(),
1608
+ ...n,
1609
+ stage: n?.stage,
1610
+ queue: !0,
1611
+ endpoint: M,
1612
+ fn_index: w
1613
+ }), r && E.connection !== "stream" && [
1614
+ "sse_v2",
1615
+ "sse_v2.1",
1616
+ "sse_v3"
1617
+ ].includes(D) && tt(ee, P, r));
1618
+ r && (R({
1619
+ type: "data",
1620
+ time: /* @__PURE__ */ new Date(),
1621
+ data: G(r.data, E, l.components, "output", b.with_null_state),
1622
+ endpoint: M,
1623
+ fn_index: w
1624
+ }), r.render_config && await ge(r.render_config), F && (R({
1625
+ type: "status",
1626
+ time: /* @__PURE__ */ new Date(),
1627
+ ...F,
1628
+ stage: n?.stage,
1629
+ queue: !0,
1630
+ endpoint: M,
1631
+ fn_index: w
1632
+ }), V())), (n?.stage === "complete" || n?.stage === "error") && (_[P] && delete _[P], P in ee && delete ee[P], V());
1633
+ } catch (e) {
1634
+ console.error("Unexpected client exception", e), R({
1635
+ type: "status",
1636
+ stage: "error",
1637
+ message: "An Unexpected Error Occurred!",
1638
+ queue: !0,
1639
+ endpoint: M,
1640
+ fn_index: w,
1641
+ time: /* @__PURE__ */ new Date()
1642
+ }), [
1643
+ "sse_v2",
1644
+ "sse_v2.1",
1645
+ "sse_v3"
1646
+ ].includes(D) && (et(h, C.abort_controller), h.open = !1, V());
1647
+ }
1648
+ };
1649
+ P in g && (g[P].forEach((e) => t(e)), delete g[P]), _[P] = t, te.add(P), h.open || await this.open_stream();
1650
+ }
1651
+ });
1652
+ }
1653
+ });
1654
+ _e.catch((e) => {
1655
+ R({
1656
+ type: "status",
1657
+ stage: "error",
1658
+ message: e instanceof Error ? e.message : String(e),
1659
+ queue: !Te(w, l),
1660
+ endpoint: M,
1661
+ fn_index: w,
1662
+ time: /* @__PURE__ */ new Date()
1663
+ }), V();
1664
+ });
1665
+ let be = !1, z = [], B = [];
1666
+ function V() {
1667
+ for (be = !0; B.length > 0;) B.shift()({
1668
+ value: void 0,
1669
+ done: !0
1670
+ });
1671
+ }
1672
+ function H(e) {
1673
+ B.length > 0 ? B.shift()(e) : z.push(e);
1674
+ }
1675
+ function xe(e) {
1676
+ H(zt(e)), V();
1677
+ }
1678
+ function U(e) {
1679
+ H({
1680
+ value: e,
1681
+ done: !1
1682
+ });
1683
+ }
1684
+ function W() {
1685
+ return z.length > 0 ? Promise.resolve(z.shift()) : be ? Promise.resolve({
1686
+ value: void 0,
1687
+ done: !0
1688
+ }) : new Promise((e) => B.push(e));
1689
+ }
1690
+ let Se = {
1691
+ [Symbol.asyncIterator]: () => Se,
1692
+ next: W,
1693
+ throw: async (e) => (xe(e), W()),
1694
+ return: async () => (V(), {
1695
+ value: void 0,
1696
+ done: !0
1697
+ }),
1698
+ cancel: me,
1699
+ send_chunk: (e) => {
1700
+ this.post_data(`${l.root}${x}/stream/${j}`, {
1701
+ ...e,
1702
+ session_hash: this.session_hash
1703
+ });
1704
+ },
1705
+ close_stream: () => {
1706
+ this.post_data(`${l.root}${x}/stream/${j}/close`, {}), V();
1707
+ },
1708
+ event_id: () => j,
1709
+ wait_for_id: async () => (await _e, P)
1710
+ };
1711
+ return Se;
1712
+ } catch (e) {
1713
+ throw console.error("Submit function encountered an error:", e), e;
1714
+ }
1015
1715
  }
1016
1716
  function zt(e) {
1017
- const s = /https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/, t = e.match(s);
1018
- if (t)
1019
- return t[1];
1020
- }
1021
- const Oe = "supports-zerogpu-headers";
1022
- let Ae = !1;
1023
- function Bt() {
1024
- return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function";
1025
- }
1026
- function qe(e) {
1027
- return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null;
1028
- }
1029
- function Gt() {
1030
- if (!Bt() || Ae)
1031
- return;
1032
- window.addEventListener("message", (s) => {
1033
- s.data === Oe && (window.supports_zerogpu_headers = !0);
1034
- }), Ae = !0;
1035
- const e = qe(window.location.hostname);
1036
- e && window.parent !== window && window.parent.postMessage(Oe, e);
1037
- }
1038
- class Mt extends TransformStream {
1039
- #e = "";
1040
- /** Constructs a new instance. */
1041
- constructor(s = { allowCR: !1 }) {
1042
- super({
1043
- transform: (t, n) => {
1044
- for (t = this.#e + t; ; ) {
1045
- const o = t.indexOf(`
1046
- `), r = s.allowCR ? t.indexOf("\r") : -1;
1047
- if (r !== -1 && r !== t.length - 1 && (o === -1 || o - 1 > r)) {
1048
- n.enqueue(t.slice(0, r)), t = t.slice(r + 1);
1049
- continue;
1050
- }
1051
- if (o === -1)
1052
- break;
1053
- const i = t[o - 1] === "\r" ? o - 1 : o;
1054
- n.enqueue(t.slice(0, i)), t = t.slice(o + 1);
1055
- }
1056
- this.#e = t;
1057
- },
1058
- flush: (t) => {
1059
- if (this.#e === "")
1060
- return;
1061
- const n = s.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e;
1062
- t.enqueue(n);
1063
- }
1064
- });
1065
- }
1066
- }
1067
- function Ft(e) {
1068
- let s = new TextDecoderStream(), t = new Mt({ allowCR: !0 });
1069
- return e.pipeThrough(s).pipeThrough(t);
1070
- }
1071
- function Ht(e) {
1072
- let t = /[:]\s*/.exec(e), n = t && t.index;
1073
- if (n)
1074
- return [
1075
- e.substring(0, n),
1076
- e.substring(n + t[0].length)
1077
- ];
1078
- }
1079
- function Te(e, s, t) {
1080
- e.get(s) || e.set(s, t);
1081
- }
1082
- async function* Jt(e, s) {
1083
- if (!e.body)
1084
- return;
1085
- let t = Ft(e.body), n, o = t.getReader(), r;
1086
- for (; ; ) {
1087
- if (s && s.aborted)
1088
- return o.cancel();
1089
- if (n = await o.read(), n.done)
1090
- return;
1091
- if (!n.value) {
1092
- r && (yield r), r = void 0;
1093
- continue;
1094
- }
1095
- let [i, a] = Ht(n.value) || [];
1096
- i === "data" ? (r ||= {}, r[i] = r[i] ? r[i] + `
1097
- ` + a : a) : i === "event" ? (r ||= {}, r[i] = a) : i === "id" ? (r ||= {}, r[i] = String(+a) === a ? +a : a) : i === "retry" && (r ||= {}, r[i] = +a || void 0);
1098
- }
1099
- }
1100
- async function Wt(e, s) {
1101
- let t = new Request(e, s);
1102
- Te(t.headers, "Accept", "text/event-stream"), Te(t.headers, "Content-Type", "application/json");
1103
- let n = await fetch(t);
1104
- if (!n.ok)
1105
- throw n;
1106
- return Jt(n, t.signal);
1107
- }
1108
- async function Zt() {
1109
- let {
1110
- event_callbacks: e,
1111
- unclosed_events: s,
1112
- pending_stream_messages: t,
1113
- stream_status: n,
1114
- config: o,
1115
- jwt: r
1116
- } = this;
1117
- const i = this;
1118
- if (!o)
1119
- throw new Error("Could not resolve app config");
1120
- n.open = !0;
1121
- let a = null, u = new URLSearchParams({
1122
- session_hash: this.session_hash
1123
- }).toString(), l = new URL(`${o.root}${this.api_prefix}/${xe}?${u}`);
1124
- if (r && l.searchParams.set("__sign", r), a = this.stream(l), !a) {
1125
- console.warn("Cannot connect to SSE endpoint: " + l.toString());
1126
- return;
1127
- }
1128
- a.onmessage = async function(p) {
1129
- let c = JSON.parse(p.data);
1130
- if (c.msg === "close_stream") {
1131
- de(n, i.abort_controller);
1132
- return;
1133
- }
1134
- const g = c.event_id;
1135
- if (!g)
1136
- await Promise.all(
1137
- Object.keys(e).map(
1138
- (w) => e[w](c)
1139
- )
1140
- );
1141
- else if (e[g] && o) {
1142
- c.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes(
1143
- o.protocol
1144
- ) && s.delete(g);
1145
- let w = e[g];
1146
- typeof window < "u" && typeof document < "u" ? setTimeout(w, 0, c) : w(c);
1147
- } else
1148
- t[g] || (t[g] = []), t[g].push(c);
1149
- }, a.onerror = async function(p) {
1150
- console.error(p), await Promise.all(
1151
- Object.keys(e).map(
1152
- (c) => e[c]({
1153
- msg: "broken_connection",
1154
- message: N
1155
- })
1156
- )
1157
- );
1158
- };
1159
- }
1160
- function de(e, s) {
1161
- e && (e.open = !1, s?.abort());
1162
- }
1163
- function Kt(e, s, t) {
1164
- !e[s] ? (e[s] = [], t.data.forEach((o, r) => {
1165
- e[s][r] = o;
1166
- })) : t.data.forEach((o, r) => {
1167
- let i = Vt(e[s][r], o);
1168
- e[s][r] = i, t.data[r] = i;
1169
- });
1170
- }
1171
- function Vt(e, s) {
1172
- return s.forEach(([t, n, o]) => {
1173
- e = Yt(e, n, t, o);
1174
- }), e;
1175
- }
1176
- function Yt(e, s, t, n) {
1177
- if (s.length === 0) {
1178
- if (t === "replace")
1179
- return n;
1180
- if (t === "append")
1181
- return e + n;
1182
- throw new Error(`Unsupported action: ${t}`);
1183
- }
1184
- let o = e;
1185
- for (let i = 0; i < s.length - 1; i++)
1186
- o = o[s[i]];
1187
- const r = s[s.length - 1];
1188
- switch (t) {
1189
- case "replace":
1190
- o[r] = n;
1191
- break;
1192
- case "append":
1193
- o[r] += n;
1194
- break;
1195
- case "add":
1196
- Array.isArray(o) ? o.splice(Number(r), 0, n) : o[r] = n;
1197
- break;
1198
- case "delete":
1199
- Array.isArray(o) ? o.splice(Number(r), 1) : delete o[r];
1200
- break;
1201
- default:
1202
- throw new Error(`Unknown action: ${t}`);
1203
- }
1204
- return e;
1205
- }
1206
- function Qt(e, s = {}) {
1207
- const t = {
1208
- close: () => {
1209
- console.warn("Method not implemented.");
1210
- },
1211
- onerror: null,
1212
- onmessage: null,
1213
- onopen: null,
1214
- readyState: 0,
1215
- url: e.toString(),
1216
- withCredentials: !1,
1217
- CONNECTING: 0,
1218
- OPEN: 1,
1219
- CLOSED: 2,
1220
- addEventListener: () => {
1221
- throw new Error("Method not implemented.");
1222
- },
1223
- dispatchEvent: () => {
1224
- throw new Error("Method not implemented.");
1225
- },
1226
- removeEventListener: () => {
1227
- throw new Error("Method not implemented.");
1228
- }
1229
- };
1230
- return Wt(e, s).then(async (n) => {
1231
- t.readyState = t.OPEN;
1232
- try {
1233
- for await (const o of n)
1234
- t.onmessage && t.onmessage(o);
1235
- t.readyState = t.CLOSED;
1236
- } catch (o) {
1237
- t.onerror && t.onerror(o), t.readyState = t.CLOSED;
1238
- }
1239
- }).catch((n) => {
1240
- console.error(n), t.onerror && t.onerror(n), t.readyState = t.CLOSED;
1241
- }), t;
1242
- }
1243
- function Xt(e, s = {}, t, n, o, r) {
1244
- try {
1245
- let i = function(h) {
1246
- (o || Me[h.type]) && p(h);
1247
- }, a = function() {
1248
- for (me = !0; M.length > 0; )
1249
- M.shift()({
1250
- value: void 0,
1251
- done: !0
1252
- });
1253
- }, u = function(h) {
1254
- M.length > 0 ? M.shift()(h) : ie.push(h);
1255
- }, l = function(h) {
1256
- u(es(h)), a();
1257
- }, p = function(h) {
1258
- u({ value: h, done: !1 });
1259
- }, c = function() {
1260
- return ie.length > 0 ? Promise.resolve(ie.shift()) : me ? Promise.resolve({ value: void 0, done: !0 }) : new Promise((h) => M.push(h));
1261
- };
1262
- const { token: g } = this.options, {
1263
- fetch: w,
1264
- app_reference: C,
1265
- config: f,
1266
- session_hash: m,
1267
- api_info: H,
1268
- api_map: z,
1269
- stream_status: X,
1270
- pending_stream_messages: ee,
1271
- pending_diff_streams: te,
1272
- event_callbacks: se,
1273
- unclosed_events: ze,
1274
- post_data: ne,
1275
- options: J,
1276
- api_prefix: A
1277
- } = this, he = r || { "x-gradio-user": "api" }, Be = this;
1278
- if (!H) throw new Error("No API found");
1279
- if (!f) throw new Error("Could not resolve app config");
1280
- let { fn_index: d, endpoint_info: fe, dependency: B } = ts(
1281
- H,
1282
- e,
1283
- z,
1284
- f
1285
- ), Ge = bt(s, fe), I, T = f.protocol ?? "ws";
1286
- if (T === "ws")
1287
- throw new Error("WebSocket protocol is not supported in this version");
1288
- let U = "", ss = () => U;
1289
- const _ = typeof e == "number" ? "/predict" : e;
1290
- let W, v = null, x = !1, _e = {}, G = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "";
1291
- const Me = J?.events?.reduce(
1292
- (h, R) => (h[R] = !0, h),
1293
- {}
1294
- ) || {};
1295
- async function Fe() {
1296
- let h = {}, R = {};
1297
- h = { event_id: v }, R = { event_id: v, session_hash: m, fn_index: d };
1298
- try {
1299
- if (!f)
1300
- throw new Error("Could not resolve app config");
1301
- "event_id" in R && await w(`${f.root}${A}/${it}`, {
1302
- headers: { "Content-Type": "application/json" },
1303
- method: "POST",
1304
- body: JSON.stringify(R)
1305
- }), await w(`${f.root}${A}/${nt}`, {
1306
- headers: { "Content-Type": "application/json" },
1307
- method: "POST",
1308
- body: JSON.stringify(h)
1309
- });
1310
- } catch {
1311
- console.warn(
1312
- "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1313
- );
1314
- }
1315
- }
1316
- const He = async (h) => {
1317
- await this._resolve_heartbeat(h);
1318
- };
1319
- async function ge(h) {
1320
- if (!f) return;
1321
- let R = h.render_id;
1322
- f.components = [
1323
- ...f.components.filter((E) => E.props.rendered_in !== R),
1324
- ...h.components
1325
- ], f.dependencies = [
1326
- ...f.dependencies.filter((E) => E.rendered_in !== R),
1327
- ...h.dependencies
1328
- ];
1329
- const Z = f.components.some((E) => E.type === "state"), y = f.dependencies.some(
1330
- (E) => E.targets.some((j) => j[1] === "unload")
1331
- );
1332
- f.connect_heartbeat = Z || y, await He(f), i({
1333
- type: "render",
1334
- data: h,
1335
- endpoint: _,
1336
- fn_index: d
1337
- });
1338
- }
1339
- const Je = this.handle_blob(
1340
- f.root,
1341
- Ge,
1342
- fe
1343
- ).then(async (h) => {
1344
- if (W = {
1345
- data: V(
1346
- h,
1347
- B,
1348
- f.components,
1349
- "input",
1350
- !0
1351
- ) || [],
1352
- event_data: t,
1353
- fn_index: d,
1354
- trigger_id: n
1355
- }, Tt(d, f))
1356
- i({
1357
- type: "status",
1358
- endpoint: _,
1359
- stage: "pending",
1360
- queue: !1,
1361
- fn_index: d,
1362
- time: /* @__PURE__ */ new Date()
1363
- }), ne(
1364
- `${f.root}${A}/run${_.startsWith("/") ? _ : `/${_}`}${G ? "?" + G : ""}`,
1365
- {
1366
- ...W,
1367
- session_hash: m
1368
- },
1369
- he
1370
- ).then(async ([y, E]) => {
1371
- const j = y.data;
1372
- if (E == 200)
1373
- i({
1374
- type: "data",
1375
- endpoint: _,
1376
- fn_index: d,
1377
- data: V(
1378
- j,
1379
- B,
1380
- f.components,
1381
- "output",
1382
- J.with_null_state
1383
- ),
1384
- time: /* @__PURE__ */ new Date(),
1385
- event_data: t,
1386
- trigger_id: n
1387
- }), y.render_config && await ge(y.render_config), i({
1388
- type: "status",
1389
- endpoint: _,
1390
- fn_index: d,
1391
- stage: "complete",
1392
- eta: y.average_duration,
1393
- queue: !1,
1394
- time: /* @__PURE__ */ new Date()
1395
- });
1396
- else {
1397
- const O = y?.error === N;
1398
- i({
1399
- type: "status",
1400
- stage: "error",
1401
- endpoint: _,
1402
- fn_index: d,
1403
- message: y.error,
1404
- broken: O,
1405
- queue: !1,
1406
- time: /* @__PURE__ */ new Date()
1407
- });
1408
- }
1409
- }).catch((y) => {
1410
- i({
1411
- type: "status",
1412
- stage: "error",
1413
- message: y.message,
1414
- endpoint: _,
1415
- fn_index: d,
1416
- queue: !1,
1417
- time: /* @__PURE__ */ new Date()
1418
- });
1419
- });
1420
- else if (T == "sse") {
1421
- i({
1422
- type: "status",
1423
- stage: "pending",
1424
- queue: !0,
1425
- endpoint: _,
1426
- fn_index: d,
1427
- time: /* @__PURE__ */ new Date()
1428
- });
1429
- var Z = new URLSearchParams({
1430
- fn_index: d.toString(),
1431
- session_hash: m
1432
- }).toString();
1433
- let y = new URL(
1434
- `${f.root}${A}/${xe}?${G ? G + "&" : ""}${Z}`
1435
- );
1436
- if (this.jwt && y.searchParams.set("__sign", this.jwt), I = this.stream(y), !I)
1437
- return Promise.reject(
1438
- new Error("Cannot connect to SSE endpoint: " + y.toString())
1439
- );
1440
- I.onmessage = async function(E) {
1441
- const j = JSON.parse(E.data), { type: O, status: D, data: b } = Ee(
1442
- j,
1443
- _e[d]
1444
- );
1445
- if (O === "update" && D && !x)
1446
- i({
1447
- type: "status",
1448
- endpoint: _,
1449
- fn_index: d,
1450
- time: /* @__PURE__ */ new Date(),
1451
- ...D
1452
- }), D.stage === "error" && (I?.close(), a());
1453
- else if (O === "data") {
1454
- let [q, P] = await ne(
1455
- `${f.root}${A}/queue/data`,
1456
- {
1457
- ...W,
1458
- session_hash: m,
1459
- event_id: v
1460
- }
1461
- );
1462
- P !== 200 && (i({
1463
- type: "status",
1464
- stage: "error",
1465
- message: N,
1466
- queue: !0,
1467
- endpoint: _,
1468
- fn_index: d,
1469
- time: /* @__PURE__ */ new Date()
1470
- }), I?.close(), a());
1471
- } else O === "complete" ? x = D : O === "log" ? i({
1472
- type: "log",
1473
- title: b.title,
1474
- log: b.log,
1475
- level: b.level,
1476
- endpoint: _,
1477
- duration: b.duration,
1478
- visible: b.visible,
1479
- fn_index: d
1480
- }) : (O === "generating" || O === "streaming") && i({
1481
- type: "status",
1482
- time: /* @__PURE__ */ new Date(),
1483
- ...D,
1484
- stage: D?.stage,
1485
- queue: !0,
1486
- endpoint: _,
1487
- fn_index: d
1488
- });
1489
- b && (i({
1490
- type: "data",
1491
- time: /* @__PURE__ */ new Date(),
1492
- data: V(
1493
- b.data,
1494
- B,
1495
- f.components,
1496
- "output",
1497
- J.with_null_state
1498
- ),
1499
- endpoint: _,
1500
- fn_index: d,
1501
- event_data: t,
1502
- trigger_id: n
1503
- }), x && (i({
1504
- type: "status",
1505
- time: /* @__PURE__ */ new Date(),
1506
- ...x,
1507
- stage: D?.stage,
1508
- queue: !0,
1509
- endpoint: _,
1510
- fn_index: d
1511
- }), I?.close(), a()));
1512
- };
1513
- } else if (T == "sse_v1" || T == "sse_v2" || T == "sse_v2.1" || T == "sse_v3") {
1514
- i({
1515
- type: "status",
1516
- stage: "pending",
1517
- queue: !0,
1518
- endpoint: _,
1519
- fn_index: d,
1520
- time: /* @__PURE__ */ new Date()
1521
- });
1522
- let y = "";
1523
- typeof window < "u" && typeof document < "u" && (y = window?.location?.hostname);
1524
- const E = qe(y);
1525
- return (typeof window < "u" && typeof document < "u" && window.parent != window && !!E && window.supports_zerogpu_headers ? xt("zerogpu-headers", E) : Promise.resolve(null)).then((b) => {
1526
- const q = { ...he, ...b || {} };
1527
- return ne(
1528
- `${f.root}${A}/${Ve}?${G}`,
1529
- {
1530
- ...W,
1531
- session_hash: m
1532
- },
1533
- q
1534
- );
1535
- }).then(async ([b, q]) => {
1536
- if (b.event_id && (U = b.event_id), q === 503)
1537
- i({
1538
- type: "status",
1539
- stage: "error",
1540
- message: De,
1541
- queue: !0,
1542
- endpoint: _,
1543
- fn_index: d,
1544
- time: /* @__PURE__ */ new Date(),
1545
- visible: !0
1546
- }), a();
1547
- else if (q === 422)
1548
- i({
1549
- type: "status",
1550
- stage: "error",
1551
- message: b.detail,
1552
- queue: !0,
1553
- endpoint: _,
1554
- fn_index: d,
1555
- code: "validation_error",
1556
- time: /* @__PURE__ */ new Date(),
1557
- visible: !0
1558
- }), a();
1559
- else if (q !== 200) {
1560
- const P = b?.error === N;
1561
- i({
1562
- type: "status",
1563
- stage: "error",
1564
- broken: P,
1565
- message: P ? N : b.detail || b.error,
1566
- queue: !0,
1567
- endpoint: _,
1568
- fn_index: d,
1569
- time: /* @__PURE__ */ new Date(),
1570
- visible: !0
1571
- }), a();
1572
- } else {
1573
- v = b.event_id, U = v;
1574
- let P = async function(oe) {
1575
- try {
1576
- const { type: S, status: $, data: k, original_msg: We } = Ee(
1577
- oe,
1578
- _e[d]
1579
- );
1580
- if (S == "heartbeat")
1581
- return;
1582
- if (S === "update" && $ && !x)
1583
- i({
1584
- type: "status",
1585
- endpoint: _,
1586
- fn_index: d,
1587
- time: /* @__PURE__ */ new Date(),
1588
- original_msg: We,
1589
- ...$
1590
- });
1591
- else if (S === "complete")
1592
- x = $;
1593
- else if (S == "unexpected_error" || S == "broken_connection") {
1594
- console.error("Unexpected error", $?.message);
1595
- const Ze = S === "broken_connection";
1596
- i({
1597
- type: "status",
1598
- stage: "error",
1599
- message: $?.message || "An Unexpected Error Occurred!",
1600
- queue: !0,
1601
- endpoint: _,
1602
- broken: Ze,
1603
- session_not_found: $?.session_not_found,
1604
- fn_index: d,
1605
- time: /* @__PURE__ */ new Date()
1606
- });
1607
- } else if (S === "log") {
1608
- i({
1609
- type: "log",
1610
- title: k.title,
1611
- log: k.log,
1612
- level: k.level,
1613
- endpoint: _,
1614
- duration: k.duration,
1615
- visible: k.visible,
1616
- fn_index: d
1617
- });
1618
- return;
1619
- } else (S === "generating" || S === "streaming") && (i({
1620
- type: "status",
1621
- time: /* @__PURE__ */ new Date(),
1622
- ...$,
1623
- stage: $?.stage,
1624
- queue: !0,
1625
- endpoint: _,
1626
- fn_index: d
1627
- }), k && B.connection !== "stream" && ["sse_v2", "sse_v2.1", "sse_v3"].includes(T) && Kt(te, v, k));
1628
- k && (i({
1629
- type: "data",
1630
- time: /* @__PURE__ */ new Date(),
1631
- data: V(
1632
- k.data,
1633
- B,
1634
- f.components,
1635
- "output",
1636
- J.with_null_state
1637
- ),
1638
- endpoint: _,
1639
- fn_index: d
1640
- }), k.render_config && await ge(k.render_config), x && (i({
1641
- type: "status",
1642
- time: /* @__PURE__ */ new Date(),
1643
- ...x,
1644
- stage: $?.stage,
1645
- queue: !0,
1646
- endpoint: _,
1647
- fn_index: d
1648
- }), a())), ($?.stage === "complete" || $?.stage === "error") && (se[v] && delete se[v], v in te && delete te[v], a());
1649
- } catch (S) {
1650
- console.error("Unexpected client exception", S), i({
1651
- type: "status",
1652
- stage: "error",
1653
- message: "An Unexpected Error Occurred!",
1654
- queue: !0,
1655
- endpoint: _,
1656
- fn_index: d,
1657
- time: /* @__PURE__ */ new Date()
1658
- }), ["sse_v2", "sse_v2.1", "sse_v3"].includes(T) && (de(X, Be.abort_controller), X.open = !1, a());
1659
- }
1660
- };
1661
- v in ee && (ee[v].forEach((oe) => P(oe)), delete ee[v]), se[v] = P, ze.add(v), X.open || await this.open_stream();
1662
- }
1663
- });
1664
- }
1665
- });
1666
- let me = !1;
1667
- const ie = [], M = [], we = {
1668
- [Symbol.asyncIterator]: () => we,
1669
- next: c,
1670
- throw: async (h) => (l(h), c()),
1671
- return: async () => (a(), { value: void 0, done: !0 }),
1672
- cancel: Fe,
1673
- send_chunk: (h) => {
1674
- this.post_data(`${f.root}${A}/stream/${U}`, {
1675
- ...h,
1676
- session_hash: this.session_hash
1677
- });
1678
- },
1679
- close_stream: () => {
1680
- this.post_data(
1681
- `${f.root}${A}/stream/${U}/close`,
1682
- {}
1683
- ), a();
1684
- },
1685
- event_id: () => U,
1686
- wait_for_id: async () => (await Je, v)
1687
- };
1688
- return we;
1689
- } catch (i) {
1690
- throw console.error("Submit function encountered an error:", i), i;
1691
- }
1692
- }
1693
- function es(e) {
1694
- return {
1695
- then: (s, t) => t(e)
1696
- };
1697
- }
1698
- function ts(e, s, t, n) {
1699
- let o, r, i;
1700
- if (typeof s == "number")
1701
- o = s, r = e.unnamed_endpoints[o], i = n.dependencies.find((a) => a.id == s);
1702
- else {
1703
- const a = s.replace(/^\//, "");
1704
- o = t[a], r = e.named_endpoints[s.trim()], i = n.dependencies.find(
1705
- (u) => u.id == t[a]
1706
- );
1707
- }
1708
- if (typeof o != "number")
1709
- throw new Error(
1710
- "There is no endpoint matching that name of fn_index matching that number."
1711
- );
1712
- return { fn_index: o, endpoint_info: r, dependency: i };
1713
- }
1714
- class Y {
1715
- app_reference;
1716
- options;
1717
- deep_link = null;
1718
- config;
1719
- api_prefix = "";
1720
- api_info;
1721
- api_map = {};
1722
- session_hash = Math.random().toString(36).substring(2);
1723
- jwt = !1;
1724
- last_status = {};
1725
- cookies = null;
1726
- // streaming
1727
- stream_status = { open: !1 };
1728
- closed = !1;
1729
- pending_stream_messages = {};
1730
- pending_diff_streams = {};
1731
- event_callbacks = {};
1732
- unclosed_events = /* @__PURE__ */ new Set();
1733
- heartbeat_event = null;
1734
- abort_controller = null;
1735
- stream_instance = null;
1736
- current_payload;
1737
- get_url_config(s = null) {
1738
- if (!this.config)
1739
- throw new Error(L);
1740
- s === null && (s = window.location.href);
1741
- const t = (i) => i.replace(/^\/+|\/+$/g, "");
1742
- let n = t(new URL(this.config.root).pathname), o = t(new URL(s).pathname), r;
1743
- return o.startsWith(n) ? r = t(o.substring(n.length)) : r = "", this.get_page_config(r);
1744
- }
1745
- get_page_config(s) {
1746
- if (!this.config)
1747
- throw new Error(L);
1748
- let t = this.config;
1749
- return s in t.page || (s = ""), {
1750
- ...t,
1751
- current_page: s,
1752
- layout: t.page[s].layout,
1753
- components: t.components.filter(
1754
- (n) => t.page[s].components.includes(n.id)
1755
- ),
1756
- dependencies: this.config.dependencies.filter(
1757
- (n) => t.page[s].dependencies.includes(n.id)
1758
- )
1759
- };
1760
- }
1761
- fetch(s, t) {
1762
- const n = new Headers(t?.headers || {});
1763
- return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((r, i) => {
1764
- n.append(i, r);
1765
- }), fetch(s, { ...t, headers: n });
1766
- }
1767
- stream(s) {
1768
- const t = new Headers();
1769
- return this && this.cookies && t.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((o, r) => {
1770
- t.append(r, o);
1771
- }), this && this.options.token && t.append("Authorization", `Bearer ${this.options.token}`), this.abort_controller = new AbortController(), this.stream_instance = Qt(s.toString(), {
1772
- credentials: this.options.credentials ?? "same-origin",
1773
- headers: t,
1774
- signal: this.abort_controller.signal
1775
- }), this.stream_instance;
1776
- }
1777
- view_api;
1778
- upload_files;
1779
- upload;
1780
- handle_blob;
1781
- post_data;
1782
- submit;
1783
- predict;
1784
- open_stream;
1785
- resolve_config;
1786
- resolve_cookies;
1787
- constructor(s, t = { events: ["data"] }) {
1788
- this.app_reference = s, this.deep_link = t.query_params?.deep_link || null, t.events || (t.events = ["data"]), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = vt.bind(this), this.upload_files = Et.bind(this), this.handle_blob = Dt.bind(this), this.post_data = Ct.bind(this), this.submit = Xt.bind(this), this.predict = Pt.bind(this), this.open_stream = Zt.bind(this), this.resolve_config = ft.bind(this), this.resolve_cookies = _t.bind(this), this.upload = Ot.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this);
1789
- }
1790
- async init() {
1791
- Gt(), this.options.auth && await this.resolve_cookies(), await this._resolve_config().then(
1792
- ({ config: s }) => this._resolve_heartbeat(s)
1793
- ), this.api_info = await this.view_api(), this.api_map = ht(this.config?.dependencies || []);
1794
- }
1795
- async _resolve_heartbeat(s) {
1796
- if (s && (this.config = s, this.api_prefix = s.api_prefix || "", this.config && this.config.connect_heartbeat && this.config.space_id && this.options.token && (this.jwt = await be(
1797
- this.config.space_id,
1798
- this.options.token,
1799
- this.cookies
1800
- ))), s.space_id && this.options.token && (this.jwt = await be(s.space_id, this.options.token)), this.config && this.config.connect_heartbeat) {
1801
- const t = new URL(
1802
- `${this.config.root}${this.api_prefix}/${tt}/${this.session_hash}`
1803
- );
1804
- this.jwt && t.searchParams.set("__sign", this.jwt), this.heartbeat_event || (this.heartbeat_event = this.stream(t));
1805
- }
1806
- }
1807
- static async connect(s, t = {
1808
- events: ["data"]
1809
- }) {
1810
- const n = new this(s, t);
1811
- return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n;
1812
- }
1813
- async reconnect() {
1814
- const s = new URL(
1815
- `${this.config.root}${this.api_prefix}/${ot}`
1816
- );
1817
- let t;
1818
- try {
1819
- const n = await this.fetch(s);
1820
- if (!n.ok)
1821
- throw new Error();
1822
- t = (await n.json()).app_id;
1823
- } catch {
1824
- return "broken";
1825
- }
1826
- return t !== this.config.app_id ? "changed" : "connected";
1827
- }
1828
- close() {
1829
- this.closed = !0, de(this.stream_status, this.abort_controller);
1830
- }
1831
- set_current_payload(s) {
1832
- this.current_payload = s;
1833
- }
1834
- static async duplicate(s, t = {
1835
- events: ["data"]
1836
- }) {
1837
- return qt(s, t);
1838
- }
1839
- async _resolve_config() {
1840
- const { http_protocol: s, host: t, space_id: n } = await pe(
1841
- this.app_reference,
1842
- this.options.token
1843
- ), { status_callback: o } = this.options;
1844
- n && o && await je(n, o);
1845
- let r;
1846
- try {
1847
- let i = `${s}//${t}`;
1848
- if (r = await this.resolve_config(i), !r)
1849
- throw new Error(L);
1850
- return this.config_success(r);
1851
- } catch (i) {
1852
- if (n && o)
1853
- F(
1854
- n,
1855
- le.test(n) ? "space_name" : "subdomain",
1856
- this.handle_space_success
1857
- );
1858
- else
1859
- throw o && o({
1860
- status: "error",
1861
- message: "Could not load this space.",
1862
- load_status: "error",
1863
- detail: "NOT_FOUND"
1864
- }), Error(i);
1865
- }
1866
- }
1867
- async config_success(s) {
1868
- if (this.config = s, this.api_prefix = s.api_prefix || "", this.config.auth_required)
1869
- return this.prepare_return_obj();
1870
- try {
1871
- this.api_info = await this.view_api();
1872
- } catch (t) {
1873
- console.error(at + t.message);
1874
- }
1875
- return this.prepare_return_obj();
1876
- }
1877
- async handle_space_success(s) {
1878
- if (!this)
1879
- throw new Error(L);
1880
- const { status_callback: t } = this.options;
1881
- if (t && t(s), s.status === "running")
1882
- try {
1883
- if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config)
1884
- throw new Error(L);
1885
- return await this.config_success(this.config);
1886
- } catch (n) {
1887
- throw t && t({
1888
- status: "error",
1889
- message: "Could not load this space.",
1890
- load_status: "error",
1891
- detail: "NOT_FOUND"
1892
- }), n;
1893
- }
1894
- }
1895
- async component_server(s, t, n) {
1896
- if (!this.config)
1897
- throw new Error(L);
1898
- const o = {}, { token: r } = this.options, { session_hash: i } = this;
1899
- r && (o.Authorization = `Bearer ${this.options.token}`);
1900
- let a, u = this.config.components.find(
1901
- (p) => p.id === s
1902
- );
1903
- u?.props?.root_url ? a = u.props.root_url : a = this.config.root;
1904
- let l;
1905
- if (typeof n == "object" && n !== null && "binary" in n) {
1906
- const p = n;
1907
- l = new FormData();
1908
- for (const c in p.data)
1909
- c !== "binary" && l.append(c, p.data[c]);
1910
- l.set("component_id", s.toString()), l.set("fn_name", t), l.set("session_hash", i);
1911
- } else
1912
- l = JSON.stringify({
1913
- data: n,
1914
- component_id: s,
1915
- fn_name: t,
1916
- session_hash: i
1917
- }), o["Content-Type"] = "application/json";
1918
- r && (o.Authorization = `Bearer ${r}`);
1919
- try {
1920
- const p = await this.fetch(
1921
- `${a}${this.api_prefix}/${st}/`,
1922
- {
1923
- method: "POST",
1924
- body: l,
1925
- headers: o,
1926
- credentials: this.options.credentials ?? "same-origin"
1927
- }
1928
- );
1929
- if (!p.ok)
1930
- throw new Error(
1931
- "Could not connect to component server: " + p.statusText
1932
- );
1933
- return await p.json();
1934
- } catch (p) {
1935
- console.warn(p);
1936
- }
1937
- }
1938
- set_cookies(s) {
1939
- this.cookies = Pe(s).join("; ");
1940
- }
1941
- prepare_return_obj() {
1942
- return {
1943
- config: this.config,
1944
- predict: this.predict,
1945
- submit: this.submit,
1946
- view_api: this.view_api,
1947
- component_server: this.component_server
1948
- };
1949
- }
1950
- }
1951
- async function os(e, s = {
1952
- events: ["data"]
1953
- }) {
1954
- return await Y.connect(e, s);
1955
- }
1956
- async function rs(e, s) {
1957
- return await Y.duplicate(e, s);
1958
- }
1959
- export {
1960
- Y as Client,
1961
- Q as FileData,
1962
- lt as MISSING_CREDENTIALS_MSG,
1963
- os as client,
1964
- rs as duplicate,
1965
- is as handle_file,
1966
- Pt as predict,
1967
- ns as prepare_files,
1968
- Xt as submit,
1969
- Ot as upload,
1970
- Et as upload_files
1717
+ return { then: (t, n) => n(e) };
1718
+ }
1719
+ function Bt(e, t, n, r) {
1720
+ let i, a, o;
1721
+ if (typeof t == "number") i = t, a = e.unnamed_endpoints[i], o = r.dependencies.find((e) => e.id == t);
1722
+ else {
1723
+ let s = t.replace(/^\//, "");
1724
+ i = n[s], a = e.named_endpoints[t.trim()] ?? e.named_endpoints[`/${s}`], o = r.dependencies.find((e) => e.id == n[s]);
1725
+ }
1726
+ if (typeof i != "number" || !o) {
1727
+ let e = r.dependencies.filter((e) => e.api_name).map((e) => `"/${e.api_name}"`).join(", ");
1728
+ throw Error(`No endpoint matching ${JSON.stringify(t)} was found. ` + (e ? `Valid named endpoints are: ${e}. ` : "This app exposes no named endpoints. ") + "An fn_index (number) of an existing dependency can also be used.");
1729
+ }
1730
+ return {
1731
+ fn_index: i,
1732
+ endpoint_info: a,
1733
+ dependency: o
1734
+ };
1735
+ }
1736
+ //#endregion
1737
+ //#region src/client.ts
1738
+ var $ = class {
1739
+ app_reference;
1740
+ options;
1741
+ deep_link = null;
1742
+ config;
1743
+ api_prefix = "";
1744
+ api_info;
1745
+ api_map = {};
1746
+ session_hash = Math.random().toString(36).substring(2);
1747
+ jwt = !1;
1748
+ last_status = {};
1749
+ cookies = null;
1750
+ stream_status = { open: !1 };
1751
+ closed = !1;
1752
+ pending_stream_messages = {};
1753
+ pending_diff_streams = {};
1754
+ event_callbacks = {};
1755
+ unclosed_events = /* @__PURE__ */ new Set();
1756
+ heartbeat_event = null;
1757
+ abort_controller = null;
1758
+ stream_instance = null;
1759
+ current_payload;
1760
+ get_url_config(e = null) {
1761
+ if (!this.config) throw Error(b);
1762
+ e === null && (e = window.location.href);
1763
+ let t = (e) => e.replace(/^\/+|\/+$/g, ""), n = t(new URL(this.config.root).pathname), r = t(new URL(e).pathname), i;
1764
+ return i = r.startsWith(n) ? t(r.substring(n.length)) : "", this.get_page_config(i);
1765
+ }
1766
+ get_page_config(e) {
1767
+ if (!this.config) throw Error(b);
1768
+ let t = this.config;
1769
+ return e in t.page || (e = ""), {
1770
+ ...t,
1771
+ current_page: e,
1772
+ layout: t.page[e].layout,
1773
+ components: t.components.filter((n) => t.page[e].components.includes(n.id)),
1774
+ dependencies: this.config.dependencies.filter((n) => t.page[e].dependencies.includes(n.id))
1775
+ };
1776
+ }
1777
+ fetch(e, t) {
1778
+ let n = new Headers(t?.headers || {});
1779
+ return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => {
1780
+ n.append(t, e);
1781
+ }), fetch(e, {
1782
+ ...t,
1783
+ headers: n
1784
+ });
1785
+ }
1786
+ stream(e) {
1787
+ let t = new Headers();
1788
+ return this && this.cookies && t.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, n) => {
1789
+ t.append(n, e);
1790
+ }), this && this.options.token && t.append("Authorization", `Bearer ${this.options.token}`), this.abort_controller = new AbortController(), this.stream_instance = it(e.toString(), {
1791
+ credentials: this.options.credentials ?? "same-origin",
1792
+ headers: t,
1793
+ signal: this.abort_controller.signal
1794
+ }), this.stream_instance;
1795
+ }
1796
+ view_api;
1797
+ upload_files;
1798
+ upload;
1799
+ handle_blob;
1800
+ post_data;
1801
+ submit;
1802
+ predict;
1803
+ open_stream;
1804
+ resolve_config;
1805
+ resolve_cookies;
1806
+ constructor(e, t = { events: ["data"] }) {
1807
+ this.app_reference = e, this.deep_link = t.query_params?.deep_link || null, t.events ||= ["data"], k(t), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = be.bind(this), this.upload_files = z.bind(this), this.handle_blob = Oe.bind(this), this.post_data = Me.bind(this), this.submit = Rt.bind(this), this.predict = Ne.bind(this), this.open_stream = $e.bind(this), this.resolve_config = j.bind(this), this.resolve_cookies = N.bind(this), this.upload = H.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this);
1808
+ }
1809
+ async init() {
1810
+ Ke(), this.options.auth && await this.resolve_cookies(), await this._resolve_config().then((e) => e?.config && this._resolve_heartbeat(e.config));
1811
+ try {
1812
+ this.api_info = await this.view_api();
1813
+ } catch (e) {
1814
+ console.error(e.message);
1815
+ }
1816
+ this.api_map = fe(this.config?.dependencies || []);
1817
+ }
1818
+ async _resolve_heartbeat(e) {
1819
+ if (e && (this.config = e, this.api_prefix = e.api_prefix || "", this.config && this.config.connect_heartbeat && this.config.space_id && this.options.token && (this.jwt = await de(this.config.space_id, this.options.token, this.cookies))), e.space_id && this.options.token && (this.jwt = await de(e.space_id, this.options.token)), this.config && this.config.connect_heartbeat) {
1820
+ let e = new URL(`${this.config.root}${this.api_prefix}/${_}/${this.session_hash}`);
1821
+ this.jwt && e.searchParams.set("__sign", this.jwt), this.heartbeat_event ||= this.stream(e);
1822
+ }
1823
+ }
1824
+ static async connect(e, t = { events: ["data"] }) {
1825
+ let n = new this(e, t);
1826
+ return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n;
1827
+ }
1828
+ async reconnect() {
1829
+ let e = new URL(`${this.config.root}${this.api_prefix}/${v}`), t;
1830
+ try {
1831
+ let n = await this.fetch(e);
1832
+ if (!n.ok) throw Error();
1833
+ t = (await n.json()).app_id;
1834
+ } catch {
1835
+ return "broken";
1836
+ }
1837
+ return t === this.config.app_id ? "connected" : "changed";
1838
+ }
1839
+ close() {
1840
+ this.closed = !0, et(this.stream_status, this.abort_controller);
1841
+ }
1842
+ async refresh() {
1843
+ if (!this.config) throw Error(b);
1844
+ let e = await this.resolve_config(this.config.root, !1);
1845
+ if (!e) throw Error(b);
1846
+ this.config = e, this.api_prefix = e.api_prefix || "", this.api_map = fe(e.dependencies || []);
1847
+ try {
1848
+ this.api_info = await this.view_api();
1849
+ } catch (e) {
1850
+ console.error(S + e.message);
1851
+ }
1852
+ return this.get_url_config();
1853
+ }
1854
+ set_current_payload(e) {
1855
+ this.current_payload = e;
1856
+ }
1857
+ static async duplicate(e, t = { events: ["data"] }) {
1858
+ return Be(e, t);
1859
+ }
1860
+ async _resolve_config() {
1861
+ let { http_protocol: e, host: t, space_id: n } = await R(this.app_reference, this.options.token), { status_callback: r } = this.options;
1862
+ n && r && await Pe(n, r);
1863
+ let i;
1864
+ try {
1865
+ let n = `${e}//${t}`;
1866
+ if (i = await this.resolve_config(n), !i) throw Error(b);
1867
+ return this.config_success(i);
1868
+ } catch (e) {
1869
+ if (n && r) K(n, L.test(n) ? "space_name" : "subdomain", this.handle_space_success);
1870
+ else throw r && r({
1871
+ status: "error",
1872
+ message: "Could not load this space.",
1873
+ load_status: "error",
1874
+ detail: "NOT_FOUND"
1875
+ }), e instanceof Error ? e : Error(String(e));
1876
+ }
1877
+ }
1878
+ async config_success(e) {
1879
+ if (this.config = e, this.api_prefix = e.api_prefix || "", e.run_history === !1 && At({
1880
+ app_id: e.app_id,
1881
+ username: e.username
1882
+ }), this.config.auth_required) return this.prepare_return_obj();
1883
+ try {
1884
+ this.api_info = await this.view_api();
1885
+ } catch (e) {
1886
+ console.error(S + e.message);
1887
+ }
1888
+ return this.prepare_return_obj();
1889
+ }
1890
+ async handle_space_success(e) {
1891
+ if (!this) throw Error(b);
1892
+ let { status_callback: t } = this.options;
1893
+ if (t && t(e), e.status === "running") try {
1894
+ if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config) throw Error(b);
1895
+ return await this.config_success(this.config);
1896
+ } catch (e) {
1897
+ throw t && t({
1898
+ status: "error",
1899
+ message: "Could not load this space.",
1900
+ load_status: "error",
1901
+ detail: "NOT_FOUND"
1902
+ }), e;
1903
+ }
1904
+ }
1905
+ async component_server(e, t, n) {
1906
+ if (!this.config) throw Error(b);
1907
+ let r = {}, { token: i } = this.options, { session_hash: a } = this;
1908
+ i && (r.Authorization = `Bearer ${this.options.token}`);
1909
+ let o, s = this.config.components.find((t) => t.id === e);
1910
+ o = s?.props?.root_url ? s.props.root_url : this.config.root;
1911
+ let c;
1912
+ if (typeof n == "object" && n && "binary" in n) {
1913
+ let r = n;
1914
+ c = new FormData();
1915
+ for (let e in r.data) e !== "binary" && c.append(e, r.data[e]);
1916
+ c.set("component_id", e.toString()), c.set("fn_name", t), c.set("session_hash", a);
1917
+ } else c = JSON.stringify({
1918
+ data: n,
1919
+ component_id: e,
1920
+ fn_name: t,
1921
+ session_hash: a
1922
+ }), r["Content-Type"] = "application/json";
1923
+ i && (r.Authorization = `Bearer ${i}`);
1924
+ try {
1925
+ let e = await this.fetch(`${o}${this.api_prefix}/${te}/`, {
1926
+ method: "POST",
1927
+ body: c,
1928
+ headers: r,
1929
+ credentials: this.options.credentials ?? "same-origin"
1930
+ });
1931
+ if (!e.ok) throw Error("Could not connect to component server: " + e.statusText);
1932
+ return await e.json();
1933
+ } catch (e) {
1934
+ console.warn(e);
1935
+ }
1936
+ }
1937
+ set_cookies(e) {
1938
+ this.cookies = I(e).join("; ");
1939
+ }
1940
+ prepare_return_obj() {
1941
+ return {
1942
+ config: this.config,
1943
+ predict: this.predict,
1944
+ submit: this.submit,
1945
+ view_api: this.view_api,
1946
+ component_server: this.component_server
1947
+ };
1948
+ }
1971
1949
  };
1950
+ async function Vt(e, t = { events: ["data"] }) {
1951
+ return await $.connect(e, t);
1952
+ }
1953
+ async function Ht(e, t) {
1954
+ return await $.duplicate(e, t);
1955
+ }
1956
+ //#endregion
1957
+ export { $ as Client, U as FileData, ae as MISSING_CREDENTIALS_MSG, At as clear_run_history, Vt as client, Nt as consume_run_history_replay, jt as delete_run_history, Ht as duplicate, De as handle_file, Lt as on_run_history_change, Ne as predict, xe as prepare_files, kt as read_run_history, lt as run_history_url, Mt as stage_run_history_replay, Rt as submit, o as t, H as upload, z as upload_files };