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.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # firstbyte
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The checker for [First Byte](https://firstbyte.games), a site that shows a few new browser games each
4
+ week. It plays your game and tells you exactly what to fix before you send it.
5
+
6
+ ```
7
+ npx firstbyte check my-game.zip
8
+ ```
9
+
10
+ `my-game.zip` can also be your build folder. Every rule gets PASS or FAIL with its fix, and the last
11
+ line says what to do next. Needs Node 22 or newer.
12
+
13
+ ## Playing the game
14
+
15
+ Half the rules are checked by playing the game in a headless browser. That needs Playwright, installed
16
+ once in your game's folder:
17
+
18
+ ```
19
+ npm i -D playwright@1.63.0
20
+ npx playwright install chromium
21
+ ```
22
+
23
+ Without it the files are still checked, and the report says the play checks were skipped.
24
+
25
+ Nothing to install at all: drop your zip at [firstbyte.games/developers](https://firstbyte.games/developers)
26
+ and press **Just check it**. The same checks run there, and nothing is sent to our team until you say so.
27
+
28
+ ## Commands
29
+
30
+ | Command | What it does |
31
+ |---|---|
32
+ | `npx firstbyte check <zip or folder>` | Checks a game against every rule |
33
+ | `npx firstbyte check <zip or folder> --json` | The same report as JSON, for your AI to read |
34
+ | `npx firstbyte check <zip or folder> --no-play` | Checks the files only |
35
+ | `npx firstbyte brief` | Prints the rules, written for an AI |
36
+
37
+ The command exits with 0 when nothing fails and 1 when something does.
38
+
39
+ ## Building with an AI
40
+
41
+ Paste the brief into it first: `npx firstbyte brief`, or [firstbyte.games/ai.txt](https://firstbyte.games/ai.txt).
42
+ It has every rule by id, the SDK's calls, and a whole starter game that already passes. Then let the AI
43
+ run `npx firstbyte check . --json` and fix what it reports.
44
+
45
+ ## Start from a game that passes
46
+
47
+ [firstbyte.games/starter.zip](https://firstbyte.games/starter.zip): a tiny, complete game. Its comments
48
+ name the rule each line is there for.
49
+
50
+ ## The SDK (optional)
51
+
52
+ ```html
53
+ <script src="https://firstbyte.games/sdk.js"></script>
54
+ ```
55
+
56
+ ```js
57
+ FirstByte.ready(); /* once, when the first frame is on screen */
58
+ FirstByte.playing(true); /* a round starts; playing(false) when it ends */
59
+ await FirstByte.breakTime(); /* an ad, only at a break */
60
+ FirstByte.save({ level: 4 }); /* progress; FirstByte.load() reads it back */
61
+ FirstByte.on('mute', quiet); /* the site's mute button */
62
+ ```
63
+
64
+ Every call also works when the game runs on its own, so a game needs no special case. Without the SDK
65
+ a game is still welcome: it earns no ad share and keeps no saves with us.
66
+
67
+ ## From code
68
+
69
+ ```js
70
+ import { check, formatReport } from 'firstbyte';
71
+
72
+ const report = await check('my-game.zip');
73
+ console.log(formatReport(report));
74
+ ```
75
+
76
+ ## Sending your game
77
+
78
+ [firstbyte.games/developers](https://firstbyte.games/developers): sign in with your email, drop the zip,
79
+ name it, and say in one sentence what's new about it. Our team plays it and answers within a week.
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import { check } from '../blocks/check/Checker/Checker.js';
3
+ import { formatReport } from '../blocks/check/ReportText/ReportText.js';
4
+ import { brief } from '../blocks/rules/Brief/Brief.js';
5
+
6
+ const HELP = `First Byte
7
+
8
+ firstbyte check <build.zip | build-folder> check a game against every rule
9
+ --json print the report as JSON (for your AI)
10
+ --no-play only check the files, do not play the game
11
+ firstbyte brief print the rules, written for an AI
12
+ firstbyte help this list
13
+ `;
14
+
15
+ const [cmd, ...args] = process.argv.slice(2);
16
+
17
+ if (cmd === 'check') {
18
+ const path = args.find((a) => !a.startsWith('--'));
19
+ if (!path) {
20
+ process.stderr.write('Say which build to check: firstbyte check my-game.zip\n');
21
+ process.exit(2);
22
+ }
23
+ const rep = await check(path, { play: !args.includes('--no-play') });
24
+ if (args.includes('--json')) process.stdout.write(JSON.stringify(rep, null, 2) + '\n');
25
+ else process.stdout.write(formatReport(rep, { color: process.stdout.isTTY }));
26
+ process.exit(rep.ok ? 0 : 1);
27
+ } else if (cmd === 'brief') {
28
+ process.stdout.write(brief());
29
+ } else {
30
+ process.stdout.write(HELP);
31
+ process.exit(cmd && cmd !== 'help' && cmd !== '--help' ? 2 : 0);
32
+ }
@@ -0,0 +1,102 @@
1
+ /*
2
+ * A game's achievements: the list it ships as achievements.json, checked in plain words; the unlocks
3
+ * this browser has; how rare each one is, in whole percents. For fun only: the game reports them, so
4
+ * nothing that counts ever reads them. Plain ESM with no Node imports.
5
+ */
6
+
7
+ export const FILE = 'achievements.json';
8
+ export const LIMITS = { most: 30, idChars: 32, nameChars: 32, aboutChars: 80, minPlayers: 50 };
9
+ export const ICONS = ['star', 'crown', 'bolt', 'heart', 'flag', 'coin', 'gem', 'key', 'shield', 'sword', 'skull', 'clock', 'trophy', 'rocket', 'leaf', 'eye'];
10
+
11
+ const FIELDS = ['id', 'name', 'about', 'icon', 'secret'];
12
+ const ID = /^[a-z][a-z0-9-]*$/;
13
+ const LINK = /https?:|www\.|\b[a-z0-9-]+\.(com|net|org|io|gg|games|app|dev|co|xyz|me|ly|tv)\b/i;
14
+ const EXAMPLE = '{ "achievements": [ { "id": "first-win", "name": "First win", "about": "Win a round." } ] }';
15
+
16
+ export const isId = (s) => typeof s === 'string' && s.length <= LIMITS.idChars && ID.test(s);
17
+
18
+ /* A small, stable hash, so an id always gets the same icon. */
19
+ function hash(s) {
20
+ let h = 2166136261;
21
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
22
+ return h >>> 0;
23
+ }
24
+
25
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^[^a-z]+|-+$/g, '').slice(0, LIMITS.idChars) || 'first-win';
26
+ const letters = (s) => [...s].length;
27
+
28
+ /* The problems with one piece of text: missing, too long, markup, a link. */
29
+ function textProblems(v, what, most) {
30
+ if (typeof v !== 'string' || !v.trim()) return [`it needs ${what === 'name' ? 'a name' : 'an about line'}.`];
31
+ const out = [];
32
+ if (letters(v) > most) out.push(`the ${what === 'name' ? 'name' : 'about line'} is ${letters(v)} letters. Keep it to ${most}.`);
33
+ if (/[<>]/.test(v)) out.push(`the ${what === 'name' ? 'name' : 'about line'} has < or >. Use plain words.`);
34
+ if (LINK.test(v)) out.push(`the ${what === 'name' ? 'name' : 'about line'} has a link. Leave links out.`);
35
+ return out;
36
+ }
37
+
38
+ export function readList(text) {
39
+ let data;
40
+ try { data = JSON.parse(text); } catch (e) {
41
+ return { list: null, problems: [`${FILE} isn't valid JSON: ${String(e.message).replace(/\.$/, '')}. Fix the file, or leave it out.`] };
42
+ }
43
+ const all = data && typeof data === 'object' && !Array.isArray(data) ? data.achievements : undefined;
44
+ if (!Array.isArray(all)) return { list: null, problems: [`${FILE} needs a list called "achievements": ${EXAMPLE}.`] };
45
+ if (!all.length) return { list: null, problems: ['The list is empty. Add an achievement, or leave the file out.'] };
46
+ if (all.length > LIMITS.most) return { list: null, problems: [`There are ${all.length} achievements. Keep it to ${LIMITS.most}.`] };
47
+
48
+ const problems = [];
49
+ const seen = new Set();
50
+ const list = all.map((a, i) => {
51
+ if (!a || typeof a !== 'object' || Array.isArray(a)) {
52
+ problems.push(`Achievement ${i + 1} isn't an achievement like { "id": "first-win", "name": "First win", "about": "Win a round." }.`);
53
+ return null;
54
+ }
55
+ const at = `Achievement ${i + 1}${isId(a.id) ? ` (${a.id})` : ''}: `;
56
+ const add = (p) => problems.push(at + p);
57
+ if (!isId(a.id)) add(`the id ${JSON.stringify(a.id ?? '')} must be lowercase letters, digits and hyphens, starting with a letter, up to ${LIMITS.idChars}. Try "${slug(a.id ?? a.name ?? '')}".`);
58
+ else if (seen.has(a.id)) add('the id is used twice. Give each its own.');
59
+ seen.add(a.id);
60
+ for (const k of Object.keys(a)) if (!FIELDS.includes(k)) add(`"${k}" isn't a field. Use id, name, about, icon and secret.`);
61
+ textProblems(a.name, 'name', LIMITS.nameChars).forEach(add);
62
+ textProblems(a.about, 'about', LIMITS.aboutChars).forEach(add);
63
+ if ('icon' in a && !ICONS.includes(a.icon)) add(`${JSON.stringify(a.icon)} isn't an icon. Use one of: ${ICONS.join(', ')}.`);
64
+ if ('secret' in a && a.secret !== true) add('"secret" can only be true. Leave it out otherwise.');
65
+ const out = { id: a.id, name: a.name, about: a.about };
66
+ if ('icon' in a) out.icon = a.icon;
67
+ if ('secret' in a) out.secret = a.secret;
68
+ return out;
69
+ });
70
+ return problems.length ? { list: null, problems } : { list, problems: [] };
71
+ }
72
+
73
+ export const iconOf = (a) => (ICONS.includes(a?.icon) ? a.icon : ICONS[hash(String(a?.id ?? '')) % ICONS.length]);
74
+
75
+ export function addUnlock(have, id, ids, at) {
76
+ const base = Array.isArray(have) ? have.filter((u) => u && isId(u.id)) : [];
77
+ if (!ids.includes(id)) return { have: base, isNew: false, refused: 'unknown' };
78
+ if (base.some((u) => u.id === id)) return { have: base, isNew: false };
79
+ return { have: [...base, { id, at }], isNew: true };
80
+ }
81
+
82
+ export function rarity(counts, list) {
83
+ const players = Number(counts?.players);
84
+ const enough = Number.isFinite(players) && players >= LIMITS.minPlayers;
85
+ return Object.fromEntries(list.map((a) => {
86
+ if (!enough) return [a.id, null];
87
+ const raw = Number(counts.holders?.[a.id]);
88
+ const held = Number.isFinite(raw) ? Math.min(Math.max(0, Math.floor(raw)), players) : 0;
89
+ return [a.id, held ? Math.max(1, Math.min(100, Math.round((held / players) * 100))) : 0];
90
+ }));
91
+ }
92
+
93
+ export function forPlayer(list, have, shares = {}) {
94
+ const got = new Map((Array.isArray(have) ? have : []).map((u) => [u.id, u]));
95
+ return list.map((a) => {
96
+ const u = got.get(a.id);
97
+ const share = shares[a.id] ?? null;
98
+ if (a.secret && !u) return { id: a.id, name: 'Secret', about: 'Keep playing to find it.', icon: 'eye', secret: true, unlocked: false, share };
99
+ const shown = { id: a.id, name: a.name, about: a.about, icon: iconOf(a), secret: !!a.secret, unlocked: !!u, share };
100
+ return u ? { ...shown, at: u.at } : shown;
101
+ });
102
+ }
@@ -0,0 +1,18 @@
1
+ /*
2
+ * The kinds of game First Byte shows. This list is the only thing a person maintains, and only when a
3
+ * whole new kind of game appears. What we need each week is worked out from it (see needs.js).
4
+ * Ids are never renamed: games in the catalog point at them.
5
+ * Plain ESM with no Node imports: the site runs this same file in the browser.
6
+ */
7
+ export const CATEGORIES = [
8
+ { id: 'two-player', name: '2 players, 1 keyboard', icon: 'two' },
9
+ { id: 'rhythm', name: 'Rhythm', icon: 'music' },
10
+ { id: 'story', name: 'Short stories', icon: 'book' },
11
+ { id: 'puzzle', name: 'Puzzles', icon: 'puzzle' },
12
+ { id: 'quick-runs', name: 'Quick runs', icon: 'repeat' },
13
+ { id: 'action', name: 'Action', icon: 'tense' },
14
+ { id: 'physics', name: 'Smash and physics', icon: 'smashy' },
15
+ { id: 'builder', name: 'Builders', icon: 'cozy' },
16
+ { id: 'racing', name: 'Racing and sports', icon: 'pad' },
17
+ { id: 'merge-idle', name: 'Merge and idle', icon: 'layers' },
18
+ ];
@@ -0,0 +1,68 @@
1
+ /*
2
+ * What we need, worked out from the catalog, so nobody writes the list by hand.
3
+ *
4
+ * For each kind of game: how many recent games it has, against how many it should have.
5
+ * recent = games from the last `weeks` weeks of the catalog
6
+ * share = every kind starts equal; with play data, a kind whose games are played more than
7
+ * average gets a bigger share (players want more of it)
8
+ * target = the kind's share of the recent games, never fewer than `least`
9
+ * ratio = count / target
10
+ * level = 'Most wanted' (none), 'Wanted' (under target), 'Enough', or 'Full' (twice the target)
11
+ *
12
+ * Plain ESM with no Node imports: the site runs this same file in the browser.
13
+ */
14
+ import { CATEGORIES } from '../Kinds/Kinds.js';
15
+
16
+ export const LEVELS = ['Most wanted', 'Wanted', 'Enough', 'Full'];
17
+
18
+ export function needs(games, opts = {}) {
19
+ const categories = opts.categories || CATEGORIES;
20
+ const weeks = opts.weeks ?? 8;
21
+ const least = opts.least ?? 2;
22
+ const minutes = opts.minutes || null;
23
+
24
+ const latest = Math.max(0, ...games.map((g) => g.week || 0));
25
+ const recent = games.filter((g) => (g.week || 0) > latest - weeks);
26
+ const inKind = (c) => recent.filter((g) => (g.kinds || []).includes(c.id));
27
+
28
+ const weight = weights(categories, inKind, minutes);
29
+ const totalWeight = categories.reduce((s, c) => s + weight.get(c.id), 0);
30
+
31
+ const rows = categories.map((c, order) => {
32
+ const count = inKind(c).length;
33
+ const target = Math.max(least, Math.round(recent.length * weight.get(c.id) / totalWeight));
34
+ const ratio = count / target;
35
+ const level = count === 0 ? LEVELS[0] : ratio < 1 ? LEVELS[1] : ratio >= 2 ? LEVELS[3] : LEVELS[2];
36
+ return { id: c.id, name: c.name, icon: c.icon, level, count, target, ratio: round(ratio), weight: round(weight.get(c.id)), order };
37
+ });
38
+
39
+ rows.sort((a, b) => a.ratio - b.ratio || b.weight - a.weight || a.order - b.order);
40
+ return rows.map(({ order, ...row }) => row);
41
+ }
42
+
43
+ /* With play minutes per game id, a kind played more than average weighs more (at most 3 times). */
44
+ function weights(categories, inKind, minutes) {
45
+ const w = new Map(categories.map((c) => [c.id, 1]));
46
+ if (!minutes) return w;
47
+ const perGame = (c) => {
48
+ const games = inKind(c);
49
+ return games.length ? games.reduce((s, g) => s + (minutes[g.id] || 0), 0) / games.length : null;
50
+ };
51
+ const known = categories.map(perGame).filter((m) => m !== null);
52
+ const average = known.length ? known.reduce((s, m) => s + m, 0) / known.length : 0;
53
+ if (!average) return w;
54
+ for (const c of categories) {
55
+ const m = perGame(c);
56
+ if (m !== null) w.set(c.id, Math.min(3, Math.max(0.5, m / average)));
57
+ }
58
+ return w;
59
+ }
60
+
61
+ /* The few to show: everything we lack first, then at most one we have plenty of. */
62
+ export function shortlist(rows, n = 6) {
63
+ const lacking = rows.filter((r) => r.level === LEVELS[0] || r.level === LEVELS[1]);
64
+ const full = rows.filter((r) => r.level === LEVELS[3]).slice(-1);
65
+ return [...lacking.slice(0, n - full.length), ...full];
66
+ }
67
+
68
+ const round = (x) => Math.round(x * 100) / 100;
@@ -0,0 +1,63 @@
1
+ /* Runs every automatic rule on a build and returns one report. */
2
+ import { basename } from 'node:path';
3
+ import { loadGame, findRoot } from '../../load/Build/Build.js';
4
+ import { checkFiles } from '../FileChecks/FileChecks.js';
5
+ import { checkPlay, skipPlay } from '../PlayChecks/PlayChecks.js';
6
+ import { RULES } from '../../rules/Rulebook/Rulebook.js';
7
+ import { ZipError } from '../../load/Zip/Zip.js';
8
+
9
+ export async function check(path, opts = {}) {
10
+ let game;
11
+ try {
12
+ game = loadGame(path);
13
+ } catch (e) {
14
+ if (e.code === 'ENOENT') return broken(path, `There is nothing at "${path}".`);
15
+ if (e instanceof ZipError) return broken(path, e.message);
16
+ throw e;
17
+ }
18
+ return checkGame(game, opts);
19
+ }
20
+
21
+ export async function checkGame(game, opts = {}) {
22
+ const root = findRoot(game.files);
23
+ const results = checkFiles(game.files, root);
24
+ if (opts.play === false) results.push(...skipPlay('Skipped (--no-play).'));
25
+ else if (root === null) results.push(...skipPlay('Fix F1 first: the checker cannot find index.html to play.'));
26
+ else results.push(...await checkPlay(game.files, root, opts));
27
+ return report(game.path || 'upload.zip', game.kind, results);
28
+ }
29
+
30
+ function broken(path, why) {
31
+ return { name: basename(path), kind: null, ok: false, error: why, results: [], counts: { fail: 1 } };
32
+ }
33
+
34
+ export function report(path, kind, results) {
35
+ const byId = new Map(results.map((r) => [r.id, r]));
36
+ const full = RULES.map((rule) => {
37
+ const r = byId.get(rule.id) || (rule.check === 'person' ? { status: 'person' } : { status: 'skip', detail: ['Not checked.'] });
38
+ return { id: rule.id, key: rule.key, check: rule.check, title: rule.title, status: r.status, detail: r.detail || [], fix: r.status === 'fail' || r.status === 'warn' ? rule.fix : undefined };
39
+ });
40
+ link(full);
41
+ const counts = {};
42
+ for (const r of full) counts[r.status] = (counts[r.status] || 0) + 1;
43
+ return { name: basename(path), kind, ok: !counts.fail, results: full, counts };
44
+ }
45
+
46
+ /*
47
+ * One mistake often shows up as several failures: a script the game could not load (P1) also leaves
48
+ * the screen blank (P2), deaf to keys (P4) and silent (P5). Each such failure gets `after`, the rule
49
+ * to fix first, and its fix says so, so a developer starts in the right place. "Probably", because the
50
+ * checker has not proved it: the rule's own fix stays, for when the failure outlives the first one.
51
+ */
52
+ const AFTER_LOAD = ['P2', 'P4', 'P5', 'P8'];
53
+ function link(full) {
54
+ const by = new Map(full.map((r) => [r.id, r]));
55
+ const failed = (id) => by.get(id)?.status === 'fail';
56
+ if (failed('P1')) {
57
+ for (const id of AFTER_LOAD) if (failed(id)) by.get(id).after = 'P1';
58
+ /* Every file it missed was asked for with a path starting "/": that is F2's mistake, seen again. */
59
+ const p1 = by.get('P1');
60
+ if (failed('F2') && p1.detail.length && p1.detail.every((d) => d.startsWith('Missing file:') && d.includes('starts with "/"'))) p1.after = 'F2';
61
+ }
62
+ for (const r of full) if (r.after) r.fix = `Probably because of ${r.after}: fix that first, then check again. If it is still here: ${r.fix}`;
63
+ }
@@ -0,0 +1,198 @@
1
+ /*
2
+ * The 'files' rules (F1-F7): everything that can be checked by reading the build, without playing it.
3
+ * Spec: FileChecks.spec.md. Called by check/Checker; each rule's words and fix are in rules/Rulebook.
4
+ */
5
+ import { LIMITS } from '../../rules/Rulebook/Rulebook.js';
6
+ import { FILE as ACHIEVEMENTS, readList } from '../../achievements/Achievements/Achievements.js';
7
+
8
+ const TEXT = /\.(html?|m?js|css|json|txt|xml|svg)$/i;
9
+
10
+ export const OTHER_PORTALS = [
11
+ { name: 'CrazyGames', re: /sdk\.crazygames\.com|CrazyGames\.SDK|window\.CrazyGames\b/ },
12
+ { name: 'Poki', re: /poki-sdk|game-cdn\.poki\.com|\bPokiSDK\b/ },
13
+ { name: 'GameDistribution', re: /gamedistribution\.com|\bgdsdk\b/ },
14
+ { name: 'Yandex Games', re: /yandex\.ru\/games\/sdk|\bYaGames\b/ },
15
+ { name: 'Playgama', re: /playgama-bridge|playgama\.com/i },
16
+ { name: 'GamePix', re: /gamepix\.com|\bGamePix\./ },
17
+ { name: 'GameMonetize', re: /gamemonetize/i },
18
+ { name: 'Y8', re: /api\.y8\.com|y8\.com\/api/ },
19
+ ];
20
+
21
+ export const STORE_LINKS = [
22
+ 'store.steampowered.com', 'patreon.com', 'ko-fi.com', 'buymeacoffee.com', 'paypal.com', 'paypal.me',
23
+ 'apps.apple.com', 'play.google.com', 'itch.io', 'crazygames.com', 'poki.com', 'newgrounds.com',
24
+ 'kongregate.com', 'armorgames.com', 'gamejolt.com',
25
+ ];
26
+
27
+ /* The SDK's script tag: its src is the SDK's address, or a .js file with firstbyte in its name. Tested on one
28
+ tag at a time (scriptTags), never across a whole file, so no file can make the check slow. */
29
+ const SDK_SRC = /\ssrc\s*=\s*["']([^"']{1,500})["']/i;
30
+ const isSdkTag = (tag) => { const m = SDK_SRC.exec(tag); return !!m && (m[1] === 'https://firstbyte.games/sdk.js' || /firstbyte[^/]*\.js$/i.test(m[1])); };
31
+ /* Every <script ...> opening tag in a page, each at most 2000 characters, found in one pass. */
32
+ function scriptTags(src) {
33
+ const lower = src.toLowerCase();
34
+ const out = [];
35
+ for (let i = lower.indexOf('<script'); i !== -1 && out.length < 500; i = lower.indexOf('<script', i + 7)) {
36
+ const end = lower.indexOf('>', i);
37
+ out.push(src.slice(i, end === -1 ? i + 2000 : Math.min(end + 1, i + 2000)));
38
+ }
39
+ return out;
40
+ }
41
+ /* Strings inside the SDK itself, which survive bundling and minifying. */
42
+ const SDK_BUNDLED = /\[FirstByte\] |["']firstbyte:["']/;
43
+ const SDK_CALLS = /FirstByte\.(ready|playing|breakTime|save|load|score|achieve|on)\(/;
44
+
45
+ export function checkFiles(files, root) {
46
+ const text = new Map();
47
+ for (const [name, buf] of files) if (TEXT.test(name)) text.set(name, buf.toString('utf8'));
48
+ return [
49
+ indexTop(files, root),
50
+ relativePaths(files, text, root ?? ''),
51
+ size(files),
52
+ otherPortal(text),
53
+ storeLinks(text),
54
+ sdk(text),
55
+ achievements(files, text, root ?? ''),
56
+ ];
57
+ }
58
+
59
+ function indexTop(files, root) {
60
+ if (root === '') return { id: 'F1', status: 'pass' };
61
+ /* The whole game zipped inside one folder is the commonest way to zip a build, and plays the same:
62
+ the site and the checker both serve it from that folder (load/Build findRoot). */
63
+ if (root) return { id: 'F1', status: 'pass', detail: [`index.html is inside the folder "${root.slice(0, -1)}", which holds the whole game. That works.`] };
64
+ const names = [...files.keys()].filter((n) => !n.startsWith('__MACOSX/'));
65
+ const found = names.filter((n) => /(^|\/)index\.html$/.test(n));
66
+ /* Some engines name the page after the project ("my-game.html"): one page at the top is surely it. */
67
+ const pages = names.filter((n) => !n.includes('/') && /\.html?$/i.test(n));
68
+ const detail = found.length
69
+ ? [`index.html is at ${found.map((f) => `"${f}"`).join(', ')}, with other files outside its folder. Put index.html at the top, next to them.`]
70
+ : names.some((n) => n.split('/').pop().toLowerCase() === 'index.html')
71
+ ? ['The file must be called index.html, all lower case.']
72
+ : pages.length === 1
73
+ ? [`There is no index.html. Rename "${pages[0]}" to index.html.`]
74
+ : ['There is no index.html in the build.'];
75
+ return { id: 'F1', status: 'fail', detail };
76
+ }
77
+
78
+ function refsIn(name, src) {
79
+ const out = [];
80
+ const add = (v) => out.push(v.trim());
81
+ if (/\.html?$/i.test(name)) {
82
+ for (const m of src.matchAll(/\s(?:src|href|data-src|poster)\s*=\s*["']([^"']{1,2000})["']/gi)) add(m[1]);
83
+ }
84
+ if (/\.(html?|css)$/i.test(name)) {
85
+ for (const m of src.matchAll(/url\(\s*["']?([^"')]{1,2000})["']?\s*\)/gi)) add(m[1]);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function relativePaths(files, text, root) {
91
+ const detail = [];
92
+ let fail = false;
93
+ for (const name of files.keys()) {
94
+ if (name.includes('\\')) { fail = true; detail.push(`"${name}" has a backslash in its path. Zip it again on the command line or with 7-Zip.`); }
95
+ }
96
+ const lower = new Map([...files.keys()].map((n) => [n.toLowerCase(), n]));
97
+ for (const [name, src] of text) {
98
+ if (!name.startsWith(root)) continue;
99
+ const dir = name.slice(0, name.lastIndexOf('/') + 1);
100
+ for (const ref of refsIn(name, src)) {
101
+ if (/^(https?:|data:|blob:|mailto:|tel:|javascript:|#|about:|\/\/)/i.test(ref) || ref.includes('${') || ref === '') continue;
102
+ if (ref.startsWith('/')) { fail = true; detail.push(`${name}: "${ref}" starts with "/". Use "${ref.replace(/^\/+/, '')}".`); continue; }
103
+ if (/^(file:|[a-z]:\\)/i.test(ref)) { fail = true; detail.push(`${name}: "${ref}" points at a file on your computer.`); continue; }
104
+ const target = resolve(dir, ref.split(/[?#]/)[0]);
105
+ if (target === null || files.has(target)) continue;
106
+ const near = lower.get(target.toLowerCase());
107
+ if (near) { fail = true; detail.push(`${name}: "${ref}" is "${near.slice(root.length)}" in the build. Match the case exactly.`); }
108
+ else detail.push(`${name}: "${ref}" is not in the build.`);
109
+ }
110
+ }
111
+ if (fail) return { id: 'F2', status: 'fail', detail };
112
+ if (detail.length) return { id: 'F2', status: 'warn', detail: [...detail, 'These may be made by your code at run time. If not, the game will miss them.'] };
113
+ return { id: 'F2', status: 'pass' };
114
+ }
115
+
116
+ function resolve(dir, ref) {
117
+ let ref2;
118
+ try { ref2 = decodeURIComponent(ref); } catch { ref2 = ref; }
119
+ const parts = (dir + ref2).split('/');
120
+ const out = [];
121
+ for (const p of parts) {
122
+ if (p === '..') { if (!out.length) return null; out.pop(); }
123
+ else if (p !== '.' && p !== '') out.push(p);
124
+ }
125
+ return out.join('/');
126
+ }
127
+
128
+ function size(files) {
129
+ let total = 0;
130
+ for (const buf of files.values()) total += buf.length;
131
+ const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
132
+ if (total <= LIMITS.sizeBytes) return { id: 'F3', status: 'pass', detail: [`${mb(total)} unzipped.`] };
133
+ const biggest = [...files].sort((a, b) => b[1].length - a[1].length).slice(0, 5);
134
+ return { id: 'F3', status: 'fail', detail: [`${mb(total)} unzipped, over the 50 MB limit. Biggest files:`, ...biggest.map(([n, b]) => ` ${mb(b.length)} ${n}`)] };
135
+ }
136
+
137
+ function otherPortal(text) {
138
+ const loaded = [];
139
+ const inCode = [];
140
+ for (const { name, re } of OTHER_PORTALS) {
141
+ const tags = [...text].filter(([f, src]) => /\.html?$/i.test(f) && scriptTags(src).some((tag) => re.test(tag)));
142
+ const where = [...text].filter(([, src]) => re.test(src)).map(([f]) => f);
143
+ if (tags.length) loaded.push(`${name} SDK is loaded by ${tags.map(([f]) => f).join(', ')}.`);
144
+ else if (where.length) inCode.push(`${name} SDK code is in ${where.slice(0, 3).join(', ')}${where.length > 3 ? ` and ${where.length - 3} more` : ''}.`);
145
+ }
146
+ if (loaded.length) return { id: 'F4', status: 'fail', detail: [...loaded, ...inCode] };
147
+ if (inCode.length) return { id: 'F4', status: 'warn', detail: [...inCode, "It isn't loaded by the page, so it may be a multi-site adapter that stays quiet here. If it shows another site's ads or prompts on First Byte, make a build without it."] };
148
+ return { id: 'F4', status: 'pass' };
149
+ }
150
+
151
+ function storeLinks(text) {
152
+ const inHref = [];
153
+ const inCode = [];
154
+ for (const [name, src] of text) {
155
+ for (const host of STORE_LINKS) {
156
+ const re = new RegExp(`https?://(?:[\\w-]+\\.)*${host.replace(/\./g, '\\.')}[^\\s"'<>)]*`, 'gi');
157
+ for (const m of src.matchAll(re)) {
158
+ const before = src.slice(Math.max(0, m.index - 12), m.index);
159
+ (/\.html?$/i.test(name) && /href\s*=\s*["']?$/i.test(before) ? inHref : inCode).push(`${name}: ${m[0]}`);
160
+ }
161
+ }
162
+ }
163
+ if (inHref.length) return { id: 'F5', status: 'fail', detail: unique(inHref) };
164
+ if (inCode.length) return { id: 'F5', status: 'warn', detail: [...unique(inCode), 'Found in code, not as a link. If the game shows it to players, remove it.'] };
165
+ return { id: 'F5', status: 'pass' };
166
+ }
167
+
168
+ function sdk(text) {
169
+ for (const [name, src] of text) {
170
+ if (/\.html?$/i.test(name) && scriptTags(src).some(isSdkTag)) return { id: 'F6', status: 'pass' };
171
+ }
172
+ for (const src of text.values()) if (SDK_BUNDLED.test(src)) return { id: 'F6', status: 'pass', detail: ['The SDK is bundled into your code.'] };
173
+ const calls = [...text].find(([, src]) => SDK_CALLS.test(src));
174
+ if (calls) return { id: 'F6', status: 'fail', detail: [`${calls[0]} calls FirstByte, but the SDK is never loaded, so the game will stop with an error.`] };
175
+ return { id: 'F6', status: 'note', detail: ['No SDK found. That is allowed: the game will earn no ad share and keep no saves with us.'] };
176
+ }
177
+
178
+ const unique = (a) => [...new Set(a)].slice(0, 8);
179
+
180
+ /*
181
+ * F7: achievements.json, next to index.html, checked by achievements/Achievements. A listed id that
182
+ * is nowhere in the code is only LOOK: the code may build the id at run time, which reading can't see.
183
+ */
184
+ function achievements(files, text, root) {
185
+ const at = root + ACHIEVEMENTS;
186
+ if (!files.has(at)) {
187
+ const elsewhere = [...files.keys()].find((n) => n === ACHIEVEMENTS || n.endsWith(`/${ACHIEVEMENTS}`));
188
+ if (elsewhere) return { id: 'F7', status: 'fail', detail: [`achievements.json is at "${elsewhere}". Move it next to index.html${root ? ` (into "${root.slice(0, -1)}")` : ''}.`] };
189
+ return { id: 'F7', status: 'note', detail: ['No achievements. You can add up to 30: see npx firstbyte brief.'] };
190
+ }
191
+ const { list, problems } = readList(files.get(at).toString('utf8'));
192
+ if (!list) return { id: 'F7', status: 'fail', detail: problems };
193
+ const code = [...text].filter(([n]) => n !== at && /\.(html?|m?js)$/i.test(n)).map(([, src]) => src);
194
+ const unseen = list.filter((a) => !code.some((src) => src.includes(a.id)));
195
+ const detail = [`${list.length} achievement${list.length === 1 ? '' : 's'}.`];
196
+ if (!unseen.length) return { id: 'F7', status: 'pass', detail };
197
+ return { id: 'F7', status: 'warn', detail: [...detail, ...unseen.map((a) => `"${a.id}" isn't written in your code. Fine if your code builds the id; otherwise it can never unlock.`)] };
198
+ }