-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
158 lines (142 loc) · 6.55 KB
/
Copy pathserver.js
File metadata and controls
158 lines (142 loc) · 6.55 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
// Variance randomizer for VLA demo recording. Run: node server.js -> http://localhost:7654
const http = require('http');
const fs = require('fs');
const path = require('path');
const ROOT = __dirname;
const CONFIGS = path.join(ROOT, 'configs');
const STATE = path.join(ROOT, 'state');
const PORT = 7654;
for (const d of [CONFIGS, STATE]) fs.mkdirSync(d, { recursive: true });
const readJson = (f, fallback) => {
try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return fallback; }
};
const writeJson = (f, obj) => fs.writeFileSync(f, JSON.stringify(obj, null, 2));
const configPath = (id) => path.join(CONFIGS, `${id.replace(/[^\w-]/g, '')}.json`);
const statePath = (id) => path.join(STATE, `${id.replace(/[^\w-]/g, '')}.json`);
const listConfigs = () =>
fs.readdirSync(CONFIGS).filter((f) => f.endsWith('.json')).map((f) => readJson(path.join(CONFIGS, f), null)).filter(Boolean);
// --- drawing ---------------------------------------------------------------
// Bag shuffle: draw without replacement, refill when empty. Keeps the marginal
// distribution flat over short runs instead of merely random.
const shuffle = (a) => {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
function drawIndex(bags, key, n) {
if (!n) return 0;
if (!bags[key] || !bags[key].length) bags[key] = shuffle([...Array(n).keys()]);
return bags[key].pop();
}
const DEFAULT_SIDES = {
4: ['front', 'right', 'back', 'left'],
8: ['front', 'front-right', 'right', 'back-right', 'back', 'back-left', 'left', 'front-left'],
12: ['12 o\'clock', '1 o\'clock', '2 o\'clock', '3 o\'clock', '4 o\'clock', '5 o\'clock',
'6 o\'clock', '7 o\'clock', '8 o\'clock', '9 o\'clock', '10 o\'clock', '11 o\'clock'],
};
function drawVariable(v, bags) {
if (v.type === 'side') {
const bins = Number(v.bins) || 8;
const bin = drawIndex(bags, v.id, bins);
const labels = (v.labels || []).length === bins ? v.labels : DEFAULT_SIDES[bins] || [];
return { type: 'side', bins, bin, angle: Math.round((bin * 360) / bins), value: labels[bin] || null };
}
if (v.type === 'angle') {
const bins = Number(v.bins) || 12;
const bin = drawIndex(bags, v.id, bins);
// uniform inside the bin -> uniform on the circle, but never two neighbours in a row
const angle = (bin + Math.random()) * (360 / bins);
return { type: 'angle', angle: Math.round(angle), bins, bin };
}
if (v.type === 'itemset') {
// Two nested bags: a pool of all items handing out sets of `setSize`, and inside a set
// every item is the target exactly once before the set is swapped.
const options = v.options || [];
const size = Number(v.setSize) || 5;
let cur = bags[`cur:${v.id}`];
if (!cur || !cur.targets.length) {
if (!bags[v.id] || !bags[v.id].length) bags[v.id] = shuffle([...Array(options.length).keys()]);
const set = bags[v.id].splice(-size);
cur = bags[`cur:${v.id}`] = { set, targets: shuffle([...set]) };
}
const target = cur.targets.pop();
return {
type: 'itemset', value: options[target],
set: cur.set.map((i) => options[i]),
setLeft: cur.targets.length, poolLeft: (bags[v.id] || []).length,
};
}
const options = v.options || [];
return { type: 'choice', value: options[drawIndex(bags, v.id, options.length)] ?? '—' };
}
function nextEpisode(cfg, st) {
st.episode = (st.episode || 0) + 1;
st.bags = st.bags || {};
const values = (cfg.variables || []).map((v) => ({ id: v.id, label: v.label, note: v.note, center: v.center, ...drawVariable(v, st.bags) }));
const reminders = (cfg.reminders || [])
.filter((r) => r.every > 0 && (st.episode - 1) % r.every === 0)
.map((r) => ({
label: r.label,
every: r.every,
value: r.options && r.options.length ? r.options[drawIndex(st.bags, `rem:${r.id}`, r.options.length)] : null,
}));
st.last = { episode: st.episode, values, reminders };
return st.last;
}
// --- http ------------------------------------------------------------------
const send = (res, code, body, type = 'application/json') => {
res.writeHead(code, { 'Content-Type': type + (type.startsWith('text') || type.includes('json') ? '; charset=utf-8' : '') });
res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body));
};
const body = (req) =>
new Promise((resolve) => {
let d = '';
req.on('data', (c) => (d += c));
req.on('end', () => resolve(d ? JSON.parse(d) : {}));
});
const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' };
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
const [, api, section, id] = url.pathname.split('/');
try {
if (api === 'api') {
if (section === 'configs' && req.method === 'GET') return send(res, 200, listConfigs());
if (section === 'configs' && req.method === 'PUT') {
const cfg = await body(req);
if (!cfg.id) return send(res, 400, { error: 'id required' });
writeJson(configPath(cfg.id), cfg);
return send(res, 200, cfg);
}
if (section === 'configs' && req.method === 'DELETE') {
fs.rmSync(configPath(id), { force: true });
fs.rmSync(statePath(id), { force: true });
return send(res, 200, { ok: true });
}
if (section === 'state' && req.method === 'GET') return send(res, 200, readJson(statePath(id), { episode: 0 }));
if (section === 'next' && req.method === 'POST') {
const cfg = readJson(configPath(id), null);
if (!cfg) return send(res, 404, { error: 'no config' });
const st = readJson(statePath(id), { episode: 0, bags: {} });
const out = nextEpisode(cfg, st);
writeJson(statePath(id), st);
return send(res, 200, out);
}
if (section === 'reset' && req.method === 'POST') {
writeJson(statePath(id), { episode: 0, bags: {} });
return send(res, 200, { episode: 0 });
}
return send(res, 404, { error: 'not found' });
}
const file = path.join(ROOT, 'public', url.pathname === '/' ? 'index.html' : path.normalize(url.pathname));
if (file.startsWith(path.join(ROOT, 'public')) && fs.existsSync(file)) {
return send(res, 200, fs.readFileSync(file), MIME[path.extname(file)] || 'application/octet-stream');
}
send(res, 404, 'not found', 'text/plain');
} catch (e) {
send(res, 500, { error: String(e) });
}
});
if (require.main === module) server.listen(PORT, () => console.log(`randomizer -> http://localhost:${PORT}`));
module.exports = { nextEpisode };