gradio/js/wasm/svelte/file-url.ts
Yuichiro Tachibana (Tsuchiya) 5d00dd37ca
Make <UploadProgress /> Wasm-compatible (#6965)
* Make <UploadProgress /> Wasm-compatible

* add changeset

* Fix <DownloadLink /> not to prefetch the data in the Wasm mode

* add changeset

* Fix <DownloadLink /> to check the `window` object existence for SSR

* Lite: Fix and improve the file upload progress SSE (#6978)

* Update the Wasm ASGI connection to be able handle ReadableStream, which is used for example in <Upload />"

* Fix wasm_proxied_fetch() not to pass a leading '?' in the query_string to WorkerProxy.httpRequest() because it's required by the ASGI spec

* Fix FileUploadProgress.update() to merge a new item to the existing one in the queue

* Fix the SSE stream async task in the /upload_progress endpoint removing an unreached code block. `await asyncio.sleep()` has been moved from the unreached block to a live location, so the stream cadence has been reduced

* Fix `FileUploadProgress` to manage the `is_done` flag independent from the queue because it has a different semantics and checking it is a priority over reading other progress events to abort the SSE stream when uploading is done

* Refactoring

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
Co-authored-by: Ali Abdalla <ali.si3luwa@gmail.com>
2024-01-10 21:27:58 +04:00

56 lines
1.4 KiB
TypeScript

import { getWorkerProxyContext } from "./context";
import { is_self_host } from "../network/host";
import { getHeaderValue } from "../src/http";
type MediaSrc = string | undefined | null;
export function should_proxy_wasm_src(src: MediaSrc): boolean {
if (src == null) {
return false;
}
const url = new URL(src);
if (!is_self_host(url)) {
// `src` is not accessing a local server resource, so we don't need to proxy this request to the Wasm worker.
return false;
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
// `src` can be a data URL.
return false;
}
return true;
}
export async function resolve_wasm_src(src: MediaSrc): Promise<MediaSrc> {
if (src == null || !should_proxy_wasm_src(src)) {
return src;
}
const maybeWorkerProxy = getWorkerProxyContext();
if (maybeWorkerProxy == null) {
// We are not in the Wasm env. Just use the src as is.
return src;
}
const url = new URL(src);
const path = url.pathname;
return maybeWorkerProxy
.httpRequest({
method: "GET",
path,
headers: {},
query_string: ""
})
.then((response) => {
if (response.status !== 200) {
throw new Error(`Failed to get file ${path} from the Wasm worker.`);
}
const blob = new Blob([response.body], {
type: getHeaderValue(response.headers, "content-type")
});
const blobUrl = URL.createObjectURL(blob);
return blobUrl;
});
}