atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
a6caa2f9978665374ee51870e78151e4324328d0
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml488 lines18.8 KB
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title>jelqd</title>
6
<style>
7
.frame { border: 2px inset; background: #fff; height: 85vh; overflow: scroll; padding: 4px; }
8
#log { white-space: pre-wrap; margin: 0; }
9
pre, li, p, td, label { overflow-wrap: anywhere; }
10
</style>
11
</head>
12
<body>
13
14
<h1>jelqd</h1>
15
<p>A roguelike played over HTTP. Pick a resource, pick a method, send it. The log on the right is everything the server has said to you.
16
Language <select id="locale"><option>en-GB</option><option>en-US</option><option>en-AU</option></select></p>
17
18
<table width="100%" cellspacing="6">
19
<tr>
20
<td width="45%" valign="top">
21
<div class="frame">
22
23
<div id="alerts"></div>
24
25
<form id="form">
26
<h3>Method</h3>
27
<div id="methods"></div>
28
<datalist id="excuses">
29
<option value="changing"><option value="homework"><option value="pulled a muscle">
30
<option value="tidying"><option value="the washing up"><option value="fed the cat">
31
<option value="revising"><option value="on a call"><option value="wrapping presents">
32
<option value="folding the washing"><option value="hanging the lights">
33
<option value="helping Nan"><option value="peeling sprouts"><option value="the truth">
34
</datalist>
35
36
<h3>Request</h3>
37
<table id="fields" cellpadding="2"></table>
38
39
<p><input type="submit" id="send" value="Send" style="font-size: 1.3em"></p>
40
41
<h3>Stats</h3>
42
<table id="stats" border="1" cellspacing="0" cellpadding="3"></table>
43
44
<h3>Resource</h3>
45
<div id="targets"></div>
46
</form>
47
48
<p><small>Every request goes through <code>/ui/send</code>, which replays it inside the server, so the page can show redirects and send methods and headers that browsers refuse.</small></p>
49
</div>
50
</td>
51
<td valign="top">
52
<div class="frame" id="frame"><pre id="log"></pre></div>
53
</td>
54
</tr>
55
</table>
56
57
<script>
58
const REL = "https://jelq.dev/rels/";
59
const METHODS = ["JELQ", "HOLD", "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"];
60
const ALL_LUBES = ["", "application/baby-oil", "application/coconut-oil", "application/lotion", "application/vaseline", "text/plain; charset=spit", "image/jpeg"];
61
const DEATHS = ["vascular-event", "caught", "opened", "banned", "degloved", "zip", "watermelon", "run-ended"];
62
let stocked = null;
63
let inventorySeq = 0;
64
const STATS = [
65
  ["x-floor", "Floor"],
66
  ["x-self-reported-length", "Self-reported length"],
67
  ["x-girth", "Girth"],
68
  ["x-foreskin", "Foreskin"],
69
  ["x-friction", "Friction"],
70
  ["x-eq", "EQ (aim for 50 to 70)"],
71
  ["x-stamina", "Stamina"],
72
  ["x-suspicion", "Suspicion"],
73
  ["x-shame", "Shame"],
74
  ["x-cash", "Cash"],
75
];
76
const MEASURED = ["x-length", "Length"];
77
const QUIET = new Set(["link", "set-cookie", "server", "x-powered-by", "cache-control", "content-length", "content-type", "date"].concat(STATS.map(s => s[0]), MEASURED[0]));
78
79
const FIELDS = {
80
  seed: { label: "seed (unranked)", kind: "text" },
81
  technique: { label: "technique", kind: "select" },
82
  also: { label: "combo with", kind: "select" },
83
  intensity: { label: "intensity, 1 to 10", kind: "number", value: "5" },
84
  lube: { label: "Content-Type", header: "Content-Type", kind: "select" },
85
  patch: { label: "body", kind: "textarea", value: '[{"op": "test", "path": "/length", "value": 6}]' },
86
  range: { label: "Range", header: "Range", kind: "text", placeholder: "inches=0-2" },
87
  ifMatch: { label: "If-Match", header: "If-Match", kind: "text" },
88
  ifNoneMatch: { label: "If-None-Match", header: "If-None-Match", kind: "text" },
89
  ifModifiedSince: { label: "If-Modified-Since", header: "If-Modified-Since", kind: "text", placeholder: "an HTTP-date" },
90
  proxy: { label: "Proxy-Authorization", header: "Proxy-Authorization", kind: "text", placeholder: "Ruler 5.4" },
91
  upgrade: { label: "Upgrade", header: "Upgrade", kind: "select", options: ["", "underhand", "overhand"] },
92
  authorization: { label: "Authorization", header: "Authorization", kind: "text", placeholder: 'Excuse "homework"' },
93
  extra: { label: "other headers, one per line", kind: "textarea", placeholder: "Expect: gains" },
94
};
95
const BY_TARGET = {
96
  "runs POST": ["seed"],
97
  "run PATCH": ["patch"],
98
  "length GET": ["range"],
99
  "length HEAD": ["range"],
100
  "foreskin DELETE": ["ifMatch"],
101
  "elder GET": ["proxy", "ifModifiedSince"],
102
  "grip GET": ["upgrade"],
103
  "diagnosis GET": ["authorization", "ifNoneMatch"],
104
};
105
const GROUPS = [
106
  ["play", "Play"],
107
  ["shop", "Shop"],
108
  ["you", "You"],
109
  ["said", "From the last response"],
110
  ["reading", "Reading"],
111
  ["meta", "Meta"],
112
];
113
const GROUP_OF = { run: "play", floor: "play", drawer: "play", shop: "play", "shop-item": "shop", kitchen: "play", portal: "play", elder: "play", diagnosis: "play", length: "you", foreskin: "you", grip: "you", inventory: "you", footage: "you", techniques: "reading", thread: "reading" };
114
const NAMES = { run: "the run", thread: "the 2009 forum thread" };
115
const GLOBALS = [
116
  { key: "runs", group: "play", name: "start a new run", path: "/runs", methods: ["POST"] },
117
  { key: "global", group: "meta", name: "leaderboard", path: "/leaderboard", methods: ["GET", "HEAD", "OPTIONS"] },
118
  { key: "global", group: "meta", name: "graveyard", path: "/graveyard", methods: ["GET", "HEAD", "OPTIONS"] },
119
];
120
121
let run = null;
122
let linked = [];
123
let techniques = [];
124
let offered = [];
125
let challenged = false;
126
const etags = {};
127
let target = "/runs";
128
let method = "POST";
129
const values = {};
130
131
const $ = id => document.getElementById(id);
132
133
function short(path) {
134
  return path.replace(/[0-9a-f]{32}/, id => id.slice(0, 6) + "…");
135
}
136
137
function el(tag, props, ...children) {
138
  const node = Object.assign(document.createElement(tag), props || {});
139
  for (const child of children) node.append(child);
140
  return node;
141
}
142
143
function titled(text) {
144
  return text.charAt(0).toUpperCase() + text.slice(1);
145
}
146
147
function technique(name) {
148
  return techniques.find(t => t.name === name);
149
}
150
151
function clashes(a, b) {
152
  const rules = [a.lubricant, b.lubricant];
153
  return rules.includes("required") && rules.includes("forbidden");
154
}
155
156
// The options a field can take right now, or null for free text.
157
function options(name) {
158
  if (name === "technique") return techniques.map(t => t.name);
159
  if (name === "also") {
160
    const first = technique(fieldValue("technique"));
161
    if (!first || !first.lubricant) return [""];
162
    const partners = techniques.filter(t => t.lubricant && t.name !== first.name && !clashes(first, t));
163
    return [""].concat(partners.map(t => t.name));
164
  }
165
  if (name === "lube") {
166
    const lubes = stocked === null ? ALL_LUBES : ALL_LUBES.filter(l => l === "" || l.includes("/") && !l.startsWith("application/") || stocked.includes(l.replace("application/", "")));
167
    return lubeRule() === "required" ? lubes.filter(Boolean) : lubes;
168
  }
169
  return FIELDS[name].options || null;
170
}
171
172
function raw(name) {
173
  return values[name] ?? FIELDS[name].value ?? "";
174
}
175
176
function fieldValue(name) {
177
  const allowed = options(name);
178
  const value = raw(name);
179
  if (allowed && !allowed.includes(value)) return allowed[0] ?? "";
180
  return value;
181
}
182
183
function lubeRule() {
184
  const picked = [technique(fieldValue("technique")), technique(fieldValue("also"))].filter(Boolean);
185
  if (!picked.some(t => t.lubricant)) return "none";
186
  for (const rule of ["forbidden", "required"]) {
187
    if (picked.some(t => t.lubricant === rule)) return rule;
188
  }
189
  return "optional";
190
}
191
192
function allowedMethods(t) {
193
  return t.key === "run" && !techniques.length ? t.methods.filter(m => m !== "JELQ") : t.methods;
194
}
195
196
function targets() {
197
  const listed = run ? linked : [];
198
  const known = new Set(listed.concat(GLOBALS).map(t => t.path));
199
  const fresh = offered.filter((t, i) => !known.has(t.path) && offered.findIndex(o => o.path === t.path) === i);
200
  return listed.concat(fresh, GLOBALS);
201
}
202
203
function current() {
204
  return targets().find(t => t.path === target) || GLOBALS[0];
205
}
206
207
function chooseTarget(t) {
208
  const allowed = allowedMethods(t);
209
  target = t.path;
210
  method = allowed.includes("JELQ") ? "JELQ" : allowed.find(m => m !== "HEAD" && m !== "OPTIONS") || allowed[0];
211
  render();
212
}
213
214
function renderStats(headers) {
215
  const table = $("stats");
216
  table.replaceChildren();
217
  const stats = STATS.map(s => s[0] === "x-self-reported-length" && headers && MEASURED[0] in headers ? MEASURED : s);
218
  for (let i = 0; i < stats.length; i += 2) {
219
    const row = el("tr");
220
    for (const [name, label] of stats.slice(i, i + 2)) {
221
      const value = headers ? headers[name] : undefined;
222
      row.append(el("th", { align: "left", textContent: label }), el("td", { textContent: value === undefined ? "—" : value }));
223
    }
224
    table.append(row);
225
  }
226
}
227
228
function renderAlerts(list) {
229
  const box = $("alerts");
230
  box.replaceChildren();
231
  const alerts = [];
232
  for (const [name, value] of list || []) {
233
    if (name === "via") alerts.push(titled(value.split(" ").pop()) + " is at the door.");
234
    if (name === "x-observed-by") alerts.push((value === "cat" ? "The cat" : titled(value)) + " is watching.");
235
    if (name === "warning") {
236
      const text = (value.match(/"([^"]*)"/) || [, value])[1];
237
      alerts.push(titled(text) + ".");
238
    }
239
  }
240
  const stamina = (list || []).find(([name]) => name === "x-stamina");
241
  if (stamina && stamina[1].startsWith("0/")) alerts.push("Exhausted. HOLD for the refractory period.");
242
  for (const alert of alerts) box.append(el("h2", { textContent: alert }));
243
}
244
245
function renderTargets() {
246
  const box = $("targets");
247
  box.replaceChildren();
248
  const all = targets();
249
  for (const [group, title] of GROUPS) {
250
    const members = all.filter(t => t.group === group);
251
    if (!members.length) continue;
252
    box.append(el("h4", { textContent: title }));
253
    for (const t of members) {
254
      const radio = el("input", { type: "radio", name: "target", checked: t.path === target, onchange: () => chooseTarget(t) });
255
      box.append(el("label", {}, radio, " " + t.name + " ", el("small", { textContent: short(t.path) })), el("br"));
256
    }
257
  }
258
}
259
260
function renderMethods() {
261
  const box = $("methods");
262
  box.replaceChildren();
263
  const allowed = allowedMethods(current());
264
  for (const m of METHODS.filter(m => allowed.includes(m))) {
265
    const radio = el("input", { type: "radio", name: "method", checked: m === method, onchange: () => { method = m; render(); } });
266
    const label = el("label", {}, radio, " ");
267
    label.append(m === "JELQ" ? el("big", {}, el("b", { textContent: "JELQ" })) : m);
268
    box.append(label, " ");
269
  }
270
}
271
272
function fieldNames() {
273
  const t = current();
274
  const key = t.key + " " + method;
275
  let names = BY_TARGET[key] || [];
276
  if (key === "run JELQ") {
277
    const chosen = technique(fieldValue("technique"));
278
    names = ["technique"];
279
    if (options("also").length > 1) names.push("also");
280
    if (chosen && chosen.lubricant) names.push("intensity");
281
    if (["required", "optional"].includes(lubeRule())) names.push("lube");
282
  }
283
  const scoped = run && !["runs", "global"].includes(t.key);
284
  const asked = challenged && scoped && !names.includes("authorization");
285
  return (asked ? ["authorization"] : []).concat(names);
286
}
287
288
function renderFields() {
289
  const table = $("fields");
290
  table.replaceChildren();
291
  for (const name of fieldNames()) {
292
    const f = FIELDS[name];
293
    let value = fieldValue(name);
294
    if (name === "ifMatch" && !value) value = values.ifMatch = etags[current().path] || "";
295
    const choices = options(name);
296
    let input;
297
    if (choices) {
298
      input = el("select", {}, ...choices.map(o => el("option", { value: o, textContent: o || "(none)", selected: o === value })));
299
    } else if (f.kind === "textarea") {
300
      input = el("textarea", { rows: 3, cols: 40, value, placeholder: f.placeholder || "" });
301
    } else {
302
      input = el("input", { type: f.kind, value, placeholder: f.placeholder || "", size: 30 });
303
    }
304
    input.oninput = () => { values[name] = input.value; };
305
    input.onchange = () => { values[name] = input.value; if (choices) renderFields(); };
306
    if (name === "authorization") input.setAttribute("list", "excuses");
307
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
308
  }
309
  const extra = el("textarea", { rows: 3, cols: 40, value: raw("extra"), placeholder: FIELDS.extra.placeholder });
310
  extra.oninput = () => { values.extra = extra.value; };
311
  const more = el("details", { open: Boolean(values.extra) }, el("summary", { textContent: "more headers" }), extra);
312
  table.append(el("tr", {}, el("td"), el("td", {}, more)));
313
  $("send").value = method + " " + short(current().path);
314
}
315
316
function render() {
317
  if (!allowedMethods(current()).includes(method)) return chooseTarget(current());
318
  renderTargets();
319
  renderMethods();
320
  renderFields();
321
}
322
323
function parseLinks(header) {
324
  const resources = [];
325
  const moves = [];
326
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
327
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
328
    const name = (params.rel || "").replace(REL, "");
329
    if (name === "technique") {
330
      moves.push({ name: params.title, lubricant: params.lubricant || null });
331
      continue;
332
    }
333
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
334
    resources.push({ key: name, group: GROUP_OF[name] || "play", name: NAMES[name] || params.title || name, path: match[1], methods });
335
  }
336
  return [resources, moves];
337
}
338
339
function hrefs(value, found) {
340
  if (value && typeof value === "object") {
341
    if (typeof value.href === "string") {
342
      const name = value.title || value.item || value.name || value.href.split("/").pop();
343
      found.push({ key: "offered", group: "said", name, path: value.href, methods: [value.method || "GET"] });
344
    }
345
    for (const key in value) hrefs(value[key], found);
346
  }
347
  return found;
348
}
349
350
function log(text) {
351
  $("log").prepend(text + "\n\n");
352
  $("frame").scrollTop = 0;
353
}
354
355
function describe(r) {
356
  const lines = ["< " + r.status + " " + r.reason];
357
  for (const [name, value] of r.headers) {
358
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
359
  }
360
  let body = null;
361
  try { body = JSON.parse(r.body); } catch (e) {}
362
  if (body && typeof body === "object") {
363
    const rest = Object.assign({}, body);
364
    if (rest.detail) lines.push("  " + rest.detail);
365
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
366
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
367
  } else if (r.body) {
368
    const range = (r.headers.find(h => h[0] === "content-range") || [])[1] || "";
369
    const partial = r.status === 206 && range.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
370
    lines.push("  " + r.body);
371
    if (partial) lines.push("  [bytes " + partial[1] + "-" + partial[2] + " of " + partial[3] + ". Half-mast.]");
372
  }
373
  return lines.join("\n");
374
}
375
376
function absorb(r, sentMethod, sentPath) {
377
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
378
  if (headers.etag) etags[sentPath] = headers.etag;
379
  const digest = (headers["www-authenticate"] || "").match(/nonce="([^"]*)"/);
