import { Resource, RespackEntry } from "./resources.ts"; export abstract class Loader { num_loading: number = 0 abstract download(res: Resource): Promise abstract get_entry(): Promise>; abstract wait_ready(): Promise } export class HTTPLoader extends Loader { constructor() { super(); } // deno-lint-ignore require-await async wait_ready(): Promise { return } async download(res: Resource): Promise { this.num_loading += 1 const resp = await fetch(`http://127.0.0.1:28556/${res.toString()}`) if (!resp.ok) throw new Error("aaaa"); const buf = await resp.bytes() this.num_loading -= 1 return buf } async get_entry(): Promise> { const resp = await fetch("http://127.0.0.1:28556/entry") if (!resp.ok) throw new Error("aaaa"); return new Resource(await resp.bytes()) } } export class WSLoader extends Loader { ws: WebSocket queue: ((r: Uint8Array) => void)[] = [] constructor() { super() this.ws = new WebSocket(`http://127.0.0.1:28557/`) this.ws.onopen = () => console.log("open"); this.ws.onclose = () => console.log("close"); this.ws.onmessage = m => { if (typeof m.data == "string") throw new Error(m.data); if (m.data instanceof Blob) { const h = this.queue.shift()! m.data.arrayBuffer() .then(b => new Uint8Array(b)) .then(h) .then(() => this.num_loading -= 1) } } } wait_ready(): Promise { return new Promise(resolve => { if (this.ws.readyState == this.ws.OPEN) return resolve() else this.ws.addEventListener("open", () => resolve()) }) } download(res: Resource): Promise { return new Promise(resolve => { this.num_loading += 1 this.queue.push(resolve) this.ws.send(res.hash) }) } get_entry(): Promise> { return new Promise(resolve => { this.num_loading += 1 this.queue.push(buf => resolve(new Resource(buf))) this.ws.send("entry") }) } }