atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
4b690ff501b89a8185e0f0c9ceaa61a89ce1a056
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml362 lines13.6 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 PATCH": ["patch"],
89
  "length GET": ["range"],
90
  "length HEAD": ["range"],
91
  "foreskin DELETE": ["ifMatch"],
92
  "elder GET": ["proxy", "ifModifiedSince"],
93
  "grip GET": ["upgrade"],
94
  "diagnosis GET": ["authorization", "ifNoneMatch"],
95
};
96
const GLOBALS = [
97
  { key: "runs", name: "start a new run", path: "/runs", methods: ["POST"] },
98
  { key: "global", name: "leaderboard", path: "/leaderboard", methods: ["GET", "HEAD", "OPTIONS"] },
99
  { key: "global", name: "graveyard", path: "/graveyard", methods: ["GET", "HEAD", "OPTIONS"] },
100
  { key: "global", name: "the 2009 forum thread", path: "/forum/threads/2009", methods: ["GET", "HEAD", "OPTIONS"] },
101
];
102
103
let run = null;
104
let linked = [];
105
let offered = [];
106
let challenged = false;
107
let target = "/runs";
108
let method = "POST";
109
const values = {};
110
111
const $ = id => document.getElementById(id);
112
const fieldValue = name => values[name] ?? FIELDS[name].value ?? (FIELDS[name].options ? FIELDS[name].options[0] : "");
113
114
function short(path) {
115
  return path.replace(/[0-9a-f]{32}/, id => id.slice(0, 6) + "…");
116
}
117
118
function el(tag, props, ...children) {
119
  const node = Object.assign(document.createElement(tag), props || {});
120
  for (const child of children) node.append(child);
121
  return node;
122
}
123
124
function targets() {
125
  return (run ? linked : []).concat(offered, GLOBALS);
126
}
127
128
function current() {
129
  return targets().find(t => t.path === target) || GLOBALS[0];
130
}
131
132
function chooseTarget(t) {
133
  target = t.path;
134
  method = t.methods.includes("JELQ") ? "JELQ" : t.methods.find(m => m !== "HEAD" && m !== "OPTIONS") || t.methods[0];
135
  render();
136
}
137
138
function renderStats(headers) {
139
  const table = $("stats");
140
  table.replaceChildren();
141
  for (let i = 0; i < STATS.length; i += 2) {
142
    const row = el("tr");
143
    for (const [name, label] of STATS.slice(i, i + 2)) {
144
      const value = headers ? headers[name] : undefined;
145
      row.append(el("th", { align: "left", textContent: label }), el("td", { textContent: value === undefined ? "—" : value }));
146
    }
147
    table.append(row);
148
  }
149
}
150
151
function titled(text) {
152
  return text.charAt(0).toUpperCase() + text.slice(1);
153
}
154
155
function renderAlerts(list) {
156
  const box = $("alerts");
157
  box.replaceChildren();
158
  const alerts = [];
159
  for (const [name, value] of list || []) {
160
    if (name === "via") alerts.push(titled(value.split(" ").pop()) + " is at the door.");
161
    if (name === "x-observed-by") alerts.push((value === "cat" ? "The cat" : titled(value)) + " is watching.");
162
    if (name === "warning") {
163
      const text = (value.match(/"([^"]*)"/) || [, value])[1];
164
      alerts.push(titled(text) + ".");
165
    }
166
  }
167
  for (const alert of alerts) box.append(el("h2", { textContent: alert }));
168
}
169
170
function renderTargets() {
171
  const box = $("targets");
172
  box.replaceChildren();
173
  for (const t of targets()) {
174
    const radio = el("input", { type: "radio", name: "target", checked: t.path === target, onchange: () => chooseTarget(t) });
175
    box.append(el("label", {}, radio, " " + t.name + " ", el("small", { textContent: short(t.path) })), el("br"));
176
  }
177
}
178
179
function renderMethods() {
180
  const box = $("methods");
181
  box.replaceChildren();
182
  const allowed = current().methods;
183
  for (const m of METHODS) {
184
    const radio = el("input", { type: "radio", name: "method", disabled: !allowed.includes(m), checked: m === method, onchange: () => { method = m; render(); } });
185
    const label = el("label", {}, radio, " ");
186
    label.append(m === "JELQ" ? el("big", {}, el("b", { textContent: "JELQ" })) : m);
187
    box.append(label, " ");
188
  }
189
}
190
191
function fieldNames() {
192
  const t = current();
193
  const names = BY_TARGET[t.key + " " + method] || [];
194
  const scoped = run && !["runs", "global"].includes(t.key);
195
  const asked = challenged && scoped && !names.includes("authorization");
196
  return (asked ? ["authorization"] : []).concat(names);
197
}
198
199
function renderFields() {
200
  const table = $("fields");
201
  table.replaceChildren();
202
  for (const name of fieldNames()) {
203
    const f = FIELDS[name];
204
    const value = fieldValue(name);
205
    let input;
206
    if (f.kind === "select") {
207
      input = el("select", {}, ...f.options.map(o => el("option", { value: o, textContent: o || "(none)", selected: o === value })));
208
    } else if (f.kind === "textarea") {
209
      input = el("textarea", { rows: 3, cols: 40, value, placeholder: f.placeholder || "" });
210
    } else {
211
      input = el("input", { type: f.kind, value, placeholder: f.placeholder || "", size: 30 });
212
    }
213
    input.oninput = input.onchange = () => { values[name] = input.value; };
214
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
215
  }
216
  const extra = el("textarea", { rows: 3, cols: 40, value: fieldValue("extra"), placeholder: FIELDS.extra.placeholder });
217
  extra.oninput = () => { values.extra = extra.value; };
218
  const more = el("details", { open: Boolean(values.extra) }, el("summary", { textContent: "more headers" }), extra);
219
  table.append(el("tr", {}, el("td"), el("td", {}, more)));
220
  $("send").value = method + " " + short(current().path);
221
}
222
223
function render() {
224
  if (!current().methods.includes(method)) return chooseTarget(current());
225
  renderTargets();
226
  renderMethods();
227
  renderFields();
228
}
229
230
function parseLinks(header) {
231
  const found = [];
232
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
233
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
234
    const name = (params.rel || "").replace(REL, "");
235
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
236
    found.push({ key: name, name: name === "run" ? "the run" : name, path: match[1], methods });
237
  }
