atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
ef7d6dee59769add5c495a6bc02beb265fc01f56
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml354 lines13.0 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
29
<h3>Request</h3>
30
<table id="fields" cellpadding="2"></table>
31
32
<p><input type="submit" id="send" value="Send" style="font-size: 1.3em"></p>
33
34
<h3>Stats</h3>
35
<table id="stats" border="1" cellspacing="0" cellpadding="3"></table>
36
37
<h3>Resource</h3>
38
<div id="targets"></div>
39
</form>
40
41
<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>
42
</div>
43
</td>
44
<td valign="top">
45
<div class="frame" id="frame"><pre id="log"></pre></div>
46
</td>
47
</tr>
48
</table>
49
50
<script>
51
const REL = "https://jelq.dev/rels/";
52
const METHODS = ["JELQ", "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"];
53
const TECHNIQUES = ["warmup", "wet", "dry", "stretch", "uli", "edge", "pump", "ice", "supplement"];
54
const DEATHS = ["vascular-event", "caught", "banned", "degloved", "zip", "run-ended"];
55
const STATS = [
56
  ["x-floor", "Floor"],
57
  ["x-self-reported-length", "Self-reported length"],
58
  ["x-girth", "Girth"],
59
  ["x-foreskin", "Foreskin"],
60
  ["x-eq", "EQ (aim for 50 to 70)"],
61
  ["x-stamina", "Stamina"],
62
  ["x-suspicion", "Suspicion"],
63
  ["x-shame", "Shame"],
64
  ["x-cash", "Cash"],
65
];
66
const QUIET = new Set(["link", "set-cookie", "server", "x-powered-by", "cache-control", "content-length", "content-type", "date"].concat(STATS.map(s => s[0])));
67
68
const FIELDS = {
69
  seed: { label: "seed (unranked)", kind: "text" },
70
  technique: { label: "technique", kind: "select", options: TECHNIQUES },
71
  also: { label: "combo with", kind: "select", options: ["", "wet", "dry", "stretch", "uli"] },
72
  intensity: { label: "intensity, 1 to 10", kind: "number", value: "5" },
73
  lube: { label: "Content-Type", header: "Content-Type", kind: "select", options: ["", "application/baby-oil", "application/coconut-oil", "application/lotion", "application/vaseline", "text/plain; charset=spit", "image/jpeg"] },
74
  patch: { label: "body", kind: "textarea", value: '[{"op": "test", "path": "/length", "value": 6}]' },
75
  accept: { label: "Accept", header: "Accept", kind: "text" },
76
  range: { label: "Range", header: "Range", kind: "text", placeholder: "inches=0-2" },
77
  ifMatch: { label: "If-Match", header: "If-Match", kind: "text" },
78
  ifNoneMatch: { label: "If-None-Match", header: "If-None-Match", kind: "text" },
79
  ifModifiedSince: { label: "If-Modified-Since", header: "If-Modified-Since", kind: "text", placeholder: "an HTTP-date" },
80
  proxy: { label: "Proxy-Authorization", header: "Proxy-Authorization", kind: "text", placeholder: "Ruler 5.4" },
81
  upgrade: { label: "Upgrade", header: "Upgrade", kind: "select", options: ["", "underhand", "overhand"] },
82
  authorization: { label: "Authorization", header: "Authorization", kind: "text", placeholder: 'Excuse "homework"' },
83
  extra: { label: "other headers, one per line", kind: "textarea", placeholder: "Expect: gains" },
84
};
85
const BY_TARGET = {
86
  "runs POST": ["seed"],
87
  "run JELQ": ["technique", "also", "intensity", "lube"],
88
  "run GET": ["accept"],
89
  "run PATCH": ["patch"],
90
  "length GET": ["range"],
91
  "length HEAD": ["range"],
92
  "foreskin DELETE": ["ifMatch"],
93
  "elder GET": ["proxy", "ifModifiedSince"],
94
  "grip GET": ["upgrade"],
95
  "diagnosis GET": ["ifNoneMatch"],
96
};
97
const ALWAYS = ["authorization", "extra"];
98
const GLOBALS = [
99
  { key: "runs", name: "start a new run", path: "/runs", methods: ["POST"] },
100
  { key: "global", name: "leaderboard", path: "/leaderboard", methods: ["GET", "HEAD", "OPTIONS"] },
101
  { key: "global", name: "graveyard", path: "/graveyard", methods: ["GET", "HEAD", "OPTIONS"] },
102
  { key: "global", name: "the 2009 forum thread", path: "/forum/threads/2009", methods: ["GET", "HEAD", "OPTIONS"] },
103
];
104
105
let run = null;
106
let linked = [];
107
let offered = [];
108
let target = "/runs";
109
let method = "POST";
110
const values = {};
111
112
const $ = id => document.getElementById(id);
113
const fieldValue = name => values[name] ?? FIELDS[name].value ?? (FIELDS[name].options ? FIELDS[name].options[0] : "");
114
115
function short(path) {
116
  return path.replace(/[0-9a-f]{32}/, id => id.slice(0, 6) + "…");
117
}
118
119
function el(tag, props, ...children) {
120
  const node = Object.assign(document.createElement(tag), props || {});
121
  for (const child of children) node.append(child);
122
  return node;
123
}
124
125
function targets() {
126
  return (run ? linked : []).concat(offered, GLOBALS);
127
}
128
129
function current() {
130
  return targets().find(t => t.path === target) || GLOBALS[0];
131
}
132
133
function chooseTarget(t) {
134
  target = t.path;
135
  method = t.methods.includes("JELQ") ? "JELQ" : t.methods.find(m => m !== "HEAD" && m !== "OPTIONS") || t.methods[0];
136
  render();
137
}
138
139
function renderStats(headers) {
140
  const table = $("stats");
141
  table.replaceChildren();
142
  for (let i = 0; i < STATS.length; i += 2) {
143
    const row = el("tr");
144
    for (const [name, label] of STATS.slice(i, i + 2)) {
145
      const value = headers ? headers[name] : undefined;
146
      row.append(el("th", { align: "left", textContent: label }), el("td", { textContent: value === undefined ? "—" : value }));
147
    }
148
    table.append(row);
149
  }
150
}
151
152
function titled(text) {
153
  return text.charAt(0).toUpperCase() + text.slice(1);
154
}
155
156
function renderAlerts(list) {
157
  const box = $("alerts");
158
  box.replaceChildren();
159
  const alerts = [];
160
  for (const [name, value] of list || []) {
161
    if (name === "via") alerts.push(titled(value.split(" ").pop()) + " is at the door.");
162
    if (name === "x-observed-by") alerts.push((value === "cat" ? "The cat" : titled(value)) + " is watching.");
163
    if (name === "warning") {
164
      const text = (value.match(/"([^"]*)"/) || [, value])[1];
165
      alerts.push(titled(text) + ".");
166
    }
167
  }
168
  for (const alert of alerts) box.append(el("h2", { textContent: alert }));
169
}
170
171
function renderTargets() {
172
  const box = $("targets");
173
  box.replaceChildren();
174
  for (const t of targets()) {
175
    const radio = el("input", { type: "radio", name: "target", checked: t.path === target, onchange: () => chooseTarget(t) });
176
    box.append(el("label", {}, radio, " " + t.name + " ", el("small", { textContent: short(t.path) })), el("br"));
177
  }
178
}
179
180
function renderMethods() {
181
  const box = $("methods");
182
  box.replaceChildren();
183
  const allowed = current().methods;
184
  for (const m of METHODS) {
185
    const radio = el("input", { type: "radio", name: "method", disabled: !allowed.includes(m), checked: m === method, onchange: () => { method = m; render(); } });
186
    const label = el("label", {}, radio, " ");
187
    label.append(m === "JELQ" ? el("big", {}, el("b", { textContent: "JELQ" })) : m);
188
    box.append(label, " ");
189
  }
190
}
191
192
function fieldNames() {
193
  const key = current().key + " " + method;
194
  return (BY_TARGET[key] || []).concat(ALWAYS);
195
}
196
197
function renderFields() {
198
  const table = $("fields");
199
  table.replaceChildren();
200
  for (const name of fieldNames()) {
201
    const f = FIELDS[name];
202
    const value = fieldValue(name);
203
    let input;
204
    if (f.kind === "select") {
205
      input = el("select", {}, ...f.options.map(o => el("option", { value: o, textContent: o || "(none)", selected: o === value })));
206
    } else if (f.kind === "textarea") {
207
      input = el("textarea", { rows: 3, cols: 40, value, placeholder: f.placeholder || "" });
208
    } else {
209
      input = el("input", { type: f.kind, value, placeholder: f.placeholder || "", size: 30 });
210
    }
211
    input.oninput = input.onchange = () => { values[name] = input.value; };
212
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
213
  }
214
  $("send").value = method + " " + short(current().path);
215
}
216
217
function render() {
218
  if (!current().methods.includes(method)) return chooseTarget(current());
219
  renderTargets();
220
  renderMethods();
221
  renderFields();
222
}
223
224
function parseLinks(header) {
225
  const found = [];
226
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
227
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
228
    const name = (params.rel || "").replace(REL, "");
229
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
230
    found.push({ key: name, name: name === "run" ? "the run" : name, path: match[1], methods });
231
  }
