/** Replay M1/R4b acceptance: bun tools/capture-m1.ts <temporary cache> [out/r4b]. */
import { spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
const root = path.resolve(import.meta.dir, '..')
if (process.argv[2] === '--r4c') {
await captureDetails(process.argv[3] ?? readFileSync(path.join(root, 'out/r4c/probe-cache.txt'), 'utf8').trim())
process.exit(0)
}
if (process.argv[2] === '--r5') {
if (!process.argv[3]) throw new Error('Usage: bun tools/capture-m1.ts --r5 <temporary probe cache>')
await captureDetails(process.argv[3], true)
process.exit(0)
}
const cache = path.resolve(process.argv[2] ?? readFileSync(path.join(root, 'out/m1/capture-cache.txt'), 'utf8').trim())
const relative = path.relative(tmpdir(), cache)
if (relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('Use an OS temporary FMM_CACHE_DIR')
const outputDir = path.resolve(root, process.argv[3] ?? 'out/m1')
const fixture = 'crates/app/tests/fixtures/r2b.json'
const specimen = 'crates/core/tests/fixtures/'
const data = (name: string) => path.join(cache, 'captures', name)
mkdirSync(outputDir, { recursive: true })
// Force the owner's long-count case without depending on today's portal totals.
const longCountHtml = path.join(outputDir, 'long-counts.html')
const badge = /(id="facet-control-tag-logistic-network"[\s\S]*?class="badge"[^>]*>\s*)[\d,]+/
const browse = readFileSync(data('browse-1.html'), 'utf8')
if (!badge.test(browse)) throw new Error('Logistic network count missing from capture data')
writeFileSync(longCountHtml, browse.replace(badge, (_, prefix: string) => `${prefix}1601`))
const common = ['--fixture', fixture, '--size', '1440x945']
const portal = ['--portal-updates', data('fixture-updates.json')]
const query = ['--portal-html', specimen + 'search-query.html', '--explore-search', 'rate calculator', '--explore-filter', 'internal=off']
const cases: [string, string[]][] = [
['explore-default', ['--tab', 'explore', '--portal-html', data('browse-1.html'), ...portal]],
['explore-loading', ['--tab', 'explore', '--portal-html', data('browse-1.html'), '--explore-loading', 'true', ...portal]],
['explore-page484', ['--tab', 'explore', '--portal-html', data('browse-1.html'), '--explore-page', '484', ...portal]],
['explore-narrow', ['--tab', 'explore', '--portal-html', data('browse-1.html'), '--size', '1000x600', ...portal]],
['explore-filter-counts', ['--tab', 'explore', '--portal-html', longCountHtml, '--filter-scroll-end', 'true', ...portal]],
['explore-page2', ['--tab', 'explore', '--portal-html', data('browse-2.html'), '--explore-page', '2', ...portal]],
['explore-downloads', ['--tab', 'explore', '--portal-html', data('browse-1.html'), '--explore-sort', 'downloads', ...portal]],
['explore-search', ['--tab', 'explore', ...query, '--explore-select', 'RateCalculator', ...portal]],
['explore-filters', ['--tab', 'explore', '--portal-html', specimen + 'browse-trending.html', '--explore-sort', 'trending', '--explore-filter', 'utilities=include,content=exclude,trains=include', ...portal]],
['explore-details', ['--tab', 'explore', ...query, '--explore-select', 'factorio-rate-calculator-tooltip', '--portal-full', data('full-tagged.json'), ...portal]],
['portal-changelog', ['--tab', 'explore', ...query, '--explore-select', 'RateCalculator', '--portal-full', data('full-rate-calculator.json'), '--portal-changelog', 'true', ...portal]],
['updates', ['--tab', 'updates', ...portal]],
['explore-fallback', ['--tab', 'explore', '--portal-html', data('simulated-failure.html'), ...portal]],
['manage', ['--tab', 'manage', '--catalogue', data('no-catalogue.json')]],
]
let log = ''
function capture(exe: string, name: string, args: string[]) {
const out = path.join(outputDir, `${name}.png`)
const result = spawnSync(path.join(root, exe), ['--screenshot', out, ...common, ...args], {
cwd: root, env: { ...process.env, FMM_CACHE_DIR: cache }, encoding: 'utf8', windowsHide: true,
})
const output = `${name} (exit ${result.status})\n${result.stdout}${result.stderr}`
log += output
writeFileSync(path.join(outputDir, 'captures.log'), log)
if (result.error) throw result.error
if (result.status !== 0 || !existsSync(out)) throw new Error(output)
console.log(output.trim())
}
const baseline = [path.relative(root, path.join(outputDir, 'fmm-master.exe')), 'out/m1/baseline-target/debug/fmm.exe']
.find((exe) => existsSync(path.join(root, exe)))
if (baseline) capture(baseline, 'manage-master', ['--tab', 'manage', '--catalogue', data('no-catalogue.json')])
for (const [name, args] of cases) capture('target/release/fmm.exe', name, args)
/** R4c: saved full responses, isolated cache, and no live browser/opener or mod-folder writes. */
async function captureDetails(cachePath: string, r5 = false) {
const cache = path.resolve(cachePath)
const relative = path.relative(tmpdir(), cache)
if (relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('Use an OS temporary FMM_CACHE_DIR')
const out = path.join(root, r5 ? 'out/r5' : 'out/r4c')
mkdirSync(out, { recursive: true })
type Full = { name: string, thumbnail?: string, images: { thumbnail: string, url: string }[], description?: string, releases: { version: string, info_json: { factorio_version: string } }[] }
const mods = ['scattergun_turret', 'cybersyn', 'space-exploration', ...(r5 ? ['RateCalculator'] : [])].map((name) => JSON.parse(readFileSync(path.join(cache, `${name}.json`), 'utf8')) as Full)
const key = (url: string) => [...Buffer.from(url)].reduce((h, b) => BigInt.asUintN(64, (h ^ BigInt(b)) * 0x100000001b3n), 0xcbf29ce484222325n).toString(16).padStart(16, '0')
const atomic = (file: string, bytes: Uint8Array | string) => {
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file + '.tmp', bytes)
renameSync(file + '.tmp', file)
}
atomic(path.join(cache, 'catalogue.json'), JSON.stringify({ results: mods.map((m) => ({ ...m, latest_release: m.releases.filter((r) => r.info_json.factorio_version === '2.0').sort((a, b) => b.version.localeCompare(a.version, 'en', { numeric: true }))[0] })), pagination: null }))
const urls = new Set<string>()
for (const m of mods) {
atomic(path.join(cache, `full/${key(m.name)}.json`), JSON.stringify(m))
if (m.thumbnail) urls.add(m.thumbnail.startsWith('https://') ? m.thumbnail : 'https://assets-mod.factorio.com' + m.thumbnail)
for (const image of m.images) urls.add(image.thumbnail)
const expanded = m.images[0]
if (expanded) urls.add(expanded.url)
if (r5 && m.images[2]) urls.add(m.images[2]!.url)
for (const img of (m.description ?? '').matchAll(/!\[[^\]]*\]\((https:\/\/assets-mod\.factorio\.com\/[^)\s]+)\)/g)) urls.add(img[1]!)
}
const queue = [...urls]
let requested = 0
await Promise.all(Array.from({ length: 4 }, async () => {
while (queue.length) {
const url = queue.shift()!
const parsed = new URL(url)
if (parsed.protocol !== 'https:' || parsed.hostname !== 'assets-mod.factorio.com') throw new Error('Untrusted image host')
if (['png', 'jpg', 'gif'].some((ext) => existsSync(path.join(cache, `portal-thumbs/${key(url)}.${ext}`)))) continue
const response = await fetch(url, { redirect: 'error' })
if (!response.ok) throw new Error(`${response.status}: ${url}`)
const bytes = Buffer.from(await response.arrayBuffer())
const ext = bytes.subarray(0, 3).toString() === 'GIF' ? 'gif' : bytes[0] === 255 && bytes[1] === 216 ? 'jpg' : 'png'
atomic(path.join(cache, `portal-thumbs/${key(url)}.${ext}`), bytes)
requested++
}
}))
if (r5) {
const synthetic = path.join(out, 'inline-fixture.json')
atomic(synthetic, JSON.stringify({ ...mods[0], images: [], description: [
'# **Bold** heading', '**star bold** and __underscore bold__; *italic* and _italic_; ***both***.',
'**Bold across a hard break \nstays bold on the next line.**',
'[a **bold** and *italic* link](https://mods.factorio.com/mod/scattergun_turret)',
'* **Bold list** with *nested **strong** emphasis*',
'~~Struck out~~; `a*b`; ``a`*b``; \\*escaped stars\\*',
'<b>HTML bold</b> and <i>HTML italic</i><br>after the HTML break.',
].join('\n\n') }))
const common = ['--fixture', 'crates/app/tests/fixtures/r2b.json', '--size', '1440x945']
const explore = ['--tab', 'explore', '--catalogue', path.join(cache, 'catalogue.json'), '--explore-select', 'scattergun_turret', '--portal-full', path.join(cache, 'scattergun_turret.json')]
const cases: [string, string, string[]][] = [
['target/release/fmm.exe', 'gallery-scrollbar', [...explore, '--detail-gallery', '0']],
['target/release/fmm.exe', 'description-inline', [...explore, '--portal-full', synthetic]],
['target/release/fmm.exe', 'lightbox-fit', [...explore, '--lightbox', '2']],
['target/release/fmm.exe', 'lightbox-zoom', [...explore, '--lightbox', '2', '--lightbox-zoom', '2']],
['target/release/fmm.exe', 'updates-header', ['--tab', 'updates', '--portal-updates', path.join(cache, 'catalogue.json')]],
['out/r5/fmm-master.exe', 'manage-master', ['--tab', 'manage', '--catalogue', path.join(cache, 'absent.json')]],
['target/release/fmm.exe', 'manage', ['--tab', 'manage', '--catalogue', path.join(cache, 'absent.json')]],
]
let log = ''
for (const [exe, name, args] of cases) {
const result = spawnSync(path.join(root, exe), ['--screenshot', path.join(out, name + '.png'), ...common, ...args], {
cwd: root, env: { ...process.env, FMM_CACHE_DIR: cache }, windowsHide: true, encoding: 'utf8',
})
log += `${name} (exit ${result.status})\n${result.stdout}${result.stderr}\n`
writeFileSync(path.join(out, 'captures.log'), log)
if (result.error) throw result.error
if (result.status !== 0) throw new Error(log)
console.log(name)
}
const { decodePng } = await import('./bench/png')
const before = decodePng(readFileSync(path.join(out, 'manage-master.png')))
const after = decodePng(readFileSync(path.join(out, 'manage.png')))
if (Buffer.compare(Buffer.from(before.data), Buffer.from(after.data)) !== 0) throw new Error('Manage pixels changed')
console.log('Manage is pixel-identical to master')
return
}
let log = `R4c cached ${requested} additional images, at most four in flight.\n`
for (const m of mods) {
for (const [suffix, extra] of [
['top', []],
['gallery', ['--detail-gallery', '0']],
['description', ['--detail-scroll', '444']],
] as [string, string[]][]) {
const name = `${m.name}-${suffix}`
const result = spawnSync(path.join(root, 'target/release/fmm.exe'), [
'--screenshot', path.join(out, name + '.png'), '--fixture', 'crates/app/tests/fixtures/r2b.json', '--size', '1440x945',
'--tab', 'explore', '--catalogue', path.join(cache, 'catalogue.json'), '--explore-select', m.name, '--portal-full', path.join(cache, m.name + '.json'), ...extra,
], { cwd: root, env: { ...process.env, FMM_CACHE_DIR: cache }, windowsHide: true, encoding: 'utf8' })
log += `${name} (exit ${result.status})\n${result.stdout}${result.stderr}\n`
writeFileSync(path.join(out, 'captures.log'), log)
if (result.error) throw result.error
if (result.status !== 0) throw new Error(log)
console.log(name, (result.stderr.match(/Details instantiation[^\n]*/) ?? [''])[0])
}
}
const { decodePng, encodePng, crop } = await import('./bench/png')
for (const [kind, reference] of [['description', 'portal-description.png'], ['gallery', 'portal-gallery.png']]) {
const truth = decodePng(readFileSync(path.join(root, 'docs/reference', reference!)))
const ours = decodePng(readFileSync(path.join(out, `scattergun_turret-${kind}.png`)))
const pane = crop(ours, 824, 92, 580, 780)
const side = { width: truth.width + pane.width + 16, height: Math.max(truth.height, pane.height), data: new Uint8Array((truth.width + pane.width + 16) * Math.max(truth.height, pane.height) * 4) }
for (const [src, offset] of [[truth, 0], [pane, truth.width + 16]] as const) for (let y = 0; y < src.height; y++) side.data.set(src.data.subarray(y * src.width * 4, (y + 1) * src.width * 4), (y * side.width + offset) * 4)
writeFileSync(path.join(out, `${kind}-side.png`), encodePng(side))
}
}