380
  if (digest && !(values.authorization || "").includes(digest[1])) {
381
    values.authorization = 'Digest username="", nonce="' + digest[1] + '"';
382
  }
383
  let body = null;
384
  try { body = JSON.parse(r.body); } catch (e) {}
385
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
386
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
387
388
  if (started) {
389
    run = headers.location;
390
    log("--- a new run has started at " + short(run) + " ---");
391
  }
392
  if ("x-eq" in headers) {
393
    renderStats(headers);
394
    renderAlerts(r.headers);
395
    challenged = r.status === 401 || "via" in headers;
396
  }
397
  if (headers.link) [linked, techniques] = parseLinks(headers.link);
398
  if (run) {
399
    const active = run;
400
    const seq = ++inventorySeq;
401
    fetch("/ui/send", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ method: "GET", path: run + "/inventory", headers: [], body: "" }) })
402
      .then(r => r.json())
403
      .then(r => {
404
        if (run !== active || seq !== inventorySeq) return;
405
        try { stocked = (JSON.parse(r.body).items || []).map(i => i.name); render(); } catch (e) {}
406
      });
407
  }
408
  offered = body ? hrefs(body, []) : [];
409
  if (headers.location && !started) {
410
    offered.unshift({ key: "offered", group: "said", name: short(headers.location).split("/").pop() + " (Location)", path: headers.location, methods: ["GET"] });
411
  }
