firstbyte 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,289 @@
1
+ /*
2
+ * The 'play' rules (P1-P9): the build is served from memory and played in headless Chromium, inside
3
+ * the same page side (sdk/Host, in harness.html) the site puts around a game. Spec: PlayChecks.spec.md.
4
+ * Called by check/Checker. run() plays the game once and every rule below reads what it recorded.
5
+ */
6
+ import { createRequire } from 'node:module';
7
+ import { join } from 'node:path';
8
+ import { serve, SDK } from './serve.js';
9
+ import { decodePng, hasPicture, changed } from './png.js';
10
+ import { LIMITS, RULES } from '../../rules/Rulebook/Rulebook.js';
11
+ import { FILE as ACHIEVEMENTS, readList } from '../../achievements/Achievements/Achievements.js';
12
+
13
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
+ const secs = (ms) => `${(ms / 1000).toFixed(1)} s`;
15
+ const PLAY_IDS = RULES.filter((r) => r.check === 'play').map((r) => r.id);
16
+
17
+ /* Runs in every frame before the game's own code: records errors and sound, through __fbRecord, a binding
18
+ the checker keeps in Node; the game, on its own origin, can neither read nor rewrite what was recorded. */
19
+ const PROBE = `(() => {
20
+ const rec = (kind, msg) => { try { window.__fbRecord(kind, String(msg).slice(0, 300)); } catch (e) {} };
21
+ addEventListener('error', (e) => { if (e instanceof ErrorEvent) rec('error', e.message || 'Script error'); }, true);
22
+ addEventListener('unhandledrejection', (e) => rec('error', 'Unhandled promise rejection: ' + (e.reason && e.reason.message || e.reason)));
23
+ /* A sound file plays through AudioBufferSourceNode, which has its own start(); tones use the shared one. */
24
+ for (const P of [window.AudioScheduledSourceNode, window.AudioBufferSourceNode]) {
25
+ if (!P || !Object.prototype.hasOwnProperty.call(P.prototype, 'start')) continue;
26
+ const start = P.prototype.start;
27
+ P.prototype.start = function (...a) { rec('sound', 'Web Audio'); return start.apply(this, a); };
28
+ }
29
+ const M = window.HTMLMediaElement && HTMLMediaElement.prototype;
30
+ if (M) { const play = M.play; M.play = function (...a) { if (!this.muted && this.volume > 0) rec('sound', 'audio element'); return play.apply(this, a); }; }
31
+ if (window !== window.top) addEventListener('scroll', () => rec('scroll', 'page'), { capture: true, passive: true });
32
+ })();`;
33
+
34
+ /* The game froze the page, so nothing it did can be told: P1 fails saying so, the rest are skipped. */
35
+ function froze(ms) {
36
+ const why = `The game froze the page: it stopped answering for ${Math.round(ms / 1000)} s, so the checker stopped. Look for a loop that never ends.`;
37
+ return PLAY_IDS.map((id) => (id === 'P1' ? { id, status: 'fail', detail: [why] } : { id, status: 'skip', detail: ['The game froze the page, so this could not be checked.'] }));
38
+ }
39
+
40
+ export function skipPlay(why) {
41
+ return PLAY_IDS.map((id) => ({ id, status: 'skip', detail: [why] }));
42
+ }
43
+
44
+ /*
45
+ * Where Playwright is looked for, in order:
46
+ * 1. next to the checker itself (a project that installed both, or this repo);
47
+ * 2. a global install, found through NODE_PATH, which only require() reads;
48
+ * 3. the folder the command is run from: `npx firstbyte check` runs the checker from npm's own
49
+ * cache, far from the developer's project, where they installed Playwright.
50
+ * `near: null` skips the first two (for the test of the third).
51
+ */
52
+ export async function loadPlaywright(opts = {}, { cwd = process.cwd(), near = import.meta.url } = {}) {
53
+ if (opts.playwright) return opts.playwright;
54
+ if (near) {
55
+ try { return await import('playwright'); } catch {}
56
+ try { return createRequire(near)('playwright'); } catch {}
57
+ }
58
+ try { return createRequire(join(cwd, 'package.json'))('playwright'); } catch { return null; }
59
+ }
60
+
61
+ const isRoot = () => typeof process.getuid === 'function' && process.getuid() === 0;
62
+
63
+ /* The game is untrusted code: Chromium's own sandbox stays on, so a page that breaks out of the renderer
64
+ is still boxed in. Chromium can't sandbox itself as root, so as root it is off unless asked for. */
65
+ /* The browser it starts reaches nothing but this machine's own checker servers: every other name fails to
66
+ resolve, WebRTC can't open its own routes, and it inherits none of the worker's secrets. */
67
+ const LOCKED_ARGS = ['--autoplay-policy=no-user-gesture-required', '--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1',
68
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp', '--webrtc-ip-handling-policy=disable_non_proxied_udp'];
69
+ const QUIET_ENV = () => ({ PATH: process.env.PATH || '/usr/bin:/bin', HOME: process.env.HOME || '/tmp', TMPDIR: process.env.TMPDIR || '/tmp', LANG: 'C.UTF-8' });
70
+ /* How long one play may take in all: a game that freezes the page is failed at this, never waited on forever. */
71
+ export const DEADLINE_MS = 180_000;
72
+
73
+ async function launch(pw, sandbox) {
74
+ try {
75
+ return await pw.chromium.launch({ chromiumSandbox: sandbox, args: LOCKED_ARGS, ...(process.platform === 'win32' ? {} : { env: QUIET_ENV() }) });
76
+ } catch (e) {
77
+ if (!sandbox) throw e;
78
+ throw new Error(`Chromium's sandbox could not start, so the game was not played: ${String(e.message).split('\n')[0]} Run the checker as a normal user, not root.`);
79
+ }
80
+ }
81
+
82
+ export async function checkPlay(files, root, opts = {}) {
83
+ const readyMs = opts.readyMs ?? LIMITS.readyMs;
84
+ const pw = await loadPlaywright(opts);
85
+ if (!pw) return skipPlay('Playing the game needs a browser, which is not installed. In your game\'s folder run: npm i -D playwright@1.63.0 && npx playwright install chromium. Or install nothing: drop the zip at firstbyte.games/developers and press "Just check it".');
86
+
87
+ const ownBrowser = !opts.browser;
88
+ const browser = opts.browser || await launch(pw, opts.sandbox ?? !isRoot());
89
+ /* Whatever fails, nothing is left running: the browser this started, the context, the file server. */
90
+ let server = null;
91
+ let context = null;
92
+ try {
93
+ server = await serve(files, root);
94
+ context = await browser.newContext({ viewport: { width: 960, height: 540 }, serviceWorkers: 'block' });
95
+ /* The game's achievement ids go to the harness's sdk/Host, so P9 can see an unlock that isn't listed. */
96
+ const raw = files.get(root + ACHIEVEMENTS);
97
+ const listed = raw ? readList(raw.toString('utf8')) : null;
98
+ await context.addInitScript((ids) => { window.__fbAchievements = ids; }, listed?.list?.map((a) => a.id) ?? []);
99
+ let timer;
100
+ const frozen = new Promise((r) => { timer = setTimeout(() => r(null), opts.deadlineMs ?? DEADLINE_MS); });
101
+ const results = await Promise.race([run(context, server, readyMs, opts.screenshotMs ?? 30_000, opts.soundMs ?? 15_000), frozen]);
102
+ clearTimeout(timer);
103
+ if (!results) return froze(opts.deadlineMs ?? DEADLINE_MS);
104
+ return [...results, achievementsKnown(results.h, { hasFile: !!raw, list: listed?.list ?? null })];
105
+ } finally {
106
+ /* A frozen page can stall closing too: never wait on it for long. */
107
+ const soon = (p) => Promise.race([p.catch(() => {}), new Promise((r) => setTimeout(r, 10_000))]);
108
+ await soon(context?.close() ?? Promise.resolve());
109
+ if (ownBrowser) await soon(browser.close());
110
+ await server?.close();
111
+ }
112
+ }
113
+
114
+ async function run(context, { port, gamePort }, readyMs, shotMs, soundMs) {
115
+ const local = `127.0.0.1:${port}`;
116
+ const gameHost = `127.0.0.1:${gamePort}`;
117
+ const external = new Set();
118
+ const missing = new Set();
119
+ const errors = [];
120
+ const log = [];
121
+
122
+ await context.exposeBinding('__fbRecord', (_src, kind, msg) => { if (log.length < 2000) log.push({ kind: String(kind), msg: String(msg), at: Date.now() }); });
123
+ await context.addInitScript(PROBE);
124
+ await context.route('**/*', (route) => {
125
+ const url = new URL(route.request().url());
126
+ if (url.href === 'https://firstbyte.games/sdk.js') return route.fulfill({ body: SDK, contentType: 'text/javascript' });
127
+ if (url.host === local || url.host === gameHost) return route.continue();
128
+ external.add(url.host);
129
+ return route.abort();
130
+ });
131
+ /* A WebSocket isn't a request route() sees: catch it, name its host for P3, and never connect it. */
132
+ await context.routeWebSocket(/.*/, (ws) => { try { external.add(new URL(ws.url()).host); } catch {} ws.close(); });
133
+
134
+ const page = await context.newPage();
135
+ page.on('pageerror', (e) => errors.push(e.message));
136
+ page.on('console', (m) => {
137
+ if (m.type() === 'error' && !/Failed to load resource|net::ERR_/.test(m.text())) errors.push(m.text());
138
+ });
139
+ page.on('response', (r) => {
140
+ const url = new URL(r.url());
141
+ /* Any local miss counts, including a path that starts with "/" and so escapes the game's folder. */
142
+ if (url.host === gameHost && r.status() >= 400) missing.add(url.pathname.startsWith('/game/') ? url.pathname.slice(6) : `${url.pathname} (outside the game's folder: the path starts with "/")`);
143
+ });
144
+
145
+ const start = Date.now();
146
+ let loadError = null;
147
+ await page.goto(`http://${local}/__fb/harness.html`, { waitUntil: 'load', timeout: readyMs + 10_000 }).catch((e) => { loadError = e.message.split('\n')[0]; });
148
+
149
+ const host = () => page.evaluate(() => ({ state: window.__fbHost.state, events: window.__fb.events, now: Date.now() - window.__fb.t0 })).then((h) => ({ ...h, log: log.slice() }), () => null);
150
+ const frame = page.locator('#game');
151
+ /* Without a graphics card one picture of a 3D game can take 10 s or more, so pictures get time. */
152
+ const shot = async () => { try { return decodePng(await frame.screenshot({ timeout: shotMs })); } catch { return null; } };
153
+
154
+ while (Date.now() - start < readyMs) {
155
+ const h = await host();
156
+ if (h && h.state.ready) break;
157
+ await sleep(150);
158
+ }
159
+ const first = await host();
160
+ const a = await shot();
161
+ await sleep(800);
162
+ const b = await shot();
163
+
164
+ const inputAt = (await host())?.now ?? 0;
165
+ await page.mouse.click(480, 270).catch(() => {});
166
+ for (const key of ['Space', 'Enter', 'ArrowRight', 'ArrowUp', 'KeyW', 'KeyD']) await page.keyboard.press(key).catch(() => {});
167
+ await sleep(1000);
168
+ const c = await shot();
169
+ for (let i = 0; i < 14; i++) {
170
+ await page.keyboard.press(['ArrowLeft', 'ArrowRight', 'Space', 'ArrowUp', 'ArrowDown'][i % 5]).catch(() => {});
171
+ if (i % 4 === 3) await page.mouse.click(300 + i * 20, 200 + i * 10).catch(() => {});
172
+ await sleep(250);
173
+ }
174
+ /* Many games load their sounds only once the first click allows audio; give them time to be heard. */
175
+ for (let waited = 0; waited < soundMs; waited += 600) {
176
+ const heard = log.some((l) => l.kind === 'sound');
177
+ if (heard) break;
178
+ await page.keyboard.press(['Space', 'ArrowRight', 'ArrowLeft'][(waited / 600) % 3]).catch(() => {});
179
+ if ((waited / 600) % 2) await page.mouse.click(480, 270).catch(() => {});
180
+ await sleep(600);
181
+ }
182
+ await page.evaluate(() => window.__fbHost.mute(true)).catch(() => {});
183
+ await sleep(300);
184
+ const end = await host();
185
+
186
+ const h = end || first || { state: {}, events: [], log: [] };
187
+ const errs = [...(loadError ? [`The page did not finish loading: ${loadError}`] : []), ...errors, ...h.log.filter((l) => l.kind === 'error').map((l) => l.msg)];
188
+ const results = [
189
+ loads(errs, missing),
190
+ onScreen(first, a, readyMs),
191
+ selfContained(external),
192
+ responds(h, inputAt, a, b, c),
193
+ sound(h.log),
194
+ adsAtBreaks(h),
195
+ noAdFirst(h, inputAt),
196
+ mute(h),
197
+ ];
198
+ /* Not a result: what P9 reads, added by checkPlay, which knows the game's list. */
199
+ results.h = h;
200
+ return results;
201
+ }
202
+
203
+ function loads(errs, missing) {
204
+ const detail = [...new Set(errs)].slice(0, 6);
205
+ for (const m of missing) detail.push(`Missing file: ${m}`);
206
+ return detail.length ? { id: 'P1', status: 'fail', detail } : { id: 'P1', status: 'pass' };
207
+ }
208
+
209
+ function onScreen(h, img, readyMs) {
210
+ if (h?.state.ready) return { id: 'P2', status: 'pass', detail: [`FirstByte.ready() after ${secs(h.state.readyAt)}.`] };
211
+ if (h?.state.hello) return { id: 'P2', status: 'fail', detail: [`The SDK loaded, but FirstByte.ready() was not called within ${secs(readyMs)}.`] };
212
+ if (!img) return { id: 'P2', status: 'skip', detail: ['The checker could not take a picture of the game, so it could not tell. Call FirstByte.ready() and it can.'] };
213
+ if (hasPicture(img)) return { id: 'P2', status: 'pass', detail: [`A picture was on screen within ${secs(readyMs)}.`] };
214
+ return { id: 'P2', status: 'fail', detail: [`The screen was still blank after ${secs(readyMs)}.`] };
215
+ }
216
+
217
+ function selfContained(external) {
218
+ if (!external.size) return { id: 'P3', status: 'pass' };
219
+ return { id: 'P3', status: 'fail', detail: [`Tried to load from: ${[...external].join(', ')}.`] };
220
+ }
221
+
222
+ function responds(h, inputAt, a, b, c) {
223
+ const played = h.events.find((e) => e.type === 'playing' && e.data?.on && e.t >= inputAt);
224
+ const scrolled = h.log.some((l) => l.kind === 'scroll');
225
+ const SCROLL = 'The game page scrolled when Space or the arrow keys were pressed. Call event.preventDefault() for the keys your game uses, and give the page overflow: hidden.';
226
+ if (played && scrolled) return { id: 'P4', status: 'warn', detail: [`FirstByte.playing(true) ${secs(played.t - inputAt)} after the first input.`, SCROLL] };
227
+ if (played) return { id: 'P4', status: 'pass', detail: [`FirstByte.playing(true) ${secs(played.t - inputAt)} after the first input.`] };
228
+ if (scrolled) return { id: 'P4', status: 'fail', detail: [SCROLL] };
229
+ if (!a || !b || !c) return { id: 'P4', status: 'skip', detail: ['The checker could not take screenshots of the game.'] };
230
+ const idle = changed(a, b), after = changed(b, c);
231
+ if (after > 0.002 && after > idle * 1.5 + 0.001) return { id: 'P4', status: 'pass', detail: ['The screen changed after keys and a click.'] };
232
+ if (idle > 0.002) return { id: 'P4', status: 'warn', detail: ['The screen keeps moving on its own, so the checker could not tell whether input did anything. Call FirstByte.playing(true) when play starts and the checker can tell.'] };
233
+ /* Something changed, but too little to be sure it was the input (a small sprite that moved, or a
234
+ blinking cursor): that is not "nothing changed", so it is LOOK, never FAIL. */
235
+ if (after > 0) return { id: 'P4', status: 'warn', detail: ["Only a little of the screen changed after the keys and a click, so the checker could not tell whether the game answered them. If it did, there is nothing to fix. To make this a PASS, call FirstByte.playing(true) when the player's first key or click starts play."] };
236
+ return { id: 'P4', status: 'fail', detail: ['Nothing changed on screen after Space, Enter, the arrow keys, W, D and a click.'] };
237
+ }
238
+
239
+ function sound(log) {
240
+ const s = log.filter((l) => l.kind === 'sound');
241
+ if (s.length) return { id: 'P5', status: 'pass', detail: [`${s.length} sound${s.length === 1 ? '' : 's'} played.`] };
242
+ return { id: 'P5', status: 'fail', detail: ['No sound played during the test.'] };
243
+ }
244
+
245
+ function adsAtBreaks(h) {
246
+ if (!h.state.hello) return { id: 'P6', status: 'pass', detail: ['No SDK, so the game shows no ads here.'] };
247
+ const bad = h.events.filter((e) => e.type === 'break-refused' || (e.type === 'break' && e.refused === 'playing'));
248
+ const asked = h.events.filter((e) => e.type === 'break' || e.type === 'break-refused');
249
+ if (bad.length) return { id: 'P6', status: 'fail', detail: bad.map((e) => `breakTime() at ${secs(e.t)}, while playing.`) };
250
+ if (asked.length && !h.events.some((e) => e.type === 'playing')) {
251
+ return { id: 'P6', status: 'warn', detail: ['The game asks for ads but never calls FirstByte.playing(), so the site cannot tell a break from play. Call playing(true) when a round starts and playing(false) when it ends.'] };
252
+ }
253
+ if (asked.length) return { id: 'P6', status: 'pass', detail: [`${asked.length} ad${asked.length === 1 ? '' : 's'} asked for, each at a break.`] };
254
+ return { id: 'P6', status: 'pass', detail: ['No ad was asked for during the test.'] };
255
+ }
256
+
257
+ function noAdFirst(h, inputAt) {
258
+ const early = h.events.find((e) => (e.type === 'break' || e.type === 'break-refused') && (e.t < inputAt || (!e.everPlayed && h.events.some((x) => x.type === 'playing'))));
259
+ if (early) return { id: 'P7', status: 'fail', detail: [`An ad was asked for at ${secs(early.t)}, before the first play.`] };
260
+ return { id: 'P7', status: 'pass' };
261
+ }
262
+
263
+ function mute(h) {
264
+ if (!h.state.hello) return { id: 'P8', status: 'skip', detail: ['Needs the SDK: without it the site cannot ask the game to go quiet.'] };
265
+ if (h.state.listening?.mute) return { id: 'P8', status: 'pass' };
266
+ return { id: 'P8', status: 'fail', detail: ["The game does not listen for FirstByte.on('mute')."] };
267
+ }
268
+
269
+ /* A name for an id, for the line a developer can paste: 'night-owl' -> 'Night owl'. */
270
+ const nameOf = (id) => id.charAt(0).toUpperCase() + id.slice(1).replace(/-/g, ' ');
271
+
272
+ /*
273
+ * P9: every FirstByte.achieve() seen while playing, against the build's achievements.json. With a list
274
+ * and no unlock it is LOOK, never pass: the game was played too briefly to tell.
275
+ */
276
+ function achievementsKnown(h, { hasFile, list }) {
277
+ const seen = h.events.filter((e) => e.type === 'achieve');
278
+ const ids = [...new Set(seen.map((e) => e.data?.id))];
279
+ const paste = (id) => `{ "id": "${id}", "name": "${nameOf(id)}", "about": "What the player did." }`;
280
+ if (!hasFile) {
281
+ if (!ids.length) return { id: 'P9', status: 'note', detail: ['No achievements.'] };
282
+ return { id: 'P9', status: 'fail', detail: [`The game unlocks ${ids.map((i) => `"${i}"`).join(', ')} but has no achievements.json. Add one next to index.html: { "achievements": [ ${ids.map(paste).join(', ')} ] }`] };
283
+ }
284
+ if (!list) return { id: 'P9', status: 'skip', detail: ['achievements.json has problems (see F7), so unlocks could not be checked.'] };
285
+ const unknown = [...new Set(seen.filter((e) => e.refused === 'unknown').map((e) => e.data?.id))];
286
+ if (unknown.length) return { id: 'P9', status: 'fail', detail: unknown.map((id) => `"${id}" isn't in achievements.json. Fix its spelling in your code, or add it: ${paste(id)}`) };
287
+ if (ids.length) return { id: 'P9', status: 'pass', detail: [`Unlocked while we played: ${ids.join(', ')}.`] };
288
+ return { id: 'P9', status: 'warn', detail: [`None of the ${list.length} achievements unlocked in the ${secs(h.now ?? 0)} we played. Check one can be earned early, so players see them working.`] };
289
+ }
@@ -0,0 +1,21 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>First Byte check</title>
6
+ <style>html,body{margin:0;height:100%;background:#000}iframe{border:0;width:100%;height:100%;display:block}</style>
7
+ </head>
8
+ <body>
9
+ <iframe id="game" src="/game/index.html" allow="autoplay; fullscreen; gamepad"></iframe>
10
+ <script src="/__fb/host.js"></script>
11
+ <script>
12
+ window.__fb = { events: [], t0: Date.now() };
13
+ window.__fbHost = FirstByteHost.attach(document.getElementById('game'), {
14
+ key: 'check',
15
+ achievements: window.__fbAchievements || [],
16
+ onEvent: function (e) { window.__fb.events.push(e); },
17
+ showAd: function () { return new Promise(function (r) { setTimeout(function () { r(true); }, 50); }); }
18
+ });
19
+ </script>
20
+ </body>
21
+ </html>
@@ -0,0 +1,70 @@
1
+ /* Just enough PNG to compare screenshots: 8-bit RGB or RGBA, not interlaced (what Chromium writes). */
2
+ import { inflateSync } from 'node:zlib';
3
+
4
+ export function decodePng(buf) {
5
+ let p = 8;
6
+ let width = 0, height = 0, channels = 0;
7
+ const idat = [];
8
+ while (p < buf.length) {
9
+ const len = buf.readUInt32BE(p);
10
+ const type = buf.toString('latin1', p + 4, p + 8);
11
+ const body = buf.subarray(p + 8, p + 8 + len);
12
+ if (type === 'IHDR') {
13
+ width = body.readUInt32BE(0);
14
+ height = body.readUInt32BE(4);
15
+ const depth = body[8], color = body[9], interlace = body[12];
16
+ if (depth !== 8 || interlace !== 0 || (color !== 2 && color !== 6)) throw new Error('Unsupported PNG');
17
+ channels = color === 6 ? 4 : 3;
18
+ } else if (type === 'IDAT') idat.push(body);
19
+ else if (type === 'IEND') break;
20
+ p += 12 + len;
21
+ }
22
+ const raw = inflateSync(Buffer.concat(idat));
23
+ const stride = width * channels;
24
+ const out = Buffer.alloc(height * stride);
25
+ for (let y = 0; y < height; y++) {
26
+ const f = raw[y * (stride + 1)];
27
+ const src = y * (stride + 1) + 1;
28
+ const dst = y * stride;
29
+ for (let x = 0; x < stride; x++) {
30
+ const a = x >= channels ? out[dst + x - channels] : 0;
31
+ const b = y > 0 ? out[dst + x - stride] : 0;
32
+ const c = y > 0 && x >= channels ? out[dst + x - stride - channels] : 0;
33
+ let v = raw[src + x];
34
+ if (f === 1) v += a;
35
+ else if (f === 2) v += b;
36
+ else if (f === 3) v += (a + b) >> 1;
37
+ else if (f === 4) {
38
+ const pa = Math.abs(b - c), pb = Math.abs(a - c), pc = Math.abs(a + b - 2 * c);
39
+ v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
40
+ }
41
+ out[dst + x] = v & 255;
42
+ }
43
+ }
44
+ return { width, height, channels, data: out };
45
+ }
46
+
47
+ /* True when the picture is more than one flat colour. */
48
+ export function hasPicture(img) {
49
+ const seen = new Set();
50
+ const { data, channels } = img;
51
+ for (let i = 0; i < data.length; i += channels * 37) {
52
+ seen.add(((data[i] >> 4) << 8) | ((data[i + 1] >> 4) << 4) | (data[i + 2] >> 4));
53
+ if (seen.size > 6) return true;
54
+ }
55
+ return false;
56
+ }
57
+
58
+ /* The share of pixels (0..1) that changed noticeably between two screenshots. */
59
+ export function changed(a, b) {
60
+ if (a.width !== b.width || a.height !== b.height) return 1;
61
+ let n = 0, diff = 0;
62
+ const ch = a.channels, chb = b.channels;
63
+ for (let px = 0; px < a.width * a.height; px += 7) {
64
+ const i = px * ch, j = px * chb;
65
+ const d = Math.abs(a.data[i] - b.data[j]) + Math.abs(a.data[i + 1] - b.data[j + 1]) + Math.abs(a.data[i + 2] - b.data[j + 2]);
66
+ if (d > 30) diff++;
67
+ n++;
68
+ }
69
+ return diff / n;
70
+ }
@@ -0,0 +1,50 @@
1
+ /* Serves a build from memory on 127.0.0.1 for the checker: the game on its own port, the harness page on another. */
2
+ import { createServer } from 'node:http';
3
+ import { readFileSync } from 'node:fs';
4
+ import { served } from '../../load/Served/Served.js';
5
+
6
+ const here = (p) => new URL(p, import.meta.url);
7
+ const HARNESS = readFileSync(here('./harness.html'));
8
+ const HOST = readFileSync(here('../../sdk/Host/Host.js'));
9
+ export const SDK = readFileSync(here('../../sdk/Sdk/Sdk.js'));
10
+
11
+ /*
12
+ * Two servers: the harness page (and sdk/Host) on one port, the game on another, so the game is on its own
13
+ * origin as it is on the real site and can't reach into the page that records its results. A path that
14
+ * can't be decoded is a 400, never a crash.
15
+ */
16
+ export async function serve(files, root) {
17
+ /* Each file goes out as the live site sends it (load/Served): its type, and for a file the engine
18
+ already compressed (.br, .gz) its encoding, so the browser unpacks it as it will on the site. */
19
+ const send = (res, body, name) => {
20
+ const as = served(name);
21
+ res.writeHead(200, { 'content-type': as.type, 'cache-control': 'no-store', ...(as.encoding ? { 'content-encoding': as.encoding } : {}) });
22
+ res.end(body);
23
+ };
24
+ const notFound = (res, status = 404) => { res.writeHead(status, { 'content-type': 'text/plain' }); res.end(status === 400 ? 'Bad path' : 'Not in the build'); };
25
+ const pathOf = (req) => { try { return decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch { return null; } };
26
+ const listen = (server) => new Promise((done) => server.listen(0, '127.0.0.1', () => done(server.address().port)));
27
+
28
+ const game = createServer((req, res) => {
29
+ const path = pathOf(req);
30
+ if (path === null) return notFound(res, 400);
31
+ if (path.startsWith('/game/')) {
32
+ let name = root + path.slice(6);
33
+ if (name.endsWith('/') || name === root) name += 'index.html';
34
+ const body = files.get(name);
35
+ if (body) return send(res, body, name);
36
+ }
37
+ return notFound(res);
38
+ });
39
+ const gamePort = await listen(game);
40
+ const harness = HARNESS.toString('utf8').replace('src="/game/index.html"', `src="http://127.0.0.1:${gamePort}/game/index.html"`);
41
+ const page = createServer((req, res) => {
42
+ const path = pathOf(req);
43
+ if (path === '/__fb/harness.html') return send(res, harness, 'harness.html');
44
+ if (path === '/__fb/host.js') return send(res, HOST, 'host.js');
45
+ return notFound(res, path === null ? 400 : 404);
46
+ });
47
+ const port = await listen(page);
48
+ const close = (server) => new Promise((r) => { server.closeAllConnections?.(); server.close(r); });
49
+ return { port, gamePort, close: () => Promise.all([close(page), close(game)]) };
50
+ }
@@ -0,0 +1,57 @@
1
+ /* The report as plain text for a person. --json prints the report object itself for an AI. */
2
+
3
+ const LABEL = { pass: 'PASS', fail: 'FAIL', warn: 'LOOK', skip: 'SKIP', note: 'NOTE', person: ' · ' };
4
+ const GROUPS = [
5
+ ['files', 'Ready to send: the files'],
6
+ ['play', 'Ready to send: playing it (headless browser)'],
7
+ ['person', 'Quality review: our team plays it after you send it'],
8
+ ];
9
+
10
+ export function formatReport(rep, { color = false } = {}) {
11
+ const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
12
+ const tint = { pass: 32, fail: 31, warn: 33, skip: 90, note: 36, person: 90 };
13
+ const lines = [`First Byte check: ${rep.name}`, ''];
14
+ if (rep.error) {
15
+ lines.push(`${paint(31, 'FAIL')} ${rep.error}`, '');
16
+ return lines.join('\n');
17
+ }
18
+ for (const [check, title] of GROUPS) {
19
+ lines.push(title);
20
+ const group = rep.results.filter((x) => x.check === check);
21
+ const why = group.length && group.every((r) => r.status === 'skip' && r.detail.join() === group[0].detail.join()) ? group[0].detail : null;
22
+ if (why) {
23
+ lines.push(` ${paint(tint.skip, 'SKIP')} ${group.map((r) => r.id).join(' ')}`);
24
+ for (const d of why) lines.push(` ${d}`);
25
+ lines.push('');
26
+ continue;
27
+ }
28
+ for (const r of group) {
29
+ lines.push(` ${paint(tint[r.status], LABEL[r.status])} ${r.id} ${r.title}`);
30
+ for (const d of r.detail) lines.push(` ${d}`);
31
+ if (r.fix) lines.push(` ${paint(1, 'Fix:')} ${r.fix}`);
32
+ }
33
+ lines.push('');
34
+ }
35
+ lines.push(summary(rep, paint));
36
+ return lines.join('\n') + '\n';
37
+ }
38
+
39
+ /* One line that never says more than the checks proved. */
40
+ export function summary(rep, paint = (c, s) => s) {
41
+ const fails = rep.counts.fail || 0;
42
+ const looks = rep.counts.warn || 0;
43
+ const skips = rep.counts.skip || 0;
44
+ const look = looks ? `, ${looks} to look at` : '';
45
+ if (fails) {
46
+ /* Some failures probably come from others (check/Checker `after`): say where to start. */
47
+ const failed = rep.results.filter((r) => r.status === 'fail');
48
+ const later = failed.filter((r) => r.after).length;
49
+ if (!later) return paint(31, `${fails} to fix${look}.`) + ' Fix them and run the check again.';
50
+ const first = failed.filter((r) => !r.after).map((r) => r.id);
51
+ const start = first.length > 1 ? `${first.slice(0, -1).join(', ')} and ${first.at(-1)}` : first[0];
52
+ return paint(31, `${fails} to fix${look}.`) + ` Start with ${start}: the other ${later} will probably clear up after. Then run the check again.`;
53
+ }
54
+ if (skips) return paint(33, `Nothing to fix so far${look}, but ${skips} check${skips === 1 ? ' was' : 's were'} skipped.`) + ' Run them before you send the game.';
55
+ if (looks) return paint(33, `Nothing to fix, ${looks} to look at.`) + ' A person plays it next.';
56
+ return paint(32, 'Passed every check.') + ' A person plays it next.';
57
+ }
@@ -0,0 +1,47 @@
1
+ /* A developer's level from what they have done. Plain ESM with no Node imports. */
2
+
3
+ export const OWN_SHARE = 100;
4
+
5
+ export const LEVELS = [
6
+ { level: 0, name: 'Not picked yet', share: 0, perks: [] },
7
+ { level: 1, name: 'First Byte', share: 70, perks: ['Your First Byte badge', 'Keep 70% of ad money from our players', 'Keep 100% from players you bring'] },
8
+ { level: 2, name: 'Regular', share: 75, perks: ['Your Regular badge', 'Keep 75% of ad money from our players', 'Your uploads move up the review queue'] },
9
+ { level: 3, name: 'Trusted', share: 80, perks: ['Your Trusted badge', 'Keep 80% of ad money from our players', 'Review feedback within 48 hours'] },
10
+ { level: 4, name: 'Studio', share: 85, perks: ['Your Studio badge', 'Keep 85% of ad money from our players', 'First in line for the Monday front row'] },
11
+ ];
12
+
13
+ /* What each level needs on top of the one below it. */
14
+ const NEEDS = [
15
+ () => [],
16
+ (r) => [{ label: 'Games picked', have: r.picked, need: 1 }],
17
+ (r) => (r.weeksLive >= 8 && r.picked < 3
18
+ ? [{ label: 'Weeks one game has been live', have: r.weeksLive, need: 8 }]
19
+ : [{ label: 'Games picked', have: r.picked, need: 3 }]),
20
+ (r) => [{ label: 'Games picked', have: r.picked, need: 5 }, { label: 'Must-fix items in your last 3 reviews', have: r.recentMustFix, need: 0, atMost: true }],
21
+ (r) => [
22
+ { label: 'Games picked', have: r.picked, need: 10 },
23
+ { label: 'Players in the last 4 weeks', have: r.players, need: 100 },
24
+ { label: '% of players past the first minute', have: Math.round(r.pastFirstMinute * 100), need: 50 },
25
+ { label: '% of players back another day', have: Math.round(r.returning * 100), need: 20 },
26
+ ],
27
+ ];
28
+
29
+ const clean = (r = {}) => ({
30
+ picked: r.picked || 0, weeksLive: r.weeksLive || 0, recentMustFix: r.recentMustFix || 0,
31
+ players: r.players || 0, pastFirstMinute: r.pastFirstMinute || 0, returning: r.returning || 0,
32
+ });
33
+ const needs = (n, r) => NEEDS[n](r).map(({ atMost, ...x }) => ({ ...x, done: atMost ? x.have <= x.need : x.have >= x.need }));
34
+
35
+ export function levelOf(record, { reached = 0, cap = null } = {}) {
36
+ const r = clean(record);
37
+ let earned = 0;
38
+ while (earned < 4 && needs(earned + 1, r).every((x) => x.done)) earned++;
39
+ const best = Math.max(earned, reached || 0);
40
+ const level = cap == null ? best : Math.min(best, cap);
41
+ const L = LEVELS[level];
42
+ const n = level < 4 ? LEVELS[level + 1] : null;
43
+ return {
44
+ level, earned, name: L.name, share: L.share, ownShare: OWN_SHARE, perks: L.perks, capped: cap != null && best > cap,
45
+ next: n ? { level: n.level, name: n.name, needs: needs(n.level, r) } : null,
46
+ };
47
+ }
@@ -0,0 +1,45 @@
1
+ /* Loads a game build from a zip or a folder into one shape: a Map of path to Buffer. */
2
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import { join, relative, sep } from 'node:path';
4
+ import { readZip } from '../Zip/Zip.js';
5
+
6
+ const SKIP = new Set(['.git', '.DS_Store', 'Thumbs.db', '__MACOSX', 'node_modules']);
7
+
8
+ export function loadGame(path) {
9
+ const st = statSync(path);
10
+ if (st.isDirectory()) return { kind: 'folder', path, files: readFolder(path) };
11
+ return { ...fromZip(readFileSync(path)), path };
12
+ }
13
+
14
+ export function fromZip(buf) {
15
+ const files = readZip(buf);
16
+ for (const name of [...files.keys()]) if (name.startsWith('__MACOSX/')) files.delete(name);
17
+ return { kind: 'zip', path: null, files };
18
+ }
19
+
20
+ function readFolder(root) {
21
+ const files = new Map();
22
+ const walk = (dir) => {
23
+ for (const name of readdirSync(dir)) {
24
+ if (SKIP.has(name)) continue;
25
+ const full = join(dir, name);
26
+ if (statSync(full).isDirectory()) walk(full);
27
+ else files.set(relative(root, full).split(sep).join('/'), readFileSync(full));
28
+ }
29
+ };
30
+ walk(root);
31
+ for (const name of [...files.keys()]) if (name.startsWith('__MACOSX/')) files.delete(name);
32
+ return files;
33
+ }
34
+
35
+ /* Where index.html really is: '' when at the top, 'folder/' when the whole build sits in one folder. */
36
+ export function findRoot(files) {
37
+ const names = [...files.keys()].filter((n) => !n.startsWith('__MACOSX/'));
38
+ if (files.has('index.html')) return '';
39
+ const tops = new Set(names.map((n) => n.split('/')[0]));
40
+ if (tops.size === 1) {
41
+ const [top] = tops;
42
+ if (files.has(`${top}/index.html`)) return `${top}/`;
43
+ }
44
+ return null;
45
+ }
@@ -0,0 +1,27 @@
1
+ /*
2
+ * How one file of a build is sent to a browser: its type, and its encoding when the file is already
3
+ * compressed (game.wasm.br, game.data.gz, as Unity and other engines write them).
4
+ *
5
+ * The live site (server/GameHost) and the checker (check/PlayChecks serve.js) both ask here, so a
6
+ * build that plays in one plays in the other. Add a new file type in this table and nowhere else.
7
+ */
8
+ export const TYPES = {
9
+ html: 'text/html; charset=utf-8', htm: 'text/html; charset=utf-8', js: 'text/javascript', mjs: 'text/javascript', css: 'text/css',
10
+ json: 'application/json', wasm: 'application/wasm', data: 'application/octet-stream', bin: 'application/octet-stream',
11
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', svg: 'image/svg+xml', ico: 'image/x-icon',
12
+ mp3: 'audio/mpeg', ogg: 'audio/ogg', wav: 'audio/wav', m4a: 'audio/mp4', mp4: 'video/mp4', webm: 'video/webm',
13
+ woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf', txt: 'text/plain; charset=utf-8', xml: 'application/xml',
14
+ glb: 'model/gltf-binary', gltf: 'model/gltf+json', atlas: 'text/plain; charset=utf-8',
15
+ };
16
+
17
+ /* A last extension that means "these bytes are already compressed": the browser unpacks them. */
18
+ export const ENCODINGS = { br: 'br', gz: 'gzip' };
19
+
20
+ const ext = (name) => (name.includes('.') ? name.split('.').pop().toLowerCase() : '');
21
+ const typeOf = (name) => TYPES[ext(name)] || 'application/octet-stream';
22
+
23
+ export function served(name) {
24
+ const last = ext(name);
25
+ if (ENCODINGS[last]) return { type: typeOf(name.slice(0, -last.length - 1)), encoding: ENCODINGS[last] };
26
+ return { type: typeOf(name), encoding: null };
27
+ }