diff --git "a/browser.js" "b/browser.js" new file mode 100644--- /dev/null +++ "b/browser.js" @@ -0,0 +1,3278 @@ +//#region \0rolldown/runtime.js +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) => { + 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, { + get: ((e) => i[e]).bind(null, d), + enumerable: !(s = n(i, d)) || s.enumerable + }); + return e; +}, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", { + value: n, + enumerable: !0 +}) : a, n)), l = class { + type; + command; + meta; + fileData; + constructor(e, t) { + this.type = "command", this.command = e, this.meta = t; + } +}, u = typeof process < "u" && process.versions && process.versions.node; +function d(e, t, n) { + for (; n.length > 1;) { + let t = n.shift(); + if (typeof t == "string" || typeof t == "number") e = e[t]; + else throw Error("Invalid key type"); + } + let r = n.shift(); + if (typeof r == "string" || typeof r == "number") e[r] = t; + else throw Error("Invalid key type"); +} +async function f(e, t = void 0, n = [], r = !1, i = void 0) { + if (Array.isArray(e)) { + let a = []; + return await Promise.all(e.map(async (o, s) => { + let c = n.slice(); + c.push(String(s)); + let l = await f(e[s], r ? i?.parameters[s]?.component || void 0 : t, c, !1, i); + a = a.concat(l); + })), a; + } else if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob) return [{ + path: n, + blob: e instanceof Blob ? e : new Blob([e]), + type: t + }]; + else if (typeof e == "object" && e) { + let t = []; + for (let r of Object.keys(e)) { + let a = [...n, r], o = e[r]; + t = t.concat(await f(o, void 0, a, !1, i)); + } + return t; + } + return []; +} +function p(e, t) { + let n = t?.dependencies?.find((t) => t.id == e)?.queue; + return n == null ? !t.enable_queue : !n; +} +function m(e, t) { + return new Promise((n, r) => { + let i = new MessageChannel(); + i.port1.onmessage = (({ data: e }) => { + i.port1.close(), n(e); + }), window.parent.postMessage(e, t, [i.port2]); + }); +} +function h(e) { + if (typeof e == "string") { + if (e.startsWith("http://") || e.startsWith("https://")) return { + path: e, + url: e, + orig_name: e.split("/").pop() ?? "unknown", + meta: { _type: "gradio.FileData" } + }; + if (u) return new l("upload_file", { + path: e, + name: e, + orig_path: e + }); + } else if (typeof File < "u" && e instanceof File) return e; + else if (globalThis.Buffer && e instanceof globalThis.Buffer) return new Blob([e]); + else if (e instanceof Blob) return e; + throw Error("Invalid input: must be a URL, File, Blob, or Buffer object."); +} +function g(e, t, n, r, i = !1) { + if (r === "input" && !i) throw Error("Invalid code path. Cannot skip state inputs for input."); + if (r === "output" && i) return e; + let a = [], o = 0, s = r === "input" ? t.inputs : t.outputs; + for (let t = 0; t < s.length; t++) { + let r = s[t]; + if (n.find((e) => e.id === r)?.type === "state") { + if (i) if (e.length === s.length) { + let t = e[o]; + a.push(t), o++; + } else a.push(null); + else { + o++; + continue; + } + continue; + } else { + let t = e[o]; + a.push(t), o++; + } + } + return a; +} +var _ = [ + "/file=", + "/file/", + "/stream/", + "/proxy=" +]; +function v(e, t, n, r) { + if (!r || typeof e != "object" || !e) return; + let i = r, a = new URL(t), o = a.pathname.replace(/\/+$/, ""), s = n ? `/${n.replace(/^\/+|\/+$/g, "")}` : "", c = new Set([`${o}${s}`, s]); + s || (c.add(`${o}/gradio_api`), c.add("/gradio_api")); + function l(e) { + if (typeof e != "object" || !e) return; + let t = e; + if (t.meta?._type === "gradio.FileData" && typeof t.url == "string") { + let e = new URL(t.url, `${a.toString().replace(/\/$/, "")}/`), n = [...c].some((t) => _.some((n) => e.pathname.startsWith(`${t}${n}`))); + (e.protocol === "http:" || e.protocol === "https:") && e.origin === a.origin && n && (e.searchParams.set("__sign", i), t.url = e.toString()); + } + for (let e of Object.values(t)) l(e); + } + l(e); +} +function y(e, t) { + for (let n of e.components || []) v(n.props?.value, e.root, e.api_prefix || "", t); +} +//#endregion +//#region src/helpers/zerogpu.ts +var b = "supports-zerogpu-headers", x = !1; +function S() { + return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function"; +} +function C(e) { + return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null; +} +function w(e, t, n) { + let r, i = new Promise((e) => { + r = setTimeout(() => e(n), t); + }); + return Promise.race([e, i]).finally(() => clearTimeout(r)); +} +function ee() { + if (typeof window > "u" || typeof document > "u") return Promise.resolve(null); + let e = C(window.location.hostname); + return window.parent == window || !e || !window.supports_zerogpu_headers ? Promise.resolve(null) : m("zerogpu-headers", e); +} +function te() { + if (!S() || x) return; + let e = C(window.location.hostname); + window.addEventListener("message", (t) => { + t.data === b && t.origin === e && t.source === window.parent && (window.supports_zerogpu_headers = !0); + }), x = !0, e && window.parent !== window && window.parent.postMessage(b, e); +} +//#endregion +//#region src/helpers/console_forward.ts +var T = "gradio-console", ne = 4096, E = 1e4, D = "[Unserializable]", O = 100, k = 1e3, re = [ + "log", + "info", + "warn", + "error", + "debug" +], ie = "https://huggingface.co", ae = /^http:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/; +function oe(e, t) { + return typeof e == "string" ? e === ie || ae.test(e) ? !0 : typeof t == "string" && t.includes(".dev.") ? e === C(t) : !1 : !1; +} +function A(e, t = {}) { + try { + let t = e.parent; + if (!t || t === e) return null; + } catch { + return null; + } + let n = de(), r = "", i = null; + f(t); + let a = !0, o = !1, s = 0, c = 0, l = !1, u = null, d = []; + function f(e) { + !r && typeof e.gradio_version == "string" && (r = e.gradio_version), typeof e.untrack == "function" && (i = e.untrack); + } + function p(e) { + if (!(o || !a)) { + o = !0; + try { + e(); + } catch {} finally { + o = !1; + } + } + } + function m(e, t) { + p(() => { + let n = Date.now(), r = i ? i(t) : t(), a = { + seq: ++s, + ts: n, + level: e, + text: j(r.text) + }; + typeof r.stack == "string" && (a.stack = j(r.stack)), d.push(a), d.length > 100 && (c += d.length - 100, d.splice(0, d.length - 100)); + }); + } + function h(t) { + p(() => { + let i = t?.data; + if (typeof i != "object" || !i || i.protocol !== "gradio-console" || i.type !== "get") return; + let a = e.parent; + if (!a || t.source !== a) return; + let o = t.origin; + if (!oe(o, e.location.hostname)) return; + l = !0, u !== null && (clearTimeout(u), u = null), b(); + let s = { + protocol: T, + version: 1, + type: "state", + session_id: n, + gradio_version: r, + dropped: c, + entries: d.slice() + }; + (typeof i.id == "string" || typeof i.id == "number") && (s.id = i.id), a.postMessage(s, o); + }); + } + function g(e) { + let t, n, r = ""; + try { + t = e?.error, n = e?.message, e?.filename && (r = ` (${e.filename}:${e.lineno}:${e.colno})`); + } catch {} + m("exception", () => t == null ? { text: (typeof n == "string" && n ? n : "Unknown error") + r } : fe([t])); + } + function _(e) { + let t; + try { + t = e?.reason; + } catch { + t = void 0; + } + m("rejection", () => fe([t])); + } + let v = /* @__PURE__ */ new Map(), y = !1; + function b() { + y = !0; + for (let t of re) if (!v.has(t)) try { + let n = e.console, r = n[t]; + if (typeof r != "function") continue; + let i = function(...e) { + try { + return r.apply(this, e); + } finally { + y && m(t, () => fe(e)); + } + }; + try { + Object.defineProperty(i, "name", { value: r.name }); + } catch {} + n[t] = i, v.set(t, { + wrapped: i, + original: r + }); + } catch {} + } + function x() { + y = !1; + for (let [t, { wrapped: n, original: r }] of v) try { + e.console[t] === n && (e.console[t] = r, v.delete(t)); + } catch {} + } + function S() { + u !== null || l || !a || (u = setTimeout(() => { + u = null, l || x(); + }, E)); + } + b(); + let C = [], w = [ + ["message", h], + ["error", g], + ["unhandledrejection", _], + ["load", S] + ]; + for (let [t, n] of w) try { + e.addEventListener(t, n), C.push(() => e.removeEventListener(t, n)); + } catch {} + try { + e.document?.readyState === "complete" && S(); + } catch {} + return { + session_id: n, + configure: f, + uninstall() { + a = !1, u !== null && clearTimeout(u), u = null, x(); + for (let e of C) try { + e(); + } catch {} + } + }; +} +var se = Symbol.for("gradio.console_forward"); +function ce(e = {}) { + try { + if (typeof window > "u" || typeof window.addEventListener != "function") return null; + let t = window, n = t[se]; + if (n !== void 0) return n?.configure(e), n; + let r = A(window, e); + return t[se] = r, r; + } catch { + return null; + } +} +function le(e, t) { + try { + if (typeof window > "u" || typeof e != "string" || new URL(e).origin !== window.location.origin) return; + ce({ gradio_version: t }); + } catch {} +} +function ue() { + try { + if (typeof window > "u" || C(window.location.hostname) === null) return; + ce(); + } catch {} +} +function de() { + try { + let e = globalThis.crypto; + if (e && typeof e.randomUUID == "function") return e.randomUUID(); + } catch {} + return Date.now().toString(36) + "-" + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2); +} +function j(e) { + return e.length > 4096 ? e.slice(0, ne) : e; +} +function fe(e) { + let t = [], n, r = !1; + for (let i of e) { + if (!r && i instanceof Error) { + r = !0; + try { + typeof i.stack == "string" && (n = i.stack); + } catch {} + } + t.push(M(i)); + } + let i = { text: j(t.join(" ")) }; + return n !== void 0 && (i.stack = j(n)), i; +} +function M(e) { + try { + return typeof e == "string" ? e : e instanceof Error ? `${e.name}: ${e.message}` : pe(e) ?? String(e); + } catch { + try { + return String(e); + } catch { + return D; + } + } +} +function pe(e) { + let t = 0; + return JSON.stringify(e, (e, n) => { + if (++t > k) return "…"; + if (typeof n != "object" || !n) return n; + if (ArrayBuffer.isView(n) || n instanceof ArrayBuffer) { + let e = "length" in n ? n.length : n.byteLength; + return `[${n.constructor?.name ?? "ArrayBuffer"} length ${e}]`; + } + if (Array.isArray(n) && n.length > O) { + let e = n.slice(0, O); + return e.push(`…[${n.length - O} more]`), e; + } + return n; + }); +} +//#endregion +//#region src/constants.ts +var me = "host", he = "queue/data", ge = "queue/join", N = "upload", _e = "login", P = "config", F = "info", ve = "runtime", I = "sleeptime", L = "heartbeat", R = "component_server", ye = "reset", be = "cancel", xe = "queue/close", Se = "app_id", Ce = "This application is currently busy. Please try again. ", z = "Connection errored out. ", B = "Could not resolve app config. ", we = "Could not get space status. ", Te = "Could not get API info. ", V = "Space metadata could not be loaded. ", Ee = "Invalid URL. A full URL path is required.", H = "Not authorized to access this space. ", U = "Invalid credentials. Could not login. ", De = "Login credentials are required to access this space.", W = "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.`, ke = "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. ", Ae = "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.", G = "File system access is only available in Node.js environments", je = "Root URL not found in client config", Me = "Error uploading file"; +//#endregion +//#region src/helpers/init_helpers.ts +async function Ne(e, t, n) { + try { + return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: { + Authorization: `Bearer ${t}`, + ...n ? { Cookie: n } : {} + } })).json()).token || !1; + } catch { + return !1; + } +} +function Pe(e) { + 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.")); +} +function Fe(e) { + let t = {}; + return e.forEach(({ api_name: e, id: n }) => { + e && (t[e] = n); + }), t; +} +function Ie(e, t, n = !1) { + let r = new URL(t), i = new URL(e, r), a = i.hostname.endsWith(".colab-user-runtimes.internal") || i.hostname.endsWith(".codatalab-user-runtimes.internal"); + return n || a ? new URL(new URL(e, r).pathname, r).toString().replace(/\/$/, "") : i.hostname === r.hostname ? (i.protocol = r.protocol, i.host = r.host, i.toString().replace(/\/$/, "")) : e; +} +async function Le(e, t = !0) { + let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}; + if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") { + 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") { + let t = new URL(He(e, P)); + this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page); + let r = await K(await this.fetch(t, { + headers: n, + credentials: this.options.credentials ?? "same-origin" + }), !!this.options.auth); + r.root = e || r.root, window.gradio_config = { + ...r, + current_page: window.gradio_config.current_page + }; + } + let r = { ...window.gradio_config }; + return r.root = Ie(r.root, location.href, r.is_colab), r; + } else if (e) { + let t = new URL(He(e, P)); + this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page); + let r = await K(await this.fetch(t, { + headers: n, + credentials: this.options.credentials ?? "same-origin" + }), !!this.options.auth); + return r.root ||= e, r; + } + throw Error(B); +} +async function K(e, t) { + if (e?.status === 401 && !t) { + let t = null; + try { + t = await e.json(); + } catch { + throw Error(W); + } + let n = t?.detail?.auth_message; + throw Error(n || "Login credentials are required to access this space."); + } else if (e?.status === 401 && t) throw Error(U); + if (e?.status === 200) { + let t = await e.json(); + return t.dependencies?.forEach((e, t) => { + e.id === void 0 && (e.id = t); + }), t; + } else if (e?.status === 401) throw Error(H); + throw Error(`${B}(received status ${e?.status} when fetching the app config)`); +} +async function Re() { + let { http_protocol: e, host: t } = await Ve(this.app_reference, this.options.token); + try { + if (this.options.auth) { + let n = await q(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials); + n && this.set_cookies(n); + } + } catch (e) { + throw Error(e.message); + } +} +async function q(e, t, n, r, i, a) { + let o = new FormData(); + o.append("username", n?.[0]), o.append("password", n?.[1]); + let s = {}; + i && (s.Authorization = `Bearer ${i}`); + let c = await r(`${e}//${t}/${_e}`, { + headers: s, + method: "POST", + body: o, + credentials: a ?? "same-origin" + }); + if (c.status === 200) return c.headers.get("set-cookie"); + throw c.status === 401 ? Error(U) : Error(V); +} +function ze(e) { + if (e.startsWith("http")) { + let { protocol: t, host: n, pathname: r } = new URL(e); + return { + ws_protocol: t === "https:" ? "wss" : "ws", + http_protocol: t, + host: n + (r === "/" ? "" : r) + }; + } + return { + ws_protocol: "wss", + http_protocol: "https:", + host: new URL(e).host + }; +} +var Be = (e) => { + let t = []; + return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e) => { + let [n, r] = e.split(";")[0].split("="); + n && r && t.push(`${n.trim()}=${r.trim()}`); + }), t; +}, J = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, Y = /.*hf\.space\/{0,1}.*$/; +async function Ve(e, t) { + let n = {}; + t && (n.Authorization = `Bearer ${t}`); + let r = e.trim().replace(/\/$/, ""); + if (J.test(r)) { + let e; + try { + e = await fetch(`https://huggingface.co/api/spaces/${r}/${me}`, { headers: n }); + } catch { + throw Error(V); + } + if (e.status === 401 || e.status === 404) throw Error(Oe(r, e.status)); + let t; + try { + t = (await e.json()).host; + } catch { + throw Error(V); + } + if (!t) throw Error(V); + return { + space_id: r, + ...ze(t) + }; + } + if (Y.test(r)) { + let { ws_protocol: e, http_protocol: t, host: n } = ze(r); + return { + space_id: n.split("/")[0].replace(".hf.space", ""), + ws_protocol: e, + http_protocol: t, + host: n + }; + } + return { + space_id: !1, + ...ze(r) + }; +} +var He = (...e) => { + try { + return e.reduce((e, t) => (e = e.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, e + "/").toString())); + } catch { + throw Error(Ee); + } +}; +function Ue(e, t, n) { + let r = { + named_endpoints: {}, + unnamed_endpoints: {} + }; + return Object.keys(e).forEach((i) => { + (i === "named_endpoints" || i === "unnamed_endpoints") && (r[i] = {}, Object.entries(e[i]).forEach(([e, a]) => { + 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 ? { + generator: !1, + cancel: !1 + } : l?.types; + if (l && Array.isArray(l.inputs) && l.inputs.length !== o.length) { + let e = l.inputs.map((e) => t.components.find((t) => t.id === e)?.type); + try { + e.forEach((e, t) => { + e === "state" && o.splice(t, 0, { + component: "state", + example: null, + parameter_default: null, + parameter_has_default: !0, + parameter_name: null, + hidden: !0 + }); + }); + } catch (e) { + console.error(e); + } + } + let d = (e, t, n, r) => ({ + ...e, + description: Ge(e?.type, n), + type: We(e?.type, t, n, r) || "" + }); + r[i][e] = { + parameters: o.map((e) => d(e, e?.component, e?.serializer, "parameter")), + returns: s.map((e) => d(e, e?.component, e?.serializer, "return")), + type: u, + ...a?.oauth_token ? { oauth_token: a.oauth_token } : {} + }; + })); + }), r; +} +function We(e, t, n, r) { + if (t === "Api") return e.type; + switch (e?.type) { + case "string": return "string"; + case "boolean": return "boolean"; + case "number": return "number"; + } + if (n === "JSONSerializable" || n === "StringSerializable") return "any"; + if (n === "ListStringSerializable") return "string[]"; + if (t === "Image") return r === "parameter" ? "Blob | File | Buffer" : "string"; + 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}"; + 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))][]"; +} +function Ge(e, t) { + return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e?.description; +} +function Ke(e, t) { + switch (e.msg) { + case "send_data": return { type: "data" }; + case "send_hash": return { type: "hash" }; + case "queue_full": return { + type: "update", + status: { + queue: !0, + message: Ce, + stage: "error", + code: e.code, + success: e.success + } + }; + case "heartbeat": return { type: "heartbeat" }; + case "unexpected_error": return { + type: "unexpected_error", + status: { + queue: !0, + message: e.message, + session_not_found: e.session_not_found, + stage: "error", + success: !1 + } + }; + case "broken_connection": return { + type: "broken_connection", + status: { + queue: !0, + message: e.message, + stage: "error", + success: !1 + } + }; + case "estimation": return { + type: "update", + status: { + queue: !0, + stage: t || "pending", + code: e.code, + size: e.queue_size, + position: e.rank, + eta: e.rank_eta, + success: e.success + } + }; + case "progress": return { + type: "update", + status: { + queue: !0, + stage: "pending", + code: e.code, + progress_data: e.progress_data, + success: e.success + } + }; + case "log": return { + type: "log", + data: e + }; + case "process_generating": return { + type: "generating", + status: { + queue: !0, + message: e.success ? null : e.output.error, + stage: e.success ? "generating" : "error", + code: e.code, + progress_data: e.progress_data, + eta: e.average_duration, + changed_state_ids: e.success ? e.output.changed_state_ids : void 0 + }, + data: e.success ? e.output : null + }; + case "process_streaming": return { + type: "streaming", + status: { + queue: !0, + message: e.output.error, + stage: "streaming", + time_limit: e.time_limit, + code: e.code, + progress_data: e.progress_data, + changed_state_ids: e.output.changed_state_ids, + eta: e.eta + }, + data: e.output + }; + case "process_completed": return "error" in e.output ? { + type: "update", + status: { + queue: !0, + title: e.output.title ?? "Error", + message: e.output.error ?? "An error occurred", + visible: e.output.visible, + duration: e.output.duration, + stage: "error", + code: e.code, + success: e.success + } + } : { + type: "complete", + status: { + queue: !0, + message: e.success ? void 0 : e.output.error, + stage: e.success ? "complete" : "error", + code: e.code, + progress_data: e.progress_data, + changed_state_ids: e.success ? e.output.changed_state_ids : void 0, + used_cache: e.used_cache, + cache_duration: e.cache_duration, + avg_time: e.avg_time + }, + data: e.success ? e.output : null + }; + case "process_starts": return { + type: "update", + status: { + queue: !0, + stage: "pending", + code: e.code, + size: e.rank, + position: 0, + success: e.success, + eta: e.eta + }, + original_msg: "process_starts" + }; + } + return { + type: "none", + status: { + stage: "error", + queue: !0 + } + }; +} +var qe = (e = [], t) => { + let n = t ? t.parameters : []; + if (Array.isArray(e)) return t && n.length > 0 && e.length > n.length && console.warn("Too many arguments provided for the endpoint."), e; + let r = [], i = Object.keys(e); + return n.forEach((t, n) => { + if (e.hasOwnProperty(t.parameter_name)) r[n] = e[t.parameter_name]; + else if (t.parameter_has_default) r[n] = t.parameter_default; + else throw Error(`No value provided for required parameter: ${t.parameter_name}`); + }), i.forEach((e) => { + 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.`); + }), r.forEach((e, t) => { + if (e === void 0 && !n[t].parameter_has_default) throw Error(`No value provided for required parameter: ${n[t].parameter_name}`); + }), r; +}; +//#endregion +//#region src/utils/view_api.ts +async function Je() { + if (this.api_info) return this.api_info; + let { token: e } = this.options, { config: t } = this, n = {}; + if (e && (n.Authorization = `Bearer ${e}`), t) try { + let e, r; + if (typeof window < "u" && window.gradio_api_info) r = window.gradio_api_info; + else { + let i = new URL(He(t.root, this.api_prefix, F)); + if (this.page !== null && i.searchParams.set("page", this.page), e = await this.fetch(i, { + headers: n, + credentials: this.options.credentials ?? "same-origin" + }), !e.ok) throw Error(z); + r = await e.json(); + } + return "api" in r && (r = r.api), r.named_endpoints["/predict"] && !r.unnamed_endpoints[0] && (r.unnamed_endpoints[0] = r.named_endpoints["/predict"]), Ue(r, t, this.api_map); + } catch (e) { + throw Error("Could not get API info. " + e.message); + } +} +//#endregion +//#region src/utils/upload_files.ts +async function Ye(e, t, n) { + let r = {}; + this?.options?.token && (r.Authorization = `Bearer ${this.options.token}`); + let i = 1e3, a = [], o; + for (let s = 0; s < t.length; s += i) { + let c = t.slice(s, s + i), l = new FormData(); + c.forEach((e) => { + l.append("files", e); + }); + try { + let t = n ? `${e}${this.api_prefix}/${N}?upload_id=${n}` : `${e}${this.api_prefix}/${N}`; + o = await this.fetch(t, { + method: "POST", + body: l, + headers: r, + credentials: this.options.credentials ?? "same-origin" + }); + } catch (e) { + throw Error(z + e.message); + } + if (!o.ok) { + let e = await o.text(); + return { error: `HTTP ${o.status}: ${e}` }; + } + let u = await o.json(); + u && a.push(...u); + } + return { files: a }; +} +var Xe = { + si: { + radix: 1e3, + unit: [ + "b", + "kb", + "Mb", + "Gb", + "Tb", + "Pb", + "Eb", + "Zb", + "Yb" + ] + }, + iec: { + radix: 1024, + unit: [ + "b", + "Kib", + "Mib", + "Gib", + "Tib", + "Pib", + "Eib", + "Zib", + "Yib" + ] + }, + jedec: { + radix: 1024, + unit: [ + "b", + "Kb", + "Mb", + "Gb", + "Tb", + "Pb", + "Eb", + "Zb", + "Yb" + ] + } +}; +function Ze(e, t = 1, n = "jedec") { + e = Math.abs(e); + let { radix: r, unit: i } = Xe[n] || Xe.jedec, a = 0; + for (; e >= r;) e /= r, ++a; + return `${e.toFixed(t)} ${i[a]}`; +} +//#endregion +//#region src/upload.ts +async function Qe(e, t, n, r) { + let i = (Array.isArray(e) ? e : [e]).map((e) => e.blob), a = i.filter((e) => e.size > (r ?? Infinity)); + if (a.length) throw Error(`File(s) exceed the maximum allowed size of ${Ze(r || Infinity)}: ${a.map((e) => `"${e.name}"`).join(", ")}`); + return await Promise.all(await this.upload_files(t, i, n).then(async (n) => { + if (n.error) throw Error(n.error); + return n.files ? n.files.map((n, r) => { + let i = n.split("/").map((e) => encodeURIComponent(e)).join("/"); + return new et({ + ...e[r], + path: n, + url: `${t}${this.api_prefix}/file=${i}` + }); + }) : []; + })); +} +async function $e(e, t) { + return e.map((e) => new et({ + path: e.name, + orig_name: e.name, + blob: e, + size: e.size, + mime_type: e.type, + is_stream: t + })); +} +var et = class { + path; + url; + orig_name; + size; + blob; + is_stream; + mime_type; + alt_text; + b64; + meta = { _type: "gradio.FileData" }; + constructor({ path: e, url: t, orig_name: n, size: r, blob: i, is_stream: a, mime_type: o, alt_text: s, b64: c }) { + 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; + } +}; +//#endregion +//#region src/utils/handle_blob.ts +async function tt(e, t, n) { + let r = this; + await nt(r, t); + let i = await f(t, void 0, [], !0, n); + return (await Promise.all(i.map(async ({ path: t, blob: n, type: i }) => { + if (!n) return { + path: t, + type: i + }; + let a = await r.upload_files(e, [n]); + return { + path: t, + file_url: a.files && a.files[0], + type: i, + name: typeof File < "u" && n instanceof File ? n?.name : void 0 + }; + }))).forEach(({ path: e, file_url: n, type: r, name: i }) => { + r === "Gallery" ? d(t, n, e) : n && d(t, new et({ + path: n, + orig_name: i + }), e); + }), t; +} +async function nt(e, t) { + if (!(e.config?.root || e.config?.root_url)) throw Error(je); + await rt(e, t); +} +async function rt(e, t, n = []) { + for (let r in t) t[r] instanceof l ? await it(e, t, r) : typeof t[r] == "object" && t[r] !== null && await rt(e, t[r], [...n, r]); +} +async function it(e, t, n) { + let r = t[n], i = e.config?.root || e.config?.root_url; + if (!i) throw Error(je); + try { + let a, o; + if (typeof process < "u" && process.versions && process.versions.node) { + let e = await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1)); + 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); + } else throw Error(G); + let s = new Blob([a], { type: "application/octet-stream" }), l = await e.upload_files(i, [s]), u = l.files && l.files[0]; + u && (t[n] = new et({ + path: u, + orig_name: r.meta.name || "" + })); + } catch (e) { + console.error(Me, e); + } +} +//#endregion +//#region src/utils/post_data.ts +async function at(e, t, n) { + let r = { "Content-Type": "application/json" }; + this.options.token && (r.Authorization = `Bearer ${this.options.token}`); + try { + var i = await this.fetch(e, { + method: "POST", + body: JSON.stringify(t), + headers: { + ...r, + ...n + }, + credentials: this.options.credentials ?? "same-origin" + }); + } catch { + return [{ error: z }, 500]; + } + let a, o; + try { + a = await i.json(), o = i.status; + } catch (e) { + a = { error: `Could not parse server response: ${e}` }, o = 500; + } + return [a, o]; +} +//#endregion +//#region src/utils/predict.ts +async function ot(e, t = {}) { + let n = !1, r = !1; + if (!this.config) throw Error("Could not resolve app config"); + if (typeof e == "number") this.config.dependencies.find((t) => t.id == e); + else { + let t = e.replace(/^\//, ""); + this.config.dependencies.find((e) => e.id == this.api_map[t]); + } + let i = this.submit(e, t, null, null, !0), a; + for await (let e of i) { + if (e.type === "data" && (n = !0, a = e, r)) return a; + if (e.type === "status") { + if (e.stage === "error") { + let { message: t, ...n } = e, r = Error((typeof t == "string" ? t : t && JSON.stringify(t)) || "An unknown error occurred while making a prediction."); + throw Object.assign(r, n), r; + } + if (e.stage === "complete" && (r = !0, n)) return a; + } + } + return a; +} +//#endregion +//#region src/helpers/spaces.ts +async function st(e, t, n) { + let r = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, a; + try { + if (i = await fetch(r), a = i.status, a !== 200) throw Error(); + i = await i.json(); + } catch { + n({ + status: "error", + load_status: "error", + message: we, + detail: "NOT_FOUND" + }); + return; + } + if (!i || a !== 200) return; + let { runtime: { stage: o }, id: s } = i; + switch (o) { + case "STOPPED": + case "SLEEPING": + n({ + status: "sleeping", + load_status: "pending", + message: "Space is asleep. Waking it up...", + detail: o + }), setTimeout(() => { + st(e, t, n); + }, 1e3); + break; + case "PAUSED": + n({ + status: "paused", + load_status: "error", + message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", + detail: o, + discussions_enabled: await ut(s) + }); + break; + case "RUNNING": + case "RUNNING_BUILDING": + n({ + status: "running", + load_status: "complete", + message: "Space is running.", + detail: o + }); + break; + case "BUILDING": + n({ + status: "building", + load_status: "pending", + message: "Space is building...", + detail: o + }), setTimeout(() => { + st(e, t, n); + }, 1e3); + break; + case "APP_STARTING": + n({ + status: "starting", + load_status: "pending", + message: "Space is starting...", + detail: o + }), setTimeout(() => { + st(e, t, n); + }, 1e3); + break; + default: + n({ + status: "space_error", + load_status: "error", + message: "This space is experiencing an issue.", + detail: o, + discussions_enabled: await ut(s) + }); + break; + } +} +var ct = async (e, t) => { + let n = 0; + return new Promise((r) => { + st(e, J.test(e) ? "space_name" : "subdomain", (i) => { + 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(() => { + ct(e, t).then(r); + }, 5e3)) : r()); + }); + }); +}, lt = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; +async function ut(e) { + try { + let t = await fetch(`https://huggingface.co/api/spaces/${e}/discussions`, { method: "HEAD" }), n = t.headers.get("x-error-message"); + return !(!t.ok || n && lt.test(n)); + } catch { + return !1; + } +} +async function dt(e, t) { + let n = {}; + t && (n.Authorization = `Bearer ${t}`); + try { + let t = await fetch(`https://huggingface.co/api/spaces/${e}/${ve}`, { headers: n }); + if (t.status !== 200) throw Error("Space hardware could not be obtained."); + let { hardware: r } = await t.json(); + return r.current; + } catch (e) { + throw Error(e.message); + } +} +async function ft(e, t, n) { + let r = {}; + n && (r.Authorization = `Bearer ${n}`); + let i = { seconds: t }; + try { + let t = await fetch(`https://huggingface.co/api/spaces/${e}/${I}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...r + }, + body: JSON.stringify(i) + }); + 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."); + return await t.json(); + } catch (e) { + throw Error(e.message); + } +} +var pt = [ + "cpu-basic", + "cpu-upgrade", + "cpu-xl", + "t4-small", + "t4-medium", + "a10g-small", + "a10g-large", + "a10g-largex2", + "a10g-largex4", + "a100-large", + "zero-a10g", + "h100", + "h100x8" +]; +//#endregion +//#region src/utils/duplicate.ts +async function mt(e, t) { + Pe(t); + let { token: n, private: r, hardware: i, timeout: a, auth: o } = t; + if (i && !pt.includes(i)) throw Error(`Invalid hardware type provided. Valid types are: ${pt.map((e) => `"${e}"`).join(",")}.`); + let { http_protocol: s, host: c } = await Ve(e, n), l = null; + if (o) { + let e = await q(s, c, o, fetch, void 0, t.credentials); + e && (l = Be(e)); + } + let u = { + Authorization: `Bearer ${n}`, + "Content-Type": "application/json", + ...l ? { Cookie: l.join("; ") } : {} + }, d = (await (await fetch("https://huggingface.co/api/whoami-v2", { headers: u })).json()).name, f = e.split("/")[1], p = { repository: `${d}/${f}` }; + r && (p.private = !0); + let m; + try { + i || (m = await dt(e, n)); + } catch (e) { + throw Error(V + e.message); + } + p.hardware = i || m || "cpu-basic"; + try { + let r = await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`, { + method: "POST", + headers: u, + body: JSON.stringify(p) + }); + if (r.status === 409) try { + return await Dr.connect(`${d}/${f}`, t); + } catch (e) { + throw console.error("Failed to connect Client instance:", e), e; + } + else if (r.status !== 200) throw Error(r.statusText); + let i = await r.json(); + return await ft(`${d}/${f}`, a || 300, n), await Dr.connect(ht(i.url), t); + } catch (e) { + throw Error(e); + } +} +function ht(e) { + let t = e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/); + if (t) return t[1]; +} +//#endregion +//#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 +var gt = class extends TransformStream { + #e = ""; + constructor(e = { allowCR: !1 }) { + super({ + transform: (t, n) => { + for (t = this.#e + t;;) { + let r = t.indexOf("\n"), i = e.allowCR ? t.indexOf("\r") : -1; + if (i !== -1 && i !== t.length - 1 && (r === -1 || r - 1 > i)) { + n.enqueue(t.slice(0, i)), t = t.slice(i + 1); + continue; + } + if (r === -1) break; + let a = t[r - 1] === "\r" ? r - 1 : r; + n.enqueue(t.slice(0, a)), t = t.slice(r + 1); + } + this.#e = t; + }, + flush: (t) => { + if (this.#e === "") return; + let n = e.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e; + t.enqueue(n); + } + }); + } +}; +//#endregion +//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/utils.js +function _t(e) { + let t = new TextDecoderStream(), n = new gt({ allowCR: !0 }); + return e.pipeThrough(t).pipeThrough(n); +} +function vt(e) { + let t = /[:]\s*/.exec(e), n = t && t.index; + if (n) return [e.substring(0, n), e.substring(n + t[0].length)]; +} +function yt(e, t, n) { + e.get(t) || e.set(t, n); +} +//#endregion +//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/mod.js +async function* bt(e, t) { + if (!e.body) return; + let n = _t(e.body), r, i = n.getReader(), a; + for (;;) { + if (t && t.aborted) return i.cancel(); + if (r = await i.read(), r.done) return; + if (!r.value) { + a && (yield a), a = void 0; + continue; + } + let [e, n] = vt(r.value) || []; + 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); + } +} +async function xt(e, t) { + let n = new Request(e, t); + yt(n.headers, "Accept", "text/event-stream"), yt(n.headers, "Content-Type", "application/json"); + let r = await fetch(n); + if (!r.ok) throw r; + return bt(r, n.signal); +} +//#endregion +//#region src/utils/stream.ts +async function St() { + let { event_callbacks: e, unclosed_events: t, pending_stream_messages: n, stream_status: r, config: i, jwt: a } = this, o = this; + if (!i) throw Error("Could not resolve app config"); + if (r.open) return; + this.stream_reconnect_timer &&= (clearTimeout(this.stream_reconnect_timer), null), r.open = !0; + let s = null, c = new URLSearchParams({ + session_hash: this.session_hash, + acknowledgements: this.options.resume_sessions ? "true" : "false" + }); + this.events_to_resume.forEach((e) => { + c.append("resume_event_id", e); + }), this.events_to_resume.clear(); + let l = new URL(`${i.root}${this.api_prefix}/${he}?${c.toString()}`); + a && l.searchParams.set("__sign", a), s = this.stream(l); + let u = this.abort_controller; + if (!s) { + console.warn("Cannot connect to SSE endpoint: " + l.toString()), r.open = !1; + return; + } + s.onmessage = async function(a) { + if (o.stream_instance !== s) return; + o.stream_reconnect_attempts = 0; + let c = JSON.parse(a.data); + if (c.msg === "close_stream") { + o.stream_instance = null, Tt(r, u), !o.closed && t.size > 0 && await o.open_stream(); + return; + } + let l = c.event_id; + if (!l) await Promise.all(Object.keys(e).map((t) => e[t](c))); + else if (e[l] && i) { + c.msg === "process_completed" && [ + "sse", + "sse_v1", + "sse_v2", + "sse_v2.1", + "sse_v3" + ].includes(i.protocol) && t.delete(l); + let n = e[l]; + typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(n, 0, c) : n(c); + } else o.acknowledged_events?.has(l) || (n[l] || (n[l] = []), n[l].push(c)); + }, s.onerror = async function(n) { + if (o.stream_instance !== s) return; + if (o.closed || console.error(n), !o.options.resume_sessions) { + await Promise.all(Object.keys(e).map((t) => e[t]({ + msg: "broken_connection", + message: z + }))); + return; + } + if (Tt(r, u), t.forEach((e) => { + o.events_to_resume.add(e), delete o.pending_diff_streams[e]; + }), o.closed || o.stream_reconnect_timer || t.size === 0 && Object.keys(e).length === 0) return; + let i = Math.min(500 * 2 ** o.stream_reconnect_attempts, 5e3); + o.stream_reconnect_attempts += 1, o.stream_reconnect_timer = setTimeout(async () => { + if (o.stream_reconnect_timer = null, !(o.closed || t.size === 0 && Object.keys(e).length === 0)) try { + await o.open_stream(); + } catch (e) { + s?.onerror?.(e); + } + }, i); + }; +} +function Ct(e) { + let t = e.browser_streams ?? "auto"; + return t === "auto" ? typeof window < "u" && typeof document < "u" || globalThis.WorkerGlobalScope !== void 0 ? /^h[23]/.test(wt(e.root)) : !0 : t === "per_event"; +} +function wt(e) { + if (typeof performance?.getEntriesByType != "function") return ""; + let t; + try { + t = new URL(e, globalThis.location?.href).origin; + } catch { + return ""; + } + let n = [...performance.getEntriesByType("navigation"), ...performance.getEntriesByType("resource")]; + for (let e = n.length - 1; e >= 0; e--) { + let { name: r, nextHopProtocol: i } = n[e]; + if (i) try { + if (new URL(r).origin === t) return i; + } catch {} + } + return ""; +} +function Tt(e, t) { + e && (e.open = !1, t?.abort()); +} +function Et(e, t, n) { + e[t] ? n.data.forEach((r, i) => { + let a = Dt(i < e[t].length ? e[t][i] : null, r); + e[t][i] = a, n.data[i] = a; + }) : (e[t] = [], n.data.forEach((n, r) => { + e[t][r] = n; + })); +} +function Dt(e, t) { + return t.forEach(([t, n, r]) => { + e = Ot(e, n, t, r); + }), e; +} +function Ot(e, t, n, r) { + if (t.length === 0) { + if (n === "replace") return r; + if (n === "append") return e + r; + throw Error(`Unsupported action: ${n}`); + } + let i = e; + for (let e = 0; e < t.length - 1; e++) i = i[t[e]]; + let a = t[t.length - 1]; + switch (n) { + case "replace": + i[a] = r; + break; + case "append": + i[a] += r; + break; + case "add": + Array.isArray(i) ? i.splice(Number(a), 0, r) : i[a] = r; + break; + case "delete": + Array.isArray(i) ? i.splice(Number(a), 1) : delete i[a]; + break; + default: throw Error(`Unknown action: ${n}`); + } + return e; +} +function kt(e, t = {}) { + let n = { + close: () => { + console.warn("Method not implemented."); + }, + onerror: null, + onmessage: null, + onopen: null, + readyState: 0, + url: e.toString(), + withCredentials: !1, + CONNECTING: 0, + OPEN: 1, + CLOSED: 2, + addEventListener: () => { + throw Error("Method not implemented."); + }, + dispatchEvent: () => { + throw Error("Method not implemented."); + }, + removeEventListener: () => { + throw Error("Method not implemented."); + } + }; + return xt(e, t).then(async (e) => { + n.readyState = n.OPEN; + try { + for await (let t of e) n.onmessage && n.onmessage(t); + n.readyState = n.CLOSED; + } catch (e) { + n.onerror && n.onerror(e), n.readyState = n.CLOSED; + } + }).catch((e) => { + e?.name !== "AbortError" && console.error(e), n.onerror && n.onerror(e), n.readyState = n.CLOSED; + }), n; +} +//#endregion +//#region src/utils/browser_storage.ts +var At = "gradio", jt = 1, Mt = 1440 * 60 * 1e3, Nt = null; +function Pt() { + return typeof indexedDB < "u"; +} +function Ft() { + return Pt() ? (Nt ||= new Promise((e) => { + try { + let t = indexedDB.open(At, jt); + t.onupgradeneeded = () => { + for (let e of ["sessions", "apps"]) t.result.objectStoreNames.contains(e) || t.result.createObjectStore(e, { keyPath: "key" }).createIndex("updated", "updated"); + }, t.onsuccess = () => { + let n = t.result; + n.onversionchange = () => { + n.close(), Nt = null; + }, e(n); + }, t.onerror = () => e(null), t.onblocked = () => e(null); + } catch { + e(null); + } + }), Nt) : Promise.resolve(null); +} +function It(e) { + return new Promise((t, n) => { + e.onsuccess = () => t(e.result), e.onerror = () => n(e.error); + }); +} +async function Lt(e, t) { + let n = await Ft(); + if (n) try { + return await It(n.transaction(e, "readonly").objectStore(e).get(t)); + } catch { + return; + } +} +async function Rt(e, t) { + let n = await Ft(); + if (!n) return !1; + try { + return await It(n.transaction(e, "readwrite").objectStore(e).put(t)), !0; + } catch { + return !1; + } +} +async function zt(e, t) { + let n = await Ft(); + if (n) try { + await It(n.transaction(e, "readwrite").objectStore(e).delete(t)); + } catch {} +} +async function Bt(e, { max_age_ms: t = Infinity, keep: n = Infinity, except: r, prefix: i }) { + let a = await Ft(); + if (a) try { + let o = []; + await new Promise((t, n) => { + let r = a.transaction(e, "readonly").objectStore(e).index("updated").openKeyCursor(); + r.onsuccess = () => { + let e = r.result; + if (!e) return t(); + o.push({ + key: e.primaryKey, + updated: e.key + }), e.continue(); + }, r.onerror = () => n(r.error); + }); + let s = Date.now() - t, c = o.filter(({ key: e }) => e !== r && (!i || e.startsWith(i))), l = c.filter(({ updated: e }, t) => e < s || c.length - t > n); + for (let { key: t } of l) await zt(e, t); + } catch {} +} +function Vt(e, t) { + return `${e.replace(/\/+$/, "")}|${t ?? ""}`; +} +function Ht(e) { + return e?.type === "image" && !!e.props.streaming; +} +function Ut(e, t) { + if (!Ht(e)) return t; + if (!Gt(t)) return; + let n = { ...t }; + return delete n.value, n; +} +function Wt(e, t) { + if (Gt(t)) for (let [n, r] of Object.entries(t)) n !== "__type__" && (e[n] = r); + else e.value = t; +} +function Gt(e) { + return typeof e == "object" && !!e && !Array.isArray(e) && e.__type__ === "update"; +} +//#endregion +//#region src/utils/session.ts +var Kt = "gradio_active_session"; +function X() { + if (typeof sessionStorage > "u") return null; + try { + let e = sessionStorage.getItem(Kt); + return e ? JSON.parse(e) : null; + } catch { + return null; + } +} +function qt(e) { + if (!(typeof sessionStorage > "u")) try { + sessionStorage.setItem(Kt, JSON.stringify(e)); + } catch { + return; + } +} +function Jt() { + try { + typeof sessionStorage < "u" && sessionStorage.removeItem(Kt); + } catch { + return; + } +} +function Yt(e, t, n) { + return !!e && e.session_hash === n && e.root === t.root && e.app_key === t.app_key && (e.username ?? null) === Xt(t); +} +function Xt(e) { + return e.session_user ?? e.username ?? null; +} +function Zt() { + Jt(); +} +function Qt() { + return typeof document > "u" || !document.prerendering ? Promise.resolve() : new Promise((e) => document.addEventListener("prerenderingchange", () => e(), { once: !0 })); +} +function $t() { + let e = X(); + if (e && !e.in_use) { + if (typeof location > "u") return e.session_hash; + try { + let t = new URL(e.root); + if (t.origin === location.origin && location.pathname.startsWith(t.pathname)) return e.session_hash; + } catch { + return null; + } + } + return null; +} +function en(e, t) { + return Yt(X(), e, t); +} +function tn(e) { + let t = e.current_page ?? ""; + if (typeof location > "u") return t; + let n = new URLSearchParams(location.search); + for (let e of [...n.keys()]) (e.startsWith("__") || e === "view") && n.delete(e); + n.sort(); + let r = n.toString(); + return r ? `${t}?${r}` : t; +} +function nn(e, t) { + let n = X(); + return Yt(n, e, t) && !!n.pages?.includes(tn(e)); +} +function rn(e, t) { + let n = X(), r = Yt(n, e, t) ? n : null, i = new Set(r?.pages).add(tn(e)); + qt({ + app_key: e.app_key, + username: Xt(e), + root: e.root, + session_hash: t, + events: r?.events ?? [], + pages: [...i], + in_use: !0 + }); +} +function an(e) { + let t = X(); + t && qt({ + ...t, + in_use: e + }); +} +function on(e, t) { + let n = X(); + return Yt(n, e, t) ? n.events : (n && Jt(), []); +} +function sn(e, t, n) { + let r = X(), i = Yt(r, e, t) ? r : null, a = (i?.events ?? []).filter(({ event_id: e }) => e !== n.event_id); + qt({ + ...i, + app_key: e.app_key, + username: Xt(e), + root: e.root, + session_hash: t, + events: [...a, n] + }); +} +function cn(e) { + let t = X(); + if (!t) return; + let n = t.events.filter((t) => t.event_id !== e); + qt({ + ...t, + events: n + }); +} +//#endregion +//#region src/utils/webrtc.ts +function ln() { + let e = crypto.getRandomValues(new Uint8Array(16)); + return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join(""); +} +var un = 5e3, dn = 1e4; +function fn(e, { connected: t, ended: n, failed: r, slow: i }) { + let a = null, o = !1, s = () => { + a !== null && clearTimeout(a), a = null; + }, c = i ? setTimeout(() => { + c = null, ["new", "connecting"].includes(e.connectionState) && i(); + }, dn) : null, l = () => { + c !== null && clearTimeout(c), c = null; + }; + e.addEventListener("connectionstatechange", () => { + switch (e.connectionState) { + case "connected": + s(), l(), o || (o = !0, t()); + break; + case "disconnected": + s(), a = setTimeout(() => { + a = null, e.connectionState === "disconnected" && n(); + }, un); + break; + case "closed": + s(), l(), n(); + break; + case "failed": + s(), l(), r(); + break; + } + }); +} +async function pn({ pc: e, offer: t, webrtc_id: n, stream: r, modality: i, rtp_params: a = {}, mirror: o = !1, on_open: s = () => {}, on_message: c = () => {}, on_reject: l = () => {} }) { + let u = e.createDataChannel("text"); + if (u.onopen = () => { + u.send("handshake"), s(u); + }, u.onmessage = (e) => { + let t = null; + try { + t = JSON.parse(e.data); + } catch { + t = { type: String(e.data) }; + } + t && typeof t.type == "string" && c(t); + }, r) for (let t of r.getTracks()) { + let n = e.addTrack(t, r); + if (Object.keys(a).length) { + let e = n.getParameters(); + await n.setParameters({ + ...e, + ...a + }); + } + } + else e.addTransceiver(i, { direction: "recvonly" }); + e.onicecandidate = ({ candidate: e }) => { + e?.candidate && t({ + candidate: e.toJSON(), + webrtc_id: n, + type: "ice-candidate" + }).catch((e) => console.error("Error sending ICE candidate:", e)); + }; + let d = await e.createOffer(); + await e.setLocalDescription(d); + let f = await t({ + sdp: e.localDescription?.sdp, + type: e.localDescription?.type, + webrtc_id: n, + mirror: o + }); + if (!f || f.status === "failed") throw l(f ?? {}), Error(f?.meta?.error ?? "offer rejected"); + return await e.setRemoteDescription({ + sdp: f.sdp, + type: f.type + }), f; +} +function mn(e, { stop_tracks: t = !0 } = {}) { + e && (e.getTransceivers?.().forEach((e) => { + try { + e.stop?.(); + } catch {} + }), t && e.getSenders?.().forEach((e) => { + e.track?.stop(); + }), setTimeout(() => e.close(), 500)); +} +function hn(e) { + switch (e?.meta?.error) { + case "not_admitted": return "The stream's turn in the queue ended before it connected. Please try again."; + case "connection_already_exists": return "A connection with this id already exists."; + case "unsupported_track": return e.meta?.message ?? "This stream does not accept that kind of media."; + case "no_stream_handler": return "No stream handler is attached to this component."; + case "setup_failed": return e.meta?.message ?? "Could not establish the connection."; + default: return "Could not establish the connection."; + } +} +function gn(e, t, n, r, i, a, o = []) { + let s = t.findIndex((e) => e instanceof MediaStream), c = s >= 0 ? s : n.media_input ?? -1, l = r?.media, u = s >= 0 ? t[s] : l instanceof MediaStream ? l : null, d = ln(), f = (e) => e.filter((e, t) => t !== c), p = f(t), m = t.map((e, t) => t === c ? null : e), h = null, g = null, _ = !1, v = [...t]; + c >= 0 && (v[c] = null); + let y = this.submit(e, v, { webrtc_id: d }, i, a), b = [], x = null, S = !1, C = (e) => { + b.push(e), x?.(); + }, w = 0, ee = () => { + h?.readyState === "open" && h.send(JSON.stringify({ + type: "input", + data: p + })); + }, te = (t) => { + if (u = t, g) for (let n of g.getSenders()) { + let r = n.track?.kind, i = t.getTracks().find((e) => e.kind === r); + !r || !i || n.replaceTrack(i).catch((t) => C({ + type: "log", + level: "warning", + log: `Could not switch to the new ${r}: ${t}`, + title: null, + duration: null, + visible: !0, + time: /* @__PURE__ */ new Date(), + endpoint: String(e), + fn_index: w + })); + } + }, T = (e) => { + _ = !0, mn(g, { stop_tracks: !1 }), g = null, y.close_stream(e ?? { read_to_end: !0 }); + }, ne = async () => { + let t = await this.webrtc_rtc_configuration(d); + if (!t || "error" in t) throw Error(t?.error ?? "Could not get the connection settings from the server."); + if (_) return; + let i = new RTCPeerConnection(t); + g = i, n.media_output !== null && i.addEventListener("track", (t) => { + let r = t.streams[0] ?? new MediaStream([t.track]), i = []; + i[n.media_output] = r, C({ + type: "data", + data: i, + time: /* @__PURE__ */ new Date(), + endpoint: String(e), + fn_index: w + }); + }), fn(i, { + connected: () => {}, + ended: () => T(), + failed: () => E("The connection failed."), + slow: () => C({ + type: "log", + level: "warning", + log: "Taking a while to connect. Are you on a VPN?", + title: null, + duration: null, + visible: !0, + time: /* @__PURE__ */ new Date(), + endpoint: String(e), + fn_index: w + }) + }), await pn({ + pc: i, + offer: (e) => this.webrtc_offer(e), + webrtc_id: d, + stream: u && new MediaStream(u.getTracks().filter((e) => n.modality === "audio-video" || e.kind === n.modality)), + modality: n.modality, + rtp_params: n.rtp_params, + mirror: r?.mirror === !0, + on_open: (e) => { + h = e, ee(); + }, + on_message: (t) => { + if (t.type === "send_input") ee(); + else if ([ + "info", + "warning", + "error" + ].includes(t.type) || t.type === "end_stream" && typeof t.data == "string" && t.data) { + let n = t.type === "end_stream"; + C({ + type: "log", + level: n ? "warning" : t.type, + log: n ? String(t.data) : t.message ?? "", + title: t.title ?? null, + duration: t.duration ?? null, + visible: t.visible ?? !0, + time: /* @__PURE__ */ new Date(), + endpoint: String(e), + fn_index: w + }); + } + }, + on_reject: (e) => { + throw Error(hn(e)); + } + }); + }, E = (t) => { + _ || (C({ + type: "status", + stage: "error", + message: t, + queue: !1, + visible: !0, + time: /* @__PURE__ */ new Date(), + endpoint: String(e), + fn_index: w + }), T()); + }, D = () => T(); + typeof window < "u" && window.addEventListener("pagehide", D); + let O = !1; + (async () => { + try { + for await (let e of y) w = e.fn_index ?? w, e.type === "data" && Array.isArray(e.data) && (e.data = e.data.map((e) => e && typeof e == "object" && e.__type__ === "update" && Object.keys(e).length === 1 ? void 0 : e)), e.type === "data" && !O && e.data !== void 0 && (O = !0, _ || ne().catch((e) => E(e.message))), !(e.type === "data" && e.data === void 0) && C(e); + } finally { + _ = !0, typeof window < "u" && window.removeEventListener("pagehide", D), mn(g, { stop_tracks: !1 }), S = !0, x?.(); + } + })(); + let k = { + [Symbol.asyncIterator]: () => k, + async next() { + for (; !b.length && !S;) await new Promise((e) => x = e), x = null; + return b.length ? { + value: b.shift(), + done: !1 + } : { + value: void 0, + done: !0 + }; + }, + async throw(e) { + return T(), y.throw(e); + }, + async return() { + return T(), y.return(); + }, + cancel: async () => { + mn(g, { stop_tracks: !1 }), g = null, _ = !0, await y.cancel(); + }, + event_id: () => y.event_id(), + wait_for_id: () => y.wait_for_id(), + acknowledge: () => y.acknowledge(), + send_chunk: (e) => { + let t = e?.data; + if (t && typeof t == "object" && !Array.isArray(t)) { + let e = t, n = Object.keys(e).find((e) => !o.includes(e)); + if (n !== void 0) throw Error(`Parameter \`${n}\` is not a valid keyword argument.`); + t = m.map((t, n) => o[n] in e ? e[o[n]] : t); + } + if (!Array.isArray(t)) return; + let n = c >= 0 ? t[c] : void 0; + n instanceof MediaStream && te(n), p = f(t), m = t.map((e, t) => t === c ? null : e), ee(); + }, + close_stream: (e) => T(e) + }; + return k; +} +//#endregion +//#region src/utils/run_history.ts +var _n = "gradio:run-history:", vn = `${_n}replay:v3:`, yn = [`${_n}v2:`, `${_n}destination:v1:`], bn = 100, xn = 32; +function Z(e, t) { + try { + return e(); + } catch (e) { + return console.warn("Could not update the run history.", e), t; + } +} +function Sn(e, t = "/gradio_api") { + return `${e.replace(/\/+$/, "")}${t}/runs`; +} +var Cn = new Set(["tick", "load"]); +function wn(e, t, n) { + if (n == null) return !1; + let r = t; + for (let t = 0; t < 100 && r.trigger_after != null; t++) { + let t = e.find((e) => e.id === r.trigger_after); + if (!t) break; + r = t; + } + let i = r.targets.filter(([e]) => e === n).map(([, e]) => e); + return i.length > 0 && i.every((e) => Cn.has(e)); +} +function Q(e) { + if (typeof window > "u") return null; + let t = e?.app_key ?? e?.app_id; + if (t == null || t === "") return null; + let n = e?.username ? `|user:${encodeURIComponent(e.username)}` : ""; + return `${Vt(e?.root ?? "", String(t))}${n}`; +} +function Tn(e) { + let t = Q(e); + return t ? `${vn}${t}` : null; +} +var En = /* @__PURE__ */ new Map(), Dn = !1, On = null; +function kn() { + return On || typeof window > "u" || typeof BroadcastChannel > "u" ? On : (On = new BroadcastChannel("gradio:run-history"), On.addEventListener("message", (e) => { + let t = e.data?.key, n = typeof t == "string" ? En.get(t) : void 0; + n && Lt("apps", t).then((e) => { + e && (Mn(n, e), Jn()); + }); + }), On); +} +function An() { + if (!Dn) { + Dn = !0; + try { + for (let e of Object.keys(window.localStorage)) yn.some((t) => e.startsWith(t)) && window.localStorage.removeItem(e); + } catch {} + } +} +function jn(e, t) { + return (Date.parse(t.started_at) || 0) - (Date.parse(e.started_at) || 0); +} +function Mn(e, t) { + let n = new Map((t.runs ?? []).map((e) => [e.id, e])), r = [], i = /* @__PURE__ */ new Set(); + for (let t of e.runs) i.add(t.id), e.touched.has(t.id) ? r.push(t) : n.has(t.id) && r.push(n.get(t.id)); + for (let t of n.values()) !i.has(t.id) && !e.deleted.has(t.id) && (Date.parse(t.started_at) || 0) > e.cleared_at && r.push(t); + e.runs = r.sort(jn).slice(0, bn), e.destination === null && t.destination && (e.destination = t.destination); +} +function $(e) { + let t = En.get(e); + if (t) return t; + An(), kn(); + let n = { + runs: [], + destination: null, + loaded: Promise.resolve(), + dirty: !1, + deleted: /* @__PURE__ */ new Set(), + cleared_at: 0, + touched: /* @__PURE__ */ new Map(), + save_timer: null, + saving: null, + changed_while_saving: !1 + }; + return n.loaded = Lt("apps", e).then((t) => { + t && Mn(n, t), n.dirty && Nn(e, n), Jn(); + }), En.set(e, n), n; +} +function Nn(e, t) { + if (t.dirty = !0, Pt()) { + if (t.saving) { + t.changed_while_saving = !0; + return; + } + t.save_timer ||= setTimeout(() => { + t.save_timer = null, Pn(e, t); + }, 0); + } +} +function Pn(e, t) { + t.changed_while_saving = !1, t.saving = Ln(e, t).finally(() => { + t.saving = null, t.changed_while_saving && Nn(e, t); + }); +} +var Fn = 0; +function In(e, t) { + for (let [n, r] of t) e.touched.get(n) === r && e.touched.delete(n); +} +async function Ln(e, t) { + await t.loaded; + let n = new Map(t.touched), r = await Lt("apps", e); + r && Mn(t, r), t.dirty = !1; + let i = t.runs; + if (i.length === 0 && !t.destination) { + await zt("apps", e), In(t, n), kn()?.postMessage({ key: e }); + return; + } + for (; !(await Rt("apps", { + key: e, + updated: Date.now(), + runs: i, + ...t.destination ? { destination: t.destination } : {} + }) || i.length === 0);) i = i.slice(0, Math.floor(i.length / 2)); + In(t, n), kn()?.postMessage({ key: e }), Bt("apps", { + keep: xn, + except: e + }); +} +async function Rn(e) { + try { + let t = Q(e); + t && await $(t).loaded; + } catch (e) { + console.warn("Could not load the run history.", e); + } +} +function zn(e) { + let t = Q(e); + return t ? $(t).destination ?? { type: "browser" } : { type: "browser" }; +} +function Bn(e, t) { + let n = Q(e); + if (!n) return; + let r = $(n); + r.destination = t.type === "browser" && !t.bucket_id ? null : t, Nn(n, r), Jn(); +} +function Vn() { + return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`; +} +function Hn(e) { + let t = /* @__PURE__ */ new WeakSet(); + try { + return JSON.parse(JSON.stringify(e, (e, n) => { + if (typeof n == "bigint") return n.toString(); + if (typeof n == "object" && n) { + if (t.has(n)) return "[Circular]"; + t.add(n); + } + return n; + })); + } catch { + return "[Unserializable value]"; + } +} +function Un(e) { + let t = Q(e); + return t ? $(t).runs : []; +} +function Wn(e, t, n) { + let r = Q(e); + if (!r) return; + let i = $(r); + i.runs = t.slice(0, bn); + for (let e of n) i.touched.set(e, ++Fn); + Nn(r, i); +} +function Gn(e) { + let t = Q(e); + if (!t) return; + let n = $(t); + n.runs = [], n.touched.clear(), n.cleared_at = Date.now(), Nn(t, n), Jn(); +} +function Kn(e, t) { + let n = Q(e); + if (!n) return; + let r = $(n); + r.deleted.add(t), r.touched.delete(t), Wn(e, r.runs.filter((e) => e.id !== t), []), Jn(); +} +var qn = "gradio:run-history-change"; +function Jn() { + if (!(typeof window > "u")) try { + window.dispatchEvent(new Event(qn)); + } catch {} +} +function Yn(e) { + return typeof window > "u" ? () => {} : (window.addEventListener(qn, e), () => { + window.removeEventListener(qn, e); + }); +} +function Xn(e, t) { + let n = Tn(e); + if (n) try { + window.sessionStorage.setItem(n, JSON.stringify(t)); + } catch {} +} +function Zn(e) { + let t = Tn(e); + if (!t) return null; + try { + let e = window.sessionStorage.getItem(t); + return window.sessionStorage.removeItem(t), e ? JSON.parse(e) : null; + } catch { + return null; + } +} +function Qn(e, t, n) { + let r = e.dependencies.find((e) => e.id === t.fn_index || typeof e.api_name == "string" && `/${e.api_name.replace(/^\//, "")}` === t.api_name); + if (!r) return !1; + let i = (t, n) => n.map((n, r) => Ut(e.components.find((e) => e.id === t[r]), n)), a = i(r.inputs, Array.isArray(t.inputs) ? t.inputs : Object.values(t.inputs ?? {})), o = i(r.outputs, Array.isArray(t.outputs) ? t.outputs : t.outputs === null || t.outputs === void 0 ? [] : [t.outputs]), s = (t, n) => { + for (let [r, i] of t.entries()) { + let t = e.components.find((e) => e.id === i); + !t || n[r] === void 0 || t.type !== "state" && Wt(t.props, n[r]); + } + }; + return s(r.inputs, a), s(r.outputs, o), n?.(r.inputs, a), n?.(r.outputs, o), !0; +} +function $n(e, t) { + let n = Zn(e); + return n ? Qn(e, n, t) : !1; +} +function er(e) { + if (zn(e).type === "bucket" || !Q(e)) return null; + let t = { + id: Vn(), + endpoint: e.endpoint, + api_name: e.api_name, + fn_index: e.fn_index, + page: `${window.location.pathname}${window.location.search}`, + inputs: Hn(e.inputs), + outputs: null, + ...e.input_components ? { input_components: Hn(e.input_components) } : {}, + ...e.output_components ? { output_components: Hn(e.output_components) } : {}, + status: "running", + started_at: (/* @__PURE__ */ new Date()).toISOString() + }; + return Wn(e, [t, ...Un(e)], [t.id]), Jn(), t.id; +} +function tr(e, t, n) { + if (!t) return; + let r = Un(e), i = r.find((e) => e.id === t); + i && (i.inputs = Hn(n), Wn(e, r, [t])); +} +function nr(e, t, n) { + if (!t) return; + let r = Un(e), i = r.find((e) => e.id === t); + if (!i) return; + let a = !1; + if (n.type === "data") i.outputs = Hn(n.data); + else if (n.type === "status" && n.original_msg === "process_starts") ar(i, n.time); + else if (n.type === "status" && (n.stage === "generating" || n.stage === "streaming")) i.streamed = !0; + else if (n.type === "status" && n.stage === "complete") i.status = "completed", or(i, n), a = !0; + 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"), or(i, n), a = !0; + else return; + if (a) ir.delete(t); + else if (i.streamed) { + if (Date.now() - (ir.get(t) ?? 0) < rr) return; + ir.set(t, Date.now()); + } + Wn(e, r, [t]); +} +var rr = 500, ir = /* @__PURE__ */ new Map(); +function ar(e, t) { + if (e.process_started_at) return; + let n = t || /* @__PURE__ */ new Date(); + e.process_started_at = n.toISOString(), e.queued_ms = Math.max(0, n.getTime() - Date.parse(e.started_at)); +} +function or(e, t) { + let n = t.time || /* @__PURE__ */ new Date(); + 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)); +} +function sr(e, t, n) { + return Z(() => wn(e, t, n), !1); +} +function cr(e) { + return Z(() => Un(e), []); +} +function lr(e) { + return Z(() => zn(e), { type: "browser" }); +} +function ur(e, t) { + Z(() => Bn(e, t), void 0); +} +function dr(e) { + Z(() => Gn(e), void 0); +} +function fr(e, t) { + Z(() => Kn(e, t), void 0); +} +function pr(e, t) { + Z(() => Xn(e, t), void 0); +} +function mr(e) { + return Z(() => Zn(e), null); +} +function hr(e, t) { + return Z(() => $n(e, t), !1); +} +function gr(e) { + return Z(() => er(e), null); +} +function _r(e, t, n) { + Z(() => tr(e, t, n), void 0); +} +function vr(e, t, n) { + Z(() => nr(e, t, n), void 0); +} +function yr(e) { + return Z(() => Yn(() => Z(e, void 0)), () => {}); +} +//#endregion +//#region src/utils/submit.ts +var br = 1e3; +function xr(e, t = {}, n, r, i, a, o) { + try { + let { token: s } = this.options, { fetch: c, app_reference: l, config: u, session_hash: d, api_info: f, api_map: m, stream_status: h, pending_stream_messages: _, pending_diff_streams: y, event_callbacks: b, unclosed_events: x, post_data: S, options: C, api_prefix: w } = this, te = a || { "x-gradio-user": "api" }, T = this; + if (!f) throw Error(ke); + if (!u) throw Error("Could not resolve app config"); + let ne = u.root; + this.open_heartbeat(); + let { fn_index: E, endpoint_info: D, dependency: O } = Cr(f, e, m, u), k = O.transport?.type === "webrtc" && !Array.isArray(t) ? qe(t, D) : t; + if (O.transport?.type === "webrtc" && Array.isArray(k) && typeof MediaStream < "u" && !(n && typeof n == "object" && "webrtc_id" in n) && (O.transport.mode === "receive" || n?.media instanceof MediaStream || k.some((e) => e instanceof MediaStream))) return gn.call(this, e, k, O.transport, n, r, i, D?.parameters.map((e) => e.parameter_name) ?? []); + let re = new Set([...O.inputs, ...O.outputs]), ie = (e = []) => T.session_store.payload(re, e), ae = async (e, t, n) => { + let r = await S(e, { + ...t, + state: ie() + }, n), i = r[0]?.detail?.missing_state; + return r[1] === 409 && Array.isArray(i) ? await S(e, { + ...t, + state: ie(i) + }, n) : r; + }, oe = o ? [] : qe(t, D), A = u.supported_protocols?.includes("sse_v4") ? Ct(u) ? "sse_v4" : "sse_v3" : u.protocol ?? "ws"; + if (A === "ws") throw Error(Ae); + let se = typeof O.api_name == "string" ? `/${O.api_name}` : e, ce = typeof O.api_name == "string" ? `/${O.api_name}` : `Function ${E}`, le = (e) => { + let t = u.components.find((t) => t.id === e); + return t ? { + type: t.type, + component_class_id: t.component_class_id, + props: t.props + } : null; + }, ue = O.api_visibility === "public", de = new Set(O.targets.filter(([, e]) => e === "stream").map(([e]) => e)), j = (e) => e.map((e, t) => de.has(O.inputs[t]) ? null : e), fe = u.run_history !== !1 && this.options.record_history !== !1, M = { + root: u.root, + app_key: u.app_key, + app_id: u.app_id, + username: u.username + }, pe = lr(M), me = { + ...te, + ...fe && pe.type === "bucket" ? { "x-gradio-history-bucket": pe.bucket_id } : {} + }, N = o || !fe || !ue || sr(u.dependencies, O, r) ? null : gr({ + ...M, + endpoint: se, + api_name: ce, + fn_index: E, + inputs: j(g(oe, O, u.components, "input", !0)), + input_components: O.inputs.map(le), + output_components: O.outputs.map(le) + }), _e = "", P, F = "", ve = null, I = null, L = !1, R = !1, xe = !1, Se = !1, B = () => {}, we = new Promise((e) => { + B = e; + }), Te = () => { + ve?.abort(); + }, V = typeof e == "number" ? "/predict" : e, Ee, H = null, U = !1, De = {}, W = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "", Oe = C?.events?.reduce((e, t) => (e[t] = !0, e), {}) || {}; + function G(e) { + vr(M, N, e), (e.type === "data" || e.type === "render") && v(e.data, ne, w, T.jwt), (i || Oe[e.type]) && Ue(e); + } + async function je() { + L && !R && (R = !0, I || await we, Te(), I || Y(), I && !Se && (await I({ + msg: "process_completed", + output: {}, + success: !0, + event_id: H + }), await new Promise((e) => setTimeout(e, 0)))); + let e = {}, t = {}; + e = { event_id: H }, t = { + event_id: H, + session_hash: d, + fn_index: E + }; + try { + if (!u) throw Error("Could not resolve app config"); + let n = R && C.resume_sessions ? 32 : 1; + for (let e = 0; e < n && (await (await c(`${u.root}${w}/${be}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(t) + })).json().catch(() => null))?.found === !1; e++); + await c(`${u.root}${w}/${ye}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(e) + }); + } catch { + console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."); + } + await Me(); + } + async function Me() { + if (!F || !C.resume_sessions) return; + x.delete(F), delete b[F], delete y[F], Y(); + let e = T.acknowledged_events; + e.add(F), delete _[F], e.size > br && e.delete(e.values().next().value), (await T.fetch(`${u.root}${w}/${ye}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify({ event_id: F }) + }).catch(() => null))?.ok && cn(F); + } + let Ne = async (e) => { + await this._resolve_heartbeat(e); + }; + async function Pe(e) { + if (!u) return; + let t = e.render_id; + T.session_restored && !T.restored_renders.has(t) && (T.restored_renders.add(t), T.session_store.restore_into(e.components)), u.components = [...u.components.filter((e) => e.props.rendered_in !== t), ...e.components], u.dependencies = [...u.dependencies.filter((e) => e.rendered_in !== t), ...e.dependencies]; + let n = u.components.some((e) => e.type === "state"), r = u.dependencies.some((e) => e.targets.some((e) => e[1] === "unload")); + u.connect_heartbeat = n || r, await Ne(u), G({ + type: "render", + data: e, + endpoint: V, + fn_index: E + }); + } + function Fe(e) { + return async function(t) { + try { + let { type: n, status: r, data: i, original_msg: a } = Ke(t, De[E]); + if (n == "heartbeat") return; + if (n === "update" && r && !U) G({ + type: "status", + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date(), + original_msg: a, + ...r + }); + else if (n === "complete") U = r; + else if (n == "unexpected_error" || n == "broken_connection") { + n === "unexpected_error" && (x.delete(e), r?.session_not_found && cn(e)), console.error("Unexpected error", r?.message); + let t = n === "broken_connection"; + G({ + type: "status", + stage: "error", + message: r?.message || "An Unexpected Error Occurred!", + queue: !0, + endpoint: V, + broken: t, + session_not_found: r?.session_not_found, + fn_index: E, + time: /* @__PURE__ */ new Date() + }); + } else if (n === "log") { + G({ + type: "log", + title: i.title, + log: i.log, + level: i.level, + endpoint: V, + duration: i.duration, + visible: i.visible, + fn_index: E + }); + return; + } else (n === "generating" || n === "streaming") && (G({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...r, + stage: r?.stage, + queue: !0, + endpoint: V, + fn_index: E + }), i && O.connection !== "stream" && [ + "sse_v2", + "sse_v2.1", + "sse_v3", + "sse_v4" + ].includes(A) && Et(y, H, i)); + i && (T.session_store.apply(i.state), T.session_store.record(O.outputs, i.data || [], u.components), G({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: i.data ? g(i.data, O, u.components, "output", C.with_null_state) : i.data, + endpoint: V, + fn_index: E + }), i.render_config && await Pe(i.render_config), U && (G({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...U, + stage: r?.stage, + queue: !0, + endpoint: V, + fn_index: E + }), Y())), (r?.stage === "complete" || r?.stage === "error") && (delete b[e], delete y[e], Y()); + } catch (e) { + console.error("Unexpected client exception", e), G({ + type: "status", + stage: "error", + message: "An Unexpected Error Occurred!", + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), L ? (Te(), Y()) : [ + "sse_v2", + "sse_v2.1", + "sse_v3", + "sse_v4" + ].includes(A) && (Tt(h, T.abort_controller), h.open = !1, Y()); + } + }; + } + async function Ie(e) { + H = e, F = e; + let t = Fe(e); + if (b[e] = t, x.add(e), e in _) { + for (let n of _[e]) n.msg === "process_completed" && [ + "sse", + "sse_v1", + "sse_v2", + "sse_v2.1", + "sse_v3", + "sse_v4" + ].includes(A) && x.delete(e), await t(n); + delete _[e]; + } + !h.open && x.has(e) && await T.open_stream(); + } + o && (H = o, F = o, this.events_to_resume.add(o)); + async function Le() { + let e = await ee(); + return { + ...me, + ...e || {} + }; + } + function K(e, t) { + if (t === 503) G({ + type: "status", + stage: "error", + message: Ce, + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date(), + visible: !0 + }); + else if (t === 422) G({ + type: "status", + stage: "error", + message: e.detail, + queue: !0, + endpoint: V, + fn_index: E, + code: "validation_error", + time: /* @__PURE__ */ new Date(), + visible: !0 + }); + else if (t !== 200) { + let t = e?.error === z; + G({ + type: "status", + stage: "error", + broken: t, + message: t ? z : e.detail || e.error, + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date(), + visible: !0 + }); + } else return !1; + return Y(), !0; + } + async function Re(e, t) { + if (!u) throw Error("Could not resolve app config"); + let n = new AbortController(); + ve = n, L = !0, T.own_stream_controllers.add(n); + let r = (e) => { + let t = I; + R || !t || ((e?.msg === "process_completed" || e?.msg === "unexpected_error") && (Se = !0), typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(t, 0, e) : t(e)); + }; + try { + let i = new URL(`${u.root}${w}/${ge}?${W}`); + C.resume_sessions && i.searchParams.set("acknowledgements", "true"), T.jwt && i.searchParams.set("__sign", T.jwt); + let a = (t) => T.fetch(i, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...C.token ? { Authorization: `Bearer ${C.token}` } : {}, + ...Object.fromEntries(Object.entries(e).filter(([e]) => e.toLowerCase() !== "accept")), + Accept: "text/event-stream" + }, + body: JSON.stringify({ + ...Ee, + session_hash: d, + state: t + }), + credentials: C.credentials ?? "same-origin", + signal: n.signal + }), o; + try { + if (o = await a(ie()), o.status === 409) { + let e = (await o.json().catch(() => null))?.detail?.missing_state; + Array.isArray(e) && (o = await a(ie(e))); + } + } catch { + n.signal.aborted ? !R && !C.resume_sessions && Y() : K({ error: z }, 500); + return; + } + if (!o.ok) { + let e; + try { + e = await o.json(); + } catch (t) { + e = { error: `Could not parse server response: ${t}` }; + } + K(e, o.status); + return; + } + let s = bt(o, n.signal), c = () => new Promise((e, t) => { + let r = () => t(/* @__PURE__ */ Error("aborted")); + if (n.signal.aborted) return r(); + n.signal.addEventListener("abort", r, { once: !0 }), s.next().then(e, t).finally(() => n.signal.removeEventListener("abort", r)); + }); + try { + for (;;) { + let { value: e, done: n } = await c(); + if (n) break; + if (!e.data) continue; + let i = JSON.parse(e.data); + !I && i.event_id && (H = i.event_id, F = H, C.resume_sessions && sn(u, d, { + event_id: H, + fn_index: E + }), I = Fe(H), t(), B()), (i.msg === "process_completed" || i.msg === "unexpected_error") && (xe = !0), r(i); + } + } catch {} + if (xe) return; + n.signal.aborted ? !R && !C.resume_sessions && Y() : !I || !H ? K({ error: z }, 500) : C.resume_sessions ? (L = !1, delete y[H], T.events_to_resume.add(H), h.open && (Tt(h, T.abort_controller), x.forEach((e) => { + T.events_to_resume.add(e), delete y[e]; + })), await Ie(H)) : r({ + msg: "broken_connection", + message: z + }); + } finally { + L = !1, T.own_stream_controllers.delete(n), B(); + } + } + let q = this.handle_blob(u.root, oe, D).then(async (e) => { + if (o) { + G({ + type: "status", + stage: "pending", + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), await Ie(o); + return; + } + let t = g(e, O, u.components, "input", !0); + if (_r(M, N, j(t || [])), T.session_store.record(O.inputs, (t || []).map((e, t) => { + let n = O.inputs[t], r = u.components.find((e) => e.id === n); + return de.has(n) || Ht(r) ? void 0 : e; + }), u.components), Ee = { + data: t || [], + event_data: n, + fn_index: E, + trigger_id: r, + ...C.oauth_token && D?.oauth_token ? { oauth_token: C.oauth_token } : {} + }, p(E, u)) G({ + type: "status", + endpoint: V, + stage: "pending", + queue: !1, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), ae(`${u.root}${w}/run${V.startsWith("/") ? V : `/${V}`}${W ? "?" + W : ""}`, { + ...Ee, + session_hash: d + }, me).then(async ([e, t]) => { + let i = e.data; + if (t == 200) T.session_store.apply(e.state), T.session_store.record(O.outputs, i || [], u.components), G({ + type: "data", + endpoint: V, + fn_index: E, + data: g(i, O, u.components, "output", C.with_null_state), + time: /* @__PURE__ */ new Date(), + event_data: n, + trigger_id: r + }), e.render_config && await Pe(e.render_config), G({ + type: "status", + endpoint: V, + fn_index: E, + stage: "complete", + eta: e.average_duration, + queue: !1, + time: /* @__PURE__ */ new Date() + }); + else { + let t = e?.error === z; + G({ + type: "status", + stage: "error", + endpoint: V, + fn_index: E, + message: e.error, + broken: t, + queue: !1, + time: /* @__PURE__ */ new Date() + }); + } + }).catch((e) => { + G({ + type: "status", + stage: "error", + message: e.message, + endpoint: V, + fn_index: E, + queue: !1, + time: /* @__PURE__ */ new Date() + }); + }); + else if (A == "sse") { + G({ + type: "status", + stage: "pending", + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }); + var i = new URLSearchParams({ + fn_index: E.toString(), + session_hash: d + }).toString(); + let e = new URL(`${u.root}${w}/${he}?${W ? W + "&" : ""}${i}`); + if (this.jwt && e.searchParams.set("__sign", this.jwt), P = this.stream(e), !P) return Promise.reject(/* @__PURE__ */ Error("Cannot connect to SSE endpoint: " + e.toString())); + P.onmessage = async function(e) { + let { type: t, status: i, data: a } = Ke(JSON.parse(e.data), De[E]); + if (t === "update" && i && !U) G({ + type: "status", + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date(), + ...i + }), i.stage === "error" && (P?.close(), Y()); + else if (t === "data") { + let [e, t] = await S(`${u.root}${w}/queue/data`, { + ...Ee, + session_hash: d, + event_id: H + }, me); + t !== 200 && (G({ + type: "status", + stage: "error", + message: z, + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), P?.close(), Y()); + } else t === "complete" ? U = i : t === "log" ? G({ + type: "log", + title: a.title, + log: a.log, + level: a.level, + endpoint: V, + duration: a.duration, + visible: a.visible, + fn_index: E + }) : (t === "generating" || t === "streaming") && G({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...i, + stage: i?.stage, + queue: !0, + endpoint: V, + fn_index: E + }); + a && (G({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: g(a.data, O, u.components, "output", C.with_null_state), + endpoint: V, + fn_index: E, + event_data: n, + trigger_id: r + }), U && (G({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...U, + stage: i?.stage, + queue: !0, + endpoint: V, + fn_index: E + }), P?.close(), Y())); + }; + } else if (A == "sse_v1" || A == "sse_v2" || A == "sse_v2.1" || A == "sse_v3") return G({ + type: "status", + stage: "pending", + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), Le().then((e) => ae(`${u.root}${w}/${ge}?${W}`, { + ...Ee, + session_hash: d + }, e)).then(async ([e, t]) => { + e.event_id && (F = e.event_id), K(e, t) || (H = e.event_id, F = H, C.resume_sessions && sn(u, d, { + event_id: H, + fn_index: E + }), await Ie(H)); + }); + else if (A == "sse_v4") return G({ + type: "status", + stage: "pending", + queue: !0, + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), Le().then((e) => new Promise((t, n) => { + Re(e, t).then(t, n); + })); + }); + q.catch((e) => { + G({ + type: "status", + stage: "error", + message: e instanceof Error ? e.message : String(e), + queue: !p(E, u), + endpoint: V, + fn_index: E, + time: /* @__PURE__ */ new Date() + }), Y(); + }); + let ze = !1, Be = [], J = []; + function Y() { + for (ze = !0; J.length > 0;) J.shift()({ + value: void 0, + done: !0 + }); + } + function Ve(e) { + J.length > 0 ? J.shift()(e) : Be.push(e); + } + function He(e) { + Ve(Sr(e)), Y(); + } + function Ue(e) { + Ve({ + value: e, + done: !1 + }); + } + function We() { + return Be.length > 0 ? Promise.resolve(Be.shift()) : ze ? Promise.resolve({ + value: void 0, + done: !0 + }) : new Promise((e) => J.push(e)); + } + let Ge = (e, t) => { + q.then(() => { + F && this.post_data(`${u.root}${w}/stream/${F}${e}`, t); + }, () => {}); + }, Je = { + [Symbol.asyncIterator]: () => Je, + next: We, + throw: async (e) => (He(e), We()), + return: async () => (Y(), { + value: void 0, + done: !0 + }), + cancel: je, + send_chunk: (e) => { + Ge("", { + ...e, + session_hash: this.session_hash + }), q.then(() => { + if (!(!N || U)) try { + let t = j(g(e.data, O, u.components, "input", !0)), n = JSON.stringify(t); + if (n === _e) return; + _e = n, _r(M, N, t); + } catch (e) { + console.warn("Could not update the run history.", e); + } + }, () => {}); + }, + close_stream: (e) => { + e?.read_to_end || Y(), Ge("/close", {}); + }, + event_id: () => F, + wait_for_id: async () => (await q, H), + acknowledge: Me + }; + return Je; + } catch (e) { + throw console.error("Submit function encountered an error:", e), e; + } +} +function Sr(e) { + return { then: (t, n) => n(e) }; +} +function Cr(e, t, n, r) { + let i, a, o; + if (typeof t == "number") i = t, a = e.unnamed_endpoints[i], o = r.dependencies.find((e) => e.id == t); + else { + let s = t.replace(/^\//, ""); + i = n[s], a = e.named_endpoints[t.trim()] ?? e.named_endpoints[`/${s}`], o = r.dependencies.find((e) => e.id == n[s]); + } + if (typeof i != "number" || !o) { + let e = r.dependencies.filter((e) => e.api_name).map((e) => `"/${e.api_name}"`).join(", "); + 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."); + } + return { + fn_index: i, + endpoint_info: a, + dependency: o + }; +} +var wr = 10, Tr = new Set(["state", "browserstate"]), Er = class { + state = /* @__PURE__ */ new Map(); + values = /* @__PURE__ */ new Map(); + app_prefix = ""; + key = null; + app_key = ""; + save_timer = null; + saving = null; + changed_while_saving = !1; + found = !1; + payload(e, t = []) { + let n = new Set(Array.from(t, String)), r = {}; + for (let t of e) { + let e = String(t), i = this.state.get(e); + i && (r[e] = n.has(e) || i.token.length <= 16384 ? { token: i.token } : { ref: i.ref }); + } + return r; + } + apply(e) { + if (!e) return; + let t = !1; + for (let [n, r] of Object.entries(e)) r === null ? t = this.state.delete(n) || t : r && typeof r.token == "string" && (this.state.set(n, { + ref: r.ref, + token: r.token + }), t = !0); + t && this.schedule_save(); + } + get(e) { + return this.state.get(String(e)); + } + get size() { + return this.state.size; + } + async forget() { + let e = this.key; + for (this.key = null, this.save_timer &&= (clearTimeout(this.save_timer), null); this.saving;) await this.saving; + this.state.clear(), this.values.clear(), this.found = !1, e !== null && await zt("sessions", e); + } + record(e, t, n) { + let r = !1; + for (let [i, a] of e.entries()) { + if (i >= t.length) break; + let e = t[i]; + if (e === void 0) continue; + let o = n.find((e) => e.id === a)?.type; + if (!o || Tr.has(o) || Gt(e) && Object.keys(e).length === 1) continue; + let s = String(a), c = this.values.get(s), l = c?.type === o ? c.props : {}; + Wt(l, e), this.values.set(s, { + type: o, + props: l + }), r = !0; + } + r && this.schedule_save(); + } + restore_into(e) { + let t = !1; + for (let n of e) { + let e = this.values.get(String(n.id)); + if (!e || Tr.has(n.type) || e.type !== n.type) continue; + let r = { ...e.props }; + Ht(n) && delete r.value, Object.assign(n.props, r), t = !0; + } + return t; + } + async attach(e, t, n, r = null) { + let i = r ? `user:${encodeURIComponent(r)}` : ""; + this.app_prefix = `${Vt(e, t)}|`; + let a = `${this.app_prefix}${i}|${n}`; + this.key = a, this.app_key = t ?? ""; + let o = await Lt("sessions", a); + if (o && this.key === a && o.app_key === this.app_key) { + this.found = !0; + for (let [e, t] of Object.entries(o.state ?? {})) this.state.has(e) || this.state.set(e, t); + for (let [e, t] of Object.entries(o.values ?? {})) this.values.has(e) || this.values.set(e, t); + } + Bt("sessions", { + max_age_ms: Mt, + except: a + }).then(() => Bt("sessions", { + prefix: this.app_prefix, + keep: wr - 1, + except: a + })), (this.state.size || this.values.size) && this.schedule_save(); + } + async flush() { + for (; this.save_timer || this.saving;) this.save_timer && (clearTimeout(this.save_timer), this.save_timer = null, this.start_save()), await this.saving; + } + schedule_save() { + if (this.key !== null) { + if (this.saving) { + this.changed_while_saving = !0; + return; + } + this.save_timer ||= setTimeout(() => { + this.save_timer = null, this.start_save(); + }, 0); + } + } + start_save() { + this.changed_while_saving = !1, this.saving = this.save().finally(() => { + this.saving = null, this.changed_while_saving && this.schedule_save(); + }); + } + async save() { + let e = this.key; + if (e === null) return; + if (this.state.size === 0 && this.values.size === 0) { + await zt("sessions", e); + return; + } + let t = { + key: e, + updated: Date.now(), + app_key: this.app_key, + state: Object.fromEntries(this.state), + values: Object.fromEntries(this.values) + }; + await Rt("sessions", t) || (await Bt("sessions", { + prefix: this.app_prefix, + keep: 0, + except: e + }), await Rt("sessions", t)); + } +}, Dr = class { + app_reference; + options; + deep_link = null; + page = null; + config; + api_prefix = ""; + api_info; + api_map = {}; + session_hash = Math.random().toString(36).substring(2); + jwt = !1; + last_status = {}; + session_store = new Er(); + cookies = null; + session_restored = !1; + restored_renders = /* @__PURE__ */ new Set(); + stream_status = { open: !1 }; + closed = !1; + pending_stream_messages = {}; + pending_diff_streams = {}; + event_callbacks = {}; + unclosed_events = /* @__PURE__ */ new Set(); + acknowledged_events = /* @__PURE__ */ new Set(); + events_to_resume = /* @__PURE__ */ new Set(); + stream_reconnect_attempts = 0; + stream_reconnect_timer = null; + heartbeat_event = null; + heartbeat_controller = null; + heartbeat_wanted = typeof window < "u" && typeof document < "u"; + abort_controller = null; + stream_instance = null; + own_stream_controllers = /* @__PURE__ */ new Set(); + current_payload; + get_url_config(e = null) { + if (!this.config) throw Error(B); + e === null && (e = window.location.href); + let t = (e) => e.replace(/^\/+|\/+$/g, ""), n = t(new URL(this.config.root).pathname), r = t(new URL(e).pathname), i; + return i = r.startsWith(n) ? t(r.substring(n.length)) : "", this.get_page_config(i); + } + get_page_config(e) { + if (!this.config) throw Error(B); + let t = this.config; + return e in t.page || (e = ""), { + ...t, + current_page: e, + layout: t.page[e].layout, + components: t.components.filter((n) => t.page[e].components.includes(n.id)), + dependencies: this.config.dependencies.filter((n) => t.page[e].dependencies.includes(n.id)) + }; + } + fetch(e, t) { + let n = new Headers(t?.headers || {}); + return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => { + n.append(t, e); + }), fetch(e, { + ...t, + headers: n + }); + } + stream(e, t) { + let n = new Headers(); + return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => { + n.append(t, e); + }), this && this.options.token && n.append("Authorization", `Bearer ${this.options.token}`), t || (t = new AbortController(), this.abort_controller = t), this.stream_instance = kt(e.toString(), { + credentials: this.options.credentials ?? "same-origin", + headers: n, + signal: t.signal + }), this.stream_instance; + } + view_api; + upload_files; + upload; + handle_blob; + post_data; + submit; + resume_jobs; + predict; + open_stream; + resolve_config; + resolve_cookies; + constructor(e, t = { events: ["data"] }) { + this.app_reference = e, this.deep_link = t.query_params?.deep_link || null, this.page = t.query_params?.page ?? null, t.events ||= ["data"], Pe(t), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = Je.bind(this), this.upload_files = Ye.bind(this), this.handle_blob = tt.bind(this), this.post_data = at.bind(this), this.submit = xr.bind(this), this.resume_jobs = (e = this.get_resumable_events()) => (this.options.resume_sessions = !0, e.map(({ fn_index: e, event_id: t }) => xr.call(this, e, {}, void 0, void 0, void 0, void 0, t))), this.predict = ot.bind(this), this.open_stream = St.bind(this), this.resolve_config = Le.bind(this), this.resolve_cookies = Re.bind(this), this.upload = Qe.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this); + } + async init() { + te(), le(this.app_reference), this.options.auth && await this.resolve_cookies(); + let e = await this._resolve_config(); + if (e?.config) { + let t = e.config; + t.resume_sessions === !1 && this.options.resume_sessions && (this.options.resume_sessions = !1, Zt()); + let n = this.options.resume_sessions && typeof sessionStorage < "u" ? await this.resume_session(t) : !1; + if (await Promise.all([this.options.resume_sessions ? this.session_store.attach(t.root, t.app_key, this.session_hash, Xt(t)) : Promise.resolve(), Rn(t)]), n && this.session_store.found) { + let e = await this.session_status(t); + !e.known && !e.state_persists ? (await this.session_store.forget(), this.session_hash = Math.random().toString(36).substring(2), rn(t, this.session_hash), await this.session_store.attach(t.root, t.app_key, this.session_hash, Xt(t))) : (this.session_store.restore_into(t.components), this.session_restored = e.known); + } + await this._resolve_heartbeat(t); + } + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(e.message); + } + this.api_map = Fe(this.config?.dependencies || []); + } + async session_status(e) { + try { + let t = new URL(`${e.root}${e.api_prefix ?? ""}/session_status`); + t.searchParams.set("session_hash", this.session_hash); + let n = await this.fetch(t, { + headers: this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}, + credentials: this.options.credentials ?? "same-origin" + }); + if (!n.ok) return { + known: !1, + state_persists: !0 + }; + let r = await n.json(); + return { + known: !!r.known, + state_persists: r.state_persists !== !1 + }; + } catch { + return { + known: !1, + state_persists: !0 + }; + } + } + async resume_session(e) { + await Qt(); + let t = this.options.session_hash ? null : $t(), n = !1; + return t && en(e, t) && (this.session_hash = t, n = nn(e, t)), rn(e, this.session_hash), typeof document < "u" && document.addEventListener("visibilitychange", () => an(document.visibilityState === "visible")), n; + } + async _resolve_heartbeat(e) { + this.config = e, this.api_prefix = e.api_prefix || "", le(e.root, e.version), e.space_id && this.options.token && (this.jwt = await Ne(e.space_id, this.options.token, this.cookies)), y(this.config, this.jwt), this.heartbeat_wanted && this.open_heartbeat(); + } + open_heartbeat() { + if (this.heartbeat_wanted = !0, !this.config?.connect_heartbeat || this.heartbeat_event) return; + let e = new URL(`${this.config.root}${this.api_prefix}/${L}/${this.session_hash}`); + this.jwt && e.searchParams.set("__sign", this.jwt), this.heartbeat_controller = new AbortController(), this.heartbeat_event = this.stream(e, this.heartbeat_controller); + } + static async connect(e, t = { events: ["data"] }) { + let n = new this(e, t); + return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n; + } + get_resumable_events() { + return !this.options.resume_sessions || !this.config ? [] : on(this.config, this.session_hash); + } + async reconnect() { + let e = new URL(`${this.config.root}${this.api_prefix}/${Se}`), t; + try { + let n = await this.fetch(e); + if (!n.ok) throw Error(); + t = (await n.json()).app_id; + } catch { + return "broken"; + } + return t === this.config.app_id ? "connected" : "changed"; + } + async clear_session() { + await this.session_store.forget(), Zt(); + } + close() { + if (!this.closed && this.options.resume_sessions && this.config && typeof window < "u") { + let e = { "Content-Type": "application/json" }; + this.options.token && (e.Authorization = `Bearer ${this.options.token}`), this.fetch(`${this.config.root}${this.api_prefix}/${xe}`, { + method: "POST", + headers: e, + body: JSON.stringify({ session_hash: this.session_hash }), + credentials: this.options.credentials ?? "same-origin", + keepalive: !0 + }).catch(() => {}), an(!1), this.session_store.flush(); + } + this.closed = !0, this.stream_reconnect_timer &&= (clearTimeout(this.stream_reconnect_timer), null), Tt(this.stream_status, this.abort_controller), this.own_stream_controllers.forEach((e) => e.abort()), this.own_stream_controllers.clear(), this.heartbeat_controller?.abort(), this.heartbeat_controller = null, this.heartbeat_event = null; + } + async refresh() { + if (!this.config) throw Error(B); + let e = await this.resolve_config(this.config.root, !1); + if (!e) throw Error(B); + this.config = e, this.api_prefix = e.api_prefix || "", this.api_map = Fe(e.dependencies || []), y(this.config, this.jwt); + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(Te + e.message); + } + return this.get_url_config(); + } + set_current_payload(e) { + this.current_payload = e; + } + static async duplicate(e, t = { events: ["data"] }) { + return mt(e, t); + } + async _resolve_config() { + let { http_protocol: e, host: t, space_id: n } = await Ve(this.app_reference, this.options.token), { status_callback: r } = this.options; + n && r && await ct(n, r); + let i; + try { + let n = `${e}//${t}`; + if (i = await this.resolve_config(n), !i) throw Error(B); + return this.config_success(i); + } catch (e) { + if (n && r) st(n, J.test(n) ? "space_name" : "subdomain", this.handle_space_success); + else throw r && r({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }), e instanceof Error ? e : Error(String(e)); + } + } + async config_success(e) { + if (this.config = e, this.api_prefix = e.api_prefix || "", e.run_history === !1 && dr(e), this.config.auth_required) return this.prepare_return_obj(); + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(Te + e.message); + } + return this.prepare_return_obj(); + } + async handle_space_success(e) { + if (!this) throw Error(B); + let { status_callback: t } = this.options; + if (t && t(e), e.status === "running") try { + if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config) throw Error(B); + return await this.config_success(this.config); + } catch (e) { + throw t && t({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }), e; + } + } + async component_server(e, t, n) { + if (!this.config) throw Error(B); + let r = {}, { token: i } = this.options, { session_hash: a } = this; + i && (r.Authorization = `Bearer ${this.options.token}`); + let o, s = this.config.components.find((t) => t.id === e); + o = s?.props?.root_url ? s.props.root_url : this.config.root; + let c; + if (typeof n == "object" && n && "binary" in n) { + let r = n; + c = new FormData(); + for (let e in r.data) e !== "binary" && c.append(e, r.data[e]); + c.set("component_id", e.toString()), c.set("fn_name", t), c.set("session_hash", a); + } else c = JSON.stringify({ + data: n, + component_id: e, + fn_name: t, + session_hash: a + }), r["Content-Type"] = "application/json"; + i && (r.Authorization = `Bearer ${i}`); + try { + let e = await this.fetch(`${o}${this.api_prefix}/${R}/`, { + method: "POST", + body: c, + headers: r, + credentials: this.options.credentials ?? "same-origin" + }); + if (!e.ok) throw Error("Could not connect to component server: " + e.statusText); + let t = await e.json(); + return v(t, this.config.root, this.config.api_prefix || "", this.jwt), t; + } catch (e) { + console.warn(e); + } + } + async webrtc_offer(e) { + let t = e.type === "offer" ? await w(ee(), 5e3, null) ?? {} : {}; + return this.post_webrtc("offer", e, t); + } + async webrtc_rtc_configuration(e) { + return this.post_webrtc("rtc_configuration", { webrtc_id: e }, {}); + } + async post_webrtc(e, t, n) { + if (!this.config) throw Error(B); + let [r, i] = await this.post_data(`${this.config.root}${this.api_prefix}/webrtc/${e}`, { + ...t, + session_hash: this.session_hash + }, n); + if (i !== 200) { + console.warn(`Could not reach the WebRTC ${e} route`, r); + return; + } + return r; + } + set_cookies(e) { + this.cookies = Be(e).join("; "); + } + prepare_return_obj() { + return { + config: this.config, + predict: this.predict, + submit: this.submit, + view_api: this.view_api, + component_server: this.component_server + }; + } +}; +async function Or(e, t = { events: ["data"] }) { + return await Dr.connect(e, t); +} +async function kr(e, t) { + return await Dr.duplicate(e, t); +} +//#endregion +//#region src/utils/bucket_sync.ts +var Ar = /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-][a-zA-Z0-9_./-]*$/; +function jr(e) { + return Ar.test(e) ? !e.split("/").some((e) => e === "" || e === "." || e === "..") : !1; +} +function Mr(e, t, n) { + let r = n ? `?${new URLSearchParams(n)}` : "", i = e.replace(/\/+$/, ""); + return i ? `${i}/gradio_api/run-history/${t}${r}` : typeof document < "u" && document.baseURI ? new URL(`gradio_api/run-history/${t}${r}`, document.baseURI).toString() : `gradio_api/run-history/${t}${r}`; +} +async function Nr(e) { + try { + let t = await e.json(); + return typeof t?.detail == "string" ? t.detail : `${e.status}`; + } catch { + return `${e.status}`; + } +} +async function Pr(e, t, n, r) { + try { + let i = await fetch(e, { + credentials: "include", + ...t + }); + return i.ok ? { + ok: !0, + status: i.status, + data: r(await i.json()) + } : { + ok: !1, + status: i.status, + data: n, + detail: await Nr(i) + }; + } catch (e) { + return { + ok: !1, + status: 0, + data: n, + detail: String(e) + }; + } +} +async function Fr(e, t, n) { + return jr(t) ? Pr(Mr(e, "connect"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(n ? { + bucket_id: t, + token: n + } : { bucket_id: t }) + }, null, () => null) : { + ok: !1, + status: 422, + data: null, + detail: "invalid bucket id" + }; +} +async function Ir(e) { + return Pr(Mr(e, "disconnect"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "{}" + }, null, () => null); +} +async function Lr(e) { + return Pr(Mr(e, "buckets"), {}, [], (e) => Array.isArray(e?.buckets) ? e.buckets : []); +} +async function Rr(e, t) { + return Pr(Mr(e, "records", { bucket: t }), {}, [], (e) => Array.isArray(e?.records) ? e.records : []); +} +function zr(e, t, n, r, i) { + return Mr(e, `records/${encodeURIComponent(n)}/${encodeURIComponent(r)}/assets/${encodeURIComponent(i)}`, { bucket: t }); +} +//#endregion +//#region src/index.ts +ue(); +//#endregion +export { Dr as Client, et as FileData, De as MISSING_CREDENTIALS_MSG, hr as apply_run_history_replay, zr as asset_url, dr as clear_run_history, Or as client, Fr as connect_bucket, mr as consume_run_history_replay, fr as delete_run_history, Ir as disconnect_bucket, kr as duplicate, C as get_zerogpu_origin, h as handle_file, ce as initialize_console_forwarding, oe as is_console_forward_origin_allowed, jr as is_valid_bucket_id, Rr as list_bucket_records, Lr as list_user_buckets, Rn as load_run_history, yr as on_run_history_change, ot as predict, $e as prepare_files, cr as read_run_history, lr as read_run_history_storage, Sn as run_history_url, ur as set_run_history_storage, pr as stage_run_history_replay, xr as submit, o as t, Qe as upload, Ye as upload_files };