gradio/js/wasm/svelte/file-url.ts
Yuichiro Tachibana (Tsuchiya) 11a3007916
Lite: Support opening the entrypoint HTML page directly in browser via the file: protocol (#5972)
* Use a special fake hostname for the API access when the page is opened via the `file:` protocol

* Move js/app/src/lite/url.ts -> js/wasm/svelte/host.ts

* Add a comment

* Move js/wasm/svelte/host.ts -> js/wasm/network/host.ts

* add changeset

* Add a comment

* add changeset

* Update js/wasm/package.json adding a ESM subpath

* Fix `is_self_host()`

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
2023-10-17 23:25:01 -07:00

46 lines
1.1 KiB
TypeScript

import { getWorkerProxyContext } from "./context";
import { is_self_host } from "../network/host";
type MediaSrc = string | undefined | null;
export async function resolve_wasm_src(src: MediaSrc): Promise<MediaSrc> {
if (src == null) {
return src;
}
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 src;
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
// `src` can be a data URL.
return src;
}
const maybeWorkerProxy = getWorkerProxyContext();
if (maybeWorkerProxy == null) {
// We are not in the Wasm env. Just use the src as is.
return 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: response.headers["Content-Type"]
});
const blobUrl = URL.createObjectURL(blob);
return blobUrl;
});
}