File size: 1,782 Bytes
b87996d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Downloads big files once into the browser's origin-private file system (OPFS) and hands them back as lazily-read File objects.
const root = () => navigator.storage.getDirectory();
const exists = async (dir, name) => { try { return await dir.getFileHandle(name); } catch { return null; } };

export async function cachedFile(name, url, bytes, onProgress) {
  const dir = await root();
  const ok = await exists(dir, name + '.ok'), fh = await exists(dir, name);
  if (ok && fh) { const f = await fh.getFile(); if (f.size === bytes) return f; }
  await dir.removeEntry(name + '.ok').catch(() => {});
  const r = await fetch(url);
  if (!r.ok) throw new Error(`download of ${name} failed (HTTP ${r.status})`);
  let got = 0;
  const counter = new TransformStream({ transform(chunk, ctl) { got += chunk.length; onProgress?.(got, bytes); ctl.enqueue(chunk); } });
  const handle = await dir.getFileHandle(name, { create: true });
  try { await r.body.pipeThrough(counter).pipeTo(await handle.createWritable()); }
  catch (e) { await dir.removeEntry(name).catch(() => {}); throw /quota/i.test(`${e?.name} ${e?.message}`) ? new Error('Not enough free disk space in this browser for the model (about 5 GB).') : e; }
  const f = await handle.getFile();
  if (f.size !== bytes) { await dir.removeEntry(name).catch(() => {}); throw new Error(`${name}: expected ${bytes} bytes, got ${f.size}`); }
  await (await dir.getFileHandle(name + '.ok', { create: true })).createWritable().then((w) => w.close());
  return f;
}
export async function wipe() { const dir = await root(); for await (const [n] of dir.entries()) await dir.removeEntry(n, { recursive: true }); }
export async function usage() { try { const e = await navigator.storage.estimate(); return e.usage || 0; } catch { return 0; } }