feat(m4): playtest friction: perf overlay, fresh import, token seed (#82)

Opt-in ?perf=1 overlay (fps, frame p50/p95, JS p50/p95, tokens, zoom; no node or ticker work when off). fff-vtt import creates and migrates a fresh/empty state dir through the shared server startup path; devbox run serve gains --image. devbox run seed creates deterministic labelled NPC tokens over the real WS (idempotent rerun, --replace), and the GM token form defaults X/Y to the viewport centre.
This commit is contained in:
2026-11-21 17:20:05 +01:00
parent 356705823b
commit 9c7f9de910
20 changed files with 933 additions and 53 deletions
+32 -14
View File
@@ -8,7 +8,6 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { createPlayer, freePort, httpsBaseUrl, namePlayer } from './lib.mjs'
@@ -137,6 +136,38 @@ test('map import CLI: a fixture slices into v1 tiles, the scene row and a 200 th
}
})
test('map import CLI: a fresh/empty state dir is created, migrated and servable (#82)',
async () => {
const root = makeStateDir()
const stateDir = path.join(root, 'fresh')
const img = writeFixtureImage(path.join(root, 'map.png'))
try {
assert.equal(fs.existsSync(stateDir), false, 'the state dir starts absent')
const imported = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.equal(imported.status, 0, imported.stderr)
assert.match(imported.stderr, /created\/migrated .*schema step/)
assert.match(imported.stdout, /256x192 px, tile 64 px, 4x3 tiles/)
assert.equal(fs.existsSync(path.join(stateDir, 'state.db')), true, 'the DB is created')
assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v1')).length, 12,
'the imported tile tree exists without a prior server or gm-key run')
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await openAs(s.origin, gmKey)
const hello = await gm.ws.waitText('hello')
assert.equal(hello.scene.w, 256, 'the server serves the imported scene')
assert.equal(hello.scene.h, 192)
assert.equal(hello.scene.tile_size, 64)
gm.ws.close()
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(root, { recursive: true, force: true })
}
})
test('map import CLI: every refused import exits non-zero with a message and changes nothing',
async () => {
const stateDir = makeStateDir()
@@ -170,19 +201,6 @@ test('map import CLI: every refused import exits non-zero with a message and cha
assert.match(help.stdout, /--image=<path>/)
assert.match(help.stdout, /state-dir lock is refused/)
const ghost = path.join(os.tmpdir(), `fffvtt-absent-${process.pid}-${Date.now()}`)
const absent = runImport(ghost, [`--image=${img}`])
assert.notEqual(absent.status, 0)
assert.match(absent.stderr, /does not exist/)
assert.equal(fs.existsSync(ghost), false, 'an absent state dir is not created')
const empty = makeStateDir()
const noDb = runImport(empty, [`--image=${img}`])
assert.notEqual(noDb.status, 0)
assert.match(noDb.stderr, /no state\.db/)
assert.equal(fs.existsSync(path.join(empty, 'tiles')), false)
fs.rmSync(empty, { recursive: true, force: true })
// An unreadable DB (the state-dir contents cannot be opened) is a clear runtime error, not a
// migration attempt or a partial import.
const dbFile = path.join(stateDir, 'state.db')
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env node
// `devbox run seed` (#82): fill the playtest scene with NPC tokens over the real WebSocket,
// exactly as the GM panel does (`token.create`), instead of 49 form submits.
//
// It signs in with the GM key (or reads it from the state dir), connects to the real LAN/loopback
// URL, spreads N tokens deterministically over the scene, optionally gives the first K vision, and
// stops. Labels are `Seed 01`, `Seed 02`, … so a rerun skips what is already there; `--replace`
// removes the labelled tokens first.
//
// NODE_EXTRA_CA_CERTS=run/lan/tls/cert.pem \
// devbox run seed -- --url=https://192.168.1.50:8443 --tokens=49 --vision=1
//
// TLS is real (the playtest stack's certificate is self-signed), so the node process must trust it:
// NODE_EXTRA_CA_CERTS=<state-dir>/tls/cert.pem. Pass --key to avoid reading the state dir.
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { sleep } from './lib.mjs'
import { gmKeyOf, openAs } from './withserver.mjs'
const USAGE = `usage: devbox run seed -- --url=<origin> [--key=<gm-key>] [options]
Create N NPC tokens through the real WebSocket as the GM. The GM key is read from the state dir
when --key is absent.
--url=<origin> Server origin, e.g. https://192.168.1.50:8443 (required)
--key=<gm-key> GM key; default: read/emit it from --state-dir with fff-vtt gm-key
--state-dir=<path> State dir used for the GM key (default: run/lan)
--bin=<path> Server binary for gm-key (default: run/fff-vtt)
--tokens=<n> How many NPC tokens to have (default: 49)
--seed=<n> Deterministic position seed (default: 1)
--vision=<n> Give the first n tokens vision (default: 0)
--vision-radius=<px> Vision radius for those tokens (default: 400)
--prefix=<text> Label prefix (default: Seed)
--replace Remove the labelled tokens first, then create the full set
The playtest stack uses a self-signed certificate: run with
NODE_EXTRA_CA_CERTS=<state-dir>/tls/cert.pem, or the WebSocket upgrade fails.
`
const VALUE_OPTIONS = new Set(
['url', 'key', 'state-dir', 'bin', 'tokens', 'seed', 'vision', 'vision-radius', 'prefix'],
)
function parseArgs(argv) {
const opts = {}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (arg === '-h' || arg === '--help') { process.stdout.write(USAGE); process.exit(0) }
const m = /^--([a-z-]+)(?:=(.*))?$/.exec(arg)
if (!m) throw new Error(`unexpected argument ${JSON.stringify(arg)} (see --help)`)
const key = m[1]
if (key === 'replace') { opts.replace = true; continue }
if (!VALUE_OPTIONS.has(key)) throw new Error(`unknown option --${key} (see --help)`)
let value = m[2]
if (value === undefined) {
if (i + 1 >= argv.length) throw new Error(`--${key}: missing value (see --help)`)
value = argv[++i]
}
if (key === 'tokens' || key === 'seed' || key === 'vision' || key === 'vision-radius') {
const number = Number(value)
if (!Number.isInteger(number) || number < 0) {
throw new Error(`--${key}: expected a whole number >= 0, got ${JSON.stringify(value)}`)
}
opts[key === 'vision-radius' ? 'visionRadius' : key] = number
} else if (key === 'state-dir') opts.stateDir = value
else if (key === 'bin') opts.bin = value
else opts[key] = value
}
return opts
}
/** mulberry32: tiny deterministic PRNG, so the same --seed gives the same layout everywhere. */
function mulberry32(seed) {
let a = seed >>> 0
return () => {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/** N positions spread on a near-square grid with seeded jitter, inset from the scene edge. */
export function seedPositions(scene, count, seed) {
if (count <= 0) return []
const cols = Math.ceil(Math.sqrt(count))
const rows = Math.ceil(count / cols)
const marginX = scene.w * 0.08
const marginY = scene.h * 0.08
const cellW = (scene.w - 2 * marginX) / cols
const cellH = (scene.h - 2 * marginY) / rows
const random = mulberry32(seed)
const points = []
for (let i = 0; i < count; i += 1) {
const col = i % cols
const row = Math.floor(i / cols)
const jitterX = (random() - 0.5) * cellW * 0.3
const jitterY = (random() - 0.5) * cellH * 0.3
const x = marginX + (col + 0.5) * cellW + jitterX
const y = marginY + (row + 0.5) * cellH + jitterY
points.push([
Math.round(Math.min(scene.w - 1, Math.max(1, x))),
Math.round(Math.min(scene.h - 1, Math.max(1, y))),
])
}
return points
}
function labelFor(prefix, index, width) {
return `${prefix} ${String(index + 1).padStart(width, '0')}`
}
function initialTokens(ws) {
const byId = new Map()
for (const message of ws.messages) {
if (message && message.t === 'token' && typeof message.id === 'string') byId.set(message.id, message)
}
return [...byId.values()]
}
async function main() {
const opts = parseArgs(process.argv.slice(2))
const url = opts.url
if (!url) throw new Error(`--url is required (see --help)\n\n${USAGE}`)
const tokens = opts.tokens ?? 49
const seed = opts.seed ?? 1
const vision = opts.vision ?? 0
const visionRadius = opts.visionRadius ?? 400
const prefix = opts.prefix ?? 'Seed'
let key = opts.key
if (!key) {
const stateDir = path.resolve(opts.stateDir ?? 'run/lan')
key = gmKeyOf(stateDir, path.resolve(opts.bin ?? 'run/fff-vtt'))
}
const conn = await openAs(url, key)
const hello = await conn.ws.waitText('hello', 10000)
if (!hello.scene) throw new Error('the GM hello carried no scene; check --url and the key')
// The GM resync is hello, roster, walls, then every token. Give the token frames a moment to
// arrive before deciding what already exists (the wire has no "resync complete" marker).
await conn.ws.waitText('walls', 10000)
await sleep(400)
const width = Math.max(2, String(tokens).length)
const labels = Array.from({ length: tokens }, (_, i) => labelFor(prefix, i, width))
const wanted = new Set(labels)
const labelPattern = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\d+$`)
const nameOf = token => token.descriptive_name ?? token.name ?? ''
const existing = initialTokens(conn.ws)
const labelled = existing.filter(token => labelPattern.test(nameOf(token)))
let removed = 0
if (opts.replace) {
for (const token of labelled) {
const ack = await conn.ws.request({ t: 'token.remove', id: token.id })
if (!ack.ok) throw new Error(`token.remove ${token.id}: ${JSON.stringify(ack)}`)
removed += 1
}
}
const present = new Set(
(opts.replace ? [] : labelled.map(nameOf)).filter(name => wanted.has(name)),
)
const positions = seedPositions(hello.scene, tokens, seed)
let created = 0
for (let i = 0; i < tokens; i += 1) {
const name = labels[i]
if (present.has(name)) continue
const fields = {
t: 'token.create',
scene: hello.scene.id,
kind: 'npc',
pos: positions[i],
descriptive_name: name,
actual_name: name,
}
if (i < vision) {
fields.flags = { vision: true }
fields.vision_radius = visionRadius
}
const ack = await conn.ws.request(fields)
if (!ack.ok) throw new Error(`token.create ${name}: ${JSON.stringify(ack)}`)
created += 1
}
const kept = tokens - created
process.stdout.write(
`seeded ${tokens} tokens (${created} created, ${kept} already present, ${removed} removed) ` +
`on ${url} scene ${hello.scene.id} ${hello.scene.w}x${hello.scene.h}, seed ${seed}` +
`${vision > 0 ? `, vision ${vision} x ${visionRadius} px` : ''}\n`,
)
conn.ws.close()
await conn.ws.closed
}
const invokedDirectly =
process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
if (invokedDirectly) {
main().catch(error => {
process.stderr.write(`seed: ${error.stack ?? error}\n`)
process.exit(1)
})
}
+90
View File
@@ -0,0 +1,90 @@
// #82: `tools/seed.mjs` over the real wire. It signs in as GM, creates deterministic NPC tokens,
// skips labels on a rerun and `--replace` clears the labelled set first.
import test from 'node:test'
import assert from 'node:assert/strict'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { projectRoot, sleep } from './lib.mjs'
import { openAs, withGmServer } from './withserver.mjs'
function runSeed(args) {
const r = spawnSync(process.execPath, [path.join(projectRoot, 'tools', 'seed.mjs'), ...args],
{ cwd: projectRoot, encoding: 'utf8' })
return { status: r.status, stdout: r.stdout, stderr: r.stderr }
}
/** The GM's current token set, deduped by id from a fresh connection's resync. */
async function collectTokens(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
await gm.ws.waitText('walls')
await sleep(400)
const byId = new Map()
for (const message of gm.ws.messages) {
if (message.t === 'token' && typeof message.id === 'string') byId.set(message.id, message)
}
gm.ws.close()
await gm.ws.closed
return { scene: hello.scene, tokens: [...byId.values()] }
}
const byName = tokens => [...tokens].sort((a, b) => a.name.localeCompare(b.name))
test('seed: creates N deterministic NPC tokens, skips a rerun, and --replace starts over',
{ timeout: 180000 }, async () => {
await withGmServer(async (server, gmKey) => {
const url = server.origin
const args = [`--url=${url}`, `--key=${gmKey}`, '--tokens=6', '--vision=2', '--seed=7']
const first = runSeed(args)
assert.equal(first.status, 0, first.stderr)
assert.match(first.stdout, /seeded 6 tokens \(6 created, 0 already present, 0 removed\)/)
const firstSet = await collectTokens(url, gmKey)
assert.equal(firstSet.tokens.length, 6)
const tokens = byName(firstSet.tokens)
assert.deepEqual(tokens.map(t => t.name), ['Seed 01', 'Seed 02', 'Seed 03', 'Seed 04', 'Seed 05', 'Seed 06'])
for (const token of tokens) {
assert.equal(token.kind, 'npc')
assert.equal(token.controller, null, 'an NPC stays GM-controlled')
assert.equal(token.gm_only, false)
assert.ok(token.pos[0] >= 1 && token.pos[0] < firstSet.scene.w)
assert.ok(token.pos[1] >= 1 && token.pos[1] < firstSet.scene.h)
}
assert.equal(tokens[0].flags.vision, true, 'the first token has vision')
assert.equal(tokens[0].vision_radius, 400)
assert.equal(tokens[1].flags.vision, true)
assert.equal(tokens[2].flags.vision, undefined, 'the rest keep the DESIGN 8 {} default')
const positions = tokens.map(t => t.pos.join(','))
assert.equal(new Set(positions).size, 6, 'positions are distinct')
// Same seed on a second fresh scene: same layout (ids differ, positions do not).
await withGmServer(async (other, otherKey) => {
const second = runSeed([`--url=${other.origin}`, `--key=${otherKey}`, '--tokens=6',
'--seed=7'])
assert.equal(second.status, 0, second.stderr)
const otherSet = await collectTokens(other.origin, otherKey)
assert.deepEqual(byName(otherSet.tokens).map(t => t.pos), byName(tokens).map(t => t.pos))
})
// Rerun without --replace: no duplicates.
const again = runSeed(args)
assert.equal(again.status, 0, again.stderr)
assert.match(again.stdout, /seeded 6 tokens \(0 created, 6 already present, 0 removed\)/)
assert.equal((await collectTokens(url, gmKey)).tokens.length, 6)
// A smaller run without --replace leaves the extra labelled tokens alone; --replace clears
// every labelled token (even one outside the new count) and rebuilds exactly N.
const small = runSeed([`--url=${url}`, `--key=${gmKey}`, '--tokens=4', '--seed=7'])
assert.equal(small.status, 0, small.stderr)
assert.equal((await collectTokens(url, gmKey)).tokens.length, 6)
const replaced = runSeed([`--url=${url}`, `--key=${gmKey}`, '--tokens=4', '--seed=7',
'--replace'])
assert.equal(replaced.status, 0, replaced.stderr)
assert.match(replaced.stdout, /4 created, 0 already present, 6 removed/)
const after = await collectTokens(url, gmKey)
assert.equal(after.tokens.length, 4)
assert.deepEqual(byName(after.tokens).map(t => t.name),
['Seed 01', 'Seed 02', 'Seed 03', 'Seed 04'])
})
})
+98
View File
@@ -0,0 +1,98 @@
// #82: `serve --image` is an end-to-end smoke of the playtest command: import runs first into a
// fresh state dir, then the real server + TLS/HTTP2 nginx start and the GM sees the imported
// scene. The internal probe is a child node with NODE_EXTRA_CA_CERTS set to the generated cert.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { spawn, spawnSync } from 'node:child_process'
import { freePort, projectRoot, sleep } from './lib.mjs'
import { buildServer, makeStateDir } from './withserver.mjs'
import { pngBytesWH } from './tilefixture.mjs'
const PROBE = `
import { openAs } from './tools/withserver.mjs'
const gm = await openAs(process.env.PROBE_URL, process.env.PROBE_KEY)
const hello = await gm.ws.waitText('hello')
process.stdout.write(JSON.stringify(hello.scene) + '\\n')
gm.ws.close()
process.exit(0)
`
function waitFor(child, pattern, timeoutMs = 60000) {
return new Promise((resolve, reject) => {
let out = ''
let err = ''
const timer = setTimeout(() => {
cleanup()
reject(new Error(`timed out waiting for ${pattern}\n--- stdout ---\n${out}\n--- stderr ---\n${err}`))
}, timeoutMs)
const onData = chunk => {
out += chunk
const match = pattern.exec(out)
if (match) { cleanup(); resolve({ match, out }) }
}
const onErr = chunk => { err += chunk }
const onExit = code => {
cleanup()
reject(new Error(`serve exited (code=${code}) before ${pattern}\n--- stdout ---\n${out}\n--- stderr ---\n${err}`))
}
function cleanup() {
clearTimeout(timer)
child.stdout.off('data', onData)
child.stderr.off('data', onErr)
child.off('exit', onExit)
}
child.stdout.on('data', onData)
child.stderr.on('data', onErr)
child.on('exit', onExit)
})
}
test('serve --image: imports into a fresh dir, then serves the scene (#82)', { timeout: 120000 },
async () => {
const root = makeStateDir()
const stateDir = path.join(root, 'lan')
const image = path.join(root, 'map.png')
fs.writeFileSync(image, pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, 128]))
const port = await freePort()
const bin = buildServer()
const child = spawn(process.execPath, [
path.join(projectRoot, 'tools', 'serve.mjs'),
'--host=127.0.0.1', `--port=${port}`, `--state-dir=${stateDir}`,
`--image=${image}`, '--tile-size=64', `--server-bin=${bin}`,
], { cwd: projectRoot, stdio: ['ignore', 'pipe', 'pipe'] })
try {
const { out } = await waitFor(child, /GM key:\s+([A-Z0-9-]+)/)
assert.match(out, /importing .*map\.png before starting the server/)
assert.match(out, /URL:\s+https:\/\/127\.0\.0\.1:\d+/)
assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1', 'v1')).filter(n => n.endsWith('.png')).length,
12, 'the import ran before the server and published v1 tiles')
const url = /URL:\s+(https:\/\/\S+)/.exec(out)[1]
const key = /GM key:\s+([A-Z0-9-]+)/.exec(out)[1]
const probe = spawnSync(process.execPath, ['--input-type=module', '-e', PROBE], {
cwd: projectRoot,
encoding: 'utf8',
env: {
...process.env,
NODE_EXTRA_CA_CERTS: path.join(stateDir, 'tls', 'cert.pem'),
PROBE_URL: url,
PROBE_KEY: key,
},
})
assert.equal(probe.status, 0, probe.stderr)
const scene = JSON.parse(probe.stdout.trim())
assert.equal(scene.w, 256)
assert.equal(scene.h, 192)
assert.equal(scene.tile_size, 64)
} finally {
child.kill('SIGINT')
const exited = await Promise.race([
new Promise(resolve => child.once('exit', code => resolve(code))),
sleep(15000).then(() => 'timeout'),
])
assert.equal(exited, 0, 'SIGINT stops nginx and the server')
fs.rmSync(root, { recursive: true, force: true })
}
})
+54 -6
View File
@@ -10,32 +10,53 @@
// --dist=<path> FFF_VTT_LAN_DIST default: client/dist
// --server-bin=<path> FFF_VTT_SERVER_BIN default: run/fff-vtt
// --server-port=<n> FFF_VTT_SERVER_PORT default: a free loopback port
// --image=<file> FFF_VTT_LAN_IMAGE import this map before the server starts (#82);
// the import runs offline and refuses (exit 3) if a server holds the lock
// --tile-size=<px> FFF_VTT_LAN_TILE optional for --image (64 is the playtest fallback)
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { DEFAULT_DIST, DEFAULT_LAN_PORT, DEFAULT_SERVER_BIN, DEFAULT_STATE_DIR,
detectLanIp, startLanServe } from './lanserve.mjs'
const USAGE = `usage: devbox run serve [-- --host=<ip>] [-- --port=<n>] [-- --state-dir=<path>]
[-- --image=<file> [-- --tile-size=<px>]]
Starts the FFF_vtt server behind a TLS/HTTP2 nginx on the LAN. State, GM key and certificate
persist under the state dir (default ${DEFAULT_STATE_DIR}), so a session (and a trusted phone)
survives Ctrl-C and a restart. Env equivalents: FFF_VTT_LAN_HOST, FFF_VTT_LAN_PORT,
FFF_VTT_STATE_DIR.
--image imports a PNG/WebP map before starting (a fresh state dir is created and migrated first)
and then serves the imported scene; a server already holding the state-dir lock is refused (exit 3).
`
const VALUE_OPTIONS = new Set(
['host', 'port', 'state-dir', 'dist', 'server-bin', 'server-port', 'image', 'tile-size'],
)
function parseArgs(argv) {
const opts = {}
for (const arg of argv) {
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (arg === '-h' || arg === '--help') { process.stdout.write(USAGE); process.exit(0) }
const m = /^--([a-z-]+)=(.*)$/.exec(arg)
const m = /^--([a-z-]+)(?:=(.*))?$/.exec(arg)
if (!m) throw new Error(`unexpected argument ${JSON.stringify(arg)} (see --help)`)
const [, key, value] = m
const key = m[1]
if (!VALUE_OPTIONS.has(key)) throw new Error(`unknown option --${key} (see --help)`)
let value = m[2]
if (value === undefined) {
if (i + 1 >= argv.length) throw new Error(`--${key}: missing value (see --help)`)
value = argv[++i]
}
if (key === 'host') opts.host = value
else if (key === 'port') opts.port = Number(value)
else if (key === 'state-dir') opts.stateDir = value
else if (key === 'dist') opts.distDir = value
else if (key === 'server-bin') opts.bin = value
else if (key === 'server-port') opts.serverPort = Number(value)
else throw new Error(`unknown option --${key} (see --help)`)
else if (key === 'image') opts.image = value
else if (key === 'tile-size') opts.tileSize = Number(value)
}
return opts
}
@@ -49,9 +70,34 @@ function envOptions() {
if (env.FFF_VTT_LAN_DIST) opts.distDir = env.FFF_VTT_LAN_DIST
if (env.FFF_VTT_SERVER_BIN) opts.bin = env.FFF_VTT_SERVER_BIN
if (env.FFF_VTT_SERVER_PORT) opts.serverPort = Number(env.FFF_VTT_SERVER_PORT)
if (env.FFF_VTT_LAN_IMAGE) opts.image = env.FFF_VTT_LAN_IMAGE
if (env.FFF_VTT_LAN_TILE) opts.tileSize = Number(env.FFF_VTT_LAN_TILE)
return opts
}
/**
* `--image`: run the offline import before the server exists. Import creates and migrates a fresh
* state dir through the server's startup path, and refuses (exit 3) while a server holds the lock,
* so `serve` never starts a stack on top of a half-imported scene.
*/
function importImage(opts, stateDir) {
const bin = path.resolve(opts.bin ?? DEFAULT_SERVER_BIN)
if (!fs.existsSync(bin)) {
throw new Error(`server binary missing at ${bin}: run \`devbox run serve\` (it builds the ` +
'server first), or pass --server-bin')
}
const args = ['import', `--state-dir=${stateDir}`, `--image=${path.resolve(opts.image)}`]
if (Number.isFinite(opts.tileSize)) args.push(`--tile-size=${opts.tileSize}`)
process.stdout.write(`serve: importing ${opts.image} before starting the server...\n`)
const r = spawnSync(bin, args, { stdio: 'inherit', cwd: process.cwd() })
if (r.error) throw r.error
if (r.status !== 0) {
const error = new Error(`map import failed (exit ${r.status}); the server was not started`)
error.exitCode = r.status ?? 1
throw error
}
}
function printStartup(handle) {
const { origin, gmKey, stateDir, certPath, distDir, serverPort, certRegenerated } = handle
const ip = handle.host
@@ -100,8 +146,10 @@ async function main() {
const detected = detectLanIp()
if (detected) opts.host = detected
}
const stateDir = path.resolve(opts.stateDir ?? DEFAULT_STATE_DIR)
if (opts.image) importImage(opts, stateDir)
const handle = await startLanServe({
stateDir: opts.stateDir ?? DEFAULT_STATE_DIR,
stateDir,
host: opts.host,
port: opts.port ?? DEFAULT_LAN_PORT,
distDir: opts.distDir ?? DEFAULT_DIST,
@@ -134,5 +182,5 @@ async function main() {
main().catch(e => {
process.stderr.write(`serve: ${e.stack ?? e}\n`)
process.exit(1)
process.exit(e.exitCode ?? 1)
})