| 1 |
|
| 2 |
const SYNTHESIS_CACHE_VERSION = 2; |
| 3 |
document.addEventListener('DOMContentLoaded', function () { |
| 4 |
const errorDiv = document.getElementById('error'); |
| 5 |
const outputDiv = document.getElementById('output'); |
| 6 |
const stdoutDiv = document.getElementById('stdoutContainer'); |
| 7 |
const stderrDiv = document.getElementById('stderrContainer'); |
| 8 |
const stdoutBox = document.getElementById('stdout'); |
| 9 |
const stderrBox = document.getElementById('stderr'); |
| 10 |
const outputFilesContainer = document.getElementById('outputFilesContainer'); |
| 11 |
const versionBox = document.getElementById('version'); |
| 12 |
const wasmCheckbox = document.getElementById('wasm'); |
| 13 |
const inputForm = document.getElementById('inputForm'); |
| 14 |
const inputArgs = document.getElementById('inputArgs'); |
| 15 |
const synthesizeButton = document.getElementById('synthesizeButton'); |
| 16 |
const cancelButton = document.getElementById('cancelButton'); |
| 17 |
const clearCacheButton = document.getElementById('clearCacheButton'); |
| 18 |
const permalink = document.getElementById('permalink'); |
| 19 |
const statusSpan = document.getElementById('status'); |
| 20 |
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); |
| 21 |
const isMacOrIOS = /Macintosh|MacIntel|MacPPC|Mac68K|iPhone|iPad|iPod/.test(navigator.platform); |
| 22 |
|
| 23 |
function splitUnescapedSpaces(input) { |
| 24 |
return input |
| 25 |
.replace(/\\\\/g, '\u0000') |
| 26 |
.replace(/\\ /g, '\u0001') |
| 27 |
.split(/ +/) |
| 28 |
.filter(s => s) |
| 29 |
.map(s => s |
| 30 |
.replace(/\u0000/g, '\\') |
| 31 |
.replace(/\u0001/g, ' ') |
| 32 |
); |
| 33 |
} |
| 34 |
|
| 35 |
function joinWithEscaping(inputArray) { |
| 36 |
return inputArray |
| 37 |
.map(s => s |
| 38 |
.replace(/\\/g, '\\\\') |
| 39 |
.replace(/ /g, '\\ ') |
| 40 |
) |
| 41 |
.join(' '); |
| 42 |
} |
| 43 |
|
| 44 |
function parseToStringArray(str, name) { |
| 45 |
let args = JSON.parse(str); |
| 46 |
if (!Array.isArray(args) || !args.every(arg => typeof arg === 'string')) { |
| 47 |
throw new Error(`Invalid: ${name} is not an array of strings`); |
| 48 |
} |
| 49 |
return args; |
| 50 |
} |
| 51 |
|
| 52 |
function parseToStringArrayArray(str, name) { |
| 53 |
let args = JSON.parse(str); |
| 54 |
if (!Array.isArray(args) || !args.every(arg => Array.isArray(arg) && arg.every(arg2 => typeof arg2 === 'string'))) { |
| 55 |
throw new Error(`Invalid: ${name} is not an array of arrays of strings`); |
| 56 |
} |
| 57 |
return args; |
| 58 |
} |
| 59 |
|
| 60 |
function parseToStringMapStringArray(str, name) { |
| 61 |
let args = JSON.parse(str); |
| 62 |
if (typeof args !== 'object') { |
| 63 |
throw new Error(`Invalid: ${name} is not an object`); |
| 64 |
} |
| 65 |
if (args === null) { |
| 66 |
throw new Error(`Invalid: ${name} is null`); |
| 67 |
} |
| 68 |
if (Array.isArray(args)) { |
| 69 |
throw new Error(`Invalid: ${name} is an array, not a mapping from strings to arrays of strings`); |
| 70 |
} |
| 71 |
Object.entries(args).forEach(([key, value]) => { |
| 72 |
if (typeof key !== 'string') { |
| 73 |
throw new Error(`Invalid: ${name} has non-string key ${key}`); |
| 74 |
} |
| 75 |
if (!Array.isArray(value) || !value.every(value2 => typeof value2 === 'string')) { |
| 76 |
throw new Error(`Invalid: ${name} has non-array value ${value} for key ${key}`); |
| 77 |
} |
| 78 |
}); |
| 79 |
return args; |
| 80 |
} |
| 81 |
|
| 82 |
function isValidJsonStringArray(str) { |
| 83 |
try { |
| 84 |
parseToStringArray(str); |
| 85 |
return true; |
| 86 |
} catch (e) { |
| 87 |
return false; |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
function validateInput() { |
| 92 |
const isJson = document.querySelector('input[name="inputType"][value="json"]').checked; |
| 93 |
const isValid = !isJson || isValidJsonStringArray(inputArgs.value); |
| 94 |
synthesizeButton.disabled = !isValid; |
| 95 |
document.querySelector('input[name="inputType"]:not([value="json"])').disabled = !isValid; |
| 96 |
} |
| 97 |
|
| 98 |
function enableForm() { |
| 99 |
inputArgs.disabled = false; |
| 100 |
synthesizeButton.disabled = false; |
| 101 |
cancelButton.disabled = true; |
| 102 |
} |
| 103 |
|
| 104 |
function setOutputFiles(files) { |
| 105 |
|
| 106 |
outputFilesContainer.innerHTML = ''; |
| 107 |
|
| 108 |
|
| 109 |
const fileEntries = Object.entries(files); |
| 110 |
|
| 111 |
|
| 112 |
if (fileEntries.length > 0) { |
| 113 |
|
| 114 |
fileEntries.forEach(([filename, contents]) => { |
| 115 |
|
| 116 |
const fileHtml = ` |
| 117 |
<div class="code-container"> |
| 118 |
<pre class="output-filename">${escapeHtml(filename)}:</pre> |
| 119 |
<code id="output-file-${escapeHtml(filename)}" class="code"></code> |
| 120 |
<button class="copy-button" data-target="output-file-${escapeHtml(filename)}">Copy</button> |
| 121 |
</div> |
| 122 |
`; |
| 123 |
|
| 124 |
|
| 125 |
const template = document.createElement('template'); |
| 126 |
template.innerHTML = fileHtml.trim(); |
| 127 |
const entry = template.content.firstElementChild.cloneNode(true); |
| 128 |
entry.querySelector('.code').textContent = contents; |
| 129 |
outputFilesContainer.appendChild(entry); |
| 130 |
}); |
| 131 |
outputFilesContainer.classList.remove('hidden'); |
| 132 |
} else { |
| 133 |
outputFilesContainer.classList.add('hidden'); |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
function clearOutput() { |
| 138 |
errorDiv.textContent = ''; |
| 139 |
stdoutBox.textContent = ''; |
| 140 |
stderrBox.textContent = ''; |
| 141 |
setOutputFiles({}); |
| 142 |
errorDiv.classList.add('hidden'); |
| 143 |
outputDiv.classList.add('hidden'); |
| 144 |
stderrDiv.classList.add('hidden'); |
| 145 |
stdoutDiv.classList.add('hidden'); |
| 146 |
} |
| 147 |
|
| 148 |
function escapeHtml(html) { |
| 149 |
var text = document.createTextNode(html); |
| 150 |
var p = document.createElement('p'); |
| 151 |
p.appendChild(text); |
| 152 |
return p.innerHTML; |
| 153 |
} |
| 154 |
|
| 155 |
|
| 156 |
function displayError(message, isHtml = false) { |
| 157 |
if (isHtml) { |
| 158 |
errorDiv.innerHTML = message; |
| 159 |
} else { |
| 160 |
errorDiv.textContent = message; |
| 161 |
} |
| 162 |
if (message) { |
| 163 |
errorDiv.classList.remove('hidden'); |
| 164 |
const consoleMessage = message.replace(/<br\s*\/?>/gi, '\n'); |
| 165 |
console.error(consoleMessage); |
| 166 |
} else { |
| 167 |
errorDiv.classList.add('hidden'); |
| 168 |
} |
| 169 |
enableForm(); |
| 170 |
} |
| 171 |
|
| 172 |
function displayOutput(stdout, stderr, outputFiles) { |
| 173 |
stdoutBox.textContent = stdout; |
| 174 |
stderrBox.textContent = stderr; |
| 175 |
setOutputFiles(outputFiles); |
| 176 |
outputDiv.classList.remove('hidden'); |
| 177 |
if (stdout) { |
| 178 |
stdoutDiv.classList.remove('hidden'); |
| 179 |
} else { |
| 180 |
stdoutDiv.classList.add('hidden'); |
| 181 |
} |
| 182 |
if (stderr) { |
| 183 |
console.error(stderr); |
| 184 |
stderrDiv.classList.remove('hidden'); |
| 185 |
} else { |
| 186 |
stderrDiv.classList.add('hidden'); |
| 187 |
} |
| 188 |
enableForm(); |
| 189 |
} |
| 190 |
|
| 191 |
function updatePermalink(args) { |
| 192 |
const wasmString = wasmCheckbox.checked ? '&wasm' : ''; |
| 193 |
const stdin = getStdinFromFormBoxRaw(); |
| 194 |
const files = getFilesFromFormBoxRaw(); |
| 195 |
const stdinString = stdin ? `&stdin=${encodeURIComponent(stdin)}` : ''; |
| 196 |
const filesString = files ? `&files=${encodeURIComponent(files)}` : ''; |
| 197 |
const inputType = document.querySelector('input[name="inputType"]:checked').value === 'json' ? `&inputType=json` : ''; |
| 198 |
const inputTypeString = inputType !== 'string' ? `&inputType=${inputType}` : ''; |
| 199 |
const queryString = `?argv=${encodeURIComponent(JSON.stringify(args.slice(1)))}${stdinString}${filesString}${inputTypeString}&interactive${wasmString}`; |
| 200 |
|
| 201 |
let baseUrl = window.location.href.split('?')[0]; |
| 202 |
permalink.href = baseUrl + queryString; |
| 203 |
permalink.classList.remove('hidden'); |
| 204 |
} |
| 205 |
|
| 206 |
function updateStatus(message) { |
| 207 |
statusSpan.textContent = message; |
| 208 |
if (message) { |
| 209 |
statusSpan.classList.remove('hidden'); |
| 210 |
} else { |
| 211 |
statusSpan.classList.add('hidden'); |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
function handleSynthesisResultData(result) { |
| 216 |
const success = result[0]; |
| 217 |
const exceptionText = result[1]; |
| 218 |
const stdout = result[2]; |
| 219 |
const stderr = result[3]; |
| 220 |
const files = result[4]; |
| 221 |
|
| 222 |
if (!success) { |
| 223 |
displayError(exceptionText.join('\n')); |
| 224 |
} |
| 225 |
const filesMap = {}; |
| 226 |
for (const [key, value] of files) { |
| 227 |
filesMap[key] = value.join(''); |
| 228 |
} |
| 229 |
displayOutput(stdout.join(''), stderr.join(''), filesMap); |
| 230 |
} |
| 231 |
|
| 232 |
function handleException(err) { |
| 233 |
const errHtml = err === undefined ? 'undefined error message (try opening the developer console)' : escapeHtml(`${err.name}: ${err.message}`); |
| 234 |
let errorMessage = `Synthesis failed: ${errHtml}`; |
| 235 |
|
| 236 |
if (err === undefined || /stack size exceeded|too much recursion/i.test(err.message)) { |
| 237 |
if (!isSafari) { |
| 238 |
errorMessage += "<br>Unfortunately Chrome, Firefox, and the ECMAScript Standard don't support proper tail-call elimination for unfortunate <a href=\"https://stackoverflow.com/a/54721813/377022\">historical</a> <a href=\"https://medium.com/indigoag-eng/tail-call-optimization-in-the-wild-26a10e450c73\">reasons</a>."; |
| 239 |
|
| 240 |
if (!isMacOrIOS) { |
| 241 |
errorMessage += "<br>Consider using WASM or opening this page in <a href=\"https://www.apple.com/safari/\">Safari</a> on a Mac or iOS device instead."; |
| 242 |
} else { |
| 243 |
errorMessage += "<br>Consider using WASM or opening this page in <a href=\"https://www.apple.com/safari/\">Safari</a> instead."; |
| 244 |
} |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
clearOutput(); |
| 249 |
displayError(errorMessage, true); |
| 250 |
updateStatus(""); |
| 251 |
} |
| 252 |
|
| 253 |
function handleSynthesisResult(result, cached) { |
| 254 |
console.log({ 'handleSynthesisResult result': result }); |
| 255 |
const extraCachedString = [ |
| 256 |
result.fiat_crypto_version == fiat_crypto_version ? '' : ` in ${result.fiat_crypto_version}`, |
| 257 |
result.method === undefined ? '' : ` via ${result.method}`, |
| 258 |
].join(''); |
| 259 |
const cachedString = cached ? ` (cached on ${result.timestamp}${extraCachedString})` : ''; |
| 260 |
if (result.success) { |
| 261 |
clearOutput(); |
| 262 |
updateStatus(`Synthesis completed in ${result.time} seconds${cachedString}`); |
| 263 |
handleSynthesisResultData(result.result); |
| 264 |
} else { |
| 265 |
handleException(result.result); |
| 266 |
updateStatus(`Synthesis failed in ${result.time} seconds${cachedString}`); |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
let fiatCryptoWorker; |
| 271 |
let wasmFiatCryptoWorker; |
| 272 |
|
| 273 |
function setupWorkers() { |
| 274 |
fiatCryptoWorker = new Worker("fiat_crypto_worker.js"); |
| 275 |
wasmFiatCryptoWorker = new Worker("wasm_fiat_crypto_worker.js"); |
| 276 |
|
| 277 |
|
| 278 |
[fiatCryptoWorker, wasmFiatCryptoWorker].forEach(worker => { |
| 279 |
worker.onmessage = function (e) { |
| 280 |
console.log(`Early synthesis result: ${e.data}`); |
| 281 |
}; |
| 282 |
|
| 283 |
worker.onerror = function (err) { |
| 284 |
handleException(err); |
| 285 |
}; |
| 286 |
}); |
| 287 |
} |
| 288 |
|
| 289 |
function cancelWorkers() { |
| 290 |
[fiatCryptoWorker, wasmFiatCryptoWorker].forEach(worker => worker.terminate()); |
| 291 |
console.log("Synthesis workers terminated."); |
| 292 |
|
| 293 |
|
| 294 |
setupWorkers(); |
| 295 |
} |
| 296 |
|
| 297 |
|
| 298 |
function errorJSONReplacer(key, value) { |
| 299 |
|
| 300 |
if (value instanceof Error) { |
| 301 |
return { |
| 302 |
name: value.name, |
| 303 |
message: value.message, |
| 304 |
stack: value.stack, |
| 305 |
cause: value.cause, |
| 306 |
}; |
| 307 |
} |
| 308 |
return value; |
| 309 |
} |
| 310 |
|
| 311 |
function handleSynthesis(args, stdin, files) { |
| 312 |
const startTime = performance.now(); |
| 313 |
const cacheKey = 'synthesize_' + JSON.stringify([args, stdin, files]); |
| 314 |
const cached = localStorage.getItem(cacheKey); |
| 315 |
console.log({ 'synthesize args': [args, stdin, files] }); |
| 316 |
updateStatus("Synthesizing..."); |
| 317 |
updatePermalink(args); |
| 318 |
|
| 319 |
if (cached) { |
| 320 |
const cachedData = JSON.parse(cached); |
| 321 |
if (cachedData.version === SYNTHESIS_CACHE_VERSION) { |
| 322 |
handleSynthesisResult(cachedData, true); |
| 323 |
return; |
| 324 |
} else { |
| 325 |
console.log(`cache miss: version ${cachedData.version} (${cachedData.fiat_crypto_version}), expected ${SYNTHESIS_CACHE_VERSION}`) |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
const useWasm = wasmCheckbox.checked; |
| 330 |
|
| 331 |
const recieveMessage = function (success) { |
| 332 |
return function (e) { |
| 333 |
const endTime = performance.now(); |
| 334 |
const timeTaken = (endTime - startTime) / 1000; |
| 335 |
const now = new Date(); |
| 336 |
const resultData = { |
| 337 |
result: success ? (e.data.error !== undefined ? e.data.error : e.data.result) : e.data, |
| 338 |
time: timeTaken, |
| 339 |
success: success && e.data !== undefined && e.data.error === undefined, |
| 340 |
timestamp: now.toISOString(), |
| 341 |
version: SYNTHESIS_CACHE_VERSION, |
| 342 |
fiat_crypto_version: fiat_crypto_version, |
| 343 |
method: useWasm ? 'wasm_of_ocaml' : 'js_of_ocaml', |
| 344 |
}; |
| 345 |
try { |
| 346 |
localStorage.setItem(cacheKey, JSON.stringify(resultData, errorJSONReplacer)); |
| 347 |
} catch (e) { |
| 348 |
console.error(`Failed: localStorage.setItem(${JSON.stringify(cacheKey)}, ${JSON.stringify(JSON.stringify(resultData))})`); |
| 349 |
} |
| 350 |
handleSynthesisResult(resultData, false); |
| 351 |
}; |
| 352 |
}; |
| 353 |
|
| 354 |
const currentWorker = useWasm ? wasmFiatCryptoWorker : fiatCryptoWorker; |
| 355 |
const filesList = Object.entries(files).map(([name, contents]) => [name, ...contents]); |
| 356 |
currentWorker.postMessage([[args], stdin, filesList]); |
| 357 |
currentWorker.onmessage = recieveMessage(true); |
| 358 |
currentWorker.onerror = recieveMessage(false); |
| 359 |
} |
| 360 |
|
| 361 |
function parseAndRun(argv, stdinv, filesv) { |
| 362 |
try { |
| 363 |
let args = parseToStringArray(decodeURIComponent(argv), 'argv'); |
| 364 |
args.unshift('fiat_crypto.js'); |
| 365 |
let stdin = parseToStringArrayArray(decodeURIComponent(stdinv), 'stdin'); |
| 366 |
let files = parseToStringMapStringArray(decodeURIComponent(filesv), 'files'); |
| 367 |
handleSynthesis(args, stdin, files); |
| 368 |
} catch (e) { |
| 369 |
displayError(`Error: ${e.message}: ${argv}, ${stdinv}, ${filesv}`); |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
function nonFalseQueryParam(value) { |
| 374 |
return value !== null && value != 'false' && value != '0'; |
| 375 |
} |
| 376 |
|
| 377 |
function updateInputType(inputType) { |
| 378 |
if (inputType === 'string') { |
| 379 |
if (isValidJsonStringArray(inputArgs.value)) { |
| 380 |
inputArgs.value = joinWithEscaping(JSON.parse(inputArgs.value)); |
| 381 |
} |
| 382 |
} else if (inputType === 'json') { |
| 383 |
inputArgs.value = JSON.stringify(splitUnescapedSpaces(inputArgs.value)); |
| 384 |
} |
| 385 |
validateInput(); |
| 386 |
} |
| 387 |
|
| 388 |
function parseQueryParams() { |
| 389 |
const queryParams = new URLSearchParams(window.location.search); |
| 390 |
const argv = queryParams.get('argv'); |
| 391 |
const interactive = queryParams.get('interactive'); |
| 392 |
const wasm = queryParams.get('wasm') |
| 393 |
const inputType = queryParams.get('inputType') || 'string'; |
| 394 |
const stdin = queryParams.get('stdin') || '[]'; |
| 395 |
const files = queryParams.get('files') || '{}'; |
| 396 |
|
| 397 |
if (nonFalseQueryParam(wasm)) { |
| 398 |
wasmCheckbox.checked = true; |
| 399 |
} |
| 400 |
|
| 401 |
setupWorkers(); |
| 402 |
|
| 403 |
if (argv) { |
| 404 |
if (nonFalseQueryParam(interactive)) { |
| 405 |
inputArgs.value = decodeURIComponent(argv); |
| 406 |
populateStdinEntries(JSON.parse(decodeURIComponent(stdin))); |
| 407 |
populateFileEntries(JSON.parse(decodeURIComponent(files))); |
| 408 |
document.querySelector(`input[value="${inputType}"]`).checked = true; |
| 409 |
updateInputType(inputType); |
| 410 |
inputForm.classList.remove('hidden'); |
| 411 |
} |
| 412 |
parseAndRun(argv, stdin, files); |
| 413 |
} else { |
| 414 |
inputForm.classList.remove('hidden'); |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
parseQueryParams(); |
| 419 |
|
| 420 |
inputArgs.addEventListener('input', validateInput); |
| 421 |
|
| 422 |
document.querySelectorAll('input[name="inputType"]').forEach(radio => { |
| 423 |
radio.addEventListener('change', function () { |
| 424 |
updateInputType(this.value); |
| 425 |
}); |
| 426 |
}); |
| 427 |
|
| 428 |
synthesizeButton.addEventListener('click', function () { |
| 429 |
|
| 430 |
inputArgs.disabled = true; |
| 431 |
synthesizeButton.disabled = true; |
| 432 |
cancelButton.disabled = false; |
| 433 |
|
| 434 |
const argsType = document.querySelector('input[name="inputType"]:checked').value; |
| 435 |
const args = argsType === 'json' ? JSON.parse(inputArgs.value) : splitUnescapedSpaces(inputArgs.value); |
| 436 |
args.unshift('fiat_crypto.js'); |
| 437 |
const stdin = getStdinFromFormBox(); |
| 438 |
const files = getFilesFromFormBox(); |
| 439 |
handleSynthesis(args, stdin, files); |
| 440 |
}); |
| 441 |
|
| 442 |
inputForm.addEventListener('submit', function (event) { |
| 443 |
event.preventDefault(); |
| 444 |
synthesizeButton.click(); |
| 445 |
}); |
| 446 |
|
| 447 |
cancelButton.addEventListener('click', function () { |
| 448 |
|
| 449 |
inputArgs.disabled = false; |
| 450 |
synthesizeButton.disabled = false; |
| 451 |
cancelButton.disabled = true; |
| 452 |
updateStatus(""); |
| 453 |
cancelWorkers(); |
| 454 |
}); |
| 455 |
|
| 456 |
clearCacheButton.addEventListener('click', function () { |
| 457 |
localStorage.clear(); |
| 458 |
}); |
| 459 |
|
| 460 |
versionBox.textContent = `${fiat_crypto_version}`; |
| 461 |
}); |