Spaces:
Running

File size: 5,123 Bytes
1d919a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// fastloader.js is the browser side of fastloader. It has two paths:
//
//   compile / instantiate   the page compiles the guest (ai.encryptid.systems)
//   connect                 the server keeps the instance (encryptid.systems)
//
// compile runs once per URL per page. It uses the streaming compiler when
// the bytes are plain wasm. When they need peeling (opts.peel, such as
// WASMJsLoader's guestCore), the peeled core is kept in Cache Storage
// under the response's ETag. The next load skips peeling and compiles that
// core with the streaming compiler too.
//
//   import { guestCore } from "./loader.js";
//   import { compile, connect } from "./fastloader.js";
//   const mod = await compile("guest/cmdterm.wasm", { peel: guestCore });
//   const api = connect("");
//   await api.call("add", "add", [2, 3]); // "5"

const STORE = "fastloader-v1";
const memo = new Map();

// compile returns a WebAssembly.Module for url. Concurrent and repeat calls
// share one compile. opts.peel(Uint8Array) -> Uint8Array strips a wrapper.
// opts.store names the Cache Storage bucket, or false for none.
export function compile(url, opts = {}) {
  const key = new URL(url, baseURL()).href;
  let p = memo.get(key);
  if (!p) {
    p = compileOnce(key, opts);
    p.catch(() => memo.delete(key));
    memo.set(key, p);
  }
  return p;
}

// instantiate compiles url (once) and instantiates it with imports.
export async function instantiate(url, imports = {}, opts = {}) {
  const mod = await compile(url, opts);
  return WebAssembly.instantiate(mod, imports);
}

// preload starts compiles now so a later compile or instantiate is warm.
export function preload(urls, opts = {}) {
  return Promise.all(urls.map((u) => compile(u, opts)));
}

// forget drops url from this page's memo and from the store.
export async function forget(url, opts = {}) {
  const key = new URL(url, baseURL()).href;
  memo.delete(key);
  const store = await openStore(opts.store);
  if (store) await dropCores(store, key, "");
}

async function compileOnce(url, opts) {
  const res = await fetch(url);
  if (!res.ok) throw new Error("fastloader: fetch " + url + " " + res.status);
  const tag = res.headers.get("etag") || res.headers.get("last-modified") || "";
  const store = opts.peel && tag ? await openStore(opts.store) : null;
  const coreKey = store ? coreURL(url, tag) : "";

  if (store) {
    const hit = await store.match(coreKey);
    if (hit) {
      cancel(res);
      return WebAssembly.compileStreaming(hit);
    }
  }

  // Plain wasm streams straight into the compiler. A wrapped guest can be
  // a valid module itself, so with peel the bytes are always peeled.
  if (!opts.peel && isWasm(res)) return WebAssembly.compileStreaming(res);

  const raw = new Uint8Array(await res.arrayBuffer());
  const core = opts.peel ? opts.peel(raw) : raw;
  if (store) {
    // Stored after the compile starts; this load does not wait on it.
    // A quota error or private window just means no stored core.
    dropCores(store, url, coreKey)
      .then(() => store.put(coreKey, new Response(core, { headers: { "Content-Type": "application/wasm" } })))
      .catch(() => {});
  }
  return WebAssembly.compile(core);
}

// connect calls exports on an instance the fastloader server keeps open.
// call sends args as strings and returns the export's result as text.
// abi: "string" selects the packed string ABI (compileGML).
export function connect(base = "") {
  const root = String(base).replace(/\/+$/, "");
  return {
    async modules() {
      const res = await fetch(root + "/modules");
      if (!res.ok) throw new Error("fastloader: modules " + res.status + " " + (await res.text()));
      return res.json();
    },
    async call(module, fn, args = [], opts = {}) {
      const q = opts.abi === "string" ? "?abi=string" : "";
      const res = await fetch(root + "/" + encodeURIComponent(module) + "/" + encodeURIComponent(fn) + q, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(args.map(String)),
      });
      const text = await res.text();
      if (!res.ok) throw new Error("fastloader: " + module + "." + fn + ": " + text.trim());
      return text;
    },
  };
}

function baseURL() {
  return typeof location !== "undefined" ? location.href : "http://localhost/";
}

function isWasm(res) {
  return (res.headers.get("content-type") || "").split(";")[0].trim() === "application/wasm";
}

function cancel(res) {
  if (res.body) res.body.cancel().catch(() => {});
}

function coreURL(url, tag) {
  return url + (url.includes("?") ? "&" : "?") + "fastloader-core=" + encodeURIComponent(tag);
}

async function openStore(name) {
  if (name === false || typeof caches === "undefined") return null;
  try {
    return await caches.open(name || STORE);
  } catch (_) {
    return null;
  }
}

// dropCores deletes stored cores of url other than keep.
async function dropCores(store, url, keep) {
  const prefix = coreURL(url, "");
  for (const req of await store.keys()) {
    if (req.url.startsWith(prefix) && req.url !== keep) await store.delete(req);
  }
}