238
  return found;
239
}
240
241
function hrefs(value, found) {
242
  if (value && typeof value === "object") {
243
    if (typeof value.href === "string") {
244
      const name = value.title || value.item || value.name || value.href.split("/").pop();
245
      found.push({ key: "offered", name, path: value.href, methods: [value.method || "GET"] });
246
    }
247
    for (const key in value) hrefs(value[key], found);
248
  }
249
  return found;
250
}
251
252
function log(text) {
253
  $("log").append(text + "\n");
254
  $("frame").scrollTop = $("frame").scrollHeight;
255
}
256
257
function describe(r) {
258
  const lines = ["< " + r.status + " " + r.reason];
259
  for (const [name, value] of r.headers) {
260
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
261
  }
262
  let body = null;
263
  try { body = JSON.parse(r.body); } catch (e) {}
264
  if (body && typeof body === "object") {
265
    const rest = Object.assign({}, body);
266
    if (rest.detail) lines.push("  " + rest.detail);
267
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
268
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
269
  } else if (r.body) {
270
    lines.push("  " + r.body);
271
  }
272
  return lines.join("\n");
273
}
274
275
function absorb(r, sentMethod, sentPath) {
276
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
277
  let body = null;
278
  try { body = JSON.parse(r.body); } catch (e) {}
279
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
280
281
  if (sentPath.startsWith("/runs?") || sentPath === "/runs") {
282
    if (r.status === 201) {
283
      run = headers.location;
284
      log("--- a new run has started at " + short(run) + " ---");
285
    }
286
  }
287
  if ("x-eq" in headers) {
288
    renderStats(headers);
289
    renderAlerts(r.headers);
290
    challenged = r.status === 401 || "via" in headers;
291
  }
292
  if (headers.link) linked = parseLinks(headers.link);
293
  offered = body ? hrefs(body, []) : [];
294
  if (headers.location && !(sentPath === "/runs" || sentPath.startsWith("/runs?"))) {
295
    offered.unshift({ key: "offered", name: "Location", path: headers.location, methods: ["GET"] });
296
  }
297
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
298
  if (run && (abandoned || DEATHS.includes(problem))) {
299
    log("--- the run has ended ---");
300
    renderAlerts(null);
301
    challenged = false;
302
    run = null;
303
    linked = [];
304
  }
305
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
306
  if (started || !targets().some(t => t.path === target)) {
307
    const home = linked.find(t => t.key === "run");
308
    if (home) chooseTarget(home); else chooseTarget(GLOBALS[0]);
309
  } else {
310
    render();
311
  }
312
}
313
314
async function go(event) {
315
  event.preventDefault();
316
  const t = current();
317
  const key = t.key + " " + method;
318
  const value = name => fieldValue(name).trim();
319
  const headers = [];
320
  let path = t.path;
321
  let body = "";
322
  for (const name of fieldNames()) {
323
    const f = FIELDS[name];
324
    if (f.header && value(name)) headers.push([f.header, value(name)]);
325
  }
326
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
327
  for (const line of value("extra").split("\n")) {
328
    const at = line.indexOf(":");
329
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
330
  }
331
  if (key === "run JELQ") {
332
    const techniques = value("also") ? value("technique") + "," + value("also") : value("technique");
333
    path += "?technique=" + encodeURIComponent(techniques) + "&intensity=" + encodeURIComponent(value("intensity"));
334
  }
335
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
336
  if (method === "PATCH") {
337
    headers.push(["Content-Type", "application/json-patch+json"]);
338
    body = value("patch");
339
  }
340
341
  log("> " + method + " " + short(path));
342
  for (const [name, v] of headers) log("> " + name + ": " + v);
343
  headers.push(["Accept-Language", $("locale").value]);
344
  const response = await fetch("/ui/send", {
345
    method: "POST",
346
    headers: { "Content-Type": "application/json" },
347
    body: JSON.stringify({ method, path, headers, body }),
348
  });
349
  const r = await response.json();
350
  log(describe(r) + "\n");
351
  absorb(r, method, path);
352
}
353
354
$("form").onsubmit = go;
355
$("locale").value = localStorage.getItem("locale") || "en-GB";
356
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
357
renderStats(null);
358
render();
359
log("Welcome. Choose \"start a new run\" and send POST to begin.\n");
360
</script>
361
</body>
362
</html>