(id: string, text: string)
| 154 | * skipped and counted, never repaired in place. |
| 155 | */ |
| 156 | export function parseTrail(id: string, text: string): StoredTrail | null { |
| 157 | let raw: unknown; |
| 158 | try { |
| 159 | raw = JSON.parse(text); |
| 160 | } catch { |
| 161 | return null; |
| 162 | } |
| 163 | if (typeof raw !== 'object' || raw === null) return null; |
| 164 | const value = raw as Record<string, unknown>; |
| 165 | // Unversioned hand-written trails predate the stored format marker and are |
| 166 | // treated as v1. A declared future/unknown version must not be guessed at. |
| 167 | if (value.version !== undefined && value.version !== TRAIL_FORMAT_VERSION) return null; |
| 168 | if (typeof value.name !== 'string' || value.name.trim() === '') return null; |
| 169 | if (!Array.isArray(value.hops) || value.hops.length === 0) return null; |
| 170 | |
| 171 | const hops: StoredHop[] = []; |
| 172 | for (const entry of value.hops.slice(0, MAX_TRAIL_HOPS)) { |
| 173 | if (typeof entry !== 'object' || entry === null) return null; |
| 174 | const hop = entry as Record<string, unknown>; |
| 175 | const qualifiedName = typeof hop.qualifiedName === 'string' ? hop.qualifiedName : ''; |
| 176 | const name = typeof hop.name === 'string' ? hop.name : ''; |
| 177 | if (qualifiedName === '' && name === '') return null; |
| 178 | hops.push({ |
| 179 | dir: hop.dir === 'up' || hop.dir === 'down' ? hop.dir : 'start', |
| 180 | name: name || qualifiedName, |
| 181 | qualifiedName: qualifiedName || name, |
| 182 | kind: typeof hop.kind === 'string' ? hop.kind : '', |
| 183 | file: typeof hop.file === 'string' ? hop.file : '', |
| 184 | line: typeof hop.line === 'number' && hop.line > 0 ? Math.floor(hop.line) : 0, |
| 185 | id: typeof hop.id === 'string' ? hop.id : '', |
| 186 | }); |
| 187 | } |
| 188 | |
| 189 | const created = typeof value.createdAt === 'string' ? value.createdAt : ''; |
| 190 | return { |
| 191 | version: typeof value.version === 'number' ? value.version : TRAIL_FORMAT_VERSION, |
| 192 | // The FILE's name wins over any `id` inside it: the basename is what the |
| 193 | // delete route addresses, so a hand-copied file is addressable under the |
| 194 | // name it actually has rather than the one it remembers having. |
| 195 | id, |
| 196 | name: value.name.slice(0, MAX_TRAIL_NAME), |
| 197 | note: typeof value.note === 'string' ? value.note.slice(0, MAX_TRAIL_NOTE) : '', |
| 198 | author: typeof value.author === 'string' ? value.author.slice(0, 120) : '', |
| 199 | createdAt: created, |
| 200 | updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : created, |
| 201 | hops, |
| 202 | }; |
| 203 | } |
| 204 | |
| 205 | export interface StoredTrailList { |
| 206 | trails: StoredTrail[]; |
no test coverage detected