412
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
413
  if (run && (abandoned || DEATHS.includes(problem))) {
414
    log("--- the run has ended ---");
415
    renderAlerts(null);
416
    challenged = false;
417
    run = null;
418
    linked = [];
419
    techniques = [];
420
  }
421
  if (started || !targets().some(t => t.path === target)) {
422
    const home = linked.find(t => t.key === "run");
423
    chooseTarget(home || GLOBALS[0]);
424
  } else {
425
    render();
426
  }
427
}
428
429
async function go(event) {
430
  event.preventDefault();
431
  const t = current();
432
  const key = t.key + " " + method;
433
  const value = name => fieldValue(name).trim();
434
  const headers = [];
435
  let path = t.path;
436
  let body = "";
437
  for (const name of fieldNames()) {
438
    const f = FIELDS[name];
439
    if (f.header && value(name)) headers.push([f.header, value(name)]);
440
  }
441
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
442
  for (const line of raw("extra").split("\n")) {
443
    const at = line.indexOf(":");
444
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
445
  }
446
  if (key === "run JELQ") {
447
    const names = fieldNames();
448
    const chosen = [value("technique")].concat(names.includes("also") && value("also") ? [value("also")] : []);
449
    path += "?technique=" + encodeURIComponent(chosen.join(","));
450
    if (names.includes("intensity")) path += "&intensity=" + encodeURIComponent(value("intensity"));
451
  }
452
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
453
  if (method === "PATCH") {
454
    headers.push(["Content-Type", "application/json-patch+json"]);
455
    body = value("patch");
456
  }
457
458
  const sent = ["> " + method + " " + short(path)].concat(headers.map(([name, v]) => "> " + name + ": " + v)).join("\n");
459
  headers.push(["Accept-Language", $("locale").value]);
460
  let r;
461
  try {
462
    const response = await fetch("/ui/send", {
463
      method: "POST",
464
      headers: { "Content-Type": "application/json" },
465
      body: JSON.stringify({ method, path, headers, body }),
466
    });
467
    r = await response.json();
468
  } catch (error) {
469
    log(sent + "\n! The server did not answer. Is jelqd still running? (" + error.message + ")");
470
    return;
471
  }
472
  if (!Array.isArray(r.headers)) {
473
    log(sent + "\n! The page could not read that reply:\n  " + JSON.stringify(r));
474
    return;
475
  }
476
  log(sent + "\n" + describe(r));
477
  absorb(r, method, path);
478
}
479
480
$("form").onsubmit = go;
481
$("locale").value = localStorage.getItem("locale") || "en-GB";
482
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
483
renderStats(null);
484
render();
485
log("Welcome. Choose \"start a new run\" and send POST to begin. The newest turn is always at the top.");
486
</script>
487
</body>
488
</html>