logigate/app/lib/logic/project.ts

59 lines
2.6 KiB
TypeScript
Raw Normal View History

// 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 { CROSSING_STYLES, LAMP_COLORS, WIRE_COLORS, type CircuitNode, type Project } 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
}
/** 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 } : {}),
},
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
}
}
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)
}