46 lines
1.9 KiB
TypeScript
46 lines
1.9 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 { WIRE_COLORS, type Project } from './types'
|
|
|
|
/** 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 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 },
|
|
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)
|
|
}
|