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
import { html } from "https://esm.town/v/postpostscript/html";
import { getValEndpointFromUrl, getValNameFromUrl } from "https://esm.town/v/postpostscript/meta";
import { blob } from "https://esm.town/v/std/blob";
export const URL = getValEndpointFromUrl(import.meta.url);
export const DEFAULT_PREFIX = `${getValNameFromUrl(import.meta.url)}:`;
export async function poll(url = URL, { initialDelay = 1000, tries = 10, retryMs = 1000, log = true }) {
for (let i = 0; i < tries; i++) {
try {
log && console.log("provideBlob.poll attempt", url);
const res = await fetch(url, {
headers: {
"Content-Type": "application/octet-stream",
},
});
if (res.status !== 200) {
throw new Error(await res.text());
}
log && console.log("provideBlob.poll attempt succeeded", url);
return res.blob();
} catch (e) {
log && console.log("provideBlob.poll attempt failed:", e.message, url);
}
await new Promise((resolve) => setTimeout(resolve, retryMs));
}
}
export function provideBlob(getValue: (() => Promise<any> | any) | Promise<any>, prefix = DEFAULT_PREFIX) {
const id = crypto.randomUUID();
const result = (async () => {
let value;
try {
value = await (getValue instanceof Promise
? getValue
: getValue());
} catch (e) {
value = {
"error": e.message,
};
}
blob.set(`${prefix}${id}`, value);
return value;
})();
const url = `${URL}/${id}`;
return {
url,
result,
jsPromise({ initialDelay = 1000, tries = 10, retryMs = 1000, log = true } = {}) {
return html`(async () => {
// https://stackoverflow.com/a/9899701
// licence: CC BY-SA 4.0
function docReady(fn) {
if (document.readyState === "complete" || document.readyState === "interactive") {
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
const url = ${JSON.stringify(url)};
window.provideBlobCache ??= {}
const result = new Promise((resolve, reject) => {
window.provideBlobCache[url] = {
resolve,
reject,
}
})
docReady(() => {
const $script = document.createElement("script")
$script.type = "module"
$script.innerHTML = \`
import { poll } from "${import.meta.url}"
const url = ${JSON.stringify(url)}
const {
resolve,
reject,
} = window.provideBlobCache[url]
poll(url, {
initialDelay: ${initialDelay},
tries: ${tries},
retryMs: ${retryMs},
log: ${log},
})
.then(resolve)
.catch(reject)
\`
document.body.appendChild($script)
})
return result
})()`;