logigate/app/lib/logic/project.ts

109 lines
5.0 KiB
TypeScript

// Reading project data from files, links and storage. Shared by the browser
// and the share-link server, so it must stay free of browser APIs.
import { cleanPuzzle } from './puzzles'
import { CROSSING_STYLES, LAMP_COLORS, PANEL_CONTROLS, WIRE_COLORS, type CircuitNode, type PanelRow, type Project, type PuzzleSpec } from './types'
/** Drops optional node settings that are out of range, so a hand-edited file can't break the editor. */
function cleanNode(n: CircuitNode) {
if (n.hz !== undefined && !(typeof n.hz === 'number' && n.hz > 0 && n.hz <= 1000)) delete n.hz
if (n.color !== undefined && !LAMP_COLORS.includes(n.color)) delete n.color
if (n.key !== undefined && !(typeof n.key === 'string' && n.key.length === 1)) delete n.key
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
if (n.autoLabel !== undefined && n.autoLabel !== true) delete n.autoLabel
if (n.bits !== undefined && !(Number.isInteger(n.bits) && n.bits >= 2 && n.bits <= 32)) delete n.bits
if (n.attach !== undefined && typeof n.attach !== 'string') delete n.attach
if (n.skip !== undefined) {
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
else delete n.skip
}
if (n.rows !== undefined) {
if (!Array.isArray(n.rows)) delete n.rows
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
}
}
const MAX_ROWS = 256
function cleanRow(r: PanelRow): boolean {
if (!r || typeof r !== 'object' || typeof r.id !== 'string' || !r.id) return false
if (!PANEL_CONTROLS.includes(r.type)) r.type = 'switch'
for (const k of ['label', 'name'] as const) if (r[k] !== undefined && typeof r[k] !== 'string') delete r[k]
if (r.on !== undefined && typeof r.on !== 'boolean') delete r.on
if (r.hz !== undefined && !(typeof r.hz === 'number' && r.hz > 0 && r.hz <= 1000)) delete r.hz
if (r.dy !== undefined && !(Number.isInteger(r.dy) && r.dy >= 0 && r.dy <= 10_000)) delete r.dy
return true
}
/** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
/** Checks and normalises project data. Throws with a readable message. */
export function toProject(data: unknown): Project {
const p = data as Partial<Project>
if (!p || typeof p !== 'object' || !Array.isArray(p.components) || p.components.length === 0) {
throw new Error('Not a Logigate project (no components)')
}
if (p.components.length > LIMITS.components) throw new Error('Too many components')
let nodes = 0
for (const d of p.components) {
if (typeof d?.id !== 'string' || typeof d.name !== 'string' || !Array.isArray(d.nodes) || !Array.isArray(d.wires)) {
throw new Error('Not a Logigate project (broken component)')
}
nodes += d.nodes.length
d.symbol ??= 'box'
for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
}
if (nodes > LIMITS.nodes) throw new Error('Project too large')
return {
version: 1,
name: typeof p.name === 'string' && p.name.trim() ? p.name.trim().slice(0, 80) : 'Untitled',
components: p.components,
openId: p.components.some(d => d.id === p.openId) ? p.openId! : p.components[0]!.id,
settings: {
symbols: p.settings?.symbols === 'ansi' ? 'ansi' : 'iec',
flow: p.settings?.flow ?? true,
...(p.settings?.crossing && CROSSING_STYLES.includes(p.settings.crossing) ? { crossing: p.settings.crossing } : {}),
...(p.settings?.tidy === true ? { tidy: true } : {}),
},
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}),
...(p.mode === 'campaign' ? { mode: 'campaign' as const } : {}),
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
}
}
/** Challenge records: challenge id → fewest transistors, whole non-negative numbers only. */
function bestOf(raw: unknown): Record<string, number> | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
const out: Record<string, number> = {}
for (const [k, v] of Object.entries(raw)) if (typeof v === 'number' && Number.isInteger(v) && v >= 0 && k.length <= 64) out[k] = v
return Object.keys(out).length ? out : null
}
/** Puzzles kept in a project; broken ones are dropped. */
function puzzlesOf(raw: unknown): PuzzleSpec[] | null {
if (!Array.isArray(raw)) return null
const out: PuzzleSpec[] = []
for (const p of raw.slice(0, 200)) {
const id = (p as PuzzleSpec)?.id
if (typeof id !== 'string' || !/^(pz|week):[A-Za-z0-9-]{1,32}$/.test(id) || out.some(o => o.id === id)) continue
try {
out.push(cleanPuzzle(p, id))
} catch {}
}
return out.length ? out : null
}
export function parseProject(json: string): Project {
if (json.length > LIMITS.bytes) throw new Error('File too large')
let data: unknown
try {
data = JSON.parse(json)
} catch {
throw new Error('Not a valid JSON file')
}
return toProject(data)
}