| 159 | * anyone open is a fact worth a place, not a crash. |
| 160 | */ |
| 161 | export function entryLayering( |
| 162 | entry: string | null, |
| 163 | origins: readonly string[], |
| 164 | links: ReadonlyArray<{ source: string; target: string }> |
| 165 | ) { |
| 166 | return (ids: string[]): Map<string, number> => { |
| 167 | const present = new Set(ids); |
| 168 | const out = new Map<string, string[]>(ids.map((id) => [id, []])); |
| 169 | const indeg = new Map<string, number>(ids.map((id) => [id, 0])); |
| 170 | for (const l of links) { |
| 171 | if (!present.has(l.source) || !present.has(l.target) || l.source === l.target) continue; |
| 172 | out.get(l.source)!.push(l.target); |
| 173 | indeg.set(l.target, (indeg.get(l.target) ?? 0) + 1); |
| 174 | } |
| 175 | for (const list of out.values()) list.sort(); |
| 176 | |
| 177 | const depth = new Map<string, number>(); |
| 178 | // Multi-source BFS whose sources may start at different depths: buckets |
| 179 | // processed in ascending order, first assignment wins, so a node's depth |
| 180 | // is the least over every source — and a depth already set is never |
| 181 | // lowered by a later phase. |
| 182 | const walk = (starts: ReadonlyArray<[string, number]>): void => { |
| 183 | const buckets = new Map<number, string[]>(); |
| 184 | const push = (id: string, d: number): void => { |
| 185 | if (depth.has(id)) return; |
| 186 | depth.set(id, d); |
| 187 | const list = buckets.get(d); |
| 188 | if (list) list.push(id); |
| 189 | else buckets.set(d, [id]); |
| 190 | }; |
| 191 | let maxStart = 0; |
| 192 | for (const [id, d] of starts) { |
| 193 | push(id, d); |
| 194 | maxStart = Math.max(maxStart, d); |
| 195 | } |
| 196 | for (let d = 0; d <= ids.length + maxStart; d++) { |
| 197 | const list = buckets.get(d); |
| 198 | if (!list) continue; |
| 199 | for (const id of list) for (const t of out.get(id) ?? []) push(t, d + 1); |
| 200 | } |
| 201 | }; |
| 202 | |
| 203 | // Phase 1: the screens, by distance from the entry. |
| 204 | if (entry !== null && present.has(entry)) walk([[entry, 0]]); |
| 205 | // Phase 2: each origin above its shallowest placed target; then whatever |
| 206 | // only the origins reach, from them. |
| 207 | const seeds: Array<[string, number]> = []; |
| 208 | for (const origin of [...origins].filter((o) => present.has(o)).sort()) { |
| 209 | const placed = (out.get(origin) ?? []).map((t) => depth.get(t)).filter((d): d is number => d !== undefined); |
| 210 | seeds.push([origin, placed.length > 0 ? Math.max(0, Math.min(...placed) - 1) : 0]); |
| 211 | } |
| 212 | walk(seeds); |
| 213 | |
| 214 | const reachedMax = Math.max(0, ...[...depth.values()]); |
| 215 | // The unreached band: its own sources first, then whatever they open. |
| 216 | const rest = ids.filter((id) => !depth.has(id)); |
| 217 | const restDepth = new Map<string, number>(); |
| 218 | if (rest.length > 0) { |