232
  return found;
233
}
234
235
function hrefs(value, found) {
236
  if (value && typeof value === "object") {
237
    if (typeof value.href === "string") {
238
      const name = value.title || value.item || value.name || value.href.split("/").pop();
239
      found.push({ key: "offered", name, path: value.href, methods: [value.method || "GET"] });
240
    }
241
    for (const key in value) hrefs(value[key], found);
242
  }
243
  return found;
244
}
245
246
function log(text) {
247
  $("log").append(text + "\n");
248
  $("frame").scrollTop = $("frame").scrollHeight;
249
}
250
251
function describe(r) {
252
  const lines = ["< " + r.status + " " + r.reason];
253
  for (const [name, value] of r.headers) {
254
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
255
  }
256
  let body = null;
257
  try { body = JSON.parse(r.body); } catch (e) {}
258
  if (body && typeof body === "object") {
259
    const rest = Object.assign({}, body);
260
    if (rest.detail) lines.push("  " + rest.detail);
261
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
262
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
263
  } else if (r.body) {
264
    lines.push("  " + r.body);
265
  }
266
  return lines.join("\n");
267
}
268
269
function absorb(r, sentMethod, sentPath) {
270
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
271
  let body = null;
272
  try { body = JSON.parse(r.body); } catch (e) {}
273
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
274
275
  if (sentPath.startsWith("/runs?") || sentPath === "/runs") {
276
    if (r.status === 201) {
277
      run = headers.location;
278
      log("--- a new run has started at " + short(run) + " ---");
279
    }
280
  }
281
  if ("x-eq" in headers) {
282
    renderStats(headers);
283
    renderAlerts(r.headers);
284
  }
285
  if (headers.link) linked = parseLinks(headers.link);
286
  offered = body ? hrefs(body, []) : [];
287
  if (headers.location && !(sentPath === "/runs" || sentPath.startsWith("/runs?"))) {
288
    offered.unshift({ key: "offered", name: "Location", path: headers.location, methods: ["GET"] });
289
  }
290
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
291
  if (run && (abandoned || DEATHS.includes(problem))) {
292
    log("--- the run has ended ---");
293
    renderAlerts(null);
294
    run = null;
295
    linked = [];
296
  }
297
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
298
  if (started || !targets().some(t => t.path === target)) {
299
    const home = linked.find(t => t.key === "run");
300
    if (home) chooseTarget(home); else chooseTarget(GLOBALS[0]);
301
  } else {
302
    render();
303
  }
304
}
305
306
async function go(event) {
307
  event.preventDefault();
308
  const t = current();
309
  const key = t.key + " " + method;
310
  const value = name => fieldValue(name).trim();
311
  const headers = [];
312
  let path = t.path;
313
  let body = "";
314
  for (const name of fieldNames()) {
315
    const f = FIELDS[name];
316
    if (f.header && value(name)) headers.push([f.header, value(name)]);
317
  }
318
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
319
  for (const line of value("extra").split("\n")) {
320
    const at = line.indexOf(":");
321
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
322
  }
323
  if (key === "run JELQ") {
324
    const techniques = value("also") ? value("technique") + "," + value("also") : value("technique");
325
    path += "?technique=" + encodeURIComponent(techniques) + "&intensity=" + encodeURIComponent(value("intensity"));
326
  }
327
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
328
  if (method === "PATCH") {
329
    headers.push(["Content-Type", "application/json-patch+json"]);
330
    body = value("patch");
331
  }
332
333
  log("> " + method + " " + short(path));
334
  for (const [name, v] of headers) log("> " + name + ": " + v);
335
  headers.push(["Accept-Language", $("locale").value]);
336
  const response = await fetch("/ui/send", {
337
    method: "POST",
338
    headers: { "Content-Type": "application/json" },
339
    body: JSON.stringify({ method, path, headers, body }),
340
  });
341
  const r = await response.json();
342
  log(describe(r) + "\n");
343
  absorb(r, method, path);
344
}
345
346
$("form").onsubmit = go;
347
$("locale").value = localStorage.getItem("locale") || "en-GB";
348
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
349
renderStats(null);
350
render();
351
log("Welcome. Choose \"start a new run\" and send POST to begin.\n");
352
</script>
353
</body>
354
</html>