concept-collection / stan-remote-sampling
stan-remote-sampling / src / compileStanProgram.ts
59 lines · 1.7 KBBlameHistoryRaw
1// Same compilation mechanism as stan-playground: POST the program to the
2// compilation server, then download the compiled artifact. The server
3// (stan-wasm-wasi) produces a pure-WASI command module at
4// /download/{model_id}/main.wasm, runnable on wasm-exec workers.
6export const DEFAULT_WASI_SERVER_URL = "https://stan-wasm-wasi.fly.dev";
8const compileStanProgram = async (
9 serverUrl: string,
10 stanProgram: string,
11 onStatus: (s: string) => void,
12): Promise<{ artifactUrl?: string }> => {
13 try {
14 onStatus("compiling...");
16 const compileURL = `${serverUrl}/compile`;
17 const runCompile = await fetch(compileURL, {
18 method: "POST",
19 headers: {
20 "Content-Type": "text/plain",
21 Authorization: "Bearer 1234",
22 },
23 body: stanProgram,
24 });
25 if (!runCompile.ok) {
26 onStatus(`failed to compile: ${await messageOrStatus(runCompile)}`);
27 return {};
28 }
29 const compileResp = await runCompile.json();
30 const artifactUrl = `${serverUrl}/download/${compileResp.model_id}/main.wasm`;
32 // download to make sure it is there
33 onStatus("checking download of main.wasm");
34 const downloadCheck = await fetch(artifactUrl, { method: "HEAD" });
35 if (!downloadCheck.ok) {
36 onStatus(
37 `failed to download main.wasm: ${await messageOrStatus(downloadCheck)}`,
38 );
39 return {};
40 }
42 onStatus("compiled");
43 return { artifactUrl };
44 } catch (e) {
45 onStatus(`failed to compile: ${e}`);
46 return {};
47 }
48};
50const messageOrStatus = async (response: Response) => {
51 try {
52 const j = await response.json();
53 return j?.message ?? response.statusText;
54 } catch {
55 return response.statusText;
56 }
57};
59export default compileStanProgram;