| 182 | const stack: AnyNode[] = [] |
| 183 | |
| 184 | const recur = (node: AnyNode): Result => { |
| 185 | const target = options.resolve?.(node) ?? node |
| 186 | const cached = cache.get(target) |
| 187 | if (cached !== undefined || cache.has(target)) return cached! |
| 188 | |
| 189 | if (options.detectCycles !== false && visiting.has(target)) { |
| 190 | const start = stack.indexOf(target) |
| 191 | throw new Error( |
| 192 | `Cycle detected in layer tree: ${[...stack.slice(start), target].map((item) => item.name).join(" -> ")}`, |
| 193 | ) |
| 194 | } |
| 195 | |
| 196 | visiting.add(target) |
| 197 | stack.push(target) |
| 198 | try { |
| 199 | const result = visit(target, { cache, visit: recur }) |
| 200 | if (!cache.has(target)) cache.set(target, result) |
| 201 | return result |
| 202 | } finally { |
| 203 | stack.pop() |
| 204 | visiting.delete(target) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | return recur(root) |
| 209 | } |