@gradio/client 1.15.4 → 1.15.5

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