mermaid
Version:
Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.
8 lines • 622 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../../../src/rendering-util/layout-algorithms/layout-utils/geometry.ts", "../../../src/rendering-util/layout-algorithms/layout-utils/helpers.ts", "../../../src/rendering-util/layout-algorithms/grid/types.ts", "../../../src/rendering-util/layout-algorithms/grid/labelGeometry.ts", "../../../src/rendering-util/layout-algorithms/grid/edgeLabels.ts", "../../../src/rendering-util/layout-algorithms/grid/groups.ts", "../../../src/rendering-util/layout-algorithms/grid/labelSpacing.ts", "../../../src/rendering-util/layout-algorithms/grid/placement.ts", "../../../src/rendering-util/layout-algorithms/grid/routerErrors.ts", "../../../src/rendering-util/layout-algorithms/grid/routerTopology.ts", "../../../src/rendering-util/layout-algorithms/grid/routerPlanning.ts", "../../../src/rendering-util/layout-algorithms/grid/routerConstraint.ts", "../../../src/rendering-util/layout-algorithms/grid/routerOccupancy.ts", "../../../src/rendering-util/layout-algorithms/grid/routerCompatibility.ts", "../../../src/rendering-util/layout-algorithms/grid/routerInstrumentation.ts", "../../../src/rendering-util/layout-algorithms/grid/routerSearch.ts", "../../../src/rendering-util/layout-algorithms/grid/routerSparse.ts", "../../../src/rendering-util/layout-algorithms/grid/routerSession.ts", "../../../src/rendering-util/layout-algorithms/grid/router.ts", "../../../src/rendering-util/layout-algorithms/grid/layoutCore.ts", "../../../src/rendering-util/layout-algorithms/grid/lineHops.ts", "../../../src/rendering-util/layout-algorithms/grid/index.ts"],
"sourcesContent": ["/**\n * Shared geometry helpers for layout validation and scoring.\n *\n * Extracted from validateLayout.ts so both validateLayout and scoreLayout\n * can reuse the same normalization, distance, and crossing logic.\n */\nimport type { Point } from './types.js';\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Constants\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Canonical one-pixel tolerance shared by routing geometry and final layout validation. */\nexport const PIXEL_EPSILON = 1;\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Segment representation for geometry processing\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Segment {\n a: Point;\n b: Point;\n orientation: 'H' | 'V' | 'Z'; // Horizontal, Vertical, Zero-length\n}\n\nexport interface NormalizedPolyline {\n points: Point[];\n segments: Segment[];\n bends: number;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Geometry normalization helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Get segment orientation */\nexport function segmentOrientation(a: Point, b: Point, tolerance = PIXEL_EPSILON): 'H' | 'V' | 'Z' {\n const dx = Math.abs(b.x - a.x);\n const dy = Math.abs(b.y - a.y);\n if (dx <= tolerance && dy <= tolerance) {\n return 'Z';\n }\n if (dy <= tolerance) {\n return 'H';\n }\n return 'V';\n}\n\n/** Create segments from consecutive point pairs */\nexport function segmentsFromPoints(points: Point[], tolerance = PIXEL_EPSILON): Segment[] {\n const segments: Segment[] = [];\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i];\n const b = points[i + 1];\n segments.push({ a, b, orientation: segmentOrientation(a, b, tolerance) });\n }\n return segments;\n}\n\n/** Merge consecutive collinear segments */\nexport function mergeCollinear(segments: Segment[], tolerance = PIXEL_EPSILON): Segment[] {\n if (segments.length === 0) {\n return [];\n }\n const result: Segment[] = [];\n let current = { ...segments[0] };\n\n for (let i = 1; i < segments.length; i++) {\n const next = segments[i];\n // Skip zero-length segments\n if (next.orientation === 'Z') {\n continue;\n }\n if (current.orientation === 'Z') {\n current = { ...next };\n continue;\n }\n // Merge if same orientation and collinear\n if (current.orientation === next.orientation) {\n if (\n current.orientation === 'H' &&\n Math.abs(current.b.y - next.a.y) <= tolerance &&\n Math.abs(current.a.y - next.a.y) <= tolerance\n ) {\n // Extend horizontal segment\n current.b = next.b;\n continue;\n }\n if (\n current.orientation === 'V' &&\n Math.abs(current.b.x - next.a.x) <= tolerance &&\n Math.abs(current.a.x - next.a.x) <= tolerance\n ) {\n // Extend vertical segment\n current.b = next.b;\n continue;\n }\n }\n // Not mergeable: push current and start new\n // @ts-expect-error - current.orientation should be 'H' | 'V' here due to filtering, but TS doesn't track that\n if (current.orientation !== 'Z') {\n result.push(current);\n }\n current = { ...next };\n }\n if (current.orientation !== 'Z') {\n result.push(current);\n }\n return result;\n}\n\n/** Normalize a polyline: remove zero-length, merge collinear, count bends */\nexport function normalizePolyline(points: Point[], tolerance = PIXEL_EPSILON): NormalizedPolyline {\n if (points.length < 2) {\n return { points: [...points], segments: [], bends: 0 };\n }\n\n // Create segments and filter zero-length\n const rawSegments = segmentsFromPoints(points, tolerance).filter((s) => s.orientation !== 'Z');\n\n // Merge collinear\n const merged = mergeCollinear(rawSegments, tolerance);\n\n // Rebuild points from merged segments\n const newPoints: Point[] = [];\n for (const [i, element] of merged.entries()) {\n if (i === 0) {\n newPoints.push(element.a);\n }\n newPoints.push(element.b);\n }\n\n // Count bends: direction changes between consecutive segments\n let bends = 0;\n for (let i = 1; i < merged.length; i++) {\n if (merged[i - 1].orientation !== merged[i].orientation) {\n bends++;\n }\n }\n\n return { points: newPoints.length > 0 ? newPoints : [...points], segments: merged, bends };\n}\n\n/** Euclidean distance between two points */\nexport function distance(a: Point, b: Point): number {\n return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2);\n}\n\n/**\n * Check if two orthogonal segments cross.\n *\n * Detects proper interior crossings as well as T-intersections where one\n * segment's endpoint lies on the other segment's interior. The only case\n * that is excluded is a *shared endpoint*: when the intersection point is\n * an endpoint of **both** segments (two edges departing from the same node\n * corner should not count as a crossing).\n */\nexport function segmentsCross(s1: Segment, s2: Segment): boolean {\n // Must be H/V pair\n if (s1.orientation === 'Z' || s2.orientation === 'Z') {\n return false;\n }\n if (s1.orientation === s2.orientation) {\n return false;\n }\n\n const horiz = s1.orientation === 'H' ? s1 : s2;\n const vert = s1.orientation === 'V' ? s1 : s2;\n\n const hY = horiz.a.y;\n const hX1 = Math.min(horiz.a.x, horiz.b.x);\n const hX2 = Math.max(horiz.a.x, horiz.b.x);\n\n const vX = vert.a.x;\n const vY1 = Math.min(vert.a.y, vert.b.y);\n const vY2 = Math.max(vert.a.y, vert.b.y);\n\n // Use non-strict inequalities to also detect T-intersections\n if (vX >= hX1 && vX <= hX2 && hY >= vY1 && hY <= vY2) {\n // The intersection point is (vX, hY).\n // Exclude shared endpoints: if (vX, hY) matches an endpoint of BOTH\n // segments, it's a shared departure/arrival, not a real crossing.\n const TOL = 1e-6;\n const ix = vX;\n const iy = hY;\n\n const matchesHorizEndpoint =\n (Math.abs(ix - horiz.a.x) < TOL && Math.abs(iy - horiz.a.y) < TOL) ||\n (Math.abs(ix - horiz.b.x) < TOL && Math.abs(iy - horiz.b.y) < TOL);\n\n const matchesVertEndpoint =\n (Math.abs(ix - vert.a.x) < TOL && Math.abs(iy - vert.a.y) < TOL) ||\n (Math.abs(ix - vert.b.x) < TOL && Math.abs(iy - vert.b.y) < TOL);\n\n if (matchesHorizEndpoint && matchesVertEndpoint) {\n // Shared endpoint \u2014 not a crossing\n return false;\n }\n\n return true;\n }\n\n return false;\n}\n", "/**\n * Shared utility functions for the orthogonal routing pipeline.\n *\n * This module contains geometry helpers, distance calculations, and other\n * low-level utilities used across the routing stages.\n */\nimport type { Edge, Node } from '../../types.js';\nimport type { Point, Rect, PortSide } from './types.js';\n\n/**\n * Compare strings by UTF-16 code units so algorithmic ordering is independent of locale and ICU.\n */\nexport function compareCodeUnits(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * Create a Rect from a Node's x, y, width, height properties.\n * The node's x, y are assumed to be the center coordinates.\n */\nexport function rectForNode(node: Node): Rect {\n const cx = node.x ?? 0;\n const cy = node.y ?? 0;\n const w = node.width ?? 40;\n const h = node.height ?? 40;\n return {\n cx,\n cy,\n left: cx - w / 2,\n right: cx + w / 2,\n top: cy - h / 2,\n bottom: cy + h / 2,\n };\n}\n\n/**\n * Reserve the marker-facing portion of an orthogonal terminal segment.\n *\n * Placement and validation share this geometry so a label accepted during routing cannot later\n * fail because the validator modeled the arrowhead clearance differently.\n */\nexport function terminalMarkerClearanceRect(\n points: Point[],\n terminal: 'start' | 'end',\n length: number,\n halfWidth: number,\n tolerance = 0\n): Rect | null {\n if (points.length < 2) {\n return null;\n }\n\n const tip = terminal === 'end' ? points[points.length - 1] : points[0];\n const inner = terminal === 'end' ? points[points.length - 2] : points[1];\n const dx = inner.x - tip.x;\n const dy = inner.y - tip.y;\n\n if (Math.abs(dx) <= tolerance && Math.abs(dy) <= tolerance) {\n return null;\n }\n if (Math.abs(dy) <= tolerance) {\n const innerX = tip.x + Math.sign(dx) * length;\n const left = Math.min(tip.x, innerX);\n const right = Math.max(tip.x, innerX);\n return {\n cx: (left + right) / 2,\n cy: tip.y,\n left,\n right,\n top: tip.y - halfWidth,\n bottom: tip.y + halfWidth,\n };\n }\n if (Math.abs(dx) <= tolerance) {\n const innerY = tip.y + Math.sign(dy) * length;\n const top = Math.min(tip.y, innerY);\n const bottom = Math.max(tip.y, innerY);\n return {\n cx: tip.x,\n cy: (top + bottom) / 2,\n left: tip.x - halfWidth,\n right: tip.x + halfWidth,\n top,\n bottom,\n };\n }\n return null;\n}\n\nexport function hasTerminalMarker(edge: Edge, terminal: 'start' | 'end'): boolean {\n const markerType = terminal === 'start' ? edge.arrowTypeStart : edge.arrowTypeEnd;\n // Explicit terminal settings override edge.type, including values that disable markers.\n if (typeof markerType === 'string') {\n const trimmed = markerType.trim();\n if (trimmed.length > 0) {\n return trimmed !== 'none' && trimmed !== 'arrow_open';\n }\n }\n\n if (typeof edge.type !== 'string') {\n return false;\n }\n // Flowchart/swimlane edges often carry marker semantics in `type`.\n if (terminal === 'start' && edge.type.startsWith('double_')) {\n return true;\n }\n return terminal === 'end' && /arrow_(point|cross|circle|barb)|double_arrow/.test(edge.type);\n}\n\n/**\n * Check if a point is strictly inside a rectangle (not on the boundary).\n */\nexport function pointInRectInterior(p: Point, rect: Rect): boolean {\n return p.x > rect.left && p.x < rect.right && p.y > rect.top && p.y < rect.bottom;\n}\n\n/**\n * Approximate floating-point equality check.\n */\nexport function approxEqual(a: number, b: number, tol = 1e-6): boolean {\n return Math.abs(a - b) <= tol;\n}\n\nexport function orthogonalPolylineContainsPoint(\n points: Point[],\n point: Point,\n tolerance = 1e-6\n): boolean {\n for (let index = 1; index < points.length; index++) {\n const a = points[index - 1];\n const b = points[index];\n if (approxEqual(a.y, b.y, tolerance) && !approxEqual(a.x, b.x, tolerance)) {\n if (\n approxEqual(point.y, a.y, tolerance) &&\n point.x >= Math.min(a.x, b.x) - tolerance &&\n point.x <= Math.max(a.x, b.x) + tolerance\n ) {\n return true;\n }\n } else if (approxEqual(a.x, b.x, tolerance) && !approxEqual(a.y, b.y, tolerance)) {\n if (\n approxEqual(point.x, a.x, tolerance) &&\n point.y >= Math.min(a.y, b.y) - tolerance &&\n point.y <= Math.max(a.y, b.y) + tolerance\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Calculate the total Manhattan length of a polyline.\n */\nexport function manhattanLength(points: Point[]): number {\n let total = 0;\n for (let i = 1; i < points.length; i++) {\n const a = points[i - 1];\n const b = points[i];\n total += Math.abs(b.x - a.x) + Math.abs(b.y - a.y);\n }\n return total;\n}\n\n/**\n * Calculate the Manhattan distance between two points.\n */\nexport function manhattanDistance(a: Point, b: Point): number {\n return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);\n}\n\n/**\n * Count the number of bends (direction changes) in a polyline.\n */\nexport function bendCount(points: Point[]): number {\n let bends = 0;\n for (let i = 2; i < points.length; i++) {\n const a = points[i - 2];\n const b = points[i - 1];\n const c = points[i];\n const dxAB = b.x - a.x;\n const dyAB = b.y - a.y;\n const dxBC = c.x - b.x;\n const dyBC = c.y - b.y;\n const isHorizAB = !approxEqual(dxAB, 0) && approxEqual(dyAB, 0);\n const isVertAB = approxEqual(dxAB, 0) && !approxEqual(dyAB, 0);\n const isHorizBC = !approxEqual(dxBC, 0) && approxEqual(dyBC, 0);\n const isVertBC = approxEqual(dxBC, 0) && !approxEqual(dyBC, 0);\n if ((isHorizAB && isVertBC) || (isVertAB && isHorizBC)) {\n bends++;\n }\n }\n return bends;\n}\n\n/**\n * Check if an axis-aligned segment intersects a rectangle's interior.\n * Non-orthogonal segments are ignored (return false).\n */\nexport function segmentIntersectsRectInterior(a: Point, b: Point, rect: Rect): boolean {\n // We only care about axis-aligned segments; non-orthogonal segments are ignored\n // in this helper since the pipeline only produces orthogonal polylines.\n if (a.x === b.x && a.y === b.y) {\n return false;\n }\n\n if (a.y === b.y) {\n // Horizontal segment. Treat segments that run exactly along the top/bottom\n // boundary of the rectangle as collisions as well, so that edges do not\n // visually \"run under\" or \"on\" other nodes.\n const y = a.y;\n const x1 = Math.min(a.x, b.x);\n const x2 = Math.max(a.x, b.x);\n const crossesVertically = y >= rect.top && y <= rect.bottom;\n const overlapsHorizontally = Math.max(x1, rect.left) < Math.min(x2, rect.right);\n return crossesVertically && overlapsHorizontally;\n }\n\n if (a.x === b.x) {\n // Vertical segment. Similarly, segments that run exactly along the\n // left/right boundary of the rectangle are treated as collisions.\n const x = a.x;\n const y1 = Math.min(a.y, b.y);\n const y2 = Math.max(a.y, b.y);\n const crossesHorizontally = x >= rect.left && x <= rect.right;\n const overlapsVertically = Math.max(y1, rect.top) < Math.min(y2, rect.bottom);\n return crossesHorizontally && overlapsVertically;\n }\n\n return false;\n}\n\n/**\n * Check if a polyline crosses a single rectangle.\n */\nexport function polylineIntersectsRect(points: Point[], rect: Rect): boolean {\n for (let i = 1; i < points.length; i++) {\n if (segmentIntersectsRectInterior(points[i - 1], points[i], rect)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if a polyline crosses an array of obstacle rectangles.\n */\nexport function polylineIntersectsRects(points: Point[], rects: Rect[]): boolean {\n for (const rect of rects) {\n if (polylineIntersectsRect(points, rect)) {\n return true;\n }\n }\n return false;\n}\n\nexport function pointInsideAnyRectInterior(p: Point, rects: Rect[]): boolean {\n for (const r of rects) {\n if (pointInRectInterior(p, r)) {\n return true;\n }\n }\n return false;\n}\n\nexport function clamp(v: number, lo: number, hi: number): number {\n return Math.max(lo, Math.min(hi, v));\n}\n\n/**\n * Remove duplicates from a sorted number array.\n */\nexport function uniqSorted(numbers: number[]): number[] {\n const s = new Set<number>();\n for (const n of numbers) {\n s.add(n);\n }\n return [...s].sort((a, b) => a - b);\n}\n\n/**\n * Compute the boundary port point for a side of a rectangle.\n */\nexport function computeBoundaryPort(rect: Rect, side: PortSide): Point {\n switch (side) {\n case 'E':\n return { x: rect.right, y: rect.cy };\n case 'W':\n return { x: rect.left, y: rect.cy };\n case 'N':\n return { x: rect.cx, y: rect.top };\n case 'S':\n return { x: rect.cx, y: rect.bottom };\n }\n}\n", "import type { GridHorizontalAlign, GridPlacement, GridVerticalAlign } from '../../../types.js';\nimport type { LayoutData, Node } from '../../types.js';\nimport type { Point } from '../../../types.js';\nimport { DEFAULT_EDGE_CORNER_RADIUS } from '../../edgeCornerRadius.js';\nimport type {\n GridRoutingFallbackReason,\n GridRoutingInstrumentation,\n} from './routerInstrumentation.js';\nimport type { GridLabelRequirements } from './labelSpacing.js';\n\n// The root participates in the same container algorithms as groups but has no backing Node.\nexport const ROOT_CONTAINER_ID = '__grid_root__';\n// Label helpers belong to edges and must not consume cells in the node-placement forest.\nexport const GRID_LABEL_PREFIX = 'edge-label-';\n\nexport type GridContainerId = string;\nexport type GridSide = 'left' | 'right' | 'top' | 'bottom';\nexport type GridOrientation = 'H' | 'V';\nexport type GridCurve =\n | 'basis'\n | 'bumpX'\n | 'bumpY'\n | 'cardinal'\n | 'catmullRom'\n | 'linear'\n | 'monotoneX'\n | 'monotoneY'\n | 'natural'\n | 'step'\n | 'stepAfter'\n | 'stepBefore'\n | 'rounded';\nexport type RouterVertexId = number;\n\n// Routing uses a compact orthogonal visibility graph. The richer arc form supports validation and\n// overlays; RouterSearchArc is the allocation-conscious representation consumed by hot searches.\nexport interface RouterPoint {\n x: number;\n y: number;\n}\n\nexport interface RouterRect {\n left: number;\n right: number;\n top: number;\n bottom: number;\n}\n\nexport interface RouterObstacle extends RouterRect {\n id: string;\n}\n\nexport interface PortalRange {\n ownerId: string;\n side: GridSide;\n low: number;\n high: number;\n coordinate?: number;\n}\n\n// Crossing a group boundary is represented as two vertices plus one explicit transition. Keeping\n// both sides of the boundary prevents a route from accidentally treating hierarchy as open space.\nexport interface PairedPortal {\n ownerId: string;\n side: GridSide;\n tangentialCoordinate: number;\n interior: RouterPoint;\n exterior: RouterPoint;\n transition: {\n from: RouterPoint;\n to: RouterPoint;\n orientation: GridOrientation;\n length: number;\n kind: 'portal';\n };\n}\n\nexport interface RouterVertex {\n id: RouterVertexId;\n point: RouterPoint;\n kind: 'corner' | 'projection' | 'portal' | 'endpoint' | 'lane';\n ownerId?: string;\n side?: GridSide;\n}\n\nexport interface RouterArc {\n from: RouterVertexId;\n to: RouterVertexId;\n orientation: GridOrientation;\n length: number;\n kind: 'visibility' | 'terminal' | 'portal' | 'lane';\n intervalStart: number;\n intervalEnd: number;\n}\n\nexport interface RouterSearchArc {\n to: RouterVertexId;\n orientationOrdinal: 1 | 2;\n length: number;\n boundaryTransitions: 0 | 1;\n}\n\nexport interface OrthogonalIntervalIndex {\n readonly coordinateCount: number;\n readonly intervalCount: number;\n intersects(coordinate: number, intervalStart: number, intervalEnd: number): boolean;\n contains(coordinate: number, varying: number): boolean;\n nearestBoundary(coordinate: number, origin: number, direction: -1 | 1): number | undefined;\n}\n\nexport interface ContainerRoutingTopology {\n // Base topologies are immutable and shared by all edges in a container. Optional accessors expose\n // lightweight endpoint overlays without copying the base vertex and adjacency arrays.\n containerId: GridContainerId;\n bounds: RouterRect;\n obstacles: readonly RouterObstacle[];\n vertices: readonly RouterVertex[];\n pointVertexIds: ReadonlyMap<string, RouterVertexId>;\n horizontalVertexLines: ReadonlyMap<number, readonly RouterVertex[]>;\n verticalVertexLines: ReadonlyMap<number, readonly RouterVertex[]>;\n adjacency: ReadonlyMap<RouterVertexId, readonly RouterArc[]>;\n adjacencyByVertex: readonly (readonly RouterArc[])[];\n searchAdjacencyByVertex: readonly (readonly RouterSearchArc[])[];\n adjacencyEntries: number;\n horizontalIntervals: OrthogonalIntervalIndex;\n verticalIntervals: OrthogonalIntervalIndex;\n portalRanges: readonly PortalRange[];\n seedCount: number;\n estimatedBytes: number;\n readonly vertexCount?: number;\n getVertex?(id: RouterVertexId): RouterVertex | undefined;\n getSearchArcs?(id: RouterVertexId): readonly RouterSearchArc[];\n}\n\nexport interface GridRoutingContext {\n // Containers that exceed a topology cap are recorded here and routed through the validated\n // compatibility path; resource exhaustion is degradation, not permission to emit invalid paths.\n topologies: Map<GridContainerId, ContainerRoutingTopology>;\n fallbackContainers: Map<GridContainerId, GridRoutingFallbackReason>;\n searchBudget: { expandedStates: number };\n searchBudgetWarningEmitted: boolean;\n baseEstimatedBytes: number;\n metrics?: GridRoutingInstrumentation;\n}\n\nexport interface GridLayoutConfigNormalized {\n placements: Map<string, GridPlacement[]>;\n columns: number;\n rowGap: number;\n columnGap: number;\n cellGap: number;\n containerPadding: number;\n titleGap: number;\n horizontalAlign: GridHorizontalAlign;\n verticalAlign: GridVerticalAlign;\n // Routing publishes these values on each edge so shared rendering and line hops use identical\n // corner geometry without depending on grid internals.\n curve: GridCurve;\n edgeCornerRadius: number;\n}\n\nexport interface GridResolvedPlacement {\n item: Node;\n row: number;\n column: number;\n horizontalAlign: GridHorizontalAlign;\n verticalAlign: GridVerticalAlign;\n sourceOrder: number;\n explicitRow: boolean;\n explicitColumn: boolean;\n explicitCell: boolean;\n}\n\n// Multiple nodes may intentionally share a cell; they are laid out as one vertical stack.\nexport interface GridCellStack {\n row: number;\n column: number;\n items: GridResolvedPlacement[];\n width: number;\n height: number;\n verticalAlign: GridVerticalAlign;\n}\n\nexport interface GridItemLayoutMeta {\n containerId: GridContainerId;\n row: number;\n column: number;\n cellLeft: number;\n cellTop: number;\n cellWidth: number;\n cellHeight: number;\n leftCorridorX: number;\n rightCorridorX: number;\n topCorridorY: number;\n bottomCorridorY: number;\n}\n\nexport interface GridContainerLayoutMeta {\n id: GridContainerId;\n left: number;\n top: number;\n width: number;\n height: number;\n contentLeft: number;\n contentTop: number;\n contentRight: number;\n contentBottom: number;\n // Corridors describe empty track boundaries for the routing layer added by the next stack PR.\n verticalCorridors: number[];\n horizontalCorridors: number[];\n}\n\nexport interface GridForest {\n nodeById: Map<string, Node>;\n groupById: Map<string, Node & { isGroup: true }>;\n childrenByParent: Map<GridContainerId, Node[]>;\n rootChildren: Node[];\n // Children-first ordering lets parent groups measure already-sized nested groups.\n postOrderGroups: (Node & { isGroup: true })[];\n helperNodeIds: Set<string>;\n}\n\nexport interface GridAttachmentDemand {\n // demandKey identifies one edge endpoint at one hierarchy boundary and remains stable across\n // retries so portal coordinates can be captured and restored transactionally.\n ownerId: string;\n side: GridSide;\n edgeId: string;\n demandKey: string;\n oppositeCoord: number;\n preferredCoord: number;\n compactPortal: boolean;\n // The next entry inward along the endpoint chain; a compact portal lines up with its port.\n inner?: { demandKey: string; side: GridSide };\n}\n\nexport interface GridAttachment {\n port: Point;\n connect: Point;\n orientation: GridOrientation;\n side: GridSide;\n}\n\nexport interface GridLayoutResult {\n forest: GridForest;\n config: GridLayoutConfigNormalized;\n containers: Map<GridContainerId, GridContainerLayoutMeta>;\n itemMeta: Map<string, GridItemLayoutMeta>;\n sourceOrder: Map<string, number>;\n labelRequirements: GridLabelRequirements;\n}\n\nexport interface GridError extends Error {\n code: GridErrorCode;\n details?: Record<string, unknown>;\n}\n\nexport type GridErrorCode =\n | 'GRID_INVALID_COORDINATE'\n | 'GRID_CELL_ALIGNMENT_CONFLICT'\n | 'GRID_INVALID_CONTAINMENT'\n | 'GRID_MISSING_MEASUREMENT'\n | 'GRID_MISSING_ENDPOINT'\n | 'GRID_ROUTE_NOT_FOUND';\n\nexport function gridError(\n code: GridErrorCode,\n message: string,\n details?: Record<string, unknown>\n): GridError {\n const error = new Error(`${code}: ${message}`) as GridError;\n error.code = code;\n error.details = details;\n return error;\n}\n\nexport const GRID_DEFAULTS = {\n columns: 0,\n rowGap: 50,\n columnGap: 50,\n cellGap: 20,\n containerPadding: 20,\n titleGap: 8,\n horizontalAlign: 'center' as GridHorizontalAlign,\n verticalAlign: 'center' as GridVerticalAlign,\n curve: 'rounded' as GridCurve,\n edgeCornerRadius: DEFAULT_EDGE_CORNER_RADIUS,\n};\n\nexport type GridLayoutData = LayoutData;\n\nexport function isEdgeLabelNode(node: Node): boolean {\n return Boolean((node as { isEdgeLabel?: boolean }).isEdgeLabel);\n}\n\nexport function isFinitePositiveNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0;\n}\n", "import type { Node } from '../../types.js';\nimport type { GridOrientation } from './types.js';\nimport { isFinitePositiveNumber } from './types.js';\n\nexport const GRID_LABEL_CLEARANCE = 6;\nexport const GRID_EDGE_END_MARKER_CLEARANCE = 12;\nexport const GRID_LABEL_SPAN_MARGIN = 2;\n\nexport interface GridLabelSpanRequirement {\n along: number;\n cross: number;\n startInset: number;\n endInset: number;\n requiredAlongSpan: number;\n}\n\nexport function gridLabelSpanRequirement(\n labelNode: Node,\n orientation: GridOrientation\n): GridLabelSpanRequirement | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n\n const along = orientation === 'H' ? labelNode.width : labelNode.height;\n const cross = orientation === 'H' ? labelNode.height : labelNode.width;\n const startInset = Math.max(GRID_LABEL_CLEARANCE, GRID_EDGE_END_MARKER_CLEARANCE);\n const endInset = Math.max(GRID_LABEL_CLEARANCE, GRID_EDGE_END_MARKER_CLEARANCE);\n\n return {\n along,\n cross,\n startInset,\n endInset,\n requiredAlongSpan: along + startInset + endInset + GRID_LABEL_SPAN_MARGIN,\n };\n}\n\nexport function gridLabelRequiredSegmentLength(\n labelNode: Node,\n orientation: GridOrientation\n): number {\n const along = orientation === 'H' ? labelNode.width : labelNode.height;\n return isFinitePositiveNumber(along) ? along + GRID_LABEL_CLEARANCE * 2 : 0;\n}\n", "import type { Point } from '../../../types.js';\nimport { log } from '../../../logger.js';\nimport type { Edge, LayoutData, Node, NonClusterNode } from '../../types.js';\nimport {\n normalizePolyline as normalizeLayoutPolyline,\n segmentsCross,\n type Segment,\n} from '../layout-utils/geometry.js';\nimport {\n clamp,\n compareCodeUnits,\n hasTerminalMarker,\n orthogonalPolylineContainsPoint,\n polylineIntersectsRect,\n rectForNode,\n segmentIntersectsRectInterior,\n terminalMarkerClearanceRect,\n} from '../layout-utils/helpers.js';\nimport type { Rect } from '../layout-utils/types.js';\nimport {\n GRID_EDGE_END_MARKER_CLEARANCE,\n GRID_LABEL_CLEARANCE,\n gridLabelRequiredSegmentLength,\n} from './labelGeometry.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport { GRID_LABEL_PREFIX, gridError, isEdgeLabelNode, isFinitePositiveNumber } from './types.js';\n\n// prepareGridLayout moves edge label text into helper nodes linked to their owners by labelNodeId.\n// The caller measures those nodes before grid layout, but they stay out of normal node placement.\n// After routing, positionGridEdgeLabels uses their measured bounds to place labels on their owning\n// edges, rerouting affected edges as needed and storing the final helper-node positions for rendering.\nconst LABEL_CLEARANCE = GRID_LABEL_CLEARANCE;\nconst LABEL_GUTTER = 14;\nconst LABEL_GUTTER_STEP = 18;\nconst MAX_GUTTER_STEPS = 16;\nconst MAX_DETOUR_LINE_CANDIDATES = 128;\nconst MAX_DETOUR_CENTER_CANDIDATES = 64;\n// Match the router's invocation-wide search budget: retries share one deterministic work ceiling.\nconst DEFAULT_MAX_INDEX_WORK = 2_000_000;\nconst EDGE_END_MARKER_CLEARANCE = GRID_EDGE_END_MARKER_CLEARANCE;\nconst LABEL_EPSILON = 1e-6;\nconst MIN_SELF_PARALLEL_GAP = 7;\nconst MIN_SELF_PARALLEL_OVERLAP = 8;\n\n// Preserve subpixel detours with the same tolerance used to validate label anchors.\nconst normalizePolyline = (points: Point[]) => normalizeLayoutPolyline(points, LABEL_EPSILON);\n\ninterface Interval {\n start: number;\n end: number;\n}\n\ninterface PlacedLabel {\n edgeId: string;\n nodeId: string;\n center: Point;\n rect: Rect;\n}\n\ninterface SegmentCandidate {\n segment: Segment;\n segmentIndex: number;\n order: number;\n}\n\ninterface LabelWorkItem {\n edge: Edge;\n labelNode: Node;\n sourceIndex: number;\n}\n\ntype EdgePointOverrides = Map<string, Point[]>;\n\ninterface Bounds {\n left: number;\n right: number;\n top: number;\n bottom: number;\n}\n\nfunction rangeOverlapLength(\n firstStart: number,\n firstEnd: number,\n secondStart: number,\n secondEnd: number\n) {\n const start = Math.max(Math.min(firstStart, firstEnd), Math.min(secondStart, secondEnd));\n const end = Math.min(Math.max(firstStart, firstEnd), Math.max(secondStart, secondEnd));\n return Math.max(0, end - start);\n}\n\nfunction polylineHasSelfConflict(points: readonly Point[]): boolean {\n const segments = normalizePolyline([...points]).segments;\n for (let firstIndex = 0; firstIndex < segments.length; firstIndex++) {\n const first = segments[firstIndex];\n for (let secondIndex = firstIndex + 2; secondIndex < segments.length; secondIndex++) {\n const second = segments[secondIndex];\n if (segmentsCross(first, second)) {\n return true;\n }\n if (first.orientation !== second.orientation || first.orientation === 'Z') {\n continue;\n }\n\n const sameAxis =\n first.orientation === 'H'\n ? Math.abs(first.a.y - second.a.y) <= LABEL_EPSILON\n : Math.abs(first.a.x - second.a.x) <= LABEL_EPSILON;\n const overlap =\n first.orientation === 'H'\n ? rangeOverlapLength(first.a.x, first.b.x, second.a.x, second.b.x)\n : rangeOverlapLength(first.a.y, first.b.y, second.a.y, second.b.y);\n if (sameAxis && overlap > LABEL_EPSILON) {\n return true;\n }\n const gap =\n first.orientation === 'H'\n ? Math.abs(first.a.y - second.a.y)\n : Math.abs(first.a.x - second.a.x);\n if (!sameAxis && gap < MIN_SELF_PARALLEL_GAP && overlap >= MIN_SELF_PARALLEL_OVERLAP) {\n return true;\n }\n }\n }\n return false;\n}\n\ninterface ObstacleEntry {\n id: string;\n bounds: Bounds;\n rect: Rect;\n nodeId?: string;\n}\n\ninterface BorderEntry {\n id: string;\n bounds: Bounds;\n rect: Rect;\n}\n\ninterface EdgeSegmentEntry {\n id: string;\n bounds: Bounds;\n edgeId: string;\n segment: Segment;\n}\n\ninterface EdgeGeometryCache {\n points: Point[];\n segments: Segment[];\n candidateSegments: SegmentCandidate[];\n markerRects: Rect[];\n}\n\nexport interface GridEdgeLabelInstrumentation {\n obstacleRectQueries: number;\n obstacleBandQueries: number;\n obstaclePolylineQueries: number;\n obstacleCandidatesVisited: number;\n segmentRectQueries: number;\n segmentBandQueries: number;\n segmentCandidatesVisited: number;\n foreignEdgeLookups: number;\n labelPasses: number;\n frozenReservations: number;\n impactedEdgeReroutes: number;\n preservedAnchors: number;\n rerouteCandidatesEvaluated: number;\n rerouteRejectedBlockedRect: number;\n rerouteRejectedProtectedObstacle: number;\n rerouteRejectedLabelAnchor: number;\n rerouteRejectedDegenerateSpan: number;\n reroutePartialProgressCandidates: number;\n individualLabelRerouteAttempts: number;\n individualLabelRerouteSuccesses: number;\n labelOverlapFallbacks: number;\n labelOverlapReservations: number;\n degenerateLabelRoutesSkipped: number;\n unmeasuredLabelsSkipped: number;\n indexWorkUnits: number;\n indexWorkLimitFallbacks: number;\n placementSearchFallbacks: number;\n rollbacks: number;\n indexCoordinateCount: number;\n}\n\nexport interface GridEdgeLabelOptions {\n maxIndexWork?: number;\n}\n\ninterface EdgeLabelContext {\n // These indexes are updated with every provisional route so later searches see one coherent\n // geometry snapshot rather than rescanning stale edge and obstacle arrays.\n edgeById: Map<string, Edge>;\n edgeGeometryById: Map<string, EdgeGeometryCache>;\n obstacleIndex: CompressedBoundsIndex<ObstacleEntry>;\n placedLabelIndex: CompressedBoundsIndex<ObstacleEntry>;\n groupBorderIndex: CompressedBoundsIndex<BorderEntry>;\n segmentIndex: CompressedBoundsIndex<EdgeSegmentEntry>;\n searchBounds: Bounds;\n metrics?: GridEdgeLabelInstrumentation;\n}\n\ntype ObstacleQueryMetric =\n | 'obstacleRectQueries'\n | 'obstacleBandQueries'\n | 'obstaclePolylineQueries';\ntype SegmentQueryMetric = 'segmentRectQueries' | 'segmentBandQueries';\n\nexport function createGridEdgeLabelInstrumentation(): GridEdgeLabelInstrumentation {\n return {\n obstacleRectQueries: 0,\n obstacleBandQueries: 0,\n obstaclePolylineQueries: 0,\n obstacleCandidatesVisited: 0,\n segmentRectQueries: 0,\n segmentBandQueries: 0,\n segmentCandidatesVisited: 0,\n foreignEdgeLookups: 0,\n labelPasses: 0,\n frozenReservations: 0,\n impactedEdgeReroutes: 0,\n preservedAnchors: 0,\n rerouteCandidatesEvaluated: 0,\n rerouteRejectedBlockedRect: 0,\n rerouteRejectedProtectedObstacle: 0,\n rerouteRejectedLabelAnchor: 0,\n rerouteRejectedDegenerateSpan: 0,\n reroutePartialProgressCandidates: 0,\n individualLabelRerouteAttempts: 0,\n individualLabelRerouteSuccesses: 0,\n labelOverlapFallbacks: 0,\n labelOverlapReservations: 0,\n degenerateLabelRoutesSkipped: 0,\n unmeasuredLabelsSkipped: 0,\n indexWorkUnits: 0,\n indexWorkLimitFallbacks: 0,\n placementSearchFallbacks: 0,\n rollbacks: 0,\n indexCoordinateCount: 0,\n };\n}\n\nclass LabelPlacementSearchExhaustedError extends Error {\n constructor(public readonly details: Record<string, unknown> & { edgeId: string }) {\n super(`Could not place label for edge \"${details.edgeId}\"`);\n this.name = 'LabelPlacementSearchExhaustedError';\n }\n}\n\n/**\n * A dynamic coordinate-compressed bounds index. Entries are keyed by their\n * actual boundaries; no bucket is allocated for any coordinate between them.\n * Label routing mutates these indexes often enough that a sorted sweep on the\n * compressed entries is both simpler and more predictable than rebuilding a\n * tree after every provisional reservation.\n */\nclass LabelIndexWorkLimitError extends Error {\n constructor() {\n super('Grid label index work cap exceeded');\n this.name = 'LabelIndexWorkLimitError';\n }\n}\n\nclass LabelIndexWorkBudget {\n private used = 0;\n\n constructor(\n private readonly limit: number,\n private readonly metrics?: GridEdgeLabelInstrumentation\n ) {}\n\n charge(units: number): void {\n if (units <= 0) {\n return;\n }\n if (this.used + units > this.limit) {\n throw new LabelIndexWorkLimitError();\n }\n this.used += units;\n incrementMetric(this.metrics, 'indexWorkUnits', units);\n }\n}\n\nclass CompressedBoundsIndex<T extends { id: string; bounds: Bounds }> {\n private readonly entriesById = new Map<string, T>();\n private sortedByLeft: T[] = [];\n private dirty = false;\n\n constructor(\n private readonly workBudget: LabelIndexWorkBudget,\n private readonly metrics?: GridEdgeLabelInstrumentation\n ) {}\n\n upsert(entry: T): void {\n const isNew = !this.entriesById.has(entry.id);\n this.entriesById.set(entry.id, entry);\n this.dirty = true;\n if (isNew && this.metrics) {\n // Four stored boundary coordinates per entry, independent of their span.\n this.metrics.indexCoordinateCount += 4;\n }\n }\n\n remove(id: string): void {\n if (this.entriesById.delete(id)) {\n this.dirty = true;\n }\n }\n\n query(bounds: Bounds): T[] {\n if (this.dirty) {\n const entryCount = this.entriesById.size;\n // Charge a deterministic n log n estimate before sorting so the cap is independent of the\n // JavaScript engine's comparison order.\n this.workBudget.charge(entryCount * Math.max(1, Math.ceil(Math.log2(entryCount + 1))));\n this.sortedByLeft = [...this.entriesById.values()].sort(\n (a, b) => a.bounds.left - b.bounds.left || compareCodeUnits(a.id, b.id)\n );\n this.dirty = false;\n }\n const result: T[] = [];\n for (const entry of this.sortedByLeft) {\n this.workBudget.charge(1);\n if (entry.bounds.left > bounds.right) {\n break;\n }\n if (boundsOverlap(entry.bounds, bounds)) {\n result.push(entry);\n }\n }\n return result;\n }\n}\n\nfunction rectOverlap(a: Rect, b: Rect): boolean {\n return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;\n}\n\nfunction labelRectAt(node: Node, center: Point): Rect {\n const width = node.width ?? 0;\n const height = node.height ?? 0;\n return {\n cx: center.x,\n cy: center.y,\n left: center.x - width / 2,\n right: center.x + width / 2,\n top: center.y - height / 2,\n bottom: center.y + height / 2,\n };\n}\n\nfunction groupTitleRect(node: Node): Rect | null {\n const rect = node.groupTitleRect;\n if (!rect) {\n return null;\n }\n return {\n cx: (rect.left + rect.right) / 2,\n cy: (rect.top + rect.bottom) / 2,\n left: rect.left,\n right: rect.right,\n top: rect.top,\n bottom: rect.bottom,\n };\n}\n\nfunction incrementMetric(\n metrics: GridEdgeLabelInstrumentation | undefined,\n key: keyof GridEdgeLabelInstrumentation,\n delta = 1\n): void {\n if (metrics) {\n metrics[key] += delta;\n }\n}\n\nfunction clonePoint(point: Point): Point {\n return { ...point };\n}\n\nfunction boundsForRect(rect: Rect): Bounds {\n return {\n left: rect.left,\n right: rect.right,\n top: rect.top,\n bottom: rect.bottom,\n };\n}\n\nfunction boundsForSegment(segment: Segment): Bounds {\n return {\n left: Math.min(segment.a.x, segment.b.x),\n right: Math.max(segment.a.x, segment.b.x),\n top: Math.min(segment.a.y, segment.b.y),\n bottom: Math.max(segment.a.y, segment.b.y),\n };\n}\n\nfunction boundsForPoints(points: Point[]): Bounds | null {\n if (points.length === 0) {\n return null;\n }\n let left = points[0].x;\n let right = points[0].x;\n let top = points[0].y;\n let bottom = points[0].y;\n for (const point of points.slice(1)) {\n left = Math.min(left, point.x);\n right = Math.max(right, point.x);\n top = Math.min(top, point.y);\n bottom = Math.max(bottom, point.y);\n }\n return { left, right, top, bottom };\n}\n\nfunction mergeBounds(a: Bounds, b: Bounds): Bounds {\n return {\n left: Math.min(a.left, b.left),\n right: Math.max(a.right, b.right),\n top: Math.min(a.top, b.top),\n bottom: Math.max(a.bottom, b.bottom),\n };\n}\n\nfunction expandBounds(bounds: Bounds, padding: number): Bounds {\n return {\n left: bounds.left - padding,\n right: bounds.right + padding,\n top: bounds.top - padding,\n bottom: bounds.bottom + padding,\n };\n}\n\nfunction boundsOverlap(a: Bounds, b: Bounds): boolean {\n return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;\n}\n\nfunction candidateSegmentsFromSegments(segments: Segment[]): SegmentCandidate[] {\n const indexes =\n segments.length <= 2\n ? segments.map((_, index) => index)\n : [...segments.slice(1, -1).map((_, index) => index + 1), 0, segments.length - 1];\n return indexes.map((segmentIndex, order) => ({\n segment: segments[segmentIndex],\n segmentIndex,\n order,\n }));\n}\n\nfunction markerClearanceRectsFromPoints(edge: Edge, points: Point[]): Rect[] {\n const terminals = ['start', 'end'] as const;\n return terminals\n .filter((terminal) => hasTerminalMarker(edge, terminal))\n .map((terminal) =>\n terminalMarkerClearanceRect(points, terminal, EDGE_END_MARKER_CLEARANCE, 7, LABEL_EPSILON)\n )\n .filter((rect): rect is Rect => rect !== null);\n}\n\nfunction buildEdgeGeometry(edge: Edge, points: Point[]): EdgeGeometryCache {\n const normalized = normalizePolyline(points);\n return {\n points: normalized.points,\n segments: normalized.segments,\n candidateSegments: candidateSegmentsFromSegments(normalized.segments),\n markerRects: markerClearanceRectsFromPoints(edge, normalized.points),\n };\n}\n\nfunction segmentLength(segment: Segment): number {\n return segment.orientation === 'H'\n ? Math.abs(segment.b.x - segment.a.x)\n : Math.abs(segment.b.y - segment.a.y);\n}\n\nfunction borderCutsRect(rect: Rect, border: Rect): boolean {\n const corners: Point[] = [\n { x: border.left, y: border.top },\n { x: border.right, y: border.top },\n { x: border.right, y: border.bottom },\n { x: border.left, y: border.bottom },\n ];\n for (let i = 0; i < corners.length; i++) {\n if (segmentIntersectsRectInterior(corners[i], corners[(i + 1) % corners.length], rect)) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasFinitePosition(node: Node): boolean {\n return Number.isFinite(node.x) && Number.isFinite(node.y);\n}\n\nfunction pointsForEdge(\n edge: Edge,\n overrides?: EdgePointOverrides,\n context?: EdgeLabelContext\n): Point[] {\n const overridePoints = overrides?.get(edge.id);\n if (overridePoints) {\n return normalizePolyline(overridePoints).points;\n }\n const cached = context?.edgeGeometryById.get(edge.id);\n if (cached) {\n return cached.points;\n }\n return normalizePolyline(edge.points ?? []).points;\n}\n\nfunction markerClearanceRectsForEdge(\n edge: Edge,\n overrides?: EdgePointOverrides,\n context?: EdgeLabelContext\n): Rect[] {\n if (!overrides?.has(edge.id)) {\n const cached = context?.edgeGeometryById.get(edge.id);\n if (cached) {\n return cached.markerRects;\n }\n }\n return markerClearanceRectsFromPoints(edge, pointsForEdge(edge, overrides, context));\n}\n\nfunction rangeOverlaps(aStart: number, aEnd: number, bStart: number, bEnd: number): boolean {\n return (\n Math.max(Math.min(aStart, aEnd), Math.min(bStart, bEnd)) <\n Math.min(Math.max(aStart, aEnd), Math.max(bStart, bEnd)) - LABEL_EPSILON\n );\n}\n\nfunction clampInterval(interval: Interval, low: number, high: number): Interval | null {\n const start = clamp(Math.min(interval.start, interval.end), low, high);\n const end = clamp(Math.max(interval.start, interval.end), low, high);\n return end - start > LABEL_EPSILON ? { start, end } : null;\n}\n\nfunction mergeBlockedLabelIntervals(intervals: Interval[], low: number, high: number): Interval[] {\n const clamped = intervals\n .map((interval) => clampInterval(interval, low, high))\n .filter((interval): interval is Interval => interval !== null)\n .sort((a, b) => a.start - b.start || a.end - b.end);\n\n if (clamped.length === 0) {\n return [];\n }\n\n const merged: Interval[] = [clamped[0]];\n for (let index = 1; index < clamped.length; index++) {\n const current = clamped[index];\n const previous = merged[merged.length - 1];\n if (current.start <= previous.end + LABEL_EPSILON) {\n previous.end = Math.max(previous.end, current.end);\n } else {\n merged.push(current);\n }\n }\n return merged;\n}\n\nfunction centerCandidatesFromIntervals(\n low: number,\n high: number,\n blocked: Interval[],\n preferred: number\n): number[] {\n if (high - low <= LABEL_EPSILON) {\n return [];\n }\n\n const allowed: Interval[] = [];\n let cursor = low;\n for (const interval of mergeBlockedLabelIntervals(blocked, low, high)) {\n if (interval.start - cursor > LABEL_EPSILON) {\n allowed.push({ start: cursor, end: interval.start });\n }\n cursor = Math.max(cursor, interval.end);\n }\n if (high - cursor > LABEL_EPSILON) {\n allowed.push({ start: cursor, end: high });\n }\n\n const candidates = allowed.map((interval) => ({\n value: clamp(preferred, interval.start, interval.end),\n start: interval.start,\n end: interval.end,\n }));\n candidates.sort((a, b) => {\n const preferredDelta = Math.abs(a.value - preferred) - Math.abs(b.value - preferred);\n if (Math.abs(preferredDelta) > LABEL_EPSILON) {\n return preferredDelta;\n }\n const widthDelta = b.end - b.start - (a.end - a.start);\n if (Math.abs(widthDelta) > LABEL_EPSILON) {\n return widthDelta;\n }\n return a.value - b.value;\n });\n\n const seen = new Set<number>();\n const values: number[] = [];\n for (const candidate of candidates) {\n const rounded = Math.round(candidate.value * 1e6) / 1e6;\n if (seen.has(rounded)) {\n continue;\n }\n seen.add(rounded);\n values.push(candidate.value);\n }\n return values;\n}\n\nfunction obstacleRectForNode(node: Node): Rect | null {\n if (node.isGroup) {\n return null;\n }\n if (isEdgeLabelNode(node) && !hasFinitePosition(node)) {\n return null;\n }\n return rectForNode(node);\n}\n\nfunction candidateSegments(edge: Edge, context?: EdgeLabelContext): SegmentCandidate[] {\n const cached = context?.edgeGeometryById.get(edge.id);\n if (cached) {\n return cached.candidateSegments;\n }\n return candidateSegmentsFromSegments(normalizePolyline(edge.points ?? []).segments);\n}\n\nfunction storeEdgeGeometry(\n context: EdgeLabelContext,\n edgeId: string,\n geometry: EdgeGeometryCache\n): void {\n const previous = context.edgeGeometryById.get(edgeId);\n if (previous) {\n previous.segments.forEach((_, index) => context.segmentIndex.remove(`${edgeId}:${index}`));\n }\n\n context.edgeGeometryById.set(edgeId, geometry);\n geometry.segments.forEach((segment, index) => {\n context.segmentIndex.upsert({\n id: `${edgeId}:${index}`,\n edgeId,\n segment,\n bounds: boundsForSegment(segment),\n });\n });\n}\n\nfunction setEdgePoints(context: EdgeLabelContext, edge: Edge, points: Point[]): void {\n const geometry = buildEdgeGeometry(edge, points);\n edge.points = geometry.points.map(clonePoint);\n storeEdgeGeometry(context, edge.id, geometry);\n}\n\nfunction upsertPlacedLabelObstacle(context: EdgeLabelContext, placedLabel: PlacedLabel): void {\n context.placedLabelIndex.upsert({\n id: `label:${placedLabel.nodeId}`,\n nodeId: placedLabel.nodeId,\n rect: placedLabel.rect,\n bounds: boundsForRect(placedLabel.rect),\n });\n}\n\nfunction createEdgeLabelContext(\n data: LayoutData,\n workBudget: LabelIndexWorkBudget,\n metrics?: GridEdgeLabelInstrumentation\n): EdgeLabelContext {\n // A fresh context is the isolation boundary for one placement pass. Nothing indexed here is\n // reused after rollback because route proposals and label reservations are pass-local.\n const context: EdgeLabelContext = {\n edgeById: new Map(),\n edgeGeometryById: new Map(),\n obstacleIndex: new CompressedBoundsIndex<ObstacleEntry>(workBudget, metrics),\n placedLabelIndex: new CompressedBoundsIndex<ObstacleEntry>(workBudget, metrics),\n groupBorderIndex: new CompressedBoundsIndex<BorderEntry>(workBudget, metrics),\n segmentIndex: new CompressedBoundsIndex<EdgeSegmentEntry>(workBudget, metrics),\n searchBounds: { left: 0, right: 0, top: 0, bottom: 0 },\n metrics,\n };\n\n let aggregateBounds: Bounds | null = null;\n const rememberBounds = (bounds: Bounds) => {\n aggregateBounds = aggregateBounds ? mergeBounds(aggregateBounds, bounds) : { ...bounds };\n };\n\n for (const node of data.nodes) {\n if (node.isGroup) {\n const borderRect = rectForNode(node);\n const borderBounds = boundsForRect(borderRect);\n context.groupBorderIndex.upsert({\n id: `border:${node.id}`,\n rect: borderRect,\n bounds: borderBounds,\n });\n rememberBounds(borderBounds);\n\n const titleRect = groupTitleRect(node);\n if (titleRect) {\n const titleBounds = boundsForRect(titleRect);\n context.obstacleIndex.upsert({\n id: `title:${node.id}`,\n rect: titleRect,\n bounds: titleBounds,\n });\n rememberBounds(titleBounds);\n }\n continue;\n }\n\n const obstacleRect = obstacleRectForNode(node);\n if (!obstacleRect) {\n continue;\n }\n\n const entry: ObstacleEntry = {\n id: `${isEdgeLabelNode(node) ? 'label' : 'node'}:${node.id}`,\n rect: obstacleRect,\n bounds: boundsForRect(obstacleRect),\n nodeId: node.id,\n };\n if (isEdgeLabelNode(node)) {\n context.placedLabelIndex.upsert(entry);\n } else {\n context.obstacleIndex.upsert(entry);\n }\n rememberBounds(entry.bounds);\n }\n\n for (const edge of data.edges) {\n context.edgeById.set(edge.id, edge);\n const geometry = buildEdgeGeometry(edge, edge.points ?? []);\n storeEdgeGeometry(context, edge.id, geometry);\n const pointBounds = boundsForPoints(geometry.points);\n if (pointBounds) {\n rememberBounds(pointBounds);\n }\n }\n\n context.searchBounds = expandBounds(\n aggregateBounds ?? { left: 0, right: 0, top: 0, bottom: 0 },\n 128\n );\n return context;\n}\n\nfunction queryObstacleEntries(\n context: EdgeLabelContext,\n bounds: Bounds,\n metricKey: ObstacleQueryMetric,\n options: {\n excludeNodeId?: string;\n skipNodeIds?: ReadonlySet<string>;\n } = {}\n): ObstacleEntry[] {\n incrementMetric(context.metrics, metricKey);\n\n const collected: ObstacleEntry[] = [];\n const appendEntries = (entries: ObstacleEntry[]) => {\n for (const entry of entries) {\n if (\n entry.nodeId &&\n (entry.nodeId === options.excludeNodeId || options.skipNodeIds?.has(entry.nodeId))\n ) {\n continue;\n }\n collected.push(entry);\n }\n };\n\n appendEntries(context.obstacleIndex.query(bounds));\n appendEntries(context.placedLabelIndex.query(bounds));\n incrementMetric(context.metrics, 'obstacleCandidatesVisited', collected.length);\n return collected;\n}\n\nfunction queryForeignSegments(\n context: EdgeLabelContext,\n bounds: Bounds,\n selfEdgeId: string,\n overrides: EdgePointOverrides | undefined,\n metricKey: SegmentQueryMetric\n): EdgeSegmentEntry[] {\n incrementMetric(context.metrics, metricKey);\n\n const overriddenEdgeIds = overrides ? new Set(overrides.keys()) : undefined;\n const collected: EdgeSegmentEntry[] = [];\n const indexedEntries = context.segmentIndex.query(bounds);\n for (const entry of indexedEntries) {\n if (entry.edgeId === selfEdgeId || overriddenEdgeIds?.has(entry.edgeId)) {\n continue;\n }\n collected.push(entry);\n }\n\n let visited = indexedEntries.length;\n if (overrides) {\n for (const [edgeId, points] of overrides) {\n if (edgeId === selfEdgeId) {\n continue;\n }\n const edge = context.edgeById.get(edgeId);\n if (!edge) {\n continue;\n }\n const geometry = buildEdgeGeometry(edge, points);\n geometry.segments.forEach((segment, index) => {\n const segmentBounds = boundsForSegment(segment);\n if (!boundsOverlap(segmentBounds, bounds)) {\n return;\n }\n visited += 1;\n collected.push({\n id: `override:${edgeId}:${index}`,\n edgeId,\n segment,\n bounds: segmentBounds,\n });\n });\n }\n }\n\n incrementMetric(context.metrics, 'segmentCandidatesVisited', visited);\n return collected;\n}\n\nfunction foreignEdgeIdsIntersectingRect(\n context: EdgeLabelContext,\n rect: Rect,\n selfEdgeId: string,\n overrides?: EdgePointOverrides\n): string[] {\n incrementMetric(context.metrics, 'foreignEdgeLookups');\n const ids = new Set<string>();\n for (const entry of queryForeignSegments(\n context,\n boundsForRect(rect),\n selfEdgeId,\n overrides,\n 'segmentRectQueries'\n )) {\n if (segmentIntersectsRectInterior(entry.segment.a, entry.segment.b, rect)) {\n ids.add(entry.edgeId);\n }\n }\n return [...ids].sort(compareCodeUnits);\n}\n\nfunction obstacleBandQueryBounds(segment: Segment, labelNode: Node): Bounds | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n\n if (segment.orientation === 'H') {\n return {\n left: Math.min(segment.a.x, segment.b.x) - labelNode.width / 2,\n right: Math.max(segment.a.x, segment.b.x) + labelNode.width / 2,\n top: segment.a.y - labelNode.height / 2,\n bottom: segment.a.y + labelNode.height / 2,\n };\n }\n\n return {\n left: segment.a.x - labelNode.width / 2,\n right: segment.a.x + labelNode.width / 2,\n top: Math.min(segment.a.y, segment.b.y) - labelNode.height / 2,\n bottom: Math.max(segment.a.y, segment.b.y) + labelNode.height / 2,\n };\n}\n\nfunction detourLineQueryBounds(segment: Segment, labelNode: Node, searchBounds: Bounds): Bounds {\n if (segment.orientation === 'H') {\n const alongPadding = (labelNode.width ?? 0) + LABEL_CLEARANCE * 2 + LABEL_GUTTER;\n return {\n left: Math.min(segment.a.x, segment.b.x) - alongPadding,\n right: Math.max(segment.a.x, segment.b.x) + alongPadding,\n top: searchBounds.top,\n bottom: searchBounds.bottom,\n };\n }\n\n const alongPadding = (labelNode.height ?? 0) + LABEL_CLEARANCE * 2 + LABEL_GUTTER;\n return {\n left: searchBounds.left,\n right: searchBounds.right,\n top: Math.min(segment.a.y, segment.b.y) - alongPadding,\n bottom: Math.max(segment.a.y, segment.b.y) + alongPadding,\n };\n}\n\nfunction rerouteLineQueryBounds(segment: Segment, searchBounds: Bounds): Bounds {\n if (segment.orientation === 'H') {\n return {\n left: Math.min(segment.a.x, segment.b.x) - LABEL_CLEARANCE,\n right: Math.max(segment.a.x, segment.b.x) + LABEL_CLEARANCE,\n top: searchBounds.top,\n bottom: searchBounds.bottom,\n };\n }\n\n return {\n left: searchBounds.left,\n right: searchBounds.right,\n top: Math.min(segment.a.y, segment.b.y) - LABEL_CLEARANCE,\n bottom: Math.max(segment.a.y, segment.b.y) + LABEL_CLEARANCE,\n };\n}\n\nfunction rectSafeForLabel(\n rect: Rect,\n edge: Edge,\n labelNodeId: string,\n context: EdgeLabelContext,\n overrides?: EdgePointOverrides,\n allowedForeignEdgeIds?: ReadonlySet<string>\n): boolean {\n for (const obstacle of queryObstacleEntries(context, boundsForRect(rect), 'obstacleRectQueries', {\n excludeNodeId: labelNodeId,\n })) {\n if (rectOverlap(rect, obstacle.rect)) {\n return false;\n }\n }\n\n for (const border of context.groupBorderIndex.query(boundsForRect(rect))) {\n if (borderCutsRect(rect, border.rect)) {\n return false;\n }\n }\n\n for (const clearanceRect of markerClearanceRectsForEdge(edge, overrides, context)) {\n if (rectOverlap(rect, clearanceRect)) {\n return false;\n }\n }\n\n for (const foreignSegment of queryForeignSegments(\n context,\n boundsForRect(rect),\n edge.id,\n overrides,\n 'segmentRectQueries'\n )) {\n if (allowedForeignEdgeIds?.has(foreignSegment.edgeId)) {\n continue;\n }\n if (segmentIntersectsRectInterior(foreignSegment.segment.a, foreignSegment.segment.b, rect)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction requiredSegmentLength(node: Node, segment: Segment): number {\n return segment.orientation === 'Z'\n ? 0\n : gridLabelRequiredSegmentLength(node, segment.orientation);\n}\n\nfunction blockedCenterIntervals(\n edge: Edge,\n labelNode: Node,\n segment: Segment,\n context: EdgeLabelContext,\n overrides: EdgePointOverrides | undefined,\n includeForeignEdges: boolean\n): { low: number; high: number; blocked: Interval[] } | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n const labelWidth = labelNode.width;\n const labelHeight = labelNode.height;\n\n const alongHalf =\n segment.orientation === 'H'\n ? labelWidth / 2 + LABEL_CLEARANCE\n : labelHeight / 2 + LABEL_CLEARANCE;\n const low =\n segment.orientation === 'H'\n ? Math.min(segment.a.x, segment.b.x) + alongHalf\n : Math.min(segment.a.y, segment.b.y) + alongHalf;\n const high =\n segment.orientation === 'H'\n ? Math.max(segment.a.x, segment.b.x) - alongHalf\n : Math.max(segment.a.y, segment.b.y) - alongHalf;\n if (high - low <= LABEL_EPSILON) {\n return null;\n }\n\n // Project every obstacle onto the candidate segment. The remaining interval gaps are the only\n // centers worth testing, which keeps placement deterministic and avoids pixel-by-pixel search.\n const blocked: Interval[] = [];\n const bandBounds = obstacleBandQueryBounds(segment, labelNode);\n if (!bandBounds) {\n return null;\n }\n const addRect = (rect: Rect) => {\n if (segment.orientation === 'H') {\n const bandTop = segment.a.y - labelHeight / 2;\n const bandBottom = segment.a.y + labelHeight / 2;\n if (rangeOverlaps(bandTop, bandBottom, rect.top, rect.bottom)) {\n blocked.push({\n start: rect.left - labelWidth / 2,\n end: rect.right + labelWidth / 2,\n });\n }\n return;\n }\n\n const bandLeft = segment.a.x - labelWidth / 2;\n const bandRight = segment.a.x + labelWidth / 2;\n if (rangeOverlaps(bandLeft, bandRight, rect.left, rect.right)) {\n blocked.push({\n start: rect.top - labelHeight / 2,\n end: rect.bottom + labelHeight / 2,\n });\n }\n };\n\n for (const obstacle of queryObstacleEntries(context, bandBounds, 'obstacleBandQueries', {\n excludeNodeId: labelNode.id,\n })) {\n addRect(obstacle.rect);\n }\n for (const clearanceRect of markerClearanceRectsForEdge(edge, overrides, context)) {\n addRect(clearanceRect);\n }\n\n if (includeForeignEdges) {\n for (const foreignSegment of queryForeignSegments(\n context,\n bandBounds,\n edge.id,\n overrides,\n 'segmentBandQueries'\n )) {\n const segmentEntry = foreignSegment.segment;\n if (segment.orientation === 'H') {\n const bandTop = segment.a.y - labelNode.height / 2;\n const bandBottom = segment.a.y + labelNode.height / 2;\n if (segmentEntry.orientation === 'H') {\n if (bandTop < segmentEntry.a.y && bandBottom > segmentEntry.a.y) {\n blocked.push({\n start: Math.min(segmentEntry.a.x, segmentEntry.b.x) - labelNode.width / 2,\n end: Math.max(segmentEntry.a.x, segmentEntry.b.x) + labelNode.width / 2,\n });\n }\n } else if (\n rangeOverlaps(\n bandTop,\n bandBottom,\n Math.min(segmentEntry.a.y, segmentEntry.b.y),\n Math.max(segmentEntry.a.y, segmentEntry.b.y)\n )\n ) {\n blocked.push({\n start: segmentEntry.a.x - labelNode.width / 2,\n end: segmentEntry.a.x + labelNode.width / 2,\n });\n }\n continue;\n }\n\n const bandLeft = segment.a.x - labelNode.width / 2;\n const bandRight = segment.a.x + labelNode.width / 2;\n if (segmentEntry.orientation === 'V') {\n if (bandLeft < segmentEntry.a.x && bandRight > segmentEntry.a.x) {\n blocked.push({\n start: Math.min(segmentEntry.a.y, segmentEntry.b.y) - labelNode.height / 2,\n end: Math.max(segmentEntry.a.y, segmentEntry.b.y) + labelNode.height / 2,\n });\n }\n } else if (\n rangeOverlaps(\n bandLeft,\n bandRight,\n Math.min(segmentEntry.a.x, segmentEntry.b.x),\n Math.max(segmentEntry.a.x, segmentEntry.b.x)\n )\n ) {\n blocked.push({\n start: segmentEntry.a.y - labelNode.height / 2,\n end: segmentEntry.a.y + labelNode.height / 2,\n });\n }\n }\n }\n\n return { low, high, blocked };\n}\n\nfunction placementOnExistingSegment(\n edge: Edge,\n labelNode: Node,\n segment: Segment,\n context: EdgeLabelContext\n): Point | null {\n if (segmentLength(segment) < requiredSegmentLength(labelNode, segment)) {\n return null;\n }\n\n const intervalData = blockedCenterIntervals(edge, labelNode, segment, context, undefined, true);\n if (!intervalData) {\n return null;\n }\n\n const preferred =\n segment.orientation === 'H'\n ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n\n const candidates = centerCandidatesFromIntervals(\n intervalData.low,\n intervalData.high,\n intervalData.blocked,\n preferred\n );\n for (const candidate of candidates) {\n const center =\n segment.orientation === 'H'\n ? { x: candidate, y: segment.a.y }\n : { x: segment.a.x, y: candidate };\n const rect = labelRectAt(labelNode, center);\n if (rectSafeForLabel(rect, edge, labelNode.id, context)) {\n return center;\n }\n }\n\n return null;\n}\n\nfunction placementOnExistingSegmentWithReroutes(\n edge: Edge,\n labelNode: Node,\n segment: Segment,\n context: EdgeLabelContext,\n placedLabelsByEdgeId: Map<string, PlacedLabel>\n): Point | null {\n const intervalData = blockedCenterIntervals(edge, labelNode, segment, context, undefined, false);\n if (!intervalData) {\n return null;\n }\n\n const preferred =\n segment.orientation === 'H'\n ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n const candidates = centerCandidatesFromIntervals(\n intervalData.low,\n intervalData.high,\n intervalData.blocked,\n preferred\n );\n\n for (const candidate of candidates) {\n const center =\n segment.orientation === 'H'\n ? { x: candidate, y: segment.a.y }\n : { x: segment.a.x, y: candidate };\n const rect = labelRectAt(labelNode, center);\n const overrides: EdgePointOverrides = new Map();\n const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id)\n .map((edgeId) => context.edgeById.get(edgeId))\n .filter((foreignEdge): foreignEdge is Edge => foreignEdge !== undefined);\n\n let ok = true;\n for (const foreignEdge of foreignEdges) {\n const reroutedPoints = rerouteForeignEdgeAroundRect(\n foreignEdge,\n rect,\n context,\n placedLabelsByEdgeId,\n overrides\n );\n if (!reroutedPoints) {\n ok = false;\n break;\n }\n overrides.set(foreignEdge.id, reroutedPoints);\n }\n\n if (!ok) {\n continue;\n }\n if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {\n continue;\n }\n\n for (const [edgeId, points] of overrides) {\n const foreignEdge = context.edgeById.get(edgeId);\n if (foreignEdge) {\n setEdgePoints(context, foreignEdge, points);\n }\n }\n return center;\n }\n\n return null;\n}\n\nfunction polylineHitsProtectedObstacles(\n points: Point[],\n context: EdgeLabelContext,\n skipNodeIds: ReadonlySet<string>\n): boolean {\n for (const segment of normalizePolyline(points).segments) {\n for (const obstacle of queryObstacleEntries(\n context,\n boundsForSegment(segment),\n 'obstaclePolylineQueries',\n { skipNodeIds }\n )) {\n if (segmentIntersectsRectInterior(segment.a, segment.b, obstacle.rect)) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction labelStillAnchored(\n edgeId: string,\n points: Point[],\n placedLabelsByEdgeId: Map<string, PlacedLabel>\n): boolean {\n const placed = placedLabelsByEdgeId.get(edgeId);\n // Owner reroutes may change the supporting segment, but the reserved center must remain on the\n // polyline. Merely touching the label border would leave the rendered label beside its edge.\n return !placed || orthogonalPolylineContainsPoint(points, placed.center, LABEL_EPSILON);\n}\n\nfunction detourOffsets(crossHalfSize: number): number[] {\n const out: number[] = [];\n for (let step = 0; step < MAX_GUTTER_STEPS; step++) {\n const offset = crossHalfSize + LABEL_GUTTER + step * LABEL_GUTTER_STEP;\n out.push(-offset, offset);\n }\n return out;\n}\n\nfunction uniqueSortedCandidates(values: number[], anchor: number): number[] {\n const rounded = new Map<number, number>();\n for (const value of values) {\n const key = Math.round(value * 1e6) / 1e6;\n if (!rounded.has(key)) {\n rounded.set(key, value);\n }\n }\n return [...rounded.values()].sort((a, b) => {\n const distanceDelta = Math.abs(a - anchor) - Math.abs(b - anchor);\n if (Math.abs(distanceDelta) > LABEL_EPSILON) {\n return distanceDelta;\n }\n return a - b;\n });\n}\n\nfunction detourLineCandidates(\n edge: Edge,\n labelNode: Node,\n segment: Segment,\n context: EdgeLabelContext\n): number[] {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return [];\n }\n\n const labelWidth = labelNode.width;\n const labelHeight = labelNode.height;\n const anchor = segment.orientation === 'H' ? segment.a.y : segment.a.x;\n const crossHalfSize = segment.orientation === 'H' ? labelHeight / 2 : labelWidth / 2;\n const candidates = detourOffsets(crossHalfSize).map((offset) => anchor + offset);\n const addRect = (rect: Rect) => {\n if (segment.orientation === 'H') {\n candidates.push(rect.top - crossHalfSize - LABEL_GUTTER);\n candidates.push(rect.bottom + crossHalfSize + LABEL_GUTTER);\n return;\n }\n candidates.push(rect.left - crossHalfSize - LABEL_GUTTER);\n candidates.push(rect.right + crossHalfSize + LABEL_GUTTER);\n };\n\n for (const obstacle of queryObstacleEntries(\n context,\n detourLineQueryBounds(segment, labelNode, context.searchBounds),\n 'obstacleBandQueries',\n { excludeNodeId: labelNode.id }\n )) {\n addRect(obstacle.rect);\n }\n for (const clearanceRect of markerClearanceRectsForEdge(edge, undefined, context)) {\n addRect(clearanceRect);\n }\n\n return uniqueSortedCandidates(candidates, anchor).slice(0, MAX_DETOUR_LINE_CANDIDATES);\n}\n\nfunction rerouteLineCandidates(\n segment: Segment,\n blockedRect: Rect,\n context: EdgeLabelContext,\n skipNodeIds: ReadonlySet<string>,\n lane?: RerouteLane\n): number[] {\n const anchor = segment.orientation === 'H' ? segment.a.y : segment.a.x;\n const candidates: number[] = [];\n for (const offset of detourOffsets(0)) {\n if (segment.orientation === 'H') {\n candidates.push(offset < 0 ? blockedRect.top + offset : blockedRect.bottom + offset);\n } else {\n candidates.push(offset < 0 ? blockedRect.left + offset : blockedRect.right + offset);\n }\n }\n\n const addRect = (rect: Rect) => {\n if (segment.orientation === 'H') {\n candidates.push(rect.top - LABEL_GUTTER);\n candidates.push(rect.bottom + LABEL_GUTTER);\n return;\n }\n candidates.push(rect.left - LABEL_GUTTER);\n candidates.push(rect.right + LABEL_GUTTER);\n };\n\n for (const obstacle of queryObstacleEntries(\n context,\n rerouteLineQueryBounds(segment, context.searchBounds),\n 'obstacleBandQueries',\n { skipNodeIds }\n )) {\n addRect(obstacle.rect);\n }\n\n const sorted = uniqueSortedCandidates(candidates, anchor);\n const sideCandidates =\n lane?.orientation === segment.orientation\n ? sorted.filter((candidate) => {\n if (lane.side === 'top') {\n return candidate < blockedRect.top;\n }\n if (lane.side === 'bottom') {\n return candidate > blockedRect.bottom;\n }\n if (lane.side === 'left') {\n return candidate < blockedRect.left;\n }\n return candidate > blockedRect.right;\n })\n : sorted;\n return sideCandidates.slice(0, MAX_DETOUR_LINE_CANDIDATES);\n}\n\nfunction detourCenterCandidates(\n edge: Edge,\n labelNode: Node,\n segment: Segment,\n detourLineCoord: number,\n context: EdgeLabelContext\n): number[] {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return [];\n }\n\n const labelWidth = labelNode.width;\n const labelHeight = labelNode.height;\n const detourSegment: Segment =\n segment.orientation === 'H'\n ? {\n orientation: 'H',\n a: { x: segment.a.x, y: detourLineCoord },\n b: { x: segment.b.x, y: detourLineCoord },\n }\n : {\n orientation: 'V',\n a: { x: detourLineCoord, y: segment.a.y },\n b: { x: detourLineCoord, y: segment.b.y },\n };\n\n const intervalData = blockedCenterIntervals(\n edge,\n labelNode,\n detourSegment,\n context,\n undefined,\n false\n );\n if (!intervalData) {\n const preferred =\n segment.orientation === 'H'\n ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n const candidates = [preferred];\n const queryBounds = obstacleBandQueryBounds(detourSegment, labelNode);\n const addRect = (rect: Rect) => {\n if (segment.orientation === 'H') {\n candidates.push(rect.left - LABEL_GUTTER - labelWidth / 2);\n candidates.push(rect.right + LABEL_GUTTER + labelWidth / 2);\n return;\n }\n candidates.push(rect.top - LABEL_GUTTER - labelHeight / 2);\n candidates.push(rect.bottom + LABEL_GUTTER + labelHeight / 2);\n };\n if (queryBounds) {\n for (const obstacle of queryObstacleEntries(context, queryBounds, 'obstacleBandQueries', {\n excludeNodeId: labelNode.id,\n })) {\n addRect(obstacle.rect);\n }\n }\n return uniqueSortedCandidates(candidates, preferred).slice(0, MAX_DETOUR_CENTER_CANDIDATES);\n }\n\n const preferred =\n segment.orientation === 'H'\n ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n\n return centerCandidatesFromIntervals(\n intervalData.low,\n intervalData.high,\n intervalData.blocked,\n preferred\n );\n}\n\nfunction detourReturnCoordinate(\n sourceLine: number,\n detourLine: number,\n labelHalfSize: number\n): number {\n const direction = detourLine >= sourceLine ? 1 : -1;\n return detourLine + direction * (labelHalfSize + LABEL_CLEARANCE);\n}\n\ninterface DetourAxis {\n along(point: Point): number;\n cross(point: Point): number;\n point(along: number, cross: number): Point;\n labelAlongSize(labelNode: Node): number;\n labelCrossSize(labelNode: Node): number;\n}\n\nconst HORIZONTAL_DETOUR_AXIS: DetourAxis = {\n along: (point) => point.x,\n cross: (point) => point.y,\n point: (along, cross) => ({ x: along, y: cross }),\n labelAlongSize: (labelNode) => labelNode.width ?? 0,\n labelCrossSize: (labelNode) => labelNode.height ?? 0,\n};\n\nconst VERTICAL_DETOUR_AXIS: DetourAxis = {\n along: (point) => point.y,\n cross: (point) => point.x,\n point: (along, cross) => ({ x: cross, y: along }),\n labelAlongSize: (labelNode) => labelNode.height ?? 0,\n labelCrossSize: (labelNode) => labelNode.width ?? 0,\n};\n\nfunction detourAxis(segment: Segment): DetourAxis {\n return segment.orientation === 'H' ? HORIZONTAL_DETOUR_AXIS : VERTICAL_DETOUR_AXIS;\n}\n\nfunction buildLabelDetourPoints(\n points: Point[],\n segmentIndex: number,\n segment: Segment,\n labelNode: Node,\n centerAlong: number,\n detourLineCoord: number\n): Point[] | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n\n // Keep the original terminal-adjacent anchors intact; marker clearance and node clipping own\n // endpoint geometry, while label placement owns only the interior detour.\n const a = points[segmentIndex];\n const b = points[segmentIndex + 1];\n const axis = detourAxis(segment);\n const sourceLine = axis.cross(segment.a);\n const aAlong = axis.along(a);\n const bAlong = axis.along(b);\n const span = axis.labelAlongSize(labelNode) + LABEL_CLEARANCE * 2;\n const detourStart = centerAlong - span / 2;\n const detourEnd = centerAlong + span / 2;\n const extendsBeforeStart = detourStart < Math.min(aAlong, bAlong) - LABEL_EPSILON;\n const extendsAfterEnd = detourEnd > Math.max(aAlong, bAlong) + LABEL_EPSILON;\n const alongDirection = bAlong >= aAlong ? 1 : -1;\n const segmentInset = Math.max(\n 0,\n Math.min(EDGE_END_MARKER_CLEARANCE, Math.abs(bAlong - aAlong) / 2 - LABEL_EPSILON)\n );\n const entryAlong = aAlong + alongDirection * segmentInset;\n const exitAlong = bAlong - alongDirection * segmentInset;\n if (!extendsBeforeStart && !extendsAfterEnd) {\n return normalizePolyline([\n ...points.slice(0, segmentIndex),\n a,\n axis.point(detourStart, sourceLine),\n axis.point(detourStart, detourLineCoord),\n axis.point(detourEnd, detourLineCoord),\n axis.point(detourEnd, sourceLine),\n b,\n ...points.slice(segmentIndex + 2),\n ]).points;\n }\n\n const returnLine = detourReturnCoordinate(\n sourceLine,\n detourLineCoord,\n axis.labelCrossSize(labelNode) / 2\n );\n const detourPoints: Point[] = [...points.slice(0, segmentIndex), a];\n if (extendsBeforeStart) {\n detourPoints.push(\n axis.point(entryAlong, sourceLine),\n axis.point(entryAlong, returnLine),\n axis.point(detourStart, returnLine),\n axis.point(detourStart, detourLineCoord)\n );\n } else {\n detourPoints.push(\n axis.point(detourStart, sourceLine),\n axis.point(detourStart, detourLineCoord)\n );\n }\n detourPoints.push(axis.point(detourEnd, detourLineCoord));\n if (extendsAfterEnd) {\n detourPoints.push(\n axis.point(detourEnd, returnLine),\n axis.point(exitAlong, returnLine),\n axis.point(exitAlong, sourceLine)\n );\n } else {\n detourPoints.push(axis.point(detourEnd, sourceLine));\n }\n detourPoints.push(b, ...points.slice(segmentIndex + 2));\n return normalizePolyline(detourPoints).points;\n}\n\nfunction buildExtendedLabelDetourPoints(\n points: Point[],\n segmentIndex: number,\n segment: Segment,\n labelNode: Node,\n centerAlong: number,\n detourLineCoord: number,\n separateEntryAndExit: boolean\n): Point[] | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n\n const a = points[segmentIndex];\n const b = points[segmentIndex + 1];\n // Self-loop terminal segments are short; quarter points keep the entry and exit lanes distinct.\n const insetDivisor = separateEntryAndExit ? 4 : 2;\n const axis = detourAxis(segment);\n const sourceLine = axis.cross(segment.a);\n const aAlong = axis.along(a);\n const bAlong = axis.along(b);\n const span = axis.labelAlongSize(labelNode) + LABEL_CLEARANCE * 2;\n const detourStart = centerAlong - span / 2;\n const detourEnd = centerAlong + span / 2;\n const alongDirection = bAlong >= aAlong ? 1 : -1;\n const segmentInset = Math.max(\n 0,\n Math.min(EDGE_END_MARKER_CLEARANCE, Math.abs(bAlong - aAlong) / insetDivisor - LABEL_EPSILON)\n );\n const entryAlong = aAlong + alongDirection * segmentInset;\n const exitAlong = bAlong - alongDirection * segmentInset;\n const returnLine = detourReturnCoordinate(\n sourceLine,\n detourLineCoord,\n axis.labelCrossSize(labelNode) / 2\n );\n return normalizePolyline([\n ...points.slice(0, segmentIndex),\n a,\n axis.point(entryAlong, sourceLine),\n axis.point(entryAlong, detourLineCoord),\n axis.point(detourStart, detourLineCoord),\n axis.point(detourEnd, detourLineCoord),\n axis.point(detourEnd, returnLine),\n axis.point(exitAlong, returnLine),\n axis.point(exitAlong, sourceLine),\n b,\n ...points.slice(segmentIndex + 2),\n ]).points;\n}\n\nfunction externalDetourCenterCandidates(segment: Segment, labelNode: Node): number[] {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return [];\n }\n\n if (segment.orientation === 'H') {\n const minX = Math.min(segment.a.x, segment.b.x);\n const maxX = Math.max(segment.a.x, segment.b.x);\n return [minX - labelNode.width / 2 - LABEL_GUTTER, maxX + labelNode.width / 2 + LABEL_GUTTER];\n }\n\n const minY = Math.min(segment.a.y, segment.b.y);\n const maxY = Math.max(segment.a.y, segment.b.y);\n return [minY - labelNode.height / 2 - LABEL_GUTTER, maxY + labelNode.height / 2 + LABEL_GUTTER];\n}\n\ninterface BlockedIntersectionScore {\n count: number;\n length: number;\n}\n\nfunction blockedIntersectionScore(points: readonly Point[], rect: Rect): BlockedIntersectionScore {\n let count = 0;\n let length = 0;\n for (const segment of normalizePolyline([...points]).segments) {\n if (!segmentIntersectsRectInterior(segment.a, segment.b, rect)) {\n continue;\n }\n count++;\n if (segment.orientation === 'H') {\n length += Math.max(\n 0,\n Math.min(Math.max(segment.a.x, segment.b.x), rect.right) -\n Math.max(Math.min(segment.a.x, segment.b.x), rect.left)\n );\n } else if (segment.orientation === 'V') {\n length += Math.max(\n 0,\n Math.min(Math.max(segment.a.y, segment.b.y), rect.bottom) -\n Math.max(Math.min(segment.a.y, segment.b.y), rect.top)\n );\n }\n }\n return { count, length };\n}\n\nfunction reducesBlockedIntersections(\n candidate: readonly Point[],\n blockedRect: Rect,\n baseline: BlockedIntersectionScore\n): boolean {\n const score = blockedIntersectionScore(candidate, blockedRect);\n return (\n score.count < baseline.count ||\n (score.count === baseline.count && score.length < baseline.length - LABEL_EPSILON)\n );\n}\n\ninterface RerouteLane {\n key: string;\n orientation: 'H' | 'V';\n side: 'top' | 'bottom' | 'left' | 'right';\n}\n\nfunction rerouteLane(\n points: readonly Point[],\n blockedRect: Rect,\n blockingReservations: readonly PlacedLabel[]\n): RerouteLane | null {\n const segment = normalizePolyline([...points]).segments.find((candidate) =>\n segmentIntersectsRectInterior(candidate.a, candidate.b, blockedRect)\n );\n if (!segment || segment.orientation === 'Z') {\n return null;\n }\n\n const side =\n segment.orientation === 'H'\n ? Math.abs(segment.a.y - blockedRect.top) <= Math.abs(blockedRect.bottom - segment.a.y)\n ? 'top'\n : 'bottom'\n : Math.abs(segment.a.x - blockedRect.left) <= Math.abs(blockedRect.right - segment.a.x)\n ? 'left'\n : 'right';\n const reservationIds = blockingReservations\n .map((reservation) => reservation.edgeId)\n .sort(compareCodeUnits);\n return {\n key: JSON.stringify([reservationIds, segment.orientation, side]),\n orientation: segment.orientation,\n side,\n };\n}\n\nfunction rerouteSegmentAroundRect(\n edge: Edge,\n points: Point[],\n segmentIndex: number,\n blockedRect: Rect,\n context: EdgeLabelContext,\n placedLabelsByEdgeId: Map<string, PlacedLabel>,\n lane?: RerouteLane\n): Point[] | null {\n const normalized = normalizePolyline(points);\n const baselineScore = blockedIntersectionScore(normalized.points, blockedRect);\n const segment = normalized.segments[segmentIndex];\n if (!segment || segment.orientation === 'Z') {\n return null;\n }\n\n const a = normalized.points[segmentIndex];\n const b = normalized.points[segmentIndex + 1];\n const ownLabelNodeId = placedLabelsByEdgeId.get(edge.id)?.nodeId;\n const skipNodeIds = new Set<string>();\n if (ownLabelNodeId) {\n skipNodeIds.add(ownLabelNodeId);\n }\n\n // One detour may remove only the first intersection with a wide label. Accept strictly\n // monotonic progress here; the bounded outer loop completes the reroute segment by segment.\n if (segment.orientation === 'H') {\n const minX = Math.min(a.x, b.x);\n const maxX = Math.max(a.x, b.x);\n const entry = Math.max(minX, blockedRect.left - LABEL_CLEARANCE);\n const exit = Math.min(maxX, blockedRect.right + LABEL_CLEARANCE);\n if (exit - entry <= LABEL_EPSILON) {\n incrementMetric(context.metrics, 'rerouteRejectedDegenerateSpan');\n return null;\n }\n\n for (const y of rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane)) {\n incrementMetric(context.metrics, 'rerouteCandidatesEvaluated');\n const candidatePoints = normalizePolyline([\n ...normalized.points.slice(0, segmentIndex),\n a,\n { x: entry, y: segment.a.y },\n { x: entry, y },\n { x: exit, y },\n { x: exit, y: segment.a.y },\n b,\n ...normalized.points.slice(segmentIndex + 2),\n ]).points;\n if (\n polylineIntersectsRect(candidatePoints, blockedRect) &&\n !reducesBlockedIntersections(candidatePoints, blockedRect, baselineScore)\n ) {\n incrementMetric(context.metrics, 'rerouteRejectedBlockedRect');\n continue;\n }\n if (polylineIntersectsRect(candidatePoints, blockedRect)) {\n incrementMetric(context.metrics, 'reroutePartialProgressCandidates');\n }\n if (polylineHitsProtectedObstacles(candidatePoints, context, skipNodeIds)) {\n incrementMetric(context.metrics, 'rerouteRejectedProtectedObstacle');\n continue;\n }\n if (!labelStillAnchored(edge.id, candidatePoints, placedLabelsByEdgeId)) {\n incrementMetric(context.metrics, 'rerouteRejectedLabelAnchor');\n continue;\n }\n return candidatePoints;\n }\n return null;\n }\n\n const minY = Math.min(a.y, b.y);\n const maxY = Math.max(a.y, b.y);\n const entry = Math.max(minY, blockedRect.top - LABEL_CLEARANCE);\n const exit = Math.min(maxY, blockedRect.bottom + LABEL_CLEARANCE);\n if (exit - entry <= LABEL_EPSILON) {\n incrementMetric(context.metrics, 'rerouteRejectedDegenerateSpan');\n return null;\n }\n\n for (const x of rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane)) {\n incrementMetric(context.metrics, 'rerouteCandidatesEvaluated');\n const candidatePoints = normalizePolyline([\n ...normalized.points.slice(0, segmentIndex),\n a,\n { x: segment.a.x, y: entry },\n { x, y: entry },\n { x, y: exit },\n { x: segment.a.x, y: exit },\n b,\n ...normalized.points.slice(segmentIndex + 2),\n ]).points;\n if (\n polylineIntersectsRect(candidatePoints, blockedRect) &&\n !reducesBlockedIntersections(candidatePoints, blockedRect, baselineScore)\n ) {\n incrementMetric(context.metrics, 'rerouteRejectedBlockedRect');\n continue;\n }\n if (polylineIntersectsRect(candidatePoints, blockedRect)) {\n incrementMetric(context.metrics, 'reroutePartialProgressCandidates');\n }\n if (polylineHitsProtectedObstacles(candidatePoints, context, skipNodeIds)) {\n incrementMetric(context.metrics, 'rerouteRejectedProtectedObstacle');\n continue;\n }\n if (!labelStillAnchored(edge.id, candidatePoints, placedLabelsByEdgeId)) {\n incrementMetric(context.metrics, 'rerouteRejectedLabelAnchor');\n continue;\n }\n return candidatePoints;\n }\n\n return null;\n}\n\nfunction rerouteForeignEdgeAroundRect(\n edge: Edge,\n blockedRect: Rect,\n context: EdgeLabelContext,\n placedLabelsByEdgeId: Map<string, PlacedLabel>,\n overrides: EdgePointOverrides,\n lane?: RerouteLane\n): Point[] | null {\n let currentPoints = pointsForEdge(edge, overrides, context);\n for (let attempt = 0; attempt < 8; attempt++) {\n if (!polylineIntersectsRect(currentPoints, blockedRect)) {\n return currentPoints;\n }\n\n const normalized = normalizePolyline(currentPoints);\n const segmentIndex = normalized.points.findIndex((point, index) => {\n if (index === normalized.points.length - 1) {\n return false;\n }\n return segmentIntersectsRectInterior(point, normalized.points[index + 1], blockedRect);\n });\n if (segmentIndex < 0) {\n return currentPoints;\n }\n\n const rerouted = rerouteSegmentAroundRect(\n edge,\n normalized.points,\n segmentIndex,\n blockedRect,\n context,\n placedLabelsByEdgeId,\n lane\n );\n if (!rerouted) {\n return null;\n }\n currentPoints = rerouted;\n }\n\n return polylineIntersectsRect(currentPoints, blockedRect) ? null : currentPoints;\n}\n\nfunction rerouteForeignEdgeAroundLabels(\n edge: Edge,\n reservations: readonly PlacedLabel[],\n context: EdgeLabelContext,\n placedLabelsByEdgeId: Map<string, PlacedLabel>,\n overrides: EdgePointOverrides\n): Point[] | null {\n const initialPoints = pointsForEdge(edge, overrides, context);\n let currentPoints = initialPoints;\n // A detour around a later label can re-enter an earlier reservation, so make one deterministic\n // repair pass and one convergence pass before abandoning the edge-level recovery.\n for (let pass = 0; pass < 2; pass++) {\n let changed = false;\n for (const reservation of reservations) {\n if (!polylineIntersectsRect(currentPoints, reservation.rect)) {\n continue;\n }\n incrementMetric(context.metrics, 'individualLabelRerouteAttempts');\n overrides.set(edge.id, currentPoints);\n const rerouted = rerouteForeignEdgeAroundRect(\n edge,\n reservation.rect,\n context,\n placedLabelsByEdgeId,\n overrides\n );\n if (!rerouted) {\n overrides.set(edge.id, initialPoints);\n return null;\n }\n incrementMetric(context.metrics, 'individualLabelRerouteSuccesses');\n currentPoints = rerouted;\n changed = true;\n }\n if (\n reservations.every((reservation) => !polylineIntersectsRect(currentPoints, reservation.rect))\n ) {\n return currentPoints;\n }\n if (!changed) {\n break;\n }\n }\n overrides.set(edge.id, initialPoints);\n return null;\n}\n\nfunction labelPlacementWithExtendedDetour(\n edge: Edge,\n labelNode: Node,\n segmentCandidate: SegmentCandidate,\n context: EdgeLabelContext,\n placedLabelsByEdgeId: Map<string, PlacedLabel>\n): Point | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n\n const basePoints = pointsForEdge(edge, undefined, context);\n const segment = segmentCandidate.segment;\n\n for (const detourLineCoord of detourLineCandidates(edge, labelNode, segment, context)) {\n const centerCandidates = uniqueSortedCandidates(\n externalDetourCenterCandidates(segment, labelNode),\n segment.orientation === 'H'\n ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2\n );\n\n for (const centerAlong of centerCandidates) {\n const candidatePoints = buildExtendedLabelDetourPoints(\n basePoints,\n segmentCandidate.segmentIndex,\n segment,\n labelNode,\n centerAlong,\n detourLineCoord,\n edge.start === edge.end\n );\n if (!candidatePoints) {\n continue;\n }\n\n if (edge.start === edge.end && polylineHasSelfConflict(candidatePoints)) {\n continue;\n }\n\n if (polylineHitsProtectedObstacles(candidatePoints, context, new Set([labelNode.id]))) {\n continue;\n }\n\n const center =\n segment.orientation === 'H'\n ? { x: centerAlong, y: detourLineCoord }\n : { x: detourLineCoord, y: centerAlong };\n const rect = labelRectAt(labelNode, center);\n const overrides: EdgePointOverrides = new Map([[edge.id, candidatePoints]]);\n\n const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id, overrides)\n .map((edgeId) => context.edgeById.get(edgeId))\n .filter((foreignEdge): foreignEdge is Edge => foreignEdge !== undefined);\n\n let ok = true;\n for (const foreignEdge of foreignEdges) {\n const reroutedPoints = rerouteForeignEdgeAroundRect(\n foreignEdge,\n rect,\n context,\n placedLabelsByEdgeId,\n overrides\n );\n if (!reroutedPoints) {\n ok = false;\n break;\n }\n overrides.set(foreignEdge.id, reroutedPoints);\n }\n\n if (!ok) {\n continue;\n }\n if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {\n continue;\n }\n\n setEdgePoints(context, edge, candidatePoints);\n for (const [edgeId, points] of overrides) {\n if (edgeId === edge.id) {\n continue;\n }\n const foreignEdge = context.edgeById.get(edgeId);\n if (foreignEdge) {\n setEdgePoints(context, foreignEdge, points);\n }\n }\n return center;\n }\n }\n\n return null;\n}\n\nfunction labelPlacementWithDetour(\n edge: Edge,\n labelNode: Node,\n segmentCandidate: SegmentCandidate,\n context: EdgeLabelContext,\n placedLabelsByEdgeId: Map<string, PlacedLabel>\n): Point | null {\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n return null;\n }\n\n const basePoints = pointsForEdge(edge, undefined, context);\n const segment = segmentCandidate.segment;\n\n for (const detourLineCoord of detourLineCandidates(edge, labelNode, segment, context)) {\n const centerCandidates = detourCenterCandidates(\n edge,\n labelNode,\n segment,\n detourLineCoord,\n context\n );\n for (const centerAlong of centerCandidates) {\n const candidatePoints = buildLabelDetourPoints(\n basePoints,\n segmentCandidate.segmentIndex,\n segment,\n labelNode,\n centerAlong,\n detourLineCoord\n );\n if (!candidatePoints) {\n continue;\n }\n\n if (edge.start === edge.end && polylineHasSelfConflict(candidatePoints)) {\n continue;\n }\n\n if (polylineHitsProtectedObstacles(candidatePoints, context, new Set([labelNode.id]))) {\n continue;\n }\n\n const center =\n segment.orientation === 'H'\n ? { x: centerAlong, y: detourLineCoord }\n : { x: detourLineCoord, y: centerAlong };\n const rect = labelRectAt(labelNode, center);\n const overrides: EdgePointOverrides = new Map([[edge.id, candidatePoints]]);\n\n const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id, overrides)\n .map((edgeId) => context.edgeById.get(edgeId))\n .filter((foreignEdge): foreignEdge is Edge => foreignEdge !== undefined);\n\n let ok = true;\n for (const foreignEdge of foreignEdges) {\n const reroutedPoints = rerouteForeignEdgeAroundRect(\n foreignEdge,\n rect,\n context,\n placedLabelsByEdgeId,\n overrides\n );\n if (!reroutedPoints) {\n ok = false;\n break;\n }\n overrides.set(foreignEdge.id, reroutedPoints);\n }\n\n if (!ok) {\n continue;\n }\n if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {\n continue;\n }\n\n setEdgePoints(context, edge, candidatePoints);\n for (const [edgeId, points] of overrides) {\n if (edgeId === edge.id) {\n continue;\n }\n const foreignEdge = context.edgeById.get(edgeId);\n if (foreignEdge) {\n setEdgePoints(context, foreignEdge, points);\n }\n }\n return center;\n }\n }\n\n return null;\n}\n\nfunction isPreparedLabelNode(node: Node | undefined): node is NonClusterNode {\n return Boolean(node && isEdgeLabelNode(node));\n}\n\nfunction parkDegenerateLabel(\n edge: Edge,\n labelNode: Node,\n nodeById: ReadonlyMap<string, Node>\n): void {\n const routePoint = edge.points?.find(\n (point) => Number.isFinite(point.x) && Number.isFinite(point.y)\n );\n const source = edge.start ? nodeById.get(edge.start) : undefined;\n const target = edge.end ? nodeById.get(edge.end) : undefined;\n const fallback =\n routePoint ?? (source && hasFinitePosition(source) ? source : undefined) ?? target;\n if (fallback && Number.isFinite(fallback.x) && Number.isFinite(fallback.y)) {\n labelNode.x = fallback.x;\n labelNode.y = fallback.y;\n return;\n }\n delete labelNode.x;\n delete labelNode.y;\n}\n\nfunction placeLabelAtRouteMidpoint(\n edge: Edge,\n labelNode: Node,\n nodeById: ReadonlyMap<string, Node>\n): void {\n let longestSegment: Segment | undefined;\n for (const segment of normalizePolyline(edge.points ?? []).segments) {\n if (segment.orientation === 'Z') {\n continue;\n }\n if (!longestSegment || segmentLength(segment) > segmentLength(longestSegment)) {\n longestSegment = segment;\n }\n }\n if (!longestSegment) {\n parkDegenerateLabel(edge, labelNode, nodeById);\n return;\n }\n labelNode.x = (longestSegment.a.x + longestSegment.b.x) / 2;\n labelNode.y = (longestSegment.a.y + longestSegment.b.y) / 2;\n}\n\nfunction preferredGridLabelNodeId(edge: Edge): string {\n return `${GRID_LABEL_PREFIX}${edge.start ?? ''}-${edge.end ?? ''}-${edge.id}`;\n}\n\nfunction ensureUniqueGridLabelNodeId(edge: Edge, nodeById: Map<string, Node>): string {\n const baseId = edge.labelNodeId ?? preferredGridLabelNodeId(edge);\n let candidateId = baseId;\n let suffix = 1;\n while (true) {\n if (!nodeById.has(candidateId)) {\n return candidateId;\n }\n candidateId = `${baseId}-${suffix}`;\n suffix += 1;\n }\n}\n\nexport function prepareGridLayout(data: LayoutData): void {\n // Labels become measured helper nodes before grid sizing, but remain outside the placement\n // forest. The original edge text is cleared so the shared renderer does not draw it twice.\n const nodeById = new Map<string, Node>();\n for (const node of data.nodes) {\n nodeById.set(node.id, node);\n }\n\n const newNodes: NonClusterNode[] = [];\n for (const edge of data.edges) {\n if (!edge.label || edge.label.length === 0) {\n continue;\n }\n\n const sourceNode = edge.start ? nodeById.get(edge.start) : undefined;\n const existingHelper = edge.labelNodeId ? nodeById.get(edge.labelNodeId) : undefined;\n if (isPreparedLabelNode(existingHelper)) {\n existingHelper.label = edge.label;\n existingHelper.labelStyle = Array.isArray(edge.labelStyle)\n ? edge.labelStyle[0]\n : (edge.labelStyle ?? '');\n existingHelper.edgeStart = edge.start ?? '';\n existingHelper.edgeEnd = edge.end ?? '';\n if (sourceNode?.dir) {\n existingHelper.dir = sourceNode.dir;\n }\n edge.label = undefined;\n (edge as Edge & { text?: string }).text = undefined;\n continue;\n }\n\n const labelNodeId = ensureUniqueGridLabelNodeId(edge, nodeById);\n const labelNode: NonClusterNode = {\n id: labelNodeId,\n label: edge.label,\n edgeStart: edge.start ?? '',\n edgeEnd: edge.end ?? '',\n shape: 'labelRect',\n width: 0,\n height: 0,\n isEdgeLabel: true,\n isDummy: true,\n isGroup: false,\n parentId: undefined,\n labelStyle: Array.isArray(edge.labelStyle) ? edge.labelStyle[0] : (edge.labelStyle ?? ''),\n ...(sourceNode?.dir ? { dir: sourceNode.dir } : {}),\n };\n newNodes.push(labelNode);\n nodeById.set(labelNodeId, labelNode);\n edge.labelNodeId = labelNodeId;\n edge.label = undefined;\n (edge as Edge & { text?: string }).text = undefined;\n }\n\n data.nodes.push(...newNodes);\n}\n\nexport function positionGridEdgeLabels(\n data: LayoutData,\n instrumentation?: GridEdgeLabelInstrumentation,\n routingInstrumentation?: GridRoutingInstrumentation,\n options: GridEdgeLabelOptions = {}\n): void {\n const nodeById = new Map<string, Node>();\n for (const node of data.nodes) {\n nodeById.set(node.id, node);\n }\n // Coordinates belong to the previous invocation. Retain them only for rollback; the current\n // placement pass must build its obstacle index from labels placed during this invocation.\n const labelNodes = data.nodes.filter(isEdgeLabelNode);\n const baseLabelPositions = new Map<string, { x?: number; y?: number }>(\n labelNodes.map((labelNode) => [labelNode.id, { x: labelNode.x, y: labelNode.y }])\n );\n for (const labelNode of labelNodes) {\n delete labelNode.x;\n delete labelNode.y;\n }\n\n const preparedLabels = data.edges\n .map((edge, sourceIndex) => {\n if (!edge.labelNodeId) {\n return null;\n }\n const labelNode = nodeById.get(edge.labelNodeId);\n if (!labelNode) {\n return null;\n }\n if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n incrementMetric(instrumentation, 'unmeasuredLabelsSkipped');\n return null;\n }\n return { edge, labelNode, sourceIndex };\n })\n .filter((entry): entry is LabelWorkItem => entry !== null);\n\n if (preparedLabels.length === 0) {\n return;\n }\n\n // Keep the routed geometry for midpoint degradation and the full snapshot for error rollback.\n const baseEdgePoints = new Map<string, Point[] | undefined>(\n data.edges.map((edge) => [edge.id, edge.points?.map((point) => ({ ...point }))])\n );\n\n const restoreBaseEdgePoints = (): void => {\n for (const edge of data.edges) {\n const points = baseEdgePoints.get(edge.id);\n if (points) {\n edge.points = points.map((point) => ({ ...point }));\n } else {\n delete edge.points;\n }\n }\n };\n\n const restoreBaseState = (): void => {\n restoreBaseEdgePoints();\n for (const labelNode of labelNodes) {\n const position = baseLabelPositions.get(labelNode.id);\n if (position && Number.isFinite(position.x) && Number.isFinite(position.y)) {\n labelNode.x = position.x;\n labelNode.y = position.y;\n } else {\n delete labelNode.x;\n delete labelNode.y;\n }\n }\n };\n\n const workItems = preparedLabels\n .filter(({ edge, labelNode }) => {\n if (normalizePolyline(edge.points ?? []).segments.length > 0) {\n return true;\n }\n parkDegenerateLabel(edge, labelNode, nodeById);\n incrementMetric(instrumentation, 'degenerateLabelRoutesSkipped');\n return false;\n })\n .sort((a, b) => a.sourceIndex - b.sourceIndex || compareCodeUnits(a.edge.id, b.edge.id));\n if (workItems.length === 0) {\n return;\n }\n const placeLabelsAtRouteMidpoints = (): void => {\n restoreBaseEdgePoints();\n for (const { edge, labelNode } of workItems) {\n placeLabelAtRouteMidpoint(edge, labelNode, nodeById);\n }\n };\n\n const configuredIndexWork = options.maxIndexWork ?? DEFAULT_MAX_INDEX_WORK;\n const indexWorkLimit =\n Number.isFinite(configuredIndexWork) && configuredIndexWork >= 0\n ? Math.floor(configuredIndexWork)\n : DEFAULT_MAX_INDEX_WORK;\n const indexWorkBudget = new LabelIndexWorkBudget(indexWorkLimit, instrumentation);\n const placementFailures: LabelPlacementSearchExhaustedError[] = [];\n for (let pass = 1; pass <= 2; pass++) {\n // Pass 1 prefers existing segments and foreign-edge reroutes. Pass 2 additionally permits\n // owner-edge detours, rebuilding every route from the original routing result.\n incrementMetric(instrumentation, 'labelPasses');\n const context = createEdgeLabelContext(data, indexWorkBudget, instrumentation);\n const placedLabelsByEdgeId = new Map<string, PlacedLabel>();\n const allowedOverlapsByLabelEdgeId = new Map<string, Set<string>>();\n const passStartPoints = new Map(\n data.edges.map((edge) => [edge.id, pointsForEdge(edge, undefined, context).map(clonePoint)])\n );\n const proposedOwnerRoutes = new Map<string, Point[]>();\n try {\n for (const { edge, labelNode } of workItems) {\n const segments = [...candidateSegments(edge, context)].sort((a, b) => {\n const lengthDelta = segmentLength(b.segment) - segmentLength(a.segment);\n if (Math.abs(lengthDelta) > LABEL_EPSILON) {\n return lengthDelta;\n }\n return a.order - b.order;\n });\n\n let labelCenter: Point | null = null;\n for (const segmentCandidate of segments) {\n labelCenter = placementOnExistingSegment(\n edge,\n labelNode,\n segmentCandidate.segment,\n context\n );\n if (labelCenter) {\n break;\n }\n }\n\n if (!labelCenter) {\n for (const segmentCandidate of segments) {\n labelCenter = placementOnExistingSegmentWithReroutes(\n edge,\n labelNode,\n segmentCandidate.segment,\n context,\n placedLabelsByEdgeId\n );\n if (labelCenter) {\n break;\n }\n }\n }\n\n if (pass === 2 && !labelCenter) {\n for (const segmentCandidate of segments) {\n labelCenter = labelPlacementWithDetour(\n edge,\n labelNode,\n segmentCandidate,\n context,\n placedLabelsByEdgeId\n );\n if (labelCenter) {\n break;\n }\n }\n }\n\n if (pass === 2 && !labelCenter) {\n for (const segmentCandidate of segments) {\n labelCenter = labelPlacementWithExtendedDetour(\n edge,\n labelNode,\n segmentCandidate,\n context,\n placedLabelsByEdgeId\n );\n if (labelCenter) {\n break;\n }\n }\n }\n\n if (!labelCenter) {\n throw new LabelPlacementSearchExhaustedError({\n edgeId: edge.id,\n labelNodeId: labelNode.id,\n labelWidth: labelNode.width,\n labelHeight: labelNode.height,\n pointCount: edge.points?.length ?? 0,\n points: edge.points?.map((point) => ({ ...point })) ?? [],\n segments: segments.map(({ segment }) => ({\n orientation: segment.orientation,\n length: segmentLength(segment),\n a: { ...segment.a },\n b: { ...segment.b },\n })),\n });\n }\n\n labelNode.x = labelCenter.x;\n labelNode.y = labelCenter.y;\n const placedLabel: PlacedLabel = {\n edgeId: edge.id,\n nodeId: labelNode.id,\n center: labelCenter,\n rect: labelRectAt(labelNode, labelCenter),\n };\n placedLabelsByEdgeId.set(edge.id, placedLabel);\n upsertPlacedLabelObstacle(context, placedLabel);\n }\n\n // Once every label has a provisional home, freeze the complete reservation set before\n // rerouting. This prevents result order from changing which labels an edge must avoid.\n const frozenLabels = [...placedLabelsByEdgeId.values()];\n incrementMetric(instrumentation, 'frozenReservations', frozenLabels.length);\n if (routingInstrumentation) {\n routingInstrumentation.labelOverlayBuilds++;\n routingInstrumentation.labelOverlayVertices += frozenLabels.length * 4;\n }\n\n // The placement search is provisional: capture its route proposals, roll\n // the routes back to the pass boundary, and only then commit each\n // impacted edge once against the complete frozen reservation set.\n for (const edge of data.edges) {\n const passStart = passStartPoints.get(edge.id) ?? [];\n const proposed = pointsForEdge(edge, undefined, context);\n if (JSON.stringify(proposed) !== JSON.stringify(passStart)) {\n proposedOwnerRoutes.set(edge.id, proposed.map(clonePoint));\n }\n setEdgePoints(context, edge, passStart.map(clonePoint));\n }\n for (const [edgeId, points] of proposedOwnerRoutes) {\n if (!placedLabelsByEdgeId.has(edgeId)) {\n continue;\n }\n const owner = context.edgeById.get(edgeId);\n if (owner) {\n setEdgePoints(context, owner, points);\n }\n }\n\n const impacted = new Set<string>(proposedOwnerRoutes.keys());\n for (const edge of data.edges) {\n const ownLabel = placedLabelsByEdgeId.get(edge.id);\n const points = pointsForEdge(edge, undefined, context);\n for (const reservation of frozenLabels) {\n if (reservation.edgeId !== edge.id && polylineIntersectsRect(points, reservation.rect)) {\n impacted.add(edge.id);\n }\n }\n if (ownLabel && !labelStillAnchored(edge.id, points, placedLabelsByEdgeId)) {\n impacted.add(edge.id);\n }\n }\n\n const rerouteLaneOrdinals = new Map<string, number>();\n for (const edge of data.edges) {\n if (!impacted.has(edge.id)) {\n continue;\n }\n let points = pointsForEdge(edge, undefined, context);\n const overrides: EdgePointOverrides = new Map([[edge.id, points]]);\n const blockingReservations = frozenLabels.filter(\n (reservation) =>\n reservation.edgeId !== edge.id && polylineIntersectsRect(points, reservation.rect)\n );\n if (blockingReservations.length > 0) {\n const combinedRect = blockingReservations.slice(1).reduce<Rect>(\n (combined, reservation) => ({\n cx:\n (Math.min(combined.left, reservation.rect.left) +\n Math.max(combined.right, reservation.rect.right)) /\n 2,\n cy:\n (Math.min(combined.top, reservation.rect.top) +\n Math.max(combined.bottom, reservation.rect.bottom)) /\n 2,\n left: Math.min(combined.left, reservation.rect.left),\n right: Math.max(combined.right, reservation.rect.right),\n top: Math.min(combined.top, reservation.rect.top),\n bottom: Math.max(combined.bottom, reservation.rect.bottom),\n }),\n { ...blockingReservations[0].rect }\n );\n const lane = rerouteLane(points, combinedRect, blockingReservations);\n const rerouteOrdinal = lane ? (rerouteLaneOrdinals.get(lane.key) ?? 0) : 0;\n // Leave one full separation lane beyond the 6 px label clearance;\n // only routes avoiding the same reservation set on the same side share an ordinal.\n const lanePadding = (rerouteOrdinal + 2) * 12;\n const blockedRect: Rect = {\n cx: combinedRect.cx,\n cy: combinedRect.cy,\n left: combinedRect.left - lanePadding,\n right: combinedRect.right + lanePadding,\n top: combinedRect.top - lanePadding,\n bottom: combinedRect.bottom + lanePadding,\n };\n let rerouted = rerouteForeignEdgeAroundRect(\n edge,\n blockedRect,\n context,\n placedLabelsByEdgeId,\n overrides,\n lane ?? undefined\n );\n const usedScopedLane = rerouted !== null;\n rerouted ??= rerouteForeignEdgeAroundLabels(\n edge,\n blockingReservations,\n context,\n placedLabelsByEdgeId,\n overrides\n );\n if (rerouted) {\n points = rerouted;\n overrides.set(edge.id, points);\n if (lane && usedScopedLane) {\n rerouteLaneOrdinals.set(lane.key, rerouteOrdinal + 1);\n }\n } else {\n // Preserving a valid edge and anchored labels is safer than failing the whole layout.\n // Record the unavoidable overlap so final validation permits only this edge-label pair.\n incrementMetric(instrumentation, 'labelOverlapFallbacks');\n for (const reservation of blockingReservations) {\n if (!polylineIntersectsRect(points, reservation.rect)) {\n continue;\n }\n const allowedEdges =\n allowedOverlapsByLabelEdgeId.get(reservation.edgeId) ?? new Set<string>();\n if (!allowedEdges.has(edge.id)) {\n incrementMetric(instrumentation, 'labelOverlapReservations');\n }\n allowedEdges.add(edge.id);\n allowedOverlapsByLabelEdgeId.set(reservation.edgeId, allowedEdges);\n }\n }\n }\n if (!labelStillAnchored(edge.id, points, placedLabelsByEdgeId)) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Label anchor was lost for edge \"${edge.id}\"`, {\n edgeId: edge.id,\n pass,\n });\n }\n if (placedLabelsByEdgeId.has(edge.id)) {\n incrementMetric(instrumentation, 'preservedAnchors');\n }\n setEdgePoints(context, edge, points);\n incrementMetric(instrumentation, 'impactedEdgeReroutes');\n }\n for (const { edge, labelNode } of workItems) {\n const reservation = placedLabelsByEdgeId.get(edge.id);\n if (\n !reservation ||\n !labelStillAnchored(\n edge.id,\n pointsForEdge(edge, undefined, context),\n placedLabelsByEdgeId\n ) ||\n !rectSafeForLabel(\n reservation.rect,\n edge,\n labelNode.id,\n context,\n undefined,\n allowedOverlapsByLabelEdgeId.get(edge.id)\n )\n ) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Label pass ${pass} did not validate`, {\n edgeId: edge.id,\n pass,\n });\n }\n }\n return;\n } catch (error) {\n if (error instanceof LabelIndexWorkLimitError) {\n placeLabelsAtRouteMidpoints();\n incrementMetric(instrumentation, 'indexWorkLimitFallbacks');\n if (routingInstrumentation) {\n routingInstrumentation.resourceLimitFallbacks++;\n routingInstrumentation.fallbackReasons.label_index_work_cap++;\n }\n return;\n }\n if (!(error instanceof LabelPlacementSearchExhaustedError)) {\n restoreBaseState();\n incrementMetric(instrumentation, 'rollbacks');\n throw error;\n }\n placementFailures.push(error);\n // A failed pass may contain detours around provisional label positions. Restore routing\n // before retrying so the next pass depends only on the labels it successfully places.\n restoreBaseEdgePoints();\n for (const { labelNode } of workItems) {\n delete labelNode.x;\n delete labelNode.y;\n }\n }\n }\n\n placeLabelsAtRouteMidpoints();\n incrementMetric(instrumentation, 'placementSearchFallbacks');\n if (routingInstrumentation) {\n routingInstrumentation.fallbackReasons.label_placement_exhausted++;\n }\n log.warn(\n '[grid]',\n 'Label placement search exhausted; using route midpoints. Labels may overlap.',\n {\n reason: 'label_placement_exhausted',\n edgeIds: workItems.map(({ edge }) => edge.id),\n failures: placementFailures.map(({ details }) => details),\n }\n );\n}\n", "import type { Node } from '../../types.js';\nimport {\n ROOT_CONTAINER_ID,\n type GridContainerId,\n type GridForest,\n gridError,\n isEdgeLabelNode,\n} from './types.js';\n\n/*\n * Builds the containment model used by every later grid-layout phase.\n *\n * The returned forest excludes synthetic edge-label nodes from the geometry hierarchy, validates\n * every parent reference, and orders groups children-first so nested containers can be measured\n * before their parents.\n */\nfunction asGroup(node: Node): (Node & { isGroup: true }) | undefined {\n return node.isGroup ? (node as Node & { isGroup: true }) : undefined;\n}\n\nexport function buildGridForest(nodes: Node[]): GridForest {\n const nodeById = new Map<string, Node>();\n const groupById = new Map<string, Node & { isGroup: true }>();\n const helperNodeIds = new Set<string>();\n\n for (const node of nodes) {\n if (node.id === ROOT_CONTAINER_ID) {\n throw gridError(\n 'GRID_INVALID_CONTAINMENT',\n `Node id \"${ROOT_CONTAINER_ID}\" is reserved for the grid layout root`,\n { traversedIds: [node.id] }\n );\n }\n if (nodeById.has(node.id)) {\n throw gridError('GRID_INVALID_CONTAINMENT', `Duplicate node id \"${node.id}\"`, {\n traversedIds: [node.id],\n });\n }\n nodeById.set(node.id, node);\n if (isEdgeLabelNode(node)) {\n helperNodeIds.add(node.id);\n continue;\n }\n const group = asGroup(node);\n if (group) {\n groupById.set(group.id, group);\n }\n }\n\n const childrenByParent = new Map<GridContainerId, Node[]>();\n childrenByParent.set(ROOT_CONTAINER_ID, []);\n\n for (const node of nodes) {\n if (helperNodeIds.has(node.id)) {\n continue;\n }\n const parentId = node.parentId ?? ROOT_CONTAINER_ID;\n if (parentId !== ROOT_CONTAINER_ID) {\n const parent = groupById.get(parentId);\n if (!parent) {\n throw gridError(\n 'GRID_INVALID_CONTAINMENT',\n `Missing parent \"${parentId}\" for \"${node.id}\"`,\n {\n traversedIds: [node.id, parentId],\n }\n );\n }\n }\n if (!childrenByParent.has(parentId)) {\n childrenByParent.set(parentId, []);\n }\n childrenByParent.get(parentId)!.push(node);\n }\n\n const state = new Map<string, 0 | 1 | 2>();\n const postOrderGroups: (Node & { isGroup: true })[] = [];\n\n // Use an explicit stack rather than recursion so deeply nested diagrams do not consume the\n // JavaScript call stack. State 1 means \"on the active path\"; encountering it again is a cycle.\n interface VisitFrame {\n groupId: string;\n childGroups: (Node & { isGroup: true })[];\n nextChildIndex: number;\n }\n\n const directChildGroups = (groupId: string): (Node & { isGroup: true })[] =>\n (childrenByParent.get(groupId) ?? [])\n .map((child) => asGroup(child))\n .filter((group): group is Node & { isGroup: true } => group !== undefined);\n\n const visit = (startGroupId: string): void => {\n const currentState = state.get(startGroupId) ?? 0;\n if (currentState === 1) {\n throw gridError('GRID_INVALID_CONTAINMENT', `Containment cycle at \"${startGroupId}\"`, {\n traversedIds: [startGroupId],\n });\n }\n if (currentState === 2) {\n return;\n }\n\n state.set(startGroupId, 1);\n const stack: VisitFrame[] = [\n {\n groupId: startGroupId,\n childGroups: directChildGroups(startGroupId),\n nextChildIndex: 0,\n },\n ];\n\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n const child = frame.childGroups[frame.nextChildIndex];\n\n if (child) {\n frame.nextChildIndex += 1;\n const childState = state.get(child.id) ?? 0;\n if (childState === 1) {\n throw gridError('GRID_INVALID_CONTAINMENT', `Containment cycle at \"${child.id}\"`, {\n traversedIds: [...stack.map((item) => item.groupId), child.id],\n });\n }\n if (childState === 2) {\n continue;\n }\n\n state.set(child.id, 1);\n stack.push({\n groupId: child.id,\n childGroups: directChildGroups(child.id),\n nextChildIndex: 0,\n });\n continue;\n }\n\n stack.pop();\n state.set(frame.groupId, 2);\n const group = groupById.get(frame.groupId);\n if (group) {\n postOrderGroups.push(group);\n }\n }\n };\n\n for (const rootChild of childrenByParent.get(ROOT_CONTAINER_ID) ?? []) {\n const group = asGroup(rootChild);\n if (group) {\n visit(group.id);\n }\n }\n\n // Normally every group is reached from a root child. This second pass also validates malformed\n // disconnected components and produces a useful cycle error instead of silently dropping them.\n for (const groupId of groupById.keys()) {\n if ((state.get(groupId) ?? 0) === 0) {\n visit(groupId);\n }\n }\n\n return {\n nodeById,\n groupById,\n childrenByParent,\n rootChildren: childrenByParent.get(ROOT_CONTAINER_ID) ?? [],\n postOrderGroups,\n helperNodeIds,\n };\n}\n\nexport function isAncestorGroup(\n ancestorId: string,\n node: Node | undefined,\n nodeById: Map<string, Node>\n): boolean {\n let current = node;\n const seen = new Set<string>();\n // The forest builder already rejects cycles. The guard keeps this predicate safe when callers\n // provide a partially constructed or independently sourced node map.\n while (current?.parentId) {\n if (current.parentId === ancestorId) {\n return true;\n }\n if (seen.has(current.parentId)) {\n return false;\n }\n seen.add(current.parentId);\n current = nodeById.get(current.parentId);\n }\n return false;\n}\n", "import type { Edge, LayoutData, Node } from '../../types.js';\nimport { gridLabelSpanRequirement, type GridLabelSpanRequirement } from './labelGeometry.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type {\n GridCellStack,\n GridContainerId,\n GridForest,\n GridOrientation,\n GridResolvedPlacement,\n} from './types.js';\nimport { ROOT_CONTAINER_ID } from './types.js';\n\ninterface GridLabelledEdge {\n edge: Edge;\n labelNode: Node;\n}\n\nexport interface GridLabelRequirements {\n byContainer: Map<GridContainerId, GridLabelledEdge[]>;\n selfLoops: Map<string, GridLabelSpanRequirement>;\n}\n\nexport interface GridContainerLabelGaps {\n rowGapAfter: Map<number, number>;\n columnGapAfter: Map<number, number>;\n}\n\nexport function buildGridLabelRequirements(\n data: LayoutData,\n forest: GridForest,\n metrics?: GridRoutingInstrumentation\n): GridLabelRequirements {\n const byContainer = new Map<GridContainerId, GridLabelledEdge[]>();\n const selfLoops = new Map<string, GridLabelSpanRequirement>();\n\n for (const edge of data.edges) {\n if (!edge.start || !edge.end || !edge.labelNodeId) {\n continue;\n }\n if (metrics) {\n metrics.labelSpacingEdgesExamined++;\n }\n const labelNode = forest.nodeById.get(edge.labelNodeId);\n const source = forest.nodeById.get(edge.start);\n const target = forest.nodeById.get(edge.end);\n if (!labelNode || !source || !target) {\n continue;\n }\n if (edge.start === edge.end) {\n const horizontal = gridLabelSpanRequirement(labelNode, 'H');\n if (horizontal) {\n selfLoops.set(edge.id, horizontal);\n }\n continue;\n }\n const sourceContainer = source.parentId ?? ROOT_CONTAINER_ID;\n const targetContainer = target.parentId ?? ROOT_CONTAINER_ID;\n if (sourceContainer !== targetContainer) {\n continue;\n }\n const entries = byContainer.get(sourceContainer);\n if (entries) {\n entries.push({ edge, labelNode });\n } else {\n byContainer.set(sourceContainer, [{ edge, labelNode }]);\n }\n }\n\n return { byContainer, selfLoops };\n}\n\nfunction trackOrigins(\n tracks: readonly number[],\n sizes: ReadonlyMap<number, number>,\n gap: number\n): Map<number, number> {\n const origins = new Map<number, number>();\n let cursor = 0;\n for (const track of tracks) {\n origins.set(track, cursor);\n cursor += (sizes.get(track) ?? 0) + gap;\n }\n return origins;\n}\n\nfunction crossAxisFits(\n track: number,\n crossSize: number,\n tracks: readonly number[],\n sizes: ReadonlyMap<number, number>,\n gap: number\n): boolean {\n const origins = trackOrigins(tracks, sizes, gap);\n const origin = origins.get(track);\n const size = sizes.get(track);\n if (origin === undefined || size === undefined) {\n return false;\n }\n const center = origin + size / 2;\n const low = center - crossSize / 2;\n const high = center + crossSize / 2;\n return tracks.every((other) => {\n if (other === track) {\n return true;\n }\n const otherOrigin = origins.get(other)!;\n const otherEnd = otherOrigin + (sizes.get(other) ?? 0);\n return high <= otherOrigin || low >= otherEnd;\n });\n}\n\nfunction placementByNodeId(cells: ReadonlyMap<string, GridCellStack>) {\n const placements = new Map<string, GridResolvedPlacement>();\n for (const cell of cells.values()) {\n for (const placement of cell.items) {\n placements.set(placement.item.id, placement);\n }\n }\n return placements;\n}\n\nfunction areConsecutive(first: number, second: number, tracks: readonly number[]): boolean {\n const low = Math.min(first, second);\n const high = Math.max(first, second);\n const index = tracks.indexOf(low);\n return index >= 0 && tracks[index + 1] === high;\n}\n\nfunction addGapRequirement(gaps: Map<number, number>, track: number, required: number): void {\n gaps.set(track, Math.max(gaps.get(track) ?? 0, required));\n}\n\nexport function deriveGridContainerLabelGaps(\n entries: readonly GridLabelledEdge[],\n cells: ReadonlyMap<string, GridCellStack>,\n rowHeights: ReadonlyMap<number, number>,\n columnWidths: ReadonlyMap<number, number>,\n sortedRows: readonly number[],\n sortedColumns: readonly number[],\n configuredRowGap: number,\n configuredColumnGap: number,\n metrics?: GridRoutingInstrumentation\n): GridContainerLabelGaps {\n const rowGapAfter = new Map<number, number>();\n const columnGapAfter = new Map<number, number>();\n const placements = placementByNodeId(cells);\n\n const requirementFor = (\n entry: GridLabelledEdge,\n orientation: GridOrientation\n ): GridLabelSpanRequirement | null => gridLabelSpanRequirement(entry.labelNode, orientation);\n\n for (const entry of entries) {\n const source = entry.edge.start ? placements.get(entry.edge.start) : undefined;\n const target = entry.edge.end ? placements.get(entry.edge.end) : undefined;\n if (!source || !target) {\n continue;\n }\n if (source.row === target.row && areConsecutive(source.column, target.column, sortedColumns)) {\n const requirement = requirementFor(entry, 'H');\n if (\n requirement &&\n crossAxisFits(source.row, requirement.cross, sortedRows, rowHeights, configuredRowGap)\n ) {\n if (metrics) {\n metrics.labelSpacingEligibleEdges++;\n }\n addGapRequirement(\n columnGapAfter,\n Math.min(source.column, target.column),\n requirement.requiredAlongSpan\n );\n }\n continue;\n }\n if (source.column === target.column && areConsecutive(source.row, target.row, sortedRows)) {\n const requirement = requirementFor(entry, 'V');\n if (\n requirement &&\n crossAxisFits(\n source.column,\n requirement.cross,\n sortedColumns,\n columnWidths,\n configuredColumnGap\n )\n ) {\n if (metrics) {\n metrics.labelSpacingEligibleEdges++;\n }\n addGapRequirement(\n rowGapAfter,\n Math.min(source.row, target.row),\n requirement.requiredAlongSpan\n );\n }\n }\n }\n\n return { rowGapAfter, columnGapAfter };\n}\n", "import { log } from '../../../logger.js';\nimport type { GridPlacement } from '../../../types.js';\nimport {\n isGridHorizontalAlign,\n isGridVerticalAlign,\n validateGridCoordinate,\n} from '../../../utils/gridPlacement.js';\nimport { resolveEdgeCornerRadius } from '../../edgeCornerRadius.js';\nimport type { Node } from '../../types.js';\nimport { compareCodeUnits } from '../layout-utils/helpers.js';\nimport {\n GRID_DEFAULTS,\n type GridCurve,\n type GridLayoutConfigNormalized,\n type GridResolvedPlacement,\n type GridLayoutData,\n gridError,\n type GridCellStack,\n} from './types.js';\n\n/*\n * Normalizes placement input and deterministically assigns each direct child of a container to a\n * grid cell. Placement metadata on a node takes precedence over the container-level placement map.\n */\nconst GRID_LOG_PREFIX = '[grid]';\n// Grid accepts the same named curves as the shared edge renderer; rejecting unknown values here\n// keeps layout metadata serializable and leaves renderer fallback behavior unambiguous.\nconst GRID_CURVES = new Set<GridCurve>([\n 'basis',\n 'bumpX',\n 'bumpY',\n 'cardinal',\n 'catmullRom',\n 'linear',\n 'monotoneX',\n 'monotoneY',\n 'natural',\n 'step',\n 'stepAfter',\n 'stepBefore',\n 'rounded',\n]);\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction ownPlacementFrom(value: unknown): Partial<GridPlacement> {\n if (!isObjectRecord(value)) {\n return {};\n }\n const placement: Partial<GridPlacement> = {};\n if (Object.hasOwn(value, 'row')) {\n placement.row = value.row as number | undefined;\n }\n if (Object.hasOwn(value, 'column')) {\n placement.column = value.column as number | undefined;\n }\n if (isGridHorizontalAlign(value.horizontalAlign)) {\n placement.horizontalAlign = value.horizontalAlign;\n }\n if (isGridVerticalAlign(value.verticalAlign)) {\n placement.verticalAlign = value.verticalAlign;\n }\n return placement;\n}\n\nexport function buildGridSourceOrder(nodes: Node[]): Map<string, number> {\n const order = new Map<string, number>();\n let index = 0;\n for (const node of nodes) {\n if (!order.has(node.id)) {\n order.set(node.id, index++);\n }\n }\n return order;\n}\n\n/**\n * Normalizes public grid options, applying defaults to unsupported spacing and rendering values.\n * Placement objects become occurrence arrays; authored coordinates remain unchanged so\n * placement resolution can reject invalid values rather than silently moving nodes.\n */\nexport function readGridConfig(data: GridLayoutData): GridLayoutConfigNormalized {\n const raw = isObjectRecord(data.config?.grid) ? data.config.grid : {};\n const placementsRaw = isObjectRecord(raw.placements) ? raw.placements : {};\n const placements = new Map<string, GridPlacement[]>();\n for (const key of Object.keys(placementsRaw)) {\n const value = placementsRaw[key];\n const occurrencePlacements = Array.isArray(value) ? value : [value];\n placements.set(\n key,\n occurrencePlacements.map((placement) => ownPlacementFrom(placement))\n );\n }\n\n return {\n placements,\n columns:\n typeof raw.columns === 'number' && Number.isFinite(raw.columns) && raw.columns >= 0\n ? Math.trunc(raw.columns)\n : GRID_DEFAULTS.columns,\n rowGap:\n typeof raw.rowGap === 'number' && Number.isFinite(raw.rowGap) && raw.rowGap >= 0\n ? raw.rowGap\n : GRID_DEFAULTS.rowGap,\n columnGap:\n typeof raw.columnGap === 'number' && Number.isFinite(raw.columnGap) && raw.columnGap >= 0\n ? raw.columnGap\n : GRID_DEFAULTS.columnGap,\n cellGap:\n typeof raw.cellGap === 'number' && Number.isFinite(raw.cellGap) && raw.cellGap >= 0\n ? raw.cellGap\n : GRID_DEFAULTS.cellGap,\n containerPadding:\n typeof raw.containerPadding === 'number' &&\n Number.isFinite(raw.containerPadding) &&\n raw.containerPadding >= 0\n ? raw.containerPadding\n : GRID_DEFAULTS.containerPadding,\n titleGap:\n typeof raw.titleGap === 'number' && Number.isFinite(raw.titleGap) && raw.titleGap >= 0\n ? raw.titleGap\n : GRID_DEFAULTS.titleGap,\n horizontalAlign: isGridHorizontalAlign(raw.horizontalAlign)\n ? raw.horizontalAlign\n : GRID_DEFAULTS.horizontalAlign,\n verticalAlign: isGridVerticalAlign(raw.verticalAlign)\n ? raw.verticalAlign\n : GRID_DEFAULTS.verticalAlign,\n // Normalize rendering options with placement so every routed edge receives one stable style.\n curve:\n typeof raw.curve === 'string' && GRID_CURVES.has(raw.curve as GridCurve)\n ? (raw.curve as GridCurve)\n : GRID_DEFAULTS.curve,\n edgeCornerRadius: resolveEdgeCornerRadius(raw.edgeCornerRadius),\n };\n}\n\n/**\n * Warns about unknown placement targets and entries exceeding the number of matching nodes.\n * Matches authored placement IDs when available, otherwise emitted IDs; does not mutate the map.\n */\nexport function validateGridPlacementMap(\n items: Iterable<Node>,\n config: GridLayoutConfigNormalized\n): void {\n // Diagram adapters may retain a generated rendering ID while exposing the authored ID expected\n // by public placement maps. Fall back to `id` for diagrams whose IDs are already author-stable.\n const knownIdCounts = new Map<string, number>();\n for (const item of items) {\n const placementId = item.placementId ?? item.id;\n knownIdCounts.set(placementId, (knownIdCounts.get(placementId) ?? 0) + 1);\n }\n for (const [key, placements] of config.placements) {\n const matchingItems = knownIdCounts.get(key) ?? 0;\n if (matchingItems === 0) {\n log.warn(GRID_LOG_PREFIX, `Ignoring grid placement for unknown target \"${key}\"`);\n continue;\n }\n if (placements.length > matchingItems) {\n log.warn(\n GRID_LOG_PREFIX,\n `Ignoring ${placements.length - matchingItems} extra grid placement occurrence(s) for target \"${key}\"; found ${matchingItems} matching node(s)`\n );\n }\n }\n}\n\nfunction itemComparator(sourceOrder: Map<string, number>) {\n return (a: Node, b: Node): number => {\n const aOrder = sourceOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;\n const bOrder = sourceOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;\n if (aOrder !== bOrder) {\n return aOrder - bOrder;\n }\n return compareCodeUnits(a.id, b.id);\n };\n}\n\n/**\n * Resolves one authored-ID occurrence, with inline metadata overriding placement-map fields.\n * Validates coordinates before supplying placeholders for axes left to automatic placement.\n */\nfunction resolveItemPlacement(\n item: Node,\n sourceOrder: Map<string, number>,\n config: GridLayoutConfigNormalized,\n occurrenceIndex: number\n): GridResolvedPlacement {\n // Resolve configuration through the authored identity while retaining the generated rendering\n // identity for deterministic ordering and diagnostic context.\n const authoredPlacementId = item.placementId ?? item.id;\n const configPlacement = config.placements.get(authoredPlacementId)?.[occurrenceIndex] ?? {};\n const metadataPlacement = ownPlacementFrom(item.metadata);\n\n // Node metadata is closest to the authored node, so it deliberately wins over the shared map.\n // Log disagreements to make an otherwise valid but surprising layout diagnosable.\n for (const field of ['row', 'column', 'horizontalAlign', 'verticalAlign'] as const) {\n if (\n Object.hasOwn(configPlacement, field) &&\n Object.hasOwn(metadataPlacement, field) &&\n configPlacement[field] !== metadataPlacement[field]\n ) {\n log.debug(GRID_LOG_PREFIX, 'metadata overrides placement map', {\n nodeId: item.id,\n field,\n metadata: metadataPlacement[field],\n config: configPlacement[field],\n });\n }\n }\n\n const row = Object.hasOwn(metadataPlacement, 'row') ? metadataPlacement.row : configPlacement.row;\n const column = Object.hasOwn(metadataPlacement, 'column')\n ? metadataPlacement.column\n : configPlacement.column;\n validateGridCoordinate(authoredPlacementId, 'row', row, item.id);\n validateGridCoordinate(authoredPlacementId, 'column', column, item.id);\n\n return {\n item,\n row: row ?? 0,\n column: column ?? 0,\n horizontalAlign:\n metadataPlacement.horizontalAlign ??\n configPlacement.horizontalAlign ??\n config.horizontalAlign,\n verticalAlign:\n metadataPlacement.verticalAlign ?? configPlacement.verticalAlign ?? config.verticalAlign,\n sourceOrder: sourceOrder.get(item.id) ?? Number.MAX_SAFE_INTEGER,\n explicitRow: row !== undefined,\n explicitColumn: column !== undefined,\n explicitCell: row !== undefined && column !== undefined,\n };\n}\n\nfunction nextFreeColumn(row: number, occupied: Set<string>, startColumn: number): number {\n let column = startColumn;\n while (occupied.has(`${row}:${column}`)) {\n column++;\n }\n return column;\n}\n\nfunction nextFreeRow(column: number, occupied: Set<string>, startRow: number): number {\n let row = startRow;\n while (occupied.has(`${row}:${column}`)) {\n row++;\n }\n return row;\n}\n\nfunction nextAutoCell(\n occupied: Set<string>,\n candidateColumns: number,\n startIndex: number\n): {\n row: number;\n column: number;\n nextIndex: number;\n} {\n let index = startIndex;\n // The occupied set is finite while the row-major coordinate space is unbounded, so a free cell\n // must eventually be found.\n for (;;) {\n const row = Math.floor(index / candidateColumns) + 1;\n const column = (index % candidateColumns) + 1;\n index++;\n if (!occupied.has(`${row}:${column}`)) {\n return { row, column, nextIndex: index };\n }\n }\n}\n\n/**\n * Assigns sibling nodes to cells in source order, reserving explicit cells before auto-placement.\n * Repeated authored IDs consume successive map entries. Explicit cell occupants form stacks,\n * but conflicting vertical alignments throw `GRID_CELL_ALIGNMENT_CONFLICT`.\n */\nexport function resolveGridPlacements(\n items: Node[],\n sourceOrder: Map<string, number>,\n config: GridLayoutConfigNormalized\n): {\n placements: GridResolvedPlacement[];\n cells: Map<string, GridCellStack>;\n} {\n const sortedItems = [...items].sort(itemComparator(sourceOrder));\n const occurrenceByPlacementId = new Map<string, number>();\n const resolved = sortedItems.map((item) => {\n const placementId = item.placementId ?? item.id;\n const occurrenceIndex = occurrenceByPlacementId.get(placementId) ?? 0;\n occurrenceByPlacementId.set(placementId, occurrenceIndex + 1);\n return resolveItemPlacement(item, sourceOrder, config, occurrenceIndex);\n });\n\n const cells = new Map<string, GridCellStack>();\n const occupied = new Set<string>();\n\n // Reserve fully specified cells first. Auto-placement must route around authored coordinates\n // regardless of source order, while multiple explicit occupants intentionally form a stack.\n for (const placement of resolved) {\n if (!placement.explicitCell) {\n continue;\n }\n const key = `${placement.row}:${placement.column}`;\n occupied.add(key);\n const existing = cells.get(key);\n if (existing) {\n if (existing.verticalAlign !== placement.verticalAlign) {\n throw gridError(\n 'GRID_CELL_ALIGNMENT_CONFLICT',\n `Conflicting vertical alignment in cell (${placement.row}, ${placement.column})`,\n {\n containerId: placement.item.parentId ?? 'root',\n row: placement.row,\n column: placement.column,\n itemIds: [...existing.items.map((item) => item.item.id), placement.item.id],\n values: [...existing.items.map((item) => item.verticalAlign), placement.verticalAlign],\n }\n );\n }\n existing.items.push(placement);\n } else {\n cells.set(key, {\n row: placement.row,\n column: placement.column,\n items: [placement],\n width: 0,\n height: 0,\n verticalAlign: placement.verticalAlign,\n });\n }\n }\n\n const candidateColumns =\n config.columns > 0 ? config.columns : Math.max(1, Math.ceil(Math.sqrt(sortedItems.length)));\n let nextAutoIndex = 0;\n const nextColumnByRow = new Map<number, number>();\n const nextRowByColumn = new Map<number, number>();\n\n // Partially specified placements scan only their missing axis. Fully automatic placements use a\n // compact row-major grid whose default width keeps roughly square diagrams. Each cursor only\n // moves forward because occupied cells are never released.\n for (const placement of resolved) {\n if (placement.explicitCell) {\n continue;\n }\n\n if (placement.explicitRow) {\n const column = nextFreeColumn(\n placement.row,\n occupied,\n nextColumnByRow.get(placement.row) ?? 1\n );\n placement.column = column;\n nextColumnByRow.set(placement.row, column + 1);\n } else if (placement.explicitColumn) {\n const row = nextFreeRow(\n placement.column,\n occupied,\n nextRowByColumn.get(placement.column) ?? 1\n );\n placement.row = row;\n nextRowByColumn.set(placement.column, row + 1);\n } else {\n const next = nextAutoCell(occupied, candidateColumns, nextAutoIndex);\n placement.row = next.row;\n placement.column = next.column;\n nextAutoIndex = next.nextIndex;\n }\n\n const key = `${placement.row}:${placement.column}`;\n occupied.add(key);\n cells.set(key, {\n row: placement.row,\n column: placement.column,\n items: [placement],\n width: 0,\n height: 0,\n verticalAlign: placement.verticalAlign,\n });\n }\n\n return { placements: resolved, cells };\n}\n", "import type { GridRoutingFallbackReason } from './routerInstrumentation.js';\n\nexport class GridRoutingResourceLimitError extends Error {\n constructor(\n public readonly reason: GridRoutingFallbackReason,\n message: string,\n public readonly searchStateScope?: 'edge' | 'invocation'\n ) {\n super(message);\n this.name = 'GridRoutingResourceLimitError';\n }\n}\n", "import { compareCodeUnits } from '../layout-utils/helpers.js';\nimport { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type {\n ContainerRoutingTopology,\n GridOrientation,\n GridSide,\n OrthogonalIntervalIndex,\n PairedPortal,\n PortalRange,\n RouterArc,\n RouterObstacle,\n RouterPoint,\n RouterRect,\n RouterSearchArc,\n RouterVertex,\n} from './types.js';\n\n// Builds immutable orthogonal visibility graphs per container. Endpoint-specific vertices are added\n// through bounded overlays so the expensive obstacle sweep is paid once per container.\nexport const ROUTE_CLEARANCE_PX = 6;\n\n/**\n * Parallel runs of different edges closer than this are hard to tell apart, so candidates avoid them.\n * Perpendicular crossings are not affected. Lives here (rather than routerOccupancy.ts) because it is\n * shared with routerPlanning.ts and routerConstraint.ts already imports from this module.\n */\nexport const EDGE_CLEARANCE_PX = 24;\n\n// Caps bound both adversarial geometry and ordinary large-diagram memory growth. Exceeding one is a\n// recoverable routing condition handled by the validated compatibility path.\nconst DEFAULT_MAX_VERTICES = 50_000;\nconst MAX_VISIBILITY_ADJACENCY_PER_VERTEX = 4;\nexport const DEFAULT_MAX_ROUTING_ESTIMATED_BYTES = 64 * 1024 * 1024;\n\nexport interface RouterObstacleInput {\n id: string;\n bounds: RouterRect;\n}\n\nexport interface ContainerTopologyInput {\n containerId: string;\n bounds: RouterRect;\n obstacles: readonly RouterObstacleInput[];\n titleExclusions?: readonly RouterObstacleInput[];\n portalRanges?: readonly PortalRange[];\n}\n\nexport interface TopologyResourceCaps {\n maxVertices?: number;\n maxAdjacencyEntries?: number;\n maxEstimatedBytes?: number;\n}\n\nexport interface BuildTopologyOptions {\n metrics?: GridRoutingInstrumentation;\n caps?: TopologyResourceCaps;\n}\n\ninterface VertexRecord {\n point: RouterPoint;\n kind: RouterVertex['kind'];\n ownerId?: string;\n side?: GridSide;\n}\n\ninterface IndexedBand {\n low: number;\n high: number;\n intervals: readonly (readonly [number, number])[];\n}\n\nclass CompressedIntervalIndex implements OrthogonalIntervalIndex {\n // Obstacle occupancy is constant between sorted boundaries, so bands share merged interval lists.\n // Exact boundaries use strict intervals to allow visibility paths to run along obstacle edges.\n readonly coordinateCount: number;\n readonly intervalCount: number;\n private readonly byLow = new Map<number, IndexedBand>();\n private readonly byHigh = new Map<number, IndexedBand>();\n\n constructor(\n private readonly bands: readonly IndexedBand[],\n private readonly strictBoundaryIntervals: ReadonlyMap<\n number,\n readonly (readonly [number, number])[]\n >\n ) {\n this.coordinateCount = new Set(bands.flatMap(({ low, high }) => [low, high])).size;\n let intervalCount = bands.reduce((total, band) => total + band.intervals.length, 0);\n for (const intervals of strictBoundaryIntervals.values()) {\n intervalCount += intervals.length;\n }\n this.intervalCount = intervalCount;\n for (const band of bands) {\n this.byLow.set(band.low, band);\n this.byHigh.set(band.high, band);\n }\n Object.freeze(this.bands);\n Object.freeze(this);\n }\n\n private containingBand(coordinate: number): IndexedBand | undefined {\n let low = 0;\n let high = this.bands.length - 1;\n while (low <= high) {\n const middle = (low + high) >>> 1;\n const band = this.bands[middle];\n if (coordinate <= band.low) {\n high = middle - 1;\n } else if (coordinate >= band.high) {\n low = middle + 1;\n } else {\n return band;\n }\n }\n return undefined;\n }\n\n private overlaps(\n intervals: readonly (readonly [number, number])[],\n low: number,\n high: number\n ): boolean {\n let left = 0;\n let right = intervals.length;\n while (left < right) {\n const middle = (left + right) >>> 1;\n if (intervals[middle][1] <= low) {\n left = middle + 1;\n } else {\n right = middle;\n }\n }\n return left < intervals.length && intervals[left][0] < high;\n }\n\n intersects(coordinate: number, intervalStart: number, intervalEnd: number): boolean {\n const low = Math.min(intervalStart, intervalEnd);\n const high = Math.max(intervalStart, intervalEnd);\n const before = this.byHigh.get(coordinate);\n const after = this.byLow.get(coordinate);\n const containing = before || after ? undefined : this.containingBand(coordinate);\n if (containing) {\n return this.overlaps(containing.intervals, low, high);\n }\n if (!before || !after) {\n return false;\n }\n let beforeIndex = 0;\n let afterIndex = 0;\n while (beforeIndex < before.intervals.length && afterIndex < after.intervals.length) {\n const overlapLow = Math.max(\n low,\n before.intervals[beforeIndex][0],\n after.intervals[afterIndex][0]\n );\n const overlapHigh = Math.min(\n high,\n before.intervals[beforeIndex][1],\n after.intervals[afterIndex][1]\n );\n if (overlapLow < overlapHigh) {\n return true;\n }\n if (before.intervals[beforeIndex][1] < after.intervals[afterIndex][1]) {\n beforeIndex++;\n } else {\n afterIndex++;\n }\n }\n return false;\n }\n\n contains(coordinate: number, varying: number): boolean {\n const intervals =\n this.strictBoundaryIntervals.get(coordinate) ?? this.containingBand(coordinate)?.intervals;\n if (!intervals) {\n return false;\n }\n let low = 0;\n let high = intervals.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (intervals[middle][0] < varying) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return low > 0 && varying < intervals[low - 1][1];\n }\n\n nearestBoundary(coordinate: number, origin: number, direction: -1 | 1): number | undefined {\n const intervals =\n this.strictBoundaryIntervals.get(coordinate) ?? this.containingBand(coordinate)?.intervals;\n if (!intervals) {\n return undefined;\n }\n if (direction < 0) {\n let low = 0;\n let high = intervals.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (intervals[middle][1] <= origin) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return low > 0 ? intervals[low - 1][1] : undefined;\n }\n let low = 0;\n let high = intervals.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (intervals[middle][0] < origin) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return low < intervals.length ? intervals[low][0] : undefined;\n }\n}\n\nclass ImmutableMap<K, V> implements ReadonlyMap<K, V> {\n readonly [Symbol.toStringTag] = 'ImmutableMap';\n\n constructor(private readonly backing: ReadonlyMap<K, V>) {\n Object.freeze(this);\n }\n\n get size(): number {\n return this.backing.size;\n }\n\n entries(): MapIterator<[K, V]> {\n return this.backing.entries();\n }\n\n forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: unknown): void {\n for (const [key, value] of this.backing) {\n callbackfn.call(thisArg, value, key, this);\n }\n }\n\n get(key: K): V | undefined {\n return this.backing.get(key);\n }\n\n has(key: K): boolean {\n return this.backing.has(key);\n }\n\n keys(): MapIterator<K> {\n return this.backing.keys();\n }\n\n values(): MapIterator<V> {\n return this.backing.values();\n }\n\n [Symbol.iterator](): MapIterator<[K, V]> {\n return this.entries();\n }\n}\n\nclass OverlayMap<K, V> implements ReadonlyMap<K, V> {\n readonly [Symbol.toStringTag] = 'OverlayMap';\n\n constructor(\n private readonly base: ReadonlyMap<K, V>,\n private readonly overrides: ReadonlyMap<K, V>\n ) {}\n\n get size(): number {\n let added = 0;\n for (const key of this.overrides.keys()) {\n if (!this.base.has(key)) {\n added++;\n }\n }\n return this.base.size + added;\n }\n\n private materialize(): Map<K, V> {\n return new Map([...this.base, ...this.overrides]);\n }\n\n entries(): MapIterator<[K, V]> {\n return this.materialize().entries();\n }\n\n forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: unknown): void {\n for (const [key, value] of this) {\n callbackfn.call(thisArg, value, key, this);\n }\n }\n\n get(key: K): V | undefined {\n return this.overrides.get(key) ?? this.base.get(key);\n }\n\n has(key: K): boolean {\n return this.overrides.has(key) || this.base.has(key);\n }\n\n keys(): MapIterator<K> {\n return this.materialize().keys();\n }\n\n values(): MapIterator<V> {\n return this.materialize().values();\n }\n\n [Symbol.iterator](): MapIterator<[K, V]> {\n return this.entries();\n }\n}\n\nfunction overlayArray<T>(base: readonly T[], additions: readonly T[]): readonly T[] {\n // Numeric access and iteration are enough for search. A proxy avoids copying the immutable base\n // array for every endpoint pair.\n return new Proxy([] as T[], {\n get(_target, property) {\n if (property === 'length') {\n return base.length + additions.length;\n }\n if (property === Symbol.iterator) {\n return function* () {\n yield* base;\n yield* additions;\n };\n }\n if (typeof property === 'string' && /^\\d+$/.test(property)) {\n const index = Number(property);\n return index < base.length ? base[index] : additions[index - base.length];\n }\n return Reflect.get(Array.prototype, property);\n },\n });\n}\n\nfunction overrideArray<T>(\n base: readonly T[],\n overrides: ReadonlyMap<number, T>,\n length: number\n): readonly T[] {\n return new Proxy([] as T[], {\n get(_target, property) {\n if (property === 'length') {\n return length;\n }\n if (property === Symbol.iterator) {\n return function* () {\n for (let index = 0; index < length; index++) {\n yield overrides.get(index) ?? base[index];\n }\n };\n }\n if (typeof property === 'string' && /^\\d+$/.test(property)) {\n const index = Number(property);\n return overrides.get(index) ?? base[index];\n }\n return Reflect.get(Array.prototype, property);\n },\n });\n}\n\nexport class EndpointOverlayScratch {\n // One scratch object belongs to one base topology. The undo log clears only overridden base\n // vertices, keeping reset cost proportional to the previous overlay rather than the whole graph.\n readonly addedVertices: RouterVertex[] = [];\n readonly adjacencyOverrides = new Map<number, readonly RouterArc[]>();\n readonly searchAdjacencyOverrides = new Map<number, readonly RouterSearchArc[]>();\n readonly pointOverrides = new Map<string, number>();\n readonly undoLog: number[] = [];\n resetCount = 0;\n\n constructor(readonly base: ContainerRoutingTopology) {}\n\n reset(base: ContainerRoutingTopology): void {\n if (base !== this.base) {\n throw new Error('Endpoint overlay scratch cannot be shared across base topologies');\n }\n for (const id of this.undoLog) {\n this.adjacencyOverrides.delete(id);\n this.searchAdjacencyOverrides.delete(id);\n }\n this.undoLog.length = 0;\n this.addedVertices.length = 0;\n this.pointOverrides.clear();\n this.resetCount++;\n }\n\n setArcs(id: number, arcs: readonly RouterArc[]): void {\n if (!this.adjacencyOverrides.has(id)) {\n this.undoLog.push(id);\n }\n this.adjacencyOverrides.set(id, arcs);\n this.searchAdjacencyOverrides.set(id, searchArcs(arcs));\n }\n}\n\nfunction normalizeCoordinate(value: number): number {\n return Object.is(value, -0) ? 0 : value;\n}\n\nfunction normalizeRect(rect: RouterRect): RouterRect {\n const values = [rect.left, rect.right, rect.top, rect.bottom];\n if (!values.every(Number.isFinite)) {\n throw new Error('Grid routing geometry must contain only finite coordinates');\n }\n const left = normalizeCoordinate(Math.min(rect.left, rect.right));\n const right = normalizeCoordinate(Math.max(rect.left, rect.right));\n const top = normalizeCoordinate(Math.min(rect.top, rect.bottom));\n const bottom = normalizeCoordinate(Math.max(rect.top, rect.bottom));\n if (left === right || top === bottom) {\n // The production layout path should reject zero-area nodes before routing; this guards direct\n // topology callers and invalid derived geometry.\n throw new Error('Grid routing rectangles must have positive area');\n }\n return { left, right, top, bottom };\n}\n\nfunction inflateAndClip(\n input: RouterObstacleInput,\n domain: RouterRect\n): RouterObstacle | undefined {\n const bounds = normalizeRect(input.bounds);\n const obstacle = {\n id: input.id,\n left: Math.max(domain.left, bounds.left - ROUTE_CLEARANCE_PX),\n right: Math.min(domain.right, bounds.right + ROUTE_CLEARANCE_PX),\n top: Math.max(domain.top, bounds.top - ROUTE_CLEARANCE_PX),\n bottom: Math.min(domain.bottom, bounds.bottom + ROUTE_CLEARANCE_PX),\n };\n return obstacle.left < obstacle.right && obstacle.top < obstacle.bottom ? obstacle : undefined;\n}\n\nfunction mergeObstacleIntervals(\n intervals: { low: number; high: number; id: string }[]\n): { low: number; high: number; id: string }[] {\n const sorted = [...intervals].sort(\n (a, b) => a.low - b.low || a.high - b.high || compareCodeUnits(a.id, b.id)\n );\n const merged: { low: number; high: number; id: string }[] = [];\n for (const interval of sorted) {\n const previous = merged.at(-1);\n if (!previous || interval.low > previous.high) {\n merged.push({ ...interval });\n continue;\n }\n previous.high = Math.max(previous.high, interval.high);\n if (compareCodeUnits(interval.id, previous.id) < 0) {\n previous.id = interval.id;\n }\n }\n return merged;\n}\n\nfunction unionObstacles(obstacles: readonly RouterObstacle[]): RouterObstacle[] {\n // Sweep x-slabs and merge active y-intervals into a non-overlapping obstacle union. This prevents\n // intersecting inflated nodes and title exclusions from multiplying visibility vertices.\n const events = new Map<number, { starts: RouterObstacle[]; ends: RouterObstacle[] }>();\n for (const obstacle of obstacles) {\n const start = events.get(obstacle.left) ?? { starts: [], ends: [] };\n start.starts.push(obstacle);\n events.set(obstacle.left, start);\n const end = events.get(obstacle.right) ?? { starts: [], ends: [] };\n end.ends.push(obstacle);\n events.set(obstacle.right, end);\n }\n const xCoordinates = [...events.keys()].sort((a, b) => a - b);\n const active = new Set<RouterObstacle>();\n const slabs: RouterObstacle[] = [];\n let previousByInterval = new Map<string, RouterObstacle>();\n for (let index = 0; index < xCoordinates.length - 1; index++) {\n const left = xCoordinates[index];\n const right = xCoordinates[index + 1];\n const event = events.get(left)!;\n for (const obstacle of event.ends) {\n active.delete(obstacle);\n }\n for (const obstacle of event.starts) {\n active.add(obstacle);\n }\n const nextByInterval = new Map<string, RouterObstacle>();\n for (const interval of mergeObstacleIntervals(\n [...active].map((obstacle) => ({\n low: obstacle.top,\n high: obstacle.bottom,\n id: obstacle.id,\n }))\n )) {\n const key = `${interval.low}:${interval.high}`;\n const previous = previousByInterval.get(key);\n if (previous) {\n previous.right = right;\n if (compareCodeUnits(interval.id, previous.id) < 0) {\n previous.id = interval.id;\n }\n } else {\n const slab = {\n id: interval.id,\n left,\n right,\n top: interval.low,\n bottom: interval.high,\n };\n slabs.push(slab);\n nextByInterval.set(key, slab);\n continue;\n }\n nextByInterval.set(key, previous);\n }\n previousByInterval = nextByInterval;\n }\n return slabs.sort(\n (a, b) =>\n a.top - b.top ||\n a.left - b.left ||\n a.bottom - b.bottom ||\n a.right - b.right ||\n compareCodeUnits(a.id, b.id)\n );\n}\n\nexport function routingPointKey(point: RouterPoint): string {\n return `${normalizeCoordinate(point.x)}:${normalizeCoordinate(point.y)}`;\n}\n\nfunction topologySideOrdinal(side?: GridSide): number {\n return side === 'left'\n ? 0\n : side === 'right'\n ? 1\n : side === 'top'\n ? 2\n : side === 'bottom'\n ? 3\n : 4;\n}\n\nfunction vertexRecordOrder(a: VertexRecord, b: VertexRecord): number {\n return (\n compareCodeUnits(a.kind, b.kind) ||\n topologySideOrdinal(a.side) - topologySideOrdinal(b.side) ||\n a.point.x - b.point.x ||\n a.point.y - b.point.y ||\n compareCodeUnits(a.ownerId ?? '', b.ownerId ?? '')\n );\n}\n\nfunction canonicalRecords(records: readonly VertexRecord[]): VertexRecord[] {\n // Sorting before duplicate removal makes vertex identity and numeric ids independent of discovery\n // order.\n const byPoint = new Map<string, VertexRecord>();\n for (const record of [...records].sort(vertexRecordOrder)) {\n const normalized = {\n ...record,\n point: {\n x: normalizeCoordinate(record.point.x),\n y: normalizeCoordinate(record.point.y),\n },\n };\n const key = routingPointKey(normalized.point);\n if (!byPoint.has(key)) {\n byPoint.set(key, normalized);\n }\n }\n return [...byPoint.values()];\n}\n\nfunction cornerRecords(\n bounds: RouterRect,\n ownerId: string,\n kind: RouterVertex['kind'] = 'corner'\n): VertexRecord[] {\n return [\n { point: { x: bounds.left, y: bounds.top }, kind, ownerId },\n { point: { x: bounds.right, y: bounds.top }, kind, ownerId },\n { point: { x: bounds.left, y: bounds.bottom }, kind, ownerId },\n { point: { x: bounds.right, y: bounds.bottom }, kind, ownerId },\n ];\n}\n\nfunction portalRecords(range: PortalRange, bounds: RouterRect): VertexRecord[] {\n const coordinate =\n range.coordinate ??\n (range.side === 'left'\n ? bounds.left\n : range.side === 'right'\n ? bounds.right\n : range.side === 'top'\n ? bounds.top\n : bounds.bottom);\n const points =\n range.side === 'left' || range.side === 'right'\n ? [\n { x: coordinate, y: range.low },\n { x: coordinate, y: range.high },\n ]\n : [\n { x: range.low, y: coordinate },\n { x: range.high, y: coordinate },\n ];\n return points.map((value) => ({\n point: value,\n kind: 'portal',\n ownerId: range.ownerId,\n side: range.side,\n }));\n}\n\nfunction rayHit(\n point: RouterPoint,\n side: GridSide,\n bounds: RouterRect,\n horizontalIntervals: OrthogonalIntervalIndex,\n verticalIntervals: OrthogonalIntervalIndex\n): RouterPoint {\n if (side === 'left' || side === 'right') {\n const hit =\n horizontalIntervals.nearestBoundary(point.y, point.x, side === 'left' ? -1 : 1) ??\n (side === 'left' ? bounds.left : bounds.right);\n return { x: hit, y: point.y };\n }\n\n const hit =\n verticalIntervals.nearestBoundary(point.x, point.y, side === 'top' ? -1 : 1) ??\n (side === 'top' ? bounds.top : bounds.bottom);\n return { x: point.x, y: hit };\n}\n\nfunction createIntervalIndex(\n obstacles: readonly RouterObstacle[],\n orientation: GridOrientation,\n budget: { intervalCount: number; maxEstimatedBytes: number }\n): OrthogonalIntervalIndex {\n const coordinates = [\n ...new Set(\n obstacles.flatMap((obstacle) =>\n orientation === 'H' ? [obstacle.top, obstacle.bottom] : [obstacle.left, obstacle.right]\n )\n ),\n ].sort((a, b) => a - b);\n const bands: IndexedBand[] = [];\n const strictBoundaryIntervals = new Map<number, readonly (readonly [number, number])[]>();\n const starts = new Map<number, RouterObstacle[]>();\n const ends = new Map<number, RouterObstacle[]>();\n for (const obstacle of obstacles) {\n const start = orientation === 'H' ? obstacle.top : obstacle.left;\n const end = orientation === 'H' ? obstacle.bottom : obstacle.right;\n const startEvents = starts.get(start) ?? [];\n startEvents.push(obstacle);\n starts.set(start, startEvents);\n const endEvents = ends.get(end) ?? [];\n endEvents.push(obstacle);\n ends.set(end, endEvents);\n }\n const active = new Set<RouterObstacle>();\n const activeIntervals = () =>\n mergeObstacleIntervals(\n [...active].map((obstacle) =>\n orientation === 'H'\n ? { low: obstacle.left, high: obstacle.right, id: obstacle.id }\n : { low: obstacle.top, high: obstacle.bottom, id: obstacle.id }\n )\n );\n const freezeIntervals = (\n intervals: readonly { low: number; high: number }[]\n ): readonly (readonly [number, number])[] => {\n const intervalCount = budget.intervalCount + intervals.length;\n enforceCap(\n estimatedTopologyBytes(0, 0, obstacles.length, intervalCount),\n budget.maxEstimatedBytes,\n 'estimated_memory_cap'\n );\n budget.intervalCount = intervalCount;\n return Object.freeze(\n intervals.map((interval) => Object.freeze([interval.low, interval.high] as const))\n );\n };\n for (let index = 0; index < coordinates.length; index++) {\n const coordinate = coordinates[index];\n for (const obstacle of ends.get(coordinate) ?? []) {\n active.delete(obstacle);\n }\n strictBoundaryIntervals.set(coordinate, freezeIntervals(activeIntervals()));\n for (const obstacle of starts.get(coordinate) ?? []) {\n active.add(obstacle);\n }\n const high = coordinates[index + 1];\n if (high === undefined) {\n continue;\n }\n const intervals = activeIntervals();\n if (intervals.length > 0) {\n bands.push({\n low: coordinate,\n high,\n intervals: freezeIntervals(intervals),\n });\n }\n }\n return new CompressedIntervalIndex(\n Object.freeze(bands),\n new ImmutableMap(strictBoundaryIntervals)\n );\n}\n\nfunction estimatedTopologyBytes(\n vertices: number,\n adjacencyEntries: number,\n obstacles: number,\n intervals: number\n): number {\n return vertices * 64 + adjacencyEntries * 56 + obstacles * 48 + intervals * 24;\n}\n\nfunction enforceCap(\n actual: number,\n maximum: number,\n reason: 'vertex_cap' | 'adjacency_cap' | 'estimated_memory_cap'\n): void {\n if (actual > maximum) {\n throw new GridRoutingResourceLimitError(\n reason,\n `Grid routing ${reason} exceeded: ${actual} > ${maximum}`\n );\n }\n}\n\nfunction indexVertexLines(\n vertices: readonly RouterVertex[],\n orientation: GridOrientation\n): ReadonlyMap<number, readonly RouterVertex[]> {\n const lines = new Map<number, RouterVertex[]>();\n for (const vertex of vertices) {\n const fixed = orientation === 'H' ? vertex.point.y : vertex.point.x;\n const line = lines.get(fixed) ?? [];\n line.push(vertex);\n lines.set(fixed, line);\n }\n\n for (const line of lines.values()) {\n line.sort((a, b) =>\n orientation === 'H'\n ? a.point.x - b.point.x || a.id - b.id\n : a.point.y - b.point.y || a.id - b.id\n );\n Object.freeze(line);\n }\n return new ImmutableMap(lines);\n}\n\nfunction searchArcs(arcs: readonly RouterArc[]): readonly RouterSearchArc[] {\n /*\n * Occupancy and crossing tie-breakers are left for future route-quality work.\n *\n * A minimal implementation could scan every committed route segment for every candidate arc:\n * - Sum collinear overlap into an occupied-length cost.\n * - Count perpendicular interior intersections as crossings.\n * - Pass those values into the search arcs.\n * - Recompute them after each committed route.\n *\n * That approach is simple, but likely too expensive: roughly routes x route segments x graph\n * arcs for each edge search. It also risks inconsistent handling of endpoints, terminal\n * segments, portals, and touching-versus-crossing geometry.\n *\n * A production-quality implementation would need:\n * - A container-scoped horizontal/vertical segment index.\n * - Efficient overlap and perpendicular-intersection queries.\n * - Dynamic search or overlay costs without mutating the immutable base topology.\n * - Updates only after route validation succeeds.\n * - Rollback support for bundle retries.\n * - Clear rules for endpoint touches, partial shared arcs, hierarchy segments, and routes that\n * span multiple containers.\n * - Search tests proving occupancy changes only the intended late tie-breakers.\n * - Routing tests showing reduced sharing and crossings.\n * - Performance tests for the 500-edge contract.\n */\n return Object.freeze(\n arcs.map((arc) =>\n Object.freeze({\n to: arc.to,\n orientationOrdinal: arc.orientation === 'H' ? 1 : 2,\n length: arc.length,\n boundaryTransitions: arc.kind === 'portal' ? 1 : 0,\n } as const)\n )\n );\n}\n\nfunction buildVisibilityGraph(\n records: readonly VertexRecord[],\n horizontalIntervals: OrthogonalIntervalIndex,\n verticalIntervals: OrthogonalIntervalIndex,\n caps: TopologyResourceCaps\n): {\n vertices: readonly RouterVertex[];\n adjacency: ReadonlyMap<number, readonly RouterArc[]>;\n adjacencyEntries: number;\n} {\n // Vertices connect only to their immediate visible neighbor on each shared x/y line; longer paths\n // are represented by graph traversal instead of quadratic all-pairs arcs.\n const canonical = canonicalRecords(records).sort(vertexRecordOrder);\n const vertexCap = caps.maxVertices ?? DEFAULT_MAX_VERTICES;\n enforceCap(canonical.length, vertexCap, 'vertex_cap');\n const vertices = canonical.map<RouterVertex>((record, id) =>\n Object.freeze({ id, ...record, point: Object.freeze({ ...record.point }) })\n );\n const adjacency = new Map<number, RouterArc[]>(\n vertices.map((vertex) => [vertex.id, [] as RouterArc[]])\n );\n const addArcPair = (a: RouterVertex, b: RouterVertex, orientation: GridOrientation) => {\n const length = Math.abs(a.point.x - b.point.x) + Math.abs(a.point.y - b.point.y);\n if (length === 0) {\n return;\n }\n\n const intervalStart =\n orientation === 'H' ? Math.min(a.point.x, b.point.x) : Math.min(a.point.y, b.point.y);\n const intervalEnd = intervalStart + length;\n for (const [from, to] of [\n [a, b],\n [b, a],\n ] as const) {\n adjacency.get(from.id)!.push({\n from: from.id,\n to: to.id,\n orientation,\n length,\n kind: 'visibility',\n intervalStart,\n intervalEnd,\n });\n }\n };\n\n for (const orientation of ['H', 'V'] as const) {\n const lines = new Map<number, RouterVertex[]>();\n for (const vertex of vertices) {\n const coordinate = orientation === 'H' ? vertex.point.y : vertex.point.x;\n const line = lines.get(coordinate) ?? [];\n line.push(vertex);\n lines.set(coordinate, line);\n }\n for (const [fixed, line] of lines) {\n line.sort((a, b) =>\n orientation === 'H'\n ? a.point.x - b.point.x || a.id - b.id\n : a.point.y - b.point.y || a.id - b.id\n );\n for (let index = 1; index < line.length; index++) {\n const a = line[index - 1];\n const b = line[index];\n const start = orientation === 'H' ? a.point.x : a.point.y;\n const end = orientation === 'H' ? b.point.x : b.point.y;\n const intervalIndex = orientation === 'H' ? horizontalIntervals : verticalIntervals;\n if (!intervalIndex.intersects(fixed, start, end)) {\n addArcPair(a, b, orientation);\n }\n }\n }\n }\n\n const arcKindOrder: Record<RouterArc['kind'], number> = {\n visibility: 0,\n terminal: 1,\n portal: 2,\n lane: 3,\n };\n let adjacencyEntries = 0;\n const immutableAdjacency = new Map<number, readonly RouterArc[]>();\n for (const vertex of vertices) {\n const arcs = adjacency.get(vertex.id)!;\n arcs.sort(\n (a, b) =>\n arcKindOrder[a.kind] - arcKindOrder[b.kind] ||\n compareCodeUnits(a.orientation, b.orientation) ||\n vertices[a.to].point.x - vertices[b.to].point.x ||\n vertices[a.to].point.y - vertices[b.to].point.y ||\n a.to - b.to\n );\n const unique = arcs.filter(\n (arc, index) =>\n index === 0 ||\n arc.to !== arcs[index - 1].to ||\n arc.orientation !== arcs[index - 1].orientation ||\n arc.kind !== arcs[index - 1].kind\n );\n adjacencyEntries += unique.length;\n immutableAdjacency.set(vertex.id, Object.freeze(unique.map((arc) => Object.freeze(arc))));\n }\n enforceCap(\n adjacencyEntries,\n // Each vertex has at most one immediate visible neighbor in each cardinal direction. The\n // override remains a test seam for exercising adjacency-cap fallback behavior.\n caps.maxAdjacencyEntries ?? vertexCap * MAX_VISIBILITY_ADJACENCY_PER_VERTEX,\n 'adjacency_cap'\n );\n return {\n vertices: Object.freeze(vertices),\n adjacency: new ImmutableMap(immutableAdjacency),\n adjacencyEntries,\n };\n}\n\nexport function derivePortalRanges(\n ownerId: string,\n rawBounds: RouterRect,\n rawTitle?: RouterRect\n): PortalRange[] {\n const bounds = normalizeRect(rawBounds);\n const title = rawTitle ? normalizeRect(rawTitle) : undefined;\n const verticalLow = Math.max(\n bounds.top + ROUTE_CLEARANCE_PX,\n (title?.bottom ?? -Infinity) + ROUTE_CLEARANCE_PX\n );\n const verticalHigh = bounds.bottom - ROUTE_CLEARANCE_PX;\n const horizontalLow = bounds.left + ROUTE_CLEARANCE_PX;\n const horizontalHigh = bounds.right - ROUTE_CLEARANCE_PX;\n const ranges: PortalRange[] = [];\n if (verticalLow <= verticalHigh) {\n ranges.push(\n { ownerId, side: 'left', low: verticalLow, high: verticalHigh },\n { ownerId, side: 'right', low: verticalLow, high: verticalHigh }\n );\n }\n if (horizontalLow <= horizontalHigh) {\n ranges.push({ ownerId, side: 'bottom', low: horizontalLow, high: horizontalHigh });\n if (!title || title.bottom + ROUTE_CLEARANCE_PX <= bounds.top) {\n ranges.push({ ownerId, side: 'top', low: horizontalLow, high: horizontalHigh });\n }\n }\n return ranges;\n}\n\nexport function buildPairedPortal(\n ownerId: string,\n bounds: RouterRect,\n title: RouterRect | undefined,\n side: GridSide,\n tangentialCoordinate: number\n): PairedPortal {\n // Interior and exterior points sit one clearance unit from the group boundary. The explicit\n // transition is the only hierarchy-crossing arc and contributes one boundary transition to cost.\n const range = derivePortalRanges(ownerId, bounds, title).find((entry) => entry.side === side);\n if (!range || tangentialCoordinate < range.low || tangentialCoordinate > range.high) {\n throw new Error(`Illegal ${side} portal for \"${ownerId}\" at ${tangentialCoordinate}`);\n }\n const boundary =\n side === 'left'\n ? bounds.left\n : side === 'right'\n ? bounds.right\n : side === 'top'\n ? bounds.top\n : bounds.bottom;\n const inward =\n side === 'left' || side === 'top'\n ? boundary + ROUTE_CLEARANCE_PX\n : boundary - ROUTE_CLEARANCE_PX;\n const outward =\n side === 'left' || side === 'top'\n ? boundary - ROUTE_CLEARANCE_PX\n : boundary + ROUTE_CLEARANCE_PX;\n const interior =\n side === 'left' || side === 'right'\n ? { x: inward, y: tangentialCoordinate }\n : { x: tangentialCoordinate, y: inward };\n const exterior =\n side === 'left' || side === 'right'\n ? { x: outward, y: tangentialCoordinate }\n : { x: tangentialCoordinate, y: outward };\n return {\n ownerId,\n side,\n tangentialCoordinate,\n interior,\n exterior,\n transition: {\n from: interior,\n to: exterior,\n orientation: side === 'left' || side === 'right' ? 'H' : 'V',\n length: ROUTE_CLEARANCE_PX * 2,\n kind: 'portal',\n },\n };\n}\n\nexport function buildContainerRoutingTopology(\n input: ContainerTopologyInput,\n options: BuildTopologyOptions = {}\n): ContainerRoutingTopology {\n // Build phases are normalize/inflate, union obstacles, seed corners and portal endpoints, project\n // rays to blocking boundaries, then connect immediate line-of-sight neighbors.\n const bounds = normalizeRect(input.bounds);\n const inflated = [...input.obstacles, ...(input.titleExclusions ?? [])]\n .map((obstacle) => inflateAndClip(obstacle, bounds))\n .filter((obstacle): obstacle is RouterObstacle => Boolean(obstacle));\n const obstacles = unionObstacles(inflated);\n const portalRanges = [...(input.portalRanges ?? [])].sort(\n (a, b) =>\n topologySideOrdinal(a.side) - topologySideOrdinal(b.side) ||\n a.low - b.low ||\n a.high - b.high ||\n compareCodeUnits(a.ownerId, b.ownerId)\n );\n\n const seeds = canonicalRecords([\n ...cornerRecords(bounds, input.containerId),\n ...obstacles.flatMap((obstacle) => cornerRecords(obstacle, obstacle.id)),\n ...portalRanges.flatMap((range) => portalRecords(range, bounds)),\n ]);\n const intervalBudget = {\n intervalCount: 0,\n maxEstimatedBytes: options.caps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n };\n enforceCap(\n estimatedTopologyBytes(0, 0, obstacles.length, 0),\n intervalBudget.maxEstimatedBytes,\n 'estimated_memory_cap'\n );\n const horizontalIntervals = createIntervalIndex(obstacles, 'H', intervalBudget);\n const verticalIntervals = createIntervalIndex(obstacles, 'V', intervalBudget);\n const projections: VertexRecord[] = [];\n const sides: readonly GridSide[] = ['left', 'right', 'top', 'bottom'];\n for (const seed of seeds) {\n for (const side of sides) {\n const hit = rayHit(seed.point, side, bounds, horizontalIntervals, verticalIntervals);\n if (hit.x !== seed.point.x || hit.y !== seed.point.y) {\n projections.push({ point: hit, kind: 'projection', side });\n }\n }\n }\n\n const { vertices, adjacency, adjacencyEntries } = buildVisibilityGraph(\n [...seeds, ...projections],\n horizontalIntervals,\n verticalIntervals,\n options.caps ?? {}\n );\n\n const estimatedBytes = estimatedTopologyBytes(\n vertices.length,\n adjacencyEntries,\n obstacles.length,\n horizontalIntervals.intervalCount + verticalIntervals.intervalCount\n );\n enforceCap(\n estimatedBytes,\n options.caps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n 'estimated_memory_cap'\n );\n\n if (options.metrics) {\n options.metrics.containersBuilt++;\n options.metrics.baseTopologyBuilds++;\n options.metrics.baseVertices += vertices.length;\n options.metrics.baseAdjacencyEntries += adjacencyEntries;\n options.metrics.buildSweepEvents += seeds.length * 4 + obstacles.length * 4;\n options.metrics.estimatedBytes += estimatedBytes;\n }\n\n return Object.freeze({\n containerId: input.containerId,\n bounds: Object.freeze(bounds),\n obstacles: Object.freeze(obstacles.map((obstacle) => Object.freeze(obstacle))),\n vertices: Object.freeze(vertices),\n pointVertexIds: new ImmutableMap(\n new Map(vertices.map(({ id, point }) => [routingPointKey(point), id]))\n ),\n horizontalVertexLines: indexVertexLines(vertices, 'H'),\n verticalVertexLines: indexVertexLines(vertices, 'V'),\n adjacency,\n adjacencyByVertex: Object.freeze(vertices.map(({ id }) => adjacency.get(id) ?? [])),\n searchAdjacencyByVertex: Object.freeze(\n vertices.map(({ id }) => searchArcs(adjacency.get(id) ?? []))\n ),\n adjacencyEntries,\n horizontalIntervals,\n verticalIntervals,\n portalRanges: Object.freeze(portalRanges.map((range) => Object.freeze(range))),\n seedCount: seeds.length,\n estimatedBytes,\n });\n}\n\nfunction pointInsideObstacle(\n point: RouterPoint,\n horizontalIntervals: OrthogonalIntervalIndex\n): boolean {\n return horizontalIntervals.contains(point.y, point.x);\n}\n\nexport function buildEndpointRoutingOverlay(\n base: ContainerRoutingTopology,\n source: RouterPoint,\n target: RouterPoint,\n metrics?: GridRoutingInstrumentation,\n reusableScratch?: EndpointOverlayScratch,\n lanePoints: readonly RouterPoint[] = []\n): ContainerRoutingTopology {\n // Overlays are intentionally tiny: two endpoints, optional bundle lane points, orthogonal\n // projections, and four obstacle/bounds ray hits per endpoint. Local caps enforce that invariant.\n const scratch = reusableScratch ?? new EndpointOverlayScratch(base);\n scratch.reset(base);\n const endpointRecords: VertexRecord[] = [\n { point: source, kind: 'endpoint', ownerId: 'source' },\n { point: target, kind: 'endpoint', ownerId: 'target' },\n ...lanePoints\n .filter((point) => !pointInsideObstacle(point, base.horizontalIntervals))\n .map((point) => ({ point, kind: 'lane' as const })),\n ];\n for (const point of [\n { x: source.x, y: target.y },\n { x: target.x, y: source.y },\n ]) {\n if (!pointInsideObstacle(point, base.horizontalIntervals)) {\n endpointRecords.push({ point, kind: 'projection' });\n }\n }\n for (const record of endpointRecords.slice(0, 2)) {\n for (const side of ['left', 'right', 'top', 'bottom'] as const) {\n const hit = rayHit(\n record.point,\n side,\n base.bounds,\n base.horizontalIntervals,\n base.verticalIntervals\n );\n if (hit.x !== record.point.x || hit.y !== record.point.y) {\n endpointRecords.push({ point: hit, kind: 'projection', side });\n }\n }\n }\n const additions = canonicalRecords(endpointRecords)\n .filter(({ point }) => !base.pointVertexIds.has(routingPointKey(point)))\n .sort(vertexRecordOrder);\n enforceCap(additions.length, 32, 'vertex_cap');\n scratch.addedVertices.push(\n ...additions.map<RouterVertex>((record, index) =>\n Object.freeze({\n id: base.vertices.length + index,\n ...record,\n point: Object.freeze({ ...record.point }),\n })\n )\n );\n const vertices = overlayArray(base.vertices, scratch.addedVertices);\n const vertexAt = (id: number): RouterVertex =>\n id < base.vertices.length\n ? base.vertices[id]\n : scratch.addedVertices[id - base.vertices.length];\n const adjacency = new Map<number, RouterArc[]>();\n const mutableArcs = (id: number): RouterArc[] => {\n let arcs = adjacency.get(id);\n if (!arcs) {\n arcs = [...(base.adjacency.get(id) ?? [])];\n adjacency.set(id, arcs);\n }\n return arcs;\n };\n for (const vertex of scratch.addedVertices) {\n adjacency.set(vertex.id, []);\n }\n const addedIds = new Set(scratch.addedVertices.map(({ id }) => id));\n const addedArcKeys = new Set<string>();\n const connect = (a: RouterVertex, b: RouterVertex, orientation: GridOrientation): void => {\n const length = Math.abs(a.point.x - b.point.x) + Math.abs(a.point.y - b.point.y);\n if (length === 0) {\n return;\n }\n const intervalStart =\n orientation === 'H' ? Math.min(a.point.x, b.point.x) : Math.min(a.point.y, b.point.y);\n const intervalEnd = intervalStart + length;\n for (const [from, to] of [\n [a, b],\n [b, a],\n ] as const) {\n const key = `${from.id}:${to.id}:${orientation}:visibility`;\n if (\n addedArcKeys.has(key) ||\n (base.adjacency.get(from.id) ?? []).some(\n (arc) => arc.to === to.id && arc.orientation === orientation && arc.kind === 'visibility'\n )\n ) {\n continue;\n }\n addedArcKeys.add(key);\n mutableArcs(from.id).push({\n from: from.id,\n to: to.id,\n orientation,\n length,\n kind: 'visibility',\n intervalStart,\n intervalEnd,\n });\n }\n };\n\n for (const orientation of ['H', 'V'] as const) {\n const baseLines = orientation === 'H' ? base.horizontalVertexLines : base.verticalVertexLines;\n const affected = new Set(\n scratch.addedVertices.map(({ point }) => (orientation === 'H' ? point.y : point.x))\n );\n for (const fixed of affected) {\n const line = [\n ...(baseLines.get(fixed) ?? []),\n ...scratch.addedVertices.filter(\n ({ point }) => (orientation === 'H' ? point.y : point.x) === fixed\n ),\n ];\n line.sort((a, b) =>\n orientation === 'H'\n ? a.point.x - b.point.x || a.id - b.id\n : a.point.y - b.point.y || a.id - b.id\n );\n for (let index = 1; index < line.length; index++) {\n const a = line[index - 1];\n const b = line[index];\n if (!addedIds.has(a.id) && !addedIds.has(b.id)) {\n continue;\n }\n const start = orientation === 'H' ? a.point.x : a.point.y;\n const end = orientation === 'H' ? b.point.x : b.point.y;\n const intervalIndex =\n orientation === 'H' ? base.horizontalIntervals : base.verticalIntervals;\n if (!intervalIndex.intersects(fixed, start, end)) {\n connect(a, b, orientation);\n }\n }\n }\n }\n\n for (const [id, arcs] of adjacency) {\n arcs.sort(\n (a, b) =>\n compareCodeUnits(a.kind, b.kind) ||\n compareCodeUnits(a.orientation, b.orientation) ||\n vertexAt(a.to).point.x - vertexAt(b.to).point.x ||\n vertexAt(a.to).point.y - vertexAt(b.to).point.y ||\n a.to - b.to\n );\n const immutableArcs = Object.freeze(arcs.map((arc) => Object.freeze(arc)));\n scratch.setArcs(id, immutableArcs);\n }\n const adjacencyEntries = base.adjacencyEntries + addedArcKeys.size;\n enforceCap(adjacencyEntries, base.adjacencyEntries + 64, 'adjacency_cap');\n const addedVertices = additions.length;\n const estimatedBytes =\n base.estimatedBytes + addedVertices * 64 + (adjacencyEntries - base.adjacencyEntries) * 56;\n if (metrics) {\n metrics.endpointOverlayBuilds++;\n metrics.endpointOverlayVertices += addedVertices;\n metrics.estimatedBytes = Math.max(metrics.estimatedBytes, estimatedBytes);\n }\n const vertexCount = base.vertices.length + scratch.addedVertices.length;\n const adjacencyByVertex = overrideArray(\n base.adjacencyByVertex,\n scratch.adjacencyOverrides,\n vertexCount\n );\n const searchAdjacencyByVertex = overrideArray(\n base.searchAdjacencyByVertex,\n scratch.searchAdjacencyOverrides,\n vertexCount\n );\n for (const vertex of scratch.addedVertices) {\n scratch.pointOverrides.set(routingPointKey(vertex.point), vertex.id);\n }\n return Object.freeze({\n ...base,\n vertices,\n pointVertexIds: new OverlayMap(base.pointVertexIds, scratch.pointOverrides),\n adjacency: new OverlayMap(base.adjacency, scratch.adjacencyOverrides),\n adjacencyByVertex,\n searchAdjacencyByVertex,\n adjacencyEntries,\n estimatedBytes,\n vertexCount,\n getVertex: vertexAt,\n getSearchArcs: (id: number) =>\n scratch.searchAdjacencyOverrides.get(id) ?? base.searchAdjacencyByVertex[id] ?? [],\n });\n}\n", "import type { Point } from '../../../types.js';\nimport type { Edge, LayoutData, Node } from '../../types.js';\nimport { PIXEL_EPSILON } from '../layout-utils/geometry.js';\nimport { clamp, compareCodeUnits, rectForNode } from '../layout-utils/helpers.js';\nimport { isAncestorGroup } from './groups.js';\nimport { EDGE_CLEARANCE_PX, ROUTE_CLEARANCE_PX, routingPointKey } from './routerTopology.js';\nimport type {\n GridAttachmentDemand,\n GridContainerId,\n GridLayoutResult,\n GridSide,\n RouterPoint,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError } from './types.js';\n\n// Planning is deterministic and side-effect free: it resolves hierarchy chains, bundle lanes,\n// endpoint demand, and route order before the session creates any routing topology.\nconst MIN_PORT_SEPARATION_PX = 4;\nexport const TERMINAL_APPROACH_PX = 20;\nexport const LANE_SEPARATION_PX = 8;\n\nexport interface EdgeEndpointEntry {\n ownerId: string;\n side: GridSide;\n demandKey: string;\n oppositeCoord: number;\n preferredCoord: number;\n compactPortal: boolean;\n ambiguousSides?: readonly GridSide[];\n inner?: { demandKey: string; side: GridSide };\n}\n\nexport interface EdgeEndpointPlan {\n // Entries walk from the endpoint outward toward the least common container. Each adjacent pair\n // represents one hierarchy boundary that the final route must cross through a paired portal.\n chain: EdgeEndpointEntry[];\n finalKind: 'item' | 'boundary';\n}\n\nexport interface EdgeRoutePlan {\n edge: Edge;\n lcaContainerId: GridContainerId;\n source: EdgeEndpointPlan;\n target: EdgeEndpointPlan;\n laneIndex: number;\n laneOffset: number;\n bundleSize: number;\n pairKey: string;\n}\n\nexport interface EdgeRouteCandidates {\n sources: EndpointCandidate[];\n targets: EndpointCandidate[];\n}\n\nexport interface PreparedEdgeRoutes {\n plans: EdgeRoutePlan[];\n eligiblePlans: EdgeRoutePlan[];\n eligibleIds: Set<string>;\n orderedPlans: EdgeRoutePlan[];\n demandCoords: Map<string, number>;\n endpointCandidatesByEdge: Map<string, EdgeRouteCandidates>;\n endpointIncidentCounts: Map<string, number>;\n coordinatedEndpointIds: Set<string>;\n}\n\nexport function ownerGroupTitle(node: Node): boolean {\n return Boolean(node.groupTitleRect);\n}\n\nexport function ownerSideKey(ownerId: string, side: GridSide): string {\n return JSON.stringify([ownerId, side]);\n}\n\nfunction preferredSide(node: Node, toward: Point): GridSide {\n const rect = rectForNode(node);\n const dx = toward.x - rect.cx;\n const dy = toward.y - rect.cy;\n const avoidTop = node.isGroup && ownerGroupTitle(node);\n\n if (Math.abs(dx) >= Math.abs(dy)) {\n return dx >= 0 ? 'right' : 'left';\n }\n if (dy >= 0) {\n return 'bottom';\n }\n if (avoidTop) {\n return dx >= 0 ? 'right' : 'left';\n }\n return 'top';\n}\n\nfunction containerChain(node: Node, nodeById: Map<string, Node>): GridContainerId[] {\n const chain: GridContainerId[] = [];\n let currentParent = node.parentId ?? ROOT_CONTAINER_ID;\n const seen = new Set<string>();\n while (true) {\n chain.push(currentParent);\n if (currentParent === ROOT_CONTAINER_ID) {\n break;\n }\n if (seen.has(currentParent)) {\n break;\n }\n seen.add(currentParent);\n currentParent = nodeById.get(currentParent)?.parentId ?? ROOT_CONTAINER_ID;\n }\n return chain;\n}\n\nfunction commonContainerId(\n source: Node,\n target: Node,\n nodeById: Map<string, Node>\n): GridContainerId {\n if (source.isGroup && isAncestorGroup(source.id, target, nodeById)) {\n return source.parentId ?? ROOT_CONTAINER_ID;\n }\n if (target.isGroup && isAncestorGroup(target.id, source, nodeById)) {\n return target.parentId ?? ROOT_CONTAINER_ID;\n }\n const targetContainers = new Set(containerChain(target, nodeById));\n for (const containerId of containerChain(source, nodeById)) {\n if (targetContainers.has(containerId)) {\n return containerId;\n }\n }\n return ROOT_CONTAINER_ID;\n}\n\nfunction oppositeCoordFor(rect: ReturnType<typeof rectForNode>, side: GridSide): number {\n return side === 'left' || side === 'right' ? rect.cy : rect.cx;\n}\n\nfunction sideMidpoint(rect: ReturnType<typeof rectForNode>, side: GridSide): Point {\n return side === 'left' || side === 'right'\n ? { x: side === 'left' ? rect.left : rect.right, y: rect.cy }\n : { x: rect.cx, y: side === 'top' ? rect.top : rect.bottom };\n}\n\nfunction tangentialCoordinate(point: Point, side: GridSide): number {\n return side === 'left' || side === 'right' ? point.y : point.x;\n}\n\nfunction buildEndpointPlan(\n endpoint: Node,\n other: Node,\n lcaContainerId: GridContainerId,\n nodeById: Map<string, Node>,\n edgeId: string,\n role: 'source' | 'target'\n): EdgeEndpointPlan {\n const chain: EdgeEndpointEntry[] = [];\n const endpointRect = rectForNode(endpoint);\n const otherRect = rectForNode(other);\n const otherCenter = { x: other.x ?? 0, y: other.y ?? 0 };\n let current = endpoint;\n\n for (;;) {\n const parentId = current.parentId ?? ROOT_CONTAINER_ID;\n const parent = nodeById.get(parentId);\n const currentCenter = { x: current.x ?? 0, y: current.y ?? 0 };\n const dx = otherCenter.x - currentCenter.x;\n const dy = otherCenter.y - currentCenter.y;\n const titleAvoidanceTie =\n dy < 0 &&\n Math.abs(dx) <= PIXEL_EPSILON &&\n Boolean((current.isGroup ? current.groupTitleRect : undefined) ?? parent?.groupTitleRect);\n const directSideCandidates: GridSide[] = [];\n if (Math.abs(Math.abs(dx) - Math.abs(dy)) <= PIXEL_EPSILON && Math.abs(dx) > PIXEL_EPSILON) {\n directSideCandidates.push(dx >= 0 ? 'right' : 'left', dy >= 0 ? 'bottom' : 'top');\n }\n const topBlocked = Boolean(\n (current.isGroup ? current.groupTitleRect : undefined) ?? parent?.groupTitleRect\n );\n const ambiguousSides = (\n titleAvoidanceTie ? (['left', 'right'] as GridSide[]) : directSideCandidates\n ).filter((candidate) => candidate !== 'top' || !topBlocked);\n let side = preferredSide(current, otherCenter);\n if (side === 'top' && parent?.groupTitleRect) {\n side = dx >= 0 ? 'right' : 'left';\n }\n chain.push({\n ownerId: current.id,\n side,\n demandKey: JSON.stringify([edgeId, role, current.id, side]),\n oppositeCoord: oppositeCoordFor(otherRect, side),\n preferredCoord: oppositeCoordFor(endpointRect, side),\n compactPortal: current.id !== endpoint.id,\n ambiguousSides: ambiguousSides.length > 1 ? ambiguousSides : undefined,\n inner: chain.length\n ? { demandKey: chain[chain.length - 1].demandKey, side: chain[chain.length - 1].side }\n : undefined,\n });\n\n if (\n current.isGroup &&\n current.id === lcaContainerId &&\n isAncestorGroup(current.id, other, nodeById)\n ) {\n return { chain, finalKind: 'boundary' };\n }\n if (parentId === lcaContainerId) {\n return { chain, finalKind: 'item' };\n }\n\n if (!parent?.isGroup) {\n throw gridError('GRID_INVALID_CONTAINMENT', `Missing parent group \"${parentId}\"`, {\n traversedIds: chain.map((entry) => entry.ownerId),\n });\n }\n current = parent;\n }\n}\n\ninterface PairLane {\n index: number;\n size: number;\n offset: number;\n pairKey: string;\n}\n\nfunction buildPairLanes(edges: Edge[]): Map<string, PairLane> {\n const byPair = new Map<string, Edge[]>();\n for (const edge of edges) {\n if (!edge.start || !edge.end) {\n continue;\n }\n const pairKey =\n edge.start < edge.end ? `${edge.start}|${edge.end}` : `${edge.end}|${edge.start}`;\n if (!byPair.has(pairKey)) {\n byPair.set(pairKey, []);\n }\n byPair.get(pairKey)!.push(edge);\n }\n\n const out = new Map<string, PairLane>();\n for (const [pairKey, entries] of byPair) {\n // Directed endpoint order and edge id make lane assignment stable even if input edges arrive in\n // a different order.\n entries.sort(\n (a, b) =>\n compareCodeUnits(`${a.start}|${a.end}`, `${b.start}|${b.end}`) ||\n compareCodeUnits(a.id, b.id)\n );\n entries.forEach((edge, index) =>\n out.set(edge.id, {\n index,\n size: entries.length,\n offset: (index - (entries.length - 1) / 2) * LANE_SEPARATION_PX,\n pairKey,\n })\n );\n }\n return out;\n}\n\nfunction resolveAmbiguousEndpointSides(plans: EdgeRoutePlan[], result: GridLayoutResult): void {\n // Reserve geometrically preferred sides first. Equal-cost endpoint choices then use the legal\n // side with the fewest strong reservations, preserving the original preference as a stable tie.\n const reserved = new Map<string, number>();\n const reservationKey = (ownerId: string, side: GridSide) => ownerSideKey(ownerId, side);\n for (const plan of plans) {\n for (const entry of [...plan.source.chain, ...plan.target.chain]) {\n if (!entry.ambiguousSides) {\n const key = reservationKey(entry.ownerId, entry.side);\n reserved.set(key, (reserved.get(key) ?? 0) + 1);\n }\n }\n }\n\n const resolveEndpoint = (\n plan: EdgeRoutePlan,\n endpoint: EdgeEndpointPlan,\n role: 'source' | 'target'\n ): void => {\n const ambiguous = endpoint.chain.filter(({ ambiguousSides }) => ambiguousSides);\n if (ambiguous.length === 0) {\n return;\n }\n const legalSides = (['right', 'bottom', 'left', 'top'] as const).filter(\n (side) =>\n ambiguous.every((entry) => entry.ambiguousSides?.includes(side)) &&\n ambiguous.every((entry) => {\n const owner = result.forest.nodeById.get(entry.ownerId);\n return owner !== undefined && sideInterval(owner, side) !== undefined;\n })\n );\n const selected = legalSides.sort(\n (a, b) =>\n ambiguous.reduce(\n (count, entry) => count + (reserved.get(reservationKey(entry.ownerId, a)) ?? 0),\n 0\n ) -\n ambiguous.reduce(\n (count, entry) => count + (reserved.get(reservationKey(entry.ownerId, b)) ?? 0),\n 0\n ) || Number(a !== ambiguous[0].side) - Number(b !== ambiguous[0].side)\n )[0];\n if (!selected) {\n return;\n }\n for (const entry of ambiguous) {\n entry.side = selected;\n const key = reservationKey(entry.ownerId, selected);\n reserved.set(key, (reserved.get(key) ?? 0) + 1);\n const owner = result.forest.nodeById.get(entry.ownerId);\n if (owner) {\n entry.preferredCoord = oppositeCoordFor(rectForNode(owner), selected);\n }\n }\n for (const [index, entry] of endpoint.chain.entries()) {\n entry.demandKey = JSON.stringify([plan.edge.id, role, entry.ownerId, entry.side]);\n entry.inner =\n index > 0\n ? {\n demandKey: endpoint.chain[index - 1].demandKey,\n side: endpoint.chain[index - 1].side,\n }\n : undefined;\n }\n };\n\n const endpoints = plans\n .flatMap((plan) => [\n { plan, endpoint: plan.source, role: 'source' as const },\n { plan, endpoint: plan.target, role: 'target' as const },\n ])\n .sort((a, b) =>\n compareCodeUnits(\n `${a.plan.edge.start ?? ''}|${a.plan.edge.end ?? ''}|${a.plan.edge.id}|${a.role}`,\n `${b.plan.edge.start ?? ''}|${b.plan.edge.end ?? ''}|${b.plan.edge.id}|${b.role}`\n )\n );\n for (const { plan, endpoint, role } of endpoints) {\n resolveEndpoint(plan, endpoint, role);\n }\n\n for (const plan of plans) {\n const sourceFinal = plan.source.chain.at(-1);\n const targetFinal = plan.target.chain.at(-1);\n const sourceOwner = sourceFinal ? result.forest.nodeById.get(sourceFinal.ownerId) : undefined;\n const targetOwner = targetFinal ? result.forest.nodeById.get(targetFinal.ownerId) : undefined;\n if (!sourceFinal || !targetFinal || !sourceOwner || !targetOwner) {\n continue;\n }\n const sourcePoint = sideMidpoint(rectForNode(sourceOwner), sourceFinal.side);\n const targetPoint = sideMidpoint(rectForNode(targetOwner), targetFinal.side);\n for (const entry of plan.source.chain) {\n entry.oppositeCoord = tangentialCoordinate(targetPoint, entry.side);\n }\n for (const entry of plan.target.chain) {\n entry.oppositeCoord = tangentialCoordinate(sourcePoint, entry.side);\n }\n }\n}\n\nfunction collectRoutePlans(layout: LayoutData, result: GridLayoutResult): EdgeRoutePlan[] {\n const nodeById = result.forest.nodeById;\n const pairLanes = buildPairLanes(layout.edges);\n\n const plans = layout.edges.map((edge) => {\n const source = edge.start ? nodeById.get(edge.start) : undefined;\n const target = edge.end ? nodeById.get(edge.end) : undefined;\n if (!source || !target) {\n throw gridError('GRID_MISSING_ENDPOINT', `Missing endpoint for edge \"${edge.id}\"`, {\n edgeId: edge.id,\n start: edge.start,\n end: edge.end,\n });\n }\n const lcaContainerId = commonContainerId(source, target, nodeById);\n const pairLane = pairLanes.get(edge.id) ?? {\n index: 0,\n size: 1,\n offset: 0,\n pairKey: endpointPairKey(edge),\n };\n return {\n edge,\n lcaContainerId,\n source: buildEndpointPlan(source, target, lcaContainerId, nodeById, edge.id, 'source'),\n target: buildEndpointPlan(target, source, lcaContainerId, nodeById, edge.id, 'target'),\n laneIndex: pairLane.index,\n laneOffset: pairLane.offset,\n bundleSize: pairLane.size,\n pairKey: pairLane.pairKey,\n };\n });\n resolveAmbiguousEndpointSides(plans, result);\n return plans;\n}\n\nexport function assignCompactPortalCoordinates(\n desired: readonly number[],\n low: number,\n high: number\n): number[] {\n // Forward/backward constraint passes enforce minimum spacing; the final common shift preserves\n // the requested center of mass as far as the legal interval permits.\n const coordinates: number[] = [];\n for (const [index, coordinate] of desired.entries()) {\n coordinates.push(\n index === 0\n ? coordinate\n : Math.max(coordinate, coordinates[index - 1] + MIN_PORT_SEPARATION_PX)\n );\n }\n for (let index = coordinates.length - 1; index >= 0; index--) {\n coordinates[index] = Math.min(\n coordinates[index],\n index === coordinates.length - 1 ? high : coordinates[index + 1] - MIN_PORT_SEPARATION_PX\n );\n }\n const averageDesired = desired.reduce((sum, coordinate) => sum + coordinate, 0) / desired.length;\n const averageAssigned =\n coordinates.reduce((sum, coordinate) => sum + coordinate, 0) / coordinates.length;\n const minimumShift = low - coordinates[0];\n const maximumShift = high - coordinates[coordinates.length - 1];\n const shift = clamp(averageDesired - averageAssigned, minimumShift, maximumShift);\n return coordinates.map((coordinate) => coordinate + shift);\n}\n\nfunction assignDemandCoordinates(\n plans: EdgeRoutePlan[],\n result: GridLayoutResult,\n endpointIncidentCounts: ReadonlyMap<string, number>\n): Map<string, number> {\n // Allocate all demands for an owner side together. This prevents independently routed edges from\n // selecting the same port and lets bundles retain symmetric lane offsets when capacity allows.\n const nodeById = result.forest.nodeById;\n const planByEdgeId = new Map(plans.map((plan) => [plan.edge.id, plan]));\n const demandByKey = new Map<string, GridAttachmentDemand>();\n for (const plan of plans) {\n if (plan.edge.start === plan.edge.end) {\n continue;\n }\n for (const entry of [...plan.source.chain, ...plan.target.chain]) {\n if (!demandByKey.has(entry.demandKey)) {\n demandByKey.set(entry.demandKey, {\n ownerId: entry.ownerId,\n side: entry.side,\n edgeId: plan.edge.id,\n demandKey: entry.demandKey,\n oppositeCoord: entry.oppositeCoord,\n preferredCoord: entry.preferredCoord,\n compactPortal: entry.compactPortal,\n inner: entry.inner,\n });\n }\n }\n }\n\n const byOwnerSide = new Map<\n string,\n { ownerId: string; side: GridSide; demands: GridAttachmentDemand[] }\n >();\n for (const demand of demandByKey.values()) {\n const key = ownerSideKey(demand.ownerId, demand.side);\n const group = byOwnerSide.get(key) ?? {\n ownerId: demand.ownerId,\n side: demand.side,\n demands: [],\n };\n group.demands.push(demand);\n byOwnerSide.set(key, group);\n }\n\n // Ports are placed before the compact portals that line up with them, innermost group first.\n const depthOf = (ownerId: string): number => {\n const owner = nodeById.get(ownerId);\n return owner ? containerChain(owner, nodeById).length : 0;\n };\n const orderedOwnerSides = [...byOwnerSide.values()].sort(\n (a, b) =>\n Number(a.demands.every((d) => d.compactPortal)) -\n Number(b.demands.every((d) => d.compactPortal)) || depthOf(b.ownerId) - depthOf(a.ownerId)\n );\n const assigned = new Map<string, number>();\n for (const { ownerId, side, demands } of orderedOwnerSides) {\n const owner = nodeById.get(ownerId);\n if (!owner) {\n continue;\n }\n const rect = rectForNode(owner);\n let low =\n side === 'left' || side === 'right'\n ? rect.top + ROUTE_CLEARANCE_PX\n : rect.left + ROUTE_CLEARANCE_PX;\n const high =\n side === 'left' || side === 'right'\n ? rect.bottom - ROUTE_CLEARANCE_PX\n : rect.right - ROUTE_CLEARANCE_PX;\n if ((side === 'left' || side === 'right') && owner.groupTitleRect) {\n low = Math.max(low, owner.groupTitleRect.bottom + ROUTE_CLEARANCE_PX);\n }\n const span = Math.max(0, high - low);\n demands.sort(\n (a, b) => a.oppositeCoord - b.oppositeCoord || compareCodeUnits(a.edgeId, b.edgeId)\n );\n const demandPlans = demands.map((demand) => planByEdgeId.get(demand.edgeId));\n const pairKeys = new Set(demandPlans.map((plan) => plan?.pairKey));\n const compactHierarchyPortals =\n owner.isGroup && demands.every(({ compactPortal }) => compactPortal);\n if (\n !(compactHierarchyPortals && demands.length === 1) &&\n pairKeys.size === 1 &&\n demandPlans.every(\n (plan) =>\n plan &&\n plan.bundleSize === demands.length &&\n endpointIncidentCounts.get(plan.edge.start!) === plan.bundleSize &&\n endpointIncidentCounts.get(plan.edge.end!) === plan.bundleSize\n )\n ) {\n const center = (low + high) / 2;\n const coordinates = demandPlans.map((plan) => center + plan!.laneOffset);\n if (coordinates.every((coordinate) => coordinate >= low && coordinate <= high)) {\n demands.forEach((demand, index) => assigned.set(demand.demandKey, coordinates[index]));\n continue;\n }\n }\n if (compactHierarchyPortals) {\n const container = result.containers.get(owner.id);\n const corridorCoordinates =\n side === 'left' || side === 'right'\n ? container?.horizontalCorridors\n : container?.verticalCorridors;\n const innerCoordinate = (demand: GridAttachmentDemand): number => {\n const inner = demand.inner ? demandByKey.get(demand.inner.demandKey) : undefined;\n const innerOwner = inner ? nodeById.get(inner.ownerId) : undefined;\n const coordinate = inner ? assigned.get(inner.demandKey) : undefined;\n if (!inner || !innerOwner || coordinate === undefined) {\n return demand.preferredCoord;\n }\n const point = sideMidpoint(rectForNode(innerOwner), inner.side);\n if (inner.side === 'left' || inner.side === 'right') {\n point.y = coordinate;\n } else {\n point.x = coordinate;\n }\n return tangentialCoordinate(point, side);\n };\n const preferredCoordinate = (demand: GridAttachmentDemand): number => {\n const innerCoord = demand.inner ? assigned.get(demand.inner.demandKey) : undefined;\n const alignedWithInner =\n demand.inner !== undefined &&\n innerCoord !== undefined &&\n (demand.inner.side === 'left' || demand.inner.side === 'right') ===\n (side === 'left' || side === 'right');\n const clamped = clamp(alignedWithInner ? innerCoord : demand.preferredCoord, low, high);\n const nearest = corridorCoordinates?.reduce(\n (best, coordinate) =>\n Math.abs(coordinate - clamped) < Math.abs(best - clamped) ? coordinate : best,\n corridorCoordinates[0]\n );\n return nearest !== undefined && Math.abs(nearest - clamped) <= PIXEL_EPSILON\n ? nearest\n : clamped;\n };\n if (demands.length === 1) {\n assigned.set(demands[0].demandKey, preferredCoordinate(demands[0]));\n continue;\n }\n if (span >= MIN_PORT_SEPARATION_PX * (demands.length - 1)) {\n demands.sort(\n (a, b) =>\n innerCoordinate(a) - innerCoordinate(b) ||\n a.oppositeCoord - b.oppositeCoord ||\n compareCodeUnits(a.edgeId, b.edgeId)\n );\n const desired = demands.map(preferredCoordinate);\n const coordinates = assignCompactPortalCoordinates(desired, low, high);\n demands.forEach((demand, index) => assigned.set(demand.demandKey, coordinates[index]));\n continue;\n }\n }\n if (demands.length === 1 || span <= 0) {\n assigned.set(demands[0].demandKey, (low + high) / 2);\n continue;\n }\n const step = span / (demands.length - 1);\n demands.forEach((demand, index) => {\n assigned.set(demand.demandKey, low + step * index);\n });\n }\n\n // Keep a nearly aligned hierarchy route on one exact coordinate. Sub-pixel differences between\n // independently allocated endpoint and portal slots are otherwise normalized away as a diagonal,\n // which unnecessarily demotes the route to sparse search.\n for (const plan of plans) {\n if (plan.bundleSize !== 1) {\n continue;\n }\n const sourceFinal = plan.source.chain.at(-1);\n const targetFinal = plan.target.chain.at(-1);\n if (!sourceFinal || !targetFinal) {\n continue;\n }\n const verticalSide = (side: GridSide) => side === 'left' || side === 'right';\n if (verticalSide(sourceFinal.side) !== verticalSide(targetFinal.side)) {\n continue;\n }\n const sourceCoord = assigned.get(sourceFinal.demandKey);\n const targetCoord = assigned.get(targetFinal.demandKey);\n if (\n sourceCoord === undefined ||\n targetCoord === undefined ||\n Math.abs(sourceCoord - targetCoord) > PIXEL_EPSILON\n ) {\n continue;\n }\n const entries = [...plan.source.chain, ...plan.target.chain];\n if (entries.some((entry) => verticalSide(entry.side) !== verticalSide(sourceFinal.side))) {\n continue;\n }\n const alignedCoord = [sourceCoord, targetCoord].find((coordinate) =>\n entries.every((entry) => {\n const owner = nodeById.get(entry.ownerId);\n const interval = owner ? sideInterval(owner, entry.side) : undefined;\n return (\n interval !== undefined &&\n coordinate >= interval.low - PIXEL_EPSILON &&\n coordinate <= interval.high + PIXEL_EPSILON\n );\n })\n );\n if (alignedCoord !== undefined) {\n entries.forEach((entry) => assigned.set(entry.demandKey, alignedCoord));\n }\n }\n return assigned;\n}\n\nexport interface EndpointCandidate {\n ownerId: string;\n side: GridSide;\n port: RouterPoint;\n connect: RouterPoint;\n rank: number;\n // Set only at owners that mix aligned and unaligned edges: whether the candidate uses the side the\n // allocator assigned. The sparse search keeps those owners on their assigned side when it can.\n onAssignedSide?: boolean;\n}\n\ninterface EndpointDemandEntry {\n plan: EdgeRoutePlan;\n role: 'source' | 'target';\n opposite: Node;\n}\n\ninterface EndpointSlotAssignment {\n side: GridSide;\n coordinate: number;\n}\n\nexport function sideOrder(side: GridSide): number {\n // Endpoint preference order is independent of topology's canonical record ordering.\n return side === 'right' ? 0 : side === 'bottom' ? 1 : side === 'left' ? 2 : 3;\n}\n\nexport function sideInterval(\n owner: Node,\n side: GridSide\n): { low: number; high: number } | undefined {\n const rect = rectForNode(owner);\n if (side === 'top' && owner.groupTitleRect) {\n return undefined;\n }\n let low =\n side === 'left' || side === 'right'\n ? rect.top + ROUTE_CLEARANCE_PX\n : rect.left + ROUTE_CLEARANCE_PX;\n const high =\n side === 'left' || side === 'right'\n ? rect.bottom - ROUTE_CLEARANCE_PX\n : rect.right - ROUTE_CLEARANCE_PX;\n if ((side === 'left' || side === 'right') && owner.groupTitleRect) {\n low = Math.max(low, owner.groupTitleRect.bottom + ROUTE_CLEARANCE_PX);\n }\n return low <= high ? { low, high } : undefined;\n}\n\nfunction endpointPairKey(edge: Edge): string {\n const start = edge.start ?? '';\n const end = edge.end ?? '';\n return start < end ? `${start}|${end}` : `${end}|${start}`;\n}\n\nfunction compareEndpointDemands(\n a: EndpointDemandEntry,\n b: EndpointDemandEntry,\n side: GridSide\n): number {\n const aRect = rectForNode(a.opposite);\n const bRect = rectForNode(b.opposite);\n const aCoord = side === 'left' || side === 'right' ? aRect.cy : aRect.cx;\n const bCoord = side === 'left' || side === 'right' ? bRect.cy : bRect.cx;\n return (\n aCoord - bCoord ||\n compareCodeUnits(endpointPairKey(a.plan.edge), endpointPairKey(b.plan.edge)) ||\n compareCodeUnits(\n `${a.plan.edge.start}|${a.plan.edge.end}`,\n `${b.plan.edge.start}|${b.plan.edge.end}`\n ) ||\n compareCodeUnits(a.plan.edge.id, b.plan.edge.id) ||\n compareCodeUnits(a.role, b.role)\n );\n}\n\nfunction endpointDemandKey(demand: EndpointDemandEntry): string {\n return `${demand.plan.edge.id}:${demand.role}`;\n}\n\nfunction compareEndpointDemandIdentity(a: EndpointDemandEntry, b: EndpointDemandEntry): number {\n return (\n compareCodeUnits(endpointPairKey(a.plan.edge), endpointPairKey(b.plan.edge)) ||\n compareCodeUnits(\n `${a.plan.edge.start}|${a.plan.edge.end}`,\n `${b.plan.edge.start}|${b.plan.edge.end}`\n ) ||\n compareCodeUnits(a.plan.edge.id, b.plan.edge.id) ||\n compareCodeUnits(a.role, b.role)\n );\n}\n\nfunction preferredEndpointCoordinates(\n owner: Node,\n side: GridSide,\n demands: readonly EndpointDemandEntry[]\n): ReadonlyMap<EndpointDemandEntry, number> {\n const interval = sideInterval(owner, side);\n if (!interval || demands.length === 0) {\n return new Map();\n }\n const sorted = [...demands].sort((a, b) => compareEndpointDemands(a, b, side));\n if (sorted.length === 1) {\n const rect = rectForNode(owner);\n const center = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n return new Map([[sorted[0], clamp(center, interval.low, interval.high)]]);\n }\n if ((interval.high - interval.low) / (sorted.length - 1) < MIN_PORT_SEPARATION_PX) {\n return new Map(\n sorted.map((demand, index) => [\n demand,\n interval.low + (index * (interval.high - interval.low)) / (sorted.length - 1),\n ])\n );\n }\n const desired = sorted.map(({ opposite }) => {\n const rect = rectForNode(opposite);\n const coordinate = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n return clamp(coordinate, interval.low, interval.high);\n });\n const coordinates = assignCompactPortalCoordinates(desired, interval.low, interval.high);\n return new Map(sorted.map((demand, index) => [demand, coordinates[index]]));\n}\n\nfunction endpointSideCapacity(owner: Node, side: GridSide): number {\n const interval = sideInterval(owner, side);\n if (!interval) {\n return 0;\n }\n return 1 + Math.floor((interval.high - interval.low) / MIN_PORT_SEPARATION_PX);\n}\n\nfunction endpointSidePreferences(owner: Node, demand: EndpointDemandEntry): GridSide[] {\n const oppositeRect = rectForNode(demand.opposite);\n const preferred = preferredSide(owner, { x: oppositeRect.cx, y: oppositeRect.cy });\n return (['right', 'bottom', 'left', 'top'] as const)\n .filter((side) => endpointSideCapacity(owner, side) > 0)\n .sort((a, b) => {\n if (a === preferred) {\n return -1;\n }\n if (b === preferred) {\n return 1;\n }\n const ownerRect = rectForNode(owner);\n const aPoint = sideMidpoint(ownerRect, a);\n const bPoint = sideMidpoint(ownerRect, b);\n const aDistance = Math.abs(aPoint.x - oppositeRect.cx) + Math.abs(aPoint.y - oppositeRect.cy);\n const bDistance = Math.abs(bPoint.x - oppositeRect.cx) + Math.abs(bPoint.y - oppositeRect.cy);\n return aDistance - bDistance || sideOrder(a) - sideOrder(b);\n });\n}\n\nfunction isAxisAlignedDemand(owner: Node, demand: EndpointDemandEntry): boolean {\n const ownerRect = rectForNode(owner);\n const oppositeRect = rectForNode(demand.opposite);\n return (\n Math.abs(ownerRect.cx - oppositeRect.cx) <= PIXEL_EPSILON ||\n Math.abs(ownerRect.cy - oppositeRect.cy) <= PIXEL_EPSILON\n );\n}\n\n// Places unaligned ports on a side that already carries fixed (aligned) ports. Each port takes the\n// legal coordinate nearest its desired one that keeps EDGE_CLEARANCE_PX from every other port, so the\n// aligned ports stay on their straight lines. Returns undefined when the side cannot fit them all.\nfunction placePortsBesideFixed(\n owner: Node,\n side: GridSide,\n fixed: readonly number[],\n movable: readonly EndpointDemandEntry[]\n): Map<EndpointDemandEntry, number> | undefined {\n const interval = sideInterval(owner, side);\n if (!interval) {\n return undefined;\n }\n const placed = [...fixed];\n const placements = new Map<EndpointDemandEntry, number>();\n for (const demand of movable) {\n const opposite = rectForNode(demand.opposite);\n const desired = clamp(\n side === 'left' || side === 'right' ? opposite.cy : opposite.cx,\n interval.low,\n interval.high\n );\n const candidates = [\n desired,\n interval.low,\n interval.high,\n ...placed.flatMap((coordinate) => [\n coordinate - EDGE_CLEARANCE_PX,\n coordinate + EDGE_CLEARANCE_PX,\n ]),\n ]\n .filter(\n (coordinate) =>\n coordinate >= interval.low - PIXEL_EPSILON &&\n coordinate <= interval.high + PIXEL_EPSILON &&\n placed.every((other) => Math.abs(coordinate - other) >= EDGE_CLEARANCE_PX - PIXEL_EPSILON)\n )\n .sort((a, b) => Math.abs(a - desired) - Math.abs(b - desired) || a - b);\n if (candidates.length === 0) {\n return undefined;\n }\n placements.set(demand, candidates[0]);\n placed.push(candidates[0]);\n }\n return placements;\n}\n\nfunction allocateEndpointSlots(\n owner: Node,\n demands: readonly EndpointDemandEntry[]\n): ReadonlyMap<string, EndpointSlotAssignment> {\n // Aligned edges get first choice of their direct side and keep their straight port. Other edges\n // prefer an unreserved side, or share a reserved side when their port can sit a full clearance\n // away from the aligned ports. This stops a diagonal approach from displacing a straight one.\n const assignedBySide = new Map<GridSide, EndpointDemandEntry[]>();\n const capacities = new Map(\n (['right', 'bottom', 'left', 'top'] as const).map((side) => [\n side,\n endpointSideCapacity(owner, side),\n ])\n );\n\n const orderedDemands = [...demands].sort(compareEndpointDemandIdentity);\n const alignedDemands = orderedDemands.filter((demand) => isAxisAlignedDemand(owner, demand));\n const unalignedDemands = orderedDemands.filter((demand) => !isAxisAlignedDemand(owner, demand));\n const reservedSides = new Set<GridSide>();\n const alignedCoordinates = new Map<GridSide, number[]>();\n const sharedPlacements = new Map<GridSide, Map<EndpointDemandEntry, number>>();\n const hasCapacity = (candidate: GridSide) =>\n (assignedBySide.get(candidate)?.length ?? 0) < (capacities.get(candidate) ?? 0);\n const record = (demand: EndpointDemandEntry, side: GridSide) => {\n const assigned = assignedBySide.get(side) ?? [];\n assigned.push(demand);\n assignedBySide.set(side, assigned);\n };\n const assignAligned = (demand: EndpointDemandEntry): void => {\n const side = endpointSidePreferences(owner, demand).find(hasCapacity);\n if (side) {\n record(demand, side);\n reservedSides.add(side);\n }\n };\n const tryShareReservedSide = (demand: EndpointDemandEntry, side: GridSide): boolean => {\n const shared = sharedPlacements.get(side) ?? new Map<EndpointDemandEntry, number>();\n const placements = placePortsBesideFixed(\n owner,\n side,\n [...(alignedCoordinates.get(side) ?? []), ...shared.values()],\n [demand]\n );\n if (!placements) {\n return false;\n }\n shared.set(demand, placements.get(demand)!);\n sharedPlacements.set(side, shared);\n record(demand, side);\n return true;\n };\n const assignUnaligned = (demand: EndpointDemandEntry): void => {\n const preferences = endpointSidePreferences(owner, demand).filter(hasCapacity);\n const unreserved = preferences.find((candidate) => !reservedSides.has(candidate));\n const sharable = preferences.find(\n (candidate) =>\n (unreserved === undefined ||\n preferences.indexOf(candidate) < preferences.indexOf(unreserved)) &&\n reservedSides.has(candidate) &&\n tryShareReservedSide(demand, candidate)\n );\n if (sharable) {\n return;\n }\n const side = unreserved ?? preferences[0];\n if (side) {\n record(demand, side);\n }\n };\n\n for (const demand of alignedDemands) {\n assignAligned(demand);\n }\n for (const [side, assigned] of assignedBySide) {\n alignedCoordinates.set(side, [...preferredEndpointCoordinates(owner, side, assigned).values()]);\n }\n for (const demand of unalignedDemands) {\n assignUnaligned(demand);\n }\n\n const assignments = new Map<string, EndpointSlotAssignment>();\n for (const [side, assigned] of assignedBySide) {\n const interval = sideInterval(owner, side);\n if (!interval) {\n continue;\n }\n const shared = sharedPlacements.get(side);\n const fixedDemands = shared ? assigned.filter((demand) => !shared.has(demand)) : assigned;\n const preferredCoordinates = new Map([\n ...preferredEndpointCoordinates(owner, side, fixedDemands),\n ...(shared ?? []),\n ]);\n const sorted = [...assigned].sort((a, b) => compareEndpointDemands(a, b, side));\n for (const [index, demand] of sorted.entries()) {\n const coordinate =\n preferredCoordinates.get(demand) ??\n (sorted.length === 1\n ? (interval.low + interval.high) / 2\n : interval.low + (index * (interval.high - interval.low)) / (sorted.length - 1));\n assignments.set(endpointDemandKey(demand), { side, coordinate });\n }\n }\n return assignments;\n}\n\nfunction endpointCandidates(\n plan: EdgeRoutePlan,\n role: 'source' | 'target',\n demandsByOwner: ReadonlyMap<string, readonly EndpointDemandEntry[]>,\n assignmentsByOwner: ReadonlyMap<string, ReadonlyMap<string, EndpointSlotAssignment>>,\n coordinatedOwnerIds: ReadonlySet<string>,\n result: GridLayoutResult\n): EndpointCandidate[] {\n const ownerId = role === 'source' ? plan.edge.start! : plan.edge.end!;\n const oppositeId = role === 'source' ? plan.edge.end! : plan.edge.start!;\n const owner = result.forest.nodeById.get(ownerId);\n const opposite = result.forest.nodeById.get(oppositeId);\n if (!owner || !opposite) {\n throw gridError('GRID_MISSING_ENDPOINT', `Missing endpoint for edge \"${plan.edge.id}\"`);\n }\n const oppositeRect = rectForNode(opposite);\n const candidates: EndpointCandidate[] = [];\n const candidateKeys = new Set<string>();\n\n const assignment = assignmentsByOwner.get(ownerId)?.get(`${plan.edge.id}:${role}`);\n const trackAssignedSide = coordinatedOwnerIds.has(ownerId) && assignment !== undefined;\n const addCandidate = (side: GridSide, coordinate: number, rank: number): void => {\n const interval = sideInterval(owner, side);\n if (!interval || coordinate < interval.low || coordinate > interval.high) {\n return;\n }\n const rect = rectForNode(owner);\n const port =\n side === 'left' || side === 'right'\n ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n const key = `${side}:${routingPointKey(port)}`;\n if (candidateKeys.has(key)) {\n return;\n }\n candidateKeys.add(key);\n candidates.push({\n ownerId,\n side,\n port,\n connect: {\n x:\n port.x +\n (side === 'left' ? -TERMINAL_APPROACH_PX : side === 'right' ? TERMINAL_APPROACH_PX : 0),\n y:\n port.y +\n (side === 'top' ? -TERMINAL_APPROACH_PX : side === 'bottom' ? TERMINAL_APPROACH_PX : 0),\n },\n rank,\n onAssignedSide: trackAssignedSide ? side === assignment.side : undefined,\n });\n };\n\n // Negative ranks reserve precedence for the globally allocated slot and the bundle lane. The\n // remaining geometric alternatives are re-ranked after deterministic sorting.\n if (assignment && plan.bundleSize === 1) {\n addCandidate(assignment.side, assignment.coordinate, -2);\n }\n\n if (plan.bundleSize > 1) {\n const side = preferredSide(owner, { x: oppositeRect.cx, y: oppositeRect.cy });\n const ownerRect = rectForNode(owner);\n const center = side === 'left' || side === 'right' ? ownerRect.cy : ownerRect.cx;\n addCandidate(side, center + plan.laneOffset, -1);\n }\n\n const ownerDemands = [...(demandsByOwner.get(ownerId) ?? [])];\n for (const side of ['right', 'bottom', 'left', 'top'] as const) {\n const interval = sideInterval(owner, side);\n if (!interval) {\n continue;\n }\n const coordinates = preferredEndpointCoordinates(owner, side, ownerDemands);\n const demand = ownerDemands.find((entry) => entry.plan === plan && entry.role === role);\n const coordinate = demand ? coordinates.get(demand) : undefined;\n if (coordinate === undefined) {\n continue;\n }\n const rect = rectForNode(owner);\n const port =\n side === 'left' || side === 'right'\n ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n const distance = Math.abs(port.x - oppositeRect.cx) + Math.abs(port.y - oppositeRect.cy);\n addCandidate(side, coordinate, distance);\n }\n\n candidates.sort((a, b) => a.rank - b.rank || sideOrder(a.side) - sideOrder(b.side));\n candidates.forEach((candidate, index) => {\n candidate.rank = index;\n });\n return candidates;\n}\n\nexport function prepareEdgeRoutes(\n layout: LayoutData,\n result: GridLayoutResult\n): PreparedEdgeRoutes {\n // Route order is a correctness input because committed routes constrain later bundle siblings.\n // Harder hierarchy and loop routes go first, followed by fewer candidate combinations and stable\n // lexical tie-breakers.\n const plans = collectRoutePlans(layout, result);\n const pairCounts = new Map<string, number>();\n const endpointIncidentCounts = new Map<string, number>();\n for (const plan of plans) {\n const key = endpointPairKey(plan.edge);\n pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);\n if (plan.edge.start) {\n endpointIncidentCounts.set(\n plan.edge.start,\n (endpointIncidentCounts.get(plan.edge.start) ?? 0) + 1\n );\n }\n if (plan.edge.end && plan.edge.end !== plan.edge.start) {\n endpointIncidentCounts.set(\n plan.edge.end,\n (endpointIncidentCounts.get(plan.edge.end) ?? 0) + 1\n );\n }\n }\n const eligiblePlans = plans.filter(\n (plan) =>\n plan.edge.start !== plan.edge.end &&\n plan.source.chain.length === 1 &&\n plan.target.chain.length === 1 &&\n plan.source.finalKind === 'item' &&\n plan.target.finalKind === 'item'\n );\n const endpointDemandsByOwner = new Map<string, EndpointDemandEntry[]>();\n for (const plan of eligiblePlans) {\n const source = result.forest.nodeById.get(plan.edge.start!);\n const target = result.forest.nodeById.get(plan.edge.end!);\n if (!source || !target) {\n continue;\n }\n const sourceDemands = endpointDemandsByOwner.get(source.id) ?? [];\n sourceDemands.push({ plan, role: 'source', opposite: target });\n endpointDemandsByOwner.set(source.id, sourceDemands);\n const targetDemands = endpointDemandsByOwner.get(target.id) ?? [];\n targetDemands.push({ plan, role: 'target', opposite: source });\n endpointDemandsByOwner.set(target.id, targetDemands);\n }\n const endpointAssignmentsByOwner = new Map(\n [...endpointDemandsByOwner].map(([ownerId, demands]) => {\n const owner = result.forest.nodeById.get(ownerId);\n return [ownerId, owner ? allocateEndpointSlots(owner, demands) : new Map()] as const;\n })\n );\n const coordinatedEndpointIds = new Set<string>();\n const coordinatedOwnerIds = new Set<string>();\n for (const [ownerId, demands] of endpointDemandsByOwner) {\n const owner = result.forest.nodeById.get(ownerId);\n if (!owner) {\n continue;\n }\n const hasAligned = demands.some((demand) => isAxisAlignedDemand(owner, demand));\n const hasUnaligned = demands.some((demand) => !isAxisAlignedDemand(owner, demand));\n if (hasAligned && hasUnaligned) {\n coordinatedOwnerIds.add(ownerId);\n // The aligned edge already has its straight route, so only the others need the sparse search.\n for (const demand of demands) {\n if (!isAxisAlignedDemand(owner, demand)) {\n coordinatedEndpointIds.add(demand.plan.edge.id);\n }\n }\n }\n }\n const endpointCandidatesByEdge = new Map(\n eligiblePlans.map((plan) => [\n plan.edge.id,\n {\n sources: endpointCandidates(\n plan,\n 'source',\n endpointDemandsByOwner,\n endpointAssignmentsByOwner,\n coordinatedOwnerIds,\n result\n ),\n targets: endpointCandidates(\n plan,\n 'target',\n endpointDemandsByOwner,\n endpointAssignmentsByOwner,\n coordinatedOwnerIds,\n result\n ),\n },\n ])\n );\n const endpointCandidateProducts = new Map(\n [...endpointCandidatesByEdge].map(([edgeId, candidates]) => [\n edgeId,\n candidates.sources.length * candidates.targets.length,\n ])\n );\n const routeClass = (plan: EdgeRoutePlan): number => {\n const source = result.forest.nodeById.get(plan.edge.start!);\n const target = result.forest.nodeById.get(plan.edge.end!);\n if (plan.edge.start === plan.edge.end) {\n return 0;\n }\n if (\n (source?.isGroup && target && isAncestorGroup(source.id, target, result.forest.nodeById)) ||\n (target?.isGroup && source && isAncestorGroup(target.id, source, result.forest.nodeById))\n ) {\n return 1;\n }\n if ((source?.parentId ?? ROOT_CONTAINER_ID) !== (target?.parentId ?? ROOT_CONTAINER_ID)) {\n return 2;\n }\n return pairCounts.get(endpointPairKey(plan.edge))! > 1 ? 3 : 4;\n };\n const orderedPlans = [...plans].sort((a, b) => {\n const aUnordered = endpointPairKey(a.edge);\n const bUnordered = endpointPairKey(b.edge);\n const aDirected = `${a.edge.start ?? ''}|${a.edge.end ?? ''}`;\n const bDirected = `${b.edge.start ?? ''}|${b.edge.end ?? ''}`;\n const aBoundaryCount = a.source.chain.length + a.target.chain.length - 2;\n const bBoundaryCount = b.source.chain.length + b.target.chain.length - 2;\n return (\n routeClass(a) - routeClass(b) ||\n bBoundaryCount - aBoundaryCount ||\n (endpointCandidateProducts.get(a.edge.id) ?? 0) -\n (endpointCandidateProducts.get(b.edge.id) ?? 0) ||\n compareCodeUnits(aUnordered, bUnordered) ||\n compareCodeUnits(aDirected, bDirected) ||\n compareCodeUnits(a.edge.id, b.edge.id)\n );\n });\n return {\n plans,\n eligiblePlans,\n eligibleIds: new Set(eligiblePlans.map(({ edge }) => edge.id)),\n orderedPlans,\n demandCoords: assignDemandCoordinates(orderedPlans, result, endpointIncidentCounts),\n endpointCandidatesByEdge,\n endpointIncidentCounts,\n coordinatedEndpointIds,\n };\n}\n", "import type { Point } from '../../../types.js';\nimport type { Node } from '../../types.js';\nimport { normalizePolyline, PIXEL_EPSILON } from '../layout-utils/geometry.js';\nimport { rectForNode } from '../layout-utils/helpers.js';\nimport {\n LANE_SEPARATION_PX,\n TERMINAL_APPROACH_PX,\n type EndpointCandidate,\n} from './routerPlanning.js';\nimport { ROUTE_CLEARANCE_PX } from './routerTopology.js';\nimport type {\n GridContainerId,\n GridLayoutResult,\n GridOrientation,\n RouterPoint,\n RouterRect,\n} from './types.js';\nimport { isEdgeLabelNode } from './types.js';\n\n// Centralizes post-route validity checks so sparse routes, compatibility fallbacks, and bundle\n// retries all enforce the same obstacle-clearance and lane-separation contract.\nexport function isPairSeparationError(error: unknown): boolean {\n if (!(error instanceof Error) || !('details' in error)) {\n return false;\n }\n const details = error.details;\n return (\n typeof details === 'object' &&\n details !== null &&\n 'reason' in details &&\n details.reason === 'pair-separation'\n );\n}\n\nexport function routerRect(node: Node): RouterRect {\n const rect = rectForNode(node);\n return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom };\n}\n\nfunction canonicalizeOrthogonalPolyline(points: readonly Point[]): Point[] | undefined {\n if (points.length < 2 || points.some(({ x, y }) => !Number.isFinite(x) || !Number.isFinite(y))) {\n return undefined;\n }\n\n const collapsed: Point[] = [{ ...points[0] }];\n for (let index = 1; index < points.length; index++) {\n const point = points[index];\n const previous = collapsed.at(-1)!;\n const isNearDuplicate =\n Math.abs(point.x - previous.x) <= PIXEL_EPSILON &&\n Math.abs(point.y - previous.y) <= PIXEL_EPSILON;\n if (!isNearDuplicate) {\n collapsed.push({ ...point });\n continue;\n }\n if (index !== points.length - 1) {\n continue;\n }\n while (collapsed.length > 1) {\n const beforePrevious = collapsed.at(-2)!;\n if (\n Math.abs(point.x - beforePrevious.x) > PIXEL_EPSILON ||\n Math.abs(point.y - beforePrevious.y) > PIXEL_EPSILON\n ) {\n break;\n }\n collapsed.pop();\n }\n if (collapsed.length === 1) {\n return undefined;\n }\n collapsed[collapsed.length - 1] = { ...point };\n }\n if (collapsed.length < 2) {\n return undefined;\n }\n\n const orientations: GridOrientation[] = [];\n for (let index = 0; index < collapsed.length - 1; index++) {\n const a = collapsed[index];\n const b = collapsed[index + 1];\n const dx = Math.abs(b.x - a.x);\n const dy = Math.abs(b.y - a.y);\n if (dy <= PIXEL_EPSILON) {\n orientations.push('H');\n } else if (dx <= PIXEL_EPSILON) {\n orientations.push('V');\n } else {\n return undefined;\n }\n }\n\n const canonical = collapsed.map((point) => ({ ...point }));\n for (let start = 0; start < orientations.length; ) {\n const orientation = orientations[start];\n let end = start + 1;\n while (end < orientations.length && orientations[end] === orientation) {\n end++;\n }\n const axis = orientation === 'H' ? 'y' : 'x';\n if (\n start === 0 &&\n end === collapsed.length - 1 &&\n collapsed[start][axis] !== collapsed[end][axis]\n ) {\n return undefined;\n }\n const coordinate = end === collapsed.length - 1 ? collapsed[end][axis] : collapsed[start][axis];\n for (let pointIndex = start; pointIndex <= end; pointIndex++) {\n if (Math.abs(collapsed[pointIndex][axis] - coordinate) > PIXEL_EPSILON) {\n return undefined;\n }\n canonical[pointIndex][axis] = coordinate;\n }\n start = end;\n }\n return canonical;\n}\n\nfunction segmentEntersRect(a: Point, b: Point, rect: RouterRect): boolean {\n if (a.y === b.y) {\n return (\n a.y > rect.top &&\n a.y < rect.bottom &&\n Math.max(a.x, b.x) > rect.left &&\n Math.min(a.x, b.x) < rect.right\n );\n }\n if (a.x === b.x) {\n return (\n a.x > rect.left &&\n a.x < rect.right &&\n Math.max(a.y, b.y) > rect.top &&\n Math.min(a.y, b.y) < rect.bottom\n );\n }\n return true;\n}\n\nfunction inflatedRect(node: Node): RouterRect {\n const rect = routerRect(node);\n return {\n left: rect.left - ROUTE_CLEARANCE_PX,\n right: rect.right + ROUTE_CLEARANCE_PX,\n top: rect.top - ROUTE_CLEARANCE_PX,\n bottom: rect.bottom + ROUTE_CLEARANCE_PX,\n };\n}\n\nexport function validateSameContainerRoute(\n points: readonly Point[],\n source: Node,\n target: Node,\n containerId: GridContainerId,\n result: GridLayoutResult\n): boolean {\n // Terminal segments may touch their own endpoint rectangles, but must leave them directly and\n // every other segment must remain outside clearance-inflated child geometry.\n const canonical = canonicalizeOrthogonalPolyline(points);\n if (!canonical) {\n return false;\n }\n const normalized = normalizePolyline(canonical);\n if (normalized.points.length < 2) {\n return false;\n }\n if (\n normalized.segments.length > 1 &&\n (Math.abs(normalized.segments[0].a.x - normalized.segments[0].b.x) +\n Math.abs(normalized.segments[0].a.y - normalized.segments[0].b.y) <\n TERMINAL_APPROACH_PX ||\n Math.abs(normalized.segments.at(-1)!.a.x - normalized.segments.at(-1)!.b.x) +\n Math.abs(normalized.segments.at(-1)!.a.y - normalized.segments.at(-1)!.b.y) <\n TERMINAL_APPROACH_PX)\n ) {\n return false;\n }\n const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(\n (node) => !isEdgeLabelNode(node)\n );\n for (const obstacle of children) {\n const rect = inflatedRect(obstacle);\n for (let index = 0; index < normalized.points.length - 1; index++) {\n const terminalObstacle =\n (obstacle.id === source.id && index === 0) ||\n (obstacle.id === target.id && index === normalized.points.length - 2);\n if (terminalObstacle) {\n if (\n segmentEntersRect(\n normalized.points[index],\n normalized.points[index + 1],\n routerRect(obstacle)\n )\n ) {\n return false;\n }\n continue;\n }\n if (segmentEntersRect(normalized.points[index], normalized.points[index + 1], rect)) {\n return false;\n }\n }\n }\n return true;\n}\n\nexport function validateContainerSegment(\n points: readonly Point[],\n startOwnerId: string,\n endOwnerId: string,\n containerId: GridContainerId,\n result: GridLayoutResult\n): boolean {\n const canonical = canonicalizeOrthogonalPolyline(points);\n if (!canonical) {\n return false;\n }\n const normalized = normalizePolyline(canonical);\n if (normalized.points.length < 2) {\n return false;\n }\n const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(\n (node) => !isEdgeLabelNode(node)\n );\n for (const obstacle of children) {\n const rect = inflatedRect(obstacle);\n for (let index = 0; index < normalized.points.length - 1; index++) {\n const terminalObstacle =\n (obstacle.id === startOwnerId && index === 0) ||\n (obstacle.id === endOwnerId && index === normalized.points.length - 2);\n if (terminalObstacle) {\n if (\n segmentEntersRect(\n normalized.points[index],\n normalized.points[index + 1],\n routerRect(obstacle)\n )\n ) {\n return false;\n }\n continue;\n }\n if (segmentEntersRect(normalized.points[index], normalized.points[index + 1], rect)) {\n return false;\n }\n }\n }\n return true;\n}\n\nexport interface OrthogonalSegment {\n a: Point;\n b: Point;\n orientation: GridOrientation;\n}\n\nfunction segmentSpan(segment: OrthogonalSegment): { low: number; high: number } {\n return segment.orientation === 'H'\n ? { low: Math.min(segment.a.x, segment.b.x), high: Math.max(segment.a.x, segment.b.x) }\n : { low: Math.min(segment.a.y, segment.b.y), high: Math.max(segment.a.y, segment.b.y) };\n}\n\nexport function nonterminalSegments(points: readonly Point[]): OrthogonalSegment[] {\n const segments = normalizePolyline([...points])\n .segments.filter((segment) => segment.orientation !== 'Z')\n .map((segment) => ({\n a: { ...segment.a },\n b: { ...segment.b },\n orientation: segment.orientation as GridOrientation,\n }));\n if (segments.length === 0) {\n return [];\n }\n if (\n segments.length === 1 &&\n Math.abs(segments[0].a.x - segments[0].b.x) + Math.abs(segments[0].a.y - segments[0].b.y) <=\n TERMINAL_APPROACH_PX * 2\n ) {\n return [];\n }\n // Pair lanes may share the short attachment stubs at nodes. Trim those stubs before measuring\n // corridor overlap so only the independently routable interior is constrained.\n const trim = (segment: OrthogonalSegment, atStart: boolean): void => {\n if (segment.orientation === 'H') {\n const direction = Math.sign(segment.b.x - segment.a.x);\n if (atStart) {\n segment.a.x += direction * TERMINAL_APPROACH_PX;\n } else {\n segment.b.x -= direction * TERMINAL_APPROACH_PX;\n }\n } else {\n const direction = Math.sign(segment.b.y - segment.a.y);\n if (atStart) {\n segment.a.y += direction * TERMINAL_APPROACH_PX;\n } else {\n segment.b.y -= direction * TERMINAL_APPROACH_PX;\n }\n }\n };\n trim(segments[0], true);\n trim(segments[segments.length - 1], false);\n return segments.filter(({ a, b }) => a.x !== b.x || a.y !== b.y);\n}\n\nexport function pairSegmentsConflict(\n candidate: OrthogonalSegment,\n committed: OrthogonalSegment\n): boolean {\n if (candidate.orientation !== committed.orientation) {\n return false;\n }\n const first = segmentSpan(candidate);\n const second = segmentSpan(committed);\n const overlap = Math.max(0, Math.min(first.high, second.high) - Math.max(first.low, second.low));\n if (overlap <= 0) {\n return false;\n }\n const separation =\n candidate.orientation === 'H'\n ? Math.abs(candidate.a.y - committed.a.y)\n : Math.abs(candidate.a.x - committed.a.x);\n // Collinear overlap is illegal when lanes coincide for a meaningful distance or are closer than\n // the configured lane spacing. Endpoint-only contact has zero overlap and remains legal.\n return (\n (separation === 0 && overlap >= LANE_SEPARATION_PX) ||\n (separation > 0 && separation < LANE_SEPARATION_PX)\n );\n}\n\nexport function routeSatisfiesPairConstraints(\n points: readonly Point[],\n pairRoutes: readonly (readonly Point[])[]\n): boolean {\n const normalized = normalizePolyline([...points]).points;\n const candidatePorts = [normalized[0], normalized.at(-1)!];\n const candidateSegments = nonterminalSegments(normalized);\n return pairRoutes.every((route) => {\n const committed = normalizePolyline([...route]).points;\n const committedPorts = [committed[0], committed.at(-1)!];\n if (\n candidatePorts.some((port) =>\n committedPorts.some((other) => port.x === other.x && port.y === other.y)\n )\n ) {\n return false;\n }\n return candidateSegments.every((candidate) =>\n nonterminalSegments(committed).every(\n (committedSegment) => !pairSegmentsConflict(candidate, committedSegment)\n )\n );\n });\n}\n\nexport function routeHasDistinctPairPorts(\n points: readonly Point[],\n pairRoutes: readonly (readonly Point[])[]\n): boolean {\n const normalized = normalizePolyline([...points]).points;\n const candidatePorts = [normalized[0], normalized.at(-1)!];\n return pairRoutes.every((route) => {\n const committed = normalizePolyline([...route]).points;\n const committedPorts = [committed[0], committed.at(-1)!];\n return !candidatePorts.some((port) =>\n committedPorts.some((other) => port.x === other.x && port.y === other.y)\n );\n });\n}\n\nexport function pairArcAllowed(\n from: RouterPoint,\n to: RouterPoint,\n pairRoutes: readonly (readonly Point[])[]\n): boolean {\n const orientation: GridOrientation = from.y === to.y ? 'H' : 'V';\n const candidate = { a: from, b: to, orientation };\n return pairRoutes.every((route) =>\n nonterminalSegments(route).every(\n (committedSegment) => !pairSegmentsConflict(candidate, committedSegment)\n )\n );\n}\n\nexport function endpointPairLowerBound(\n source: EndpointCandidate,\n target: EndpointCandidate\n): readonly [length: number, bends: number] {\n // This admissible lower bound includes both terminal stubs and the minimum bend count implied by\n // endpoint orientations; candidate-pair search can safely prune against it.\n const sourceOrientation: GridOrientation =\n source.side === 'left' || source.side === 'right' ? 'H' : 'V';\n const targetOrientation: GridOrientation =\n target.side === 'left' || target.side === 'right' ? 'H' : 'V';\n const dx = Math.abs(source.connect.x - target.connect.x);\n const dy = Math.abs(source.connect.y - target.connect.y);\n let bends: number;\n if (dx === 0 && dy === 0) {\n bends = Number(sourceOrientation !== targetOrientation);\n } else if (dx === 0 || dy === 0) {\n const pathOrientation: GridOrientation = dx === 0 ? 'V' : 'H';\n bends =\n Number(sourceOrientation !== pathOrientation) + Number(targetOrientation !== pathOrientation);\n } else {\n bends = Math.min(\n Number(sourceOrientation !== 'H') + 1 + Number(targetOrientation !== 'V'),\n Number(sourceOrientation !== 'V') + 1 + Number(targetOrientation !== 'H')\n );\n }\n return [TERMINAL_APPROACH_PX * 2 + dx + dy, bends];\n}\n", "import type { Point } from '../../../types.js';\nimport { nonterminalSegments, type OrthogonalSegment } from './routerConstraint.js';\nimport { EDGE_CLEARANCE_PX } from './routerTopology.js';\nimport type { GridOrientation, RouterPoint } from './types.js';\n\nfunction segmentsTooClose(candidate: OrthogonalSegment, committed: OrthogonalSegment): boolean {\n if (candidate.orientation !== committed.orientation) {\n return false;\n }\n const horizontal = candidate.orientation === 'H';\n const lowOf = (segment: OrthogonalSegment) =>\n horizontal ? Math.min(segment.a.x, segment.b.x) : Math.min(segment.a.y, segment.b.y);\n const highOf = (segment: OrthogonalSegment) =>\n horizontal ? Math.max(segment.a.x, segment.b.x) : Math.max(segment.a.y, segment.b.y);\n const overlap =\n Math.min(highOf(candidate), highOf(committed)) - Math.max(lowOf(candidate), lowOf(committed));\n const separation = horizontal\n ? Math.abs(candidate.a.y - committed.a.y)\n : Math.abs(candidate.a.x - committed.a.x);\n return overlap > 0 && separation < EDGE_CLEARANCE_PX;\n}\n\ninterface OccupiedSegment {\n segment: OrthogonalSegment;\n pairKey: string;\n}\n\ninterface OccupancyLogEntry {\n orientation: GridOrientation;\n coordinate: number;\n}\n\n/**\n * Container-scoped index of committed route segments.\n *\n * Routes from different edges must not share a corridor, so every routed edge registers its\n * nonterminal segments here and later candidates query it with the clearance rule\n * (`segmentsTooClose`). Segments are bucketed by their fixed coordinate so a query\n * only inspects lines within the clearance instead of every committed segment.\n *\n * Routes are append-only and can be truncated back to an earlier size, which is how bundle retries\n * roll back state.\n */\nexport class RouteOccupancyIndex {\n private readonly lines: Record<'H' | 'V', Map<number, OccupiedSegment[]>> = {\n H: new Map(),\n V: new Map(),\n };\n private readonly sortedCoordinates: Record<'H' | 'V', number[] | undefined> = {\n H: undefined,\n V: undefined,\n };\n private readonly log: OccupancyLogEntry[] = [];\n\n get size(): number {\n return this.log.length;\n }\n\n add(route: readonly Point[], pairKey: string): void {\n for (const segment of nonterminalSegments(route)) {\n const orientation = segment.orientation as 'H' | 'V';\n const coordinate = orientation === 'H' ? segment.a.y : segment.a.x;\n const bucket = this.lines[orientation].get(coordinate);\n if (bucket) {\n bucket.push({ segment, pairKey });\n } else {\n this.lines[orientation].set(coordinate, [{ segment, pairKey }]);\n this.sortedCoordinates[orientation] = undefined;\n }\n this.log.push({ orientation, coordinate });\n }\n }\n\n truncate(size: number): void {\n while (this.log.length > size) {\n const { orientation, coordinate } = this.log.pop()!;\n this.lines[orientation].get(coordinate)?.pop();\n }\n }\n\n /** Reports whether a route shares a corridor with a committed route of another edge pair. */\n conflictsWithRoute(route: readonly Point[], pairKey: string): boolean {\n return nonterminalSegments(route).some((segment) => this.conflicts(segment, pairKey));\n }\n\n conflictsWithArc(from: RouterPoint, to: RouterPoint, pairKey: string): boolean {\n const orientation: GridOrientation = from.y === to.y ? 'H' : 'V';\n return this.conflicts({ a: from, b: to, orientation }, pairKey);\n }\n\n private conflicts(candidate: OrthogonalSegment, pairKey: string): boolean {\n const orientation = candidate.orientation as string;\n if (orientation !== 'H' && orientation !== 'V') {\n return false;\n }\n const coordinate = orientation === 'H' ? candidate.a.y : candidate.a.x;\n const coordinates = this.coordinatesFor(orientation);\n let low = 0;\n let high = coordinates.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if (coordinates[middle] <= coordinate - EDGE_CLEARANCE_PX) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n for (let index = low; index < coordinates.length; index++) {\n const key = coordinates[index];\n if (key >= coordinate + EDGE_CLEARANCE_PX) {\n break;\n }\n for (const occupied of this.lines[orientation].get(key)!) {\n if (occupied.pairKey !== pairKey && segmentsTooClose(candidate, occupied.segment)) {\n return true;\n }\n }\n }\n return false;\n }\n\n private coordinatesFor(orientation: 'H' | 'V'): number[] {\n return (this.sortedCoordinates[orientation] ??= [...this.lines[orientation].keys()].sort(\n (a, b) => a - b\n ));\n }\n}\n", "import type { Point } from '../../../types.js';\nimport type { Node } from '../../types.js';\nimport { normalizePolyline } from '../layout-utils/geometry.js';\nimport { manhattanLength, polylineIntersectsRect, rectForNode } from '../layout-utils/helpers.js';\nimport type { Rect } from '../layout-utils/types.js';\nimport { isAncestorGroup } from './groups.js';\nimport {\n GRID_LABEL_CLEARANCE,\n GRID_LABEL_SPAN_MARGIN,\n type GridLabelSpanRequirement,\n} from './labelGeometry.js';\nimport type { GridRoutingTestOptions } from './router.js';\nimport {\n routerRect,\n validateContainerSegment,\n validateSameContainerRoute,\n} from './routerConstraint.js';\nimport { RouteOccupancyIndex } from './routerOccupancy.js';\nimport {\n LANE_SEPARATION_PX,\n TERMINAL_APPROACH_PX,\n ownerGroupTitle,\n ownerSideKey,\n type EdgeEndpointPlan,\n type EdgeRoutePlan,\n type PreparedEdgeRoutes,\n} from './routerPlanning.js';\nimport { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport {\n buildContainerRoutingTopology,\n DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n derivePortalRanges,\n ROUTE_CLEARANCE_PX,\n} from './routerTopology.js';\nimport type {\n GridAttachment,\n GridContainerId,\n GridLayoutResult,\n GridRoutingContext,\n GridSide,\n PairedPortal,\n PortalRange,\n RouterRect,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError, isEdgeLabelNode } from './types.js';\n\n// Deterministic corridor routing remains the validated fast path and the resource-limit fallback\n// while sparse visibility routing is incrementally adopted for harder routes.\nconst ROOT_OUTER_MARGIN = 24;\n\nexport const SELF_LOOP_PORT_GAP = 18;\n\nconst SELF_LOOP_APPROACH = 14;\n\n// validateLayout rejects endpoints within 3 px of a node corner.\nconst SELF_LOOP_CORNER_CLEARANCE = 4;\n\nconst SELF_LOOP_TRACK_GAP = 18;\n\nexport const SELF_LOOP_PORT_OFFSET_STEP = 4;\n\nexport interface PreparedRoutingModes {\n overlapAvoidanceEnabled: boolean;\n compatibilityFastRoutes: Map<string, Point[]>;\n sparseHierarchyIds: Set<string>;\n sparseLcaIds: Set<string>;\n routedContainerIds: GridContainerId[];\n routeOccupancy: Map<GridContainerId, RouteOccupancyIndex>;\n}\n\nconst MAX_PLANS_FOR_OVERLAP_AVOIDANCE = 64;\nconst MAX_FAST_ROUTE_SEPARATION_STEPS = 4;\n\n/**\n * Moves one interior segment of a minimal corridor route sideways until it no longer shares a\n * corridor with another edge's route. Shifting an interior segment keeps both terminal stubs and\n * the Manhattan length, so the result is accepted only if it still passes the caller's validation.\n */\nfunction separateRouteFromOccupied(\n route: readonly Point[],\n occupancy: RouteOccupancyIndex,\n pairKey: string,\n isAcceptable: (candidate: Point[]) => boolean\n): Point[] | undefined {\n if (!occupancy.conflictsWithRoute(route, pairKey)) {\n return [...route];\n }\n const points = normalizePolyline([...route]).points;\n for (let step = 1; step <= MAX_FAST_ROUTE_SEPARATION_STEPS; step++) {\n for (const sign of [1, -1]) {\n const delta = sign * step * LANE_SEPARATION_PX;\n for (let index = 1; index < points.length - 2; index++) {\n const vertical = points[index].x === points[index + 1].x;\n const shifted = points.map((point, pointIndex) =>\n pointIndex === index || pointIndex === index + 1\n ? vertical\n ? { x: point.x + delta, y: point.y }\n : { x: point.x, y: point.y + delta }\n : point\n );\n if (!occupancy.conflictsWithRoute(shifted, pairKey) && isAcceptable(shifted)) {\n return shifted;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction terminalStubsAreLongEnough(points: readonly Point[]): boolean {\n const stub = (a: Point, b: Point) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);\n return (\n stub(points[0], points[1]) >= TERMINAL_APPROACH_PX &&\n stub(points.at(-1)!, points.at(-2)!) >= TERMINAL_APPROACH_PX\n );\n}\n\nexport function boundedAlternativePortalCoordinates(\n selected: number,\n low: number,\n high: number,\n corridors: readonly number[],\n limit = 3\n): number[] {\n // Retry the nearest established corridors first, then the range's canonical midpoint and ends.\n // The hard limit bounds hierarchy retry fan-out and keeps output independent of map iteration.\n const candidates = [\n ...corridors\n .filter((coordinate) => coordinate >= low && coordinate <= high)\n .sort((a, b) => Math.abs(a - selected) - Math.abs(b - selected) || a - b),\n (low + high) / 2,\n low,\n high,\n ];\n const seen = new Set<number>([selected]);\n const alternatives: number[] = [];\n for (const coordinate of candidates) {\n if (seen.has(coordinate)) {\n continue;\n }\n seen.add(coordinate);\n alternatives.push(coordinate);\n if (alternatives.length === limit) {\n break;\n }\n }\n return alternatives;\n}\n\nfunction equalPoint(a: Point, b: Point): boolean {\n return Math.abs(a.x - b.x) <= 1e-6 && Math.abs(a.y - b.y) <= 1e-6;\n}\n\nexport function areExactlyAxisAligned(a: Point, b: Point): boolean {\n return a.x === b.x || a.y === b.y;\n}\n\nfunction chooseIntermediateCoordinate(\n values: number[],\n start: number,\n end: number,\n variant: number\n): number {\n const sorted = [...values].sort(\n (a, b) =>\n Math.abs(a - start) + Math.abs(a - end) - (Math.abs(b - start) + Math.abs(b - end)) || a - b\n );\n return sorted[Math.min(variant, Math.max(0, sorted.length - 1))] ?? (start + end) / 2;\n}\n\nfunction dedupeConsecutive(points: Point[]): Point[] {\n const out: Point[] = [];\n for (const point of points) {\n if (out.length === 0 || !equalPoint(out[out.length - 1], point)) {\n out.push(point);\n }\n }\n return out;\n}\n\nexport function routeWithinContainer(\n containerId: GridContainerId,\n result: GridLayoutResult,\n start: GridAttachment,\n end: GridAttachment,\n variant: number\n): Point[] {\n // This compatibility router only chooses among measured grid corridors. `variant` selects the\n // next deterministic dogleg when a bundle retry needs a different lane.\n const container = result.containers.get(containerId);\n if (!container) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing container layout \"${containerId}\"`);\n }\n\n const points: Point[] = [start.port, start.connect];\n if (start.orientation === 'V' && end.orientation === 'V') {\n if (\n !equalPoint(start.connect, end.connect) &&\n Math.abs(start.connect.x - end.connect.x) > 1e-6\n ) {\n const y = chooseIntermediateCoordinate(\n container.horizontalCorridors,\n start.connect.y,\n end.connect.y,\n variant\n );\n points.push({ x: start.connect.x, y }, { x: end.connect.x, y });\n } else if (\n !equalPoint(start.connect, end.connect) &&\n Math.abs(start.connect.y - end.connect.y) > 1e-6 &&\n variant > 0\n ) {\n const alternateCorridors = container.verticalCorridors.filter(\n (value) => Math.abs(value - start.connect.x) > 1e-6\n );\n const x = chooseIntermediateCoordinate(\n alternateCorridors.length > 0 ? alternateCorridors : container.verticalCorridors,\n start.connect.x,\n end.connect.x,\n variant - 1\n );\n points.push({ x, y: start.connect.y }, { x, y: end.connect.y });\n }\n } else if (start.orientation === 'H' && end.orientation === 'H') {\n if (\n !equalPoint(start.connect, end.connect) &&\n Math.abs(start.connect.y - end.connect.y) > 1e-6\n ) {\n const x = chooseIntermediateCoordinate(\n container.verticalCorridors,\n start.connect.x,\n end.connect.x,\n variant\n );\n points.push({ x, y: start.connect.y }, { x, y: end.connect.y });\n }\n } else if (start.orientation === 'V' && end.orientation === 'H') {\n points.push({ x: start.connect.x, y: end.connect.y });\n } else {\n points.push({ x: end.connect.x, y: start.connect.y });\n }\n points.push(end.connect, end.port);\n return normalizePolyline(dedupeConsecutive(points)).points;\n}\n\nexport function itemAttachment(\n ownerId: string,\n side: GridSide,\n demandKey: string,\n containerId: GridContainerId,\n result: GridLayoutResult,\n demandCoords: Map<string, number>,\n coordinate?: number\n): GridAttachment {\n const owner = result.forest.nodeById.get(ownerId);\n const item = result.itemMeta.get(ownerId);\n if (!owner || !item || item.containerId !== containerId) {\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n `Missing item metadata for \"${ownerId}\" in \"${containerId}\"`\n );\n }\n\n const rect = rectForNode(owner);\n const coord =\n coordinate ??\n demandCoords.get(demandKey) ??\n (side === 'left' || side === 'right' ? rect.cy : rect.cx);\n switch (side) {\n case 'left':\n return {\n port: { x: rect.left, y: coord },\n connect: { x: item.leftCorridorX, y: coord },\n orientation: 'V',\n side,\n };\n case 'right':\n return {\n port: { x: rect.right, y: coord },\n connect: { x: item.rightCorridorX, y: coord },\n orientation: 'V',\n side,\n };\n case 'top':\n return {\n port: { x: coord, y: rect.top },\n connect: { x: coord, y: item.topCorridorY },\n orientation: 'H',\n side,\n };\n case 'bottom':\n return {\n port: { x: coord, y: rect.bottom },\n connect: { x: coord, y: item.bottomCorridorY },\n orientation: 'H',\n side,\n };\n }\n}\n\nexport function boundaryAttachment(\n containerId: GridContainerId,\n side: GridSide,\n demandKey: string,\n result: GridLayoutResult,\n demandCoords: Map<string, number>\n): GridAttachment {\n const owner = result.forest.nodeById.get(containerId);\n const container = result.containers.get(containerId);\n if (!owner || !container) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing boundary metadata for \"${containerId}\"`);\n }\n const rect = rectForNode(owner);\n const coord =\n demandCoords.get(demandKey) ?? (side === 'left' || side === 'right' ? rect.cy : rect.cx);\n switch (side) {\n case 'left':\n return {\n port: { x: rect.left, y: coord },\n connect: { x: container.verticalCorridors[0], y: coord },\n orientation: 'V',\n side,\n };\n case 'right':\n return {\n port: { x: rect.right, y: coord },\n connect: {\n x: container.verticalCorridors[container.verticalCorridors.length - 1],\n y: coord,\n },\n orientation: 'V',\n side,\n };\n case 'top':\n return {\n port: { x: coord, y: rect.top },\n connect: { x: coord, y: container.horizontalCorridors[0] },\n orientation: 'H',\n side,\n };\n case 'bottom':\n return {\n port: { x: coord, y: rect.bottom },\n connect: {\n x: coord,\n y: container.horizontalCorridors[container.horizontalCorridors.length - 1],\n },\n orientation: 'H',\n side,\n };\n }\n}\n\nexport interface SegmentAttachment extends GridAttachment {\n ownerId: string;\n}\n\nexport interface SegmentAttachmentAlternative {\n attachment: SegmentAttachment;\n select: () => void;\n}\n\nfunction portalBoundaryPoint(portal: PairedPortal): Point {\n return {\n x: (portal.interior.x + portal.exterior.x) / 2,\n y: (portal.interior.y + portal.exterior.y) / 2,\n };\n}\n\nexport function portalAttachment(portal: PairedPortal, interior: boolean): SegmentAttachment {\n // The visible port is the group boundary midpoint; search starts on one side of the clearance\n // transition so each container topology remains independent.\n return {\n ownerId: portal.ownerId,\n port: portalBoundaryPoint(portal),\n connect: interior ? portal.interior : portal.exterior,\n orientation: portal.side === 'left' || portal.side === 'right' ? 'V' : 'H',\n side: portal.side,\n };\n}\n\nexport function groupBoundaryEndpointAttachment(\n ownerId: string,\n side: GridSide,\n demandKey: string,\n result: GridLayoutResult,\n demandCoords: Map<string, number>\n): SegmentAttachment {\n const owner = result.forest.nodeById.get(ownerId);\n if (!owner?.isGroup) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing group endpoint \"${ownerId}\"`);\n }\n const rect = rectForNode(owner);\n const coordinate =\n demandCoords.get(demandKey) ?? (side === 'left' || side === 'right' ? rect.cy : rect.cx);\n const port =\n side === 'left' || side === 'right'\n ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n return {\n ownerId,\n port,\n connect: {\n x:\n port.x +\n (side === 'left' ? TERMINAL_APPROACH_PX : side === 'right' ? -TERMINAL_APPROACH_PX : 0),\n y:\n port.y +\n (side === 'top' ? TERMINAL_APPROACH_PX : side === 'bottom' ? -TERMINAL_APPROACH_PX : 0),\n },\n orientation: side === 'left' || side === 'right' ? 'V' : 'H',\n side,\n };\n}\n\nexport function reversePoints(points: Point[]): Point[] {\n return [...points].reverse();\n}\n\nexport function combinePointChains(chains: Point[][]): Point[] {\n const points: Point[] = [];\n for (const chain of chains) {\n for (const point of chain) {\n if (points.length === 0 || !equalPoint(points[points.length - 1], point)) {\n points.push(point);\n }\n }\n }\n return normalizePolyline(points).points;\n}\n\nfunction routeSelfLoop(owner: Node, side: GridSide, index: number, demandCoord: number): Point[] {\n const rect = rectForNode(owner);\n const depth = SELF_LOOP_APPROACH + (index + 1) * SELF_LOOP_TRACK_GAP;\n const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;\n switch (side) {\n case 'right': {\n const startY = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n const endY = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n return normalizePolyline([\n { x: rect.right, y: startY },\n { x: rect.right + SELF_LOOP_APPROACH, y: startY },\n { x: rect.right + depth, y: startY },\n { x: rect.right + depth, y: endY },\n { x: rect.right + SELF_LOOP_APPROACH, y: endY },\n { x: rect.right, y: endY },\n ]).points;\n }\n case 'left': {\n const startY = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n const endY = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n return normalizePolyline([\n { x: rect.left, y: startY },\n { x: rect.left - SELF_LOOP_APPROACH, y: startY },\n { x: rect.left - depth, y: startY },\n { x: rect.left - depth, y: endY },\n { x: rect.left - SELF_LOOP_APPROACH, y: endY },\n { x: rect.left, y: endY },\n ]).points;\n }\n case 'top': {\n const startX = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n const endX = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n return normalizePolyline([\n { x: startX, y: rect.top },\n { x: startX, y: rect.top - SELF_LOOP_APPROACH },\n { x: startX, y: rect.top - depth },\n { x: endX, y: rect.top - depth },\n { x: endX, y: rect.top - SELF_LOOP_APPROACH },\n { x: endX, y: rect.top },\n ]).points;\n }\n case 'bottom': {\n const startX = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n const endX = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n return normalizePolyline([\n { x: startX, y: rect.bottom },\n { x: startX, y: rect.bottom + SELF_LOOP_APPROACH },\n { x: startX, y: rect.bottom + depth },\n { x: endX, y: rect.bottom + depth },\n { x: endX, y: rect.bottom + SELF_LOOP_APPROACH },\n { x: endX, y: rect.bottom },\n ]).points;\n }\n }\n}\n\nexport function labelAwareSelfLoopCandidates(\n owner: Node,\n side: GridSide,\n index: number,\n demandCoord: number,\n requirement: GridLabelSpanRequirement\n): Point[][] {\n const rect = rectForNode(owner);\n const baseDepth = SELF_LOOP_APPROACH + (index + 1) * SELF_LOOP_TRACK_GAP;\n const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;\n const baseSpan = SELF_LOOP_PORT_GAP + portOffset * 2;\n const verticalSide = side === 'left' || side === 'right';\n const span = Math.max(\n baseSpan,\n (verticalSide ? requirement.cross : requirement.along) +\n GRID_LABEL_CLEARANCE * 2 +\n GRID_LABEL_SPAN_MARGIN\n );\n const depth = Math.max(\n baseDepth,\n (verticalSide ? requirement.along : requirement.cross) / 2 + GRID_LABEL_CLEARANCE\n );\n const interval = verticalSide ? [rect.top, rect.bottom] : [rect.left, rect.right];\n const directStart = demandCoord - span / 2;\n const directEnd = demandCoord + span / 2;\n\n if (\n directStart - interval[0] >= SELF_LOOP_CORNER_CLEARANCE &&\n interval[1] - directEnd >= SELF_LOOP_CORNER_CLEARANCE\n ) {\n switch (side) {\n case 'right':\n return [\n normalizePolyline([\n { x: rect.right, y: directStart },\n { x: rect.right + depth, y: directStart },\n { x: rect.right + depth, y: directEnd },\n { x: rect.right, y: directEnd },\n ]).points,\n ];\n case 'left':\n return [\n normalizePolyline([\n { x: rect.left, y: directStart },\n { x: rect.left - depth, y: directStart },\n { x: rect.left - depth, y: directEnd },\n { x: rect.left, y: directEnd },\n ]).points,\n ];\n case 'top':\n return [\n normalizePolyline([\n { x: directStart, y: rect.top },\n { x: directStart, y: rect.top - depth },\n { x: directEnd, y: rect.top - depth },\n { x: directEnd, y: rect.top },\n ]).points,\n ];\n case 'bottom':\n return [\n normalizePolyline([\n { x: directStart, y: rect.bottom },\n { x: directStart, y: rect.bottom + depth },\n { x: directEnd, y: rect.bottom + depth },\n { x: directEnd, y: rect.bottom },\n ]).points,\n ];\n }\n }\n\n const portStart = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n const portEnd = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n if (portStart < interval[0] || portEnd > interval[1]) {\n return [];\n }\n const outerStart = demandCoord - span / 2;\n const outerEnd = demandCoord + span / 2;\n const shoulderApproach = Math.max(SELF_LOOP_APPROACH, TERMINAL_APPROACH_PX);\n // Keep the label clear of the return shoulders as well as the owner.\n const shoulderDepth = Math.max(\n depth,\n shoulderApproach +\n (verticalSide ? requirement.along : requirement.cross) / 2 +\n GRID_LABEL_CLEARANCE\n );\n switch (side) {\n case 'right':\n return [\n normalizePolyline([\n { x: rect.right, y: portStart },\n { x: rect.right + shoulderApproach, y: portStart },\n { x: rect.right + shoulderApproach, y: outerStart },\n { x: rect.right + shoulderDepth, y: outerStart },\n { x: rect.right + shoulderDepth, y: outerEnd },\n { x: rect.right + shoulderApproach, y: outerEnd },\n { x: rect.right + shoulderApproach, y: portEnd },\n { x: rect.right, y: portEnd },\n ]).points,\n ];\n case 'left':\n return [\n normalizePolyline([\n { x: rect.left, y: portStart },\n { x: rect.left - shoulderApproach, y: portStart },\n { x: rect.left - shoulderApproach, y: outerStart },\n { x: rect.left - shoulderDepth, y: outerStart },\n { x: rect.left - shoulderDepth, y: outerEnd },\n { x: rect.left - shoulderApproach, y: outerEnd },\n { x: rect.left - shoulderApproach, y: portEnd },\n { x: rect.left, y: portEnd },\n ]).points,\n ];\n case 'top':\n return [\n normalizePolyline([\n { x: portStart, y: rect.top },\n { x: portStart, y: rect.top - shoulderApproach },\n { x: outerStart, y: rect.top - shoulderApproach },\n { x: outerStart, y: rect.top - shoulderDepth },\n { x: outerEnd, y: rect.top - shoulderDepth },\n { x: outerEnd, y: rect.top - shoulderApproach },\n { x: portEnd, y: rect.top - shoulderApproach },\n { x: portEnd, y: rect.top },\n ]).points,\n ];\n case 'bottom':\n return [\n normalizePolyline([\n { x: portStart, y: rect.bottom },\n { x: portStart, y: rect.bottom + shoulderApproach },\n { x: outerStart, y: rect.bottom + shoulderApproach },\n { x: outerStart, y: rect.bottom + shoulderDepth },\n { x: outerEnd, y: rect.bottom + shoulderDepth },\n { x: outerEnd, y: rect.bottom + shoulderApproach },\n { x: portEnd, y: rect.bottom + shoulderApproach },\n { x: portEnd, y: rect.bottom },\n ]).points,\n ];\n }\n}\n\nexport function orderedSelfLoopSides(\n node: Node,\n counts: Map<string, number>,\n selfLoopCounts: Map<string, number>\n): GridSide[] {\n const sides: GridSide[] =\n node.isGroup && ownerGroupTitle(node)\n ? ['left', 'right', 'bottom']\n : ['left', 'right', 'top', 'bottom'];\n return sides.sort((a, b) => {\n const aCount =\n (counts.get(ownerSideKey(node.id, a)) ?? 0) + (selfLoopCounts.get(`${node.id}:${a}`) ?? 0);\n const bCount =\n (counts.get(ownerSideKey(node.id, b)) ?? 0) + (selfLoopCounts.get(`${node.id}:${b}`) ?? 0);\n return aCount - bCount;\n });\n}\n\nfunction selfLoopObstacles(owner: Node, result: GridLayoutResult): Rect[] {\n const obstacles: Rect[] = [];\n for (const node of result.forest.nodeById.values()) {\n if (node.id !== owner.id && !node.isGroup && node.x !== undefined && node.y !== undefined) {\n obstacles.push(rectForNode(node));\n }\n if (node.id !== owner.id && node.groupTitleRect) {\n const { left, right, top, bottom } = node.groupTitleRect;\n obstacles.push({\n cx: (left + right) / 2,\n cy: (top + bottom) / 2,\n left,\n right,\n top,\n bottom,\n });\n }\n }\n return obstacles;\n}\n\nexport function routeObstacleClearSelfLoop(\n owner: Node,\n ownerSideCounts: Map<string, number>,\n selfLoopCounts: Map<string, number>,\n result: GridLayoutResult,\n labelRequirement?: GridLabelSpanRequirement,\n metrics?: GridRoutingInstrumentation\n): { points: Point[]; side: GridSide; index: number } {\n // Side load determines preference, but fixed side ordering breaks ties deterministically.\n const rect = rectForNode(owner);\n const obstacles = selfLoopObstacles(owner, result);\n for (const side of orderedSelfLoopSides(owner, ownerSideCounts, selfLoopCounts)) {\n const countKey = `${owner.id}:${side}`;\n const index = selfLoopCounts.get(countKey) ?? 0;\n const demandCoord = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n const candidates = labelRequirement\n ? labelAwareSelfLoopCandidates(owner, side, index, demandCoord, labelRequirement)\n : [routeSelfLoop(owner, side, index, demandCoord)];\n if (labelRequirement && metrics) {\n metrics.labelAwareSelfLoopCandidates += candidates.length;\n }\n for (const points of candidates) {\n if (!obstacles.some((obstacle) => polylineIntersectsRect(points, obstacle))) {\n return { points, side, index };\n }\n }\n }\n throw gridError('GRID_ROUTE_NOT_FOUND', `No obstacle-clear self-loop route for \"${owner.id}\"`, {\n nodeId: owner.id,\n });\n}\n\nexport function rootContainerMeta(result: GridLayoutResult): void {\n if (result.containers.has(ROOT_CONTAINER_ID)) {\n return;\n }\n let minLeft = 0;\n let maxRight = 0;\n let minTop = 0;\n let maxBottom = 0;\n let first = true;\n for (const item of result.itemMeta.values()) {\n if (item.containerId !== ROOT_CONTAINER_ID) {\n continue;\n }\n if (first) {\n minLeft = item.cellLeft;\n maxRight = item.cellLeft + item.cellWidth;\n minTop = item.cellTop;\n maxBottom = item.cellTop + item.cellHeight;\n first = false;\n } else {\n minLeft = Math.min(minLeft, item.cellLeft);\n maxRight = Math.max(maxRight, item.cellLeft + item.cellWidth);\n minTop = Math.min(minTop, item.cellTop);\n maxBottom = Math.max(maxBottom, item.cellTop + item.cellHeight);\n }\n }\n\n const horizontalCorridors = new Set<number>([\n minTop - ROOT_OUTER_MARGIN,\n maxBottom + ROOT_OUTER_MARGIN,\n ]);\n // The synthetic root has no node bounds, so derive its routable domain from root cells and keep\n // an outer track available for routes that must pass around the whole diagram.\n const verticalCorridors = new Set<number>([\n minLeft - ROOT_OUTER_MARGIN,\n maxRight + ROOT_OUTER_MARGIN,\n ]);\n for (const item of result.itemMeta.values()) {\n if (item.containerId !== ROOT_CONTAINER_ID) {\n continue;\n }\n horizontalCorridors.add(item.topCorridorY);\n horizontalCorridors.add(item.bottomCorridorY);\n verticalCorridors.add(item.leftCorridorX);\n verticalCorridors.add(item.rightCorridorX);\n }\n result.containers.set(ROOT_CONTAINER_ID, {\n id: ROOT_CONTAINER_ID,\n left: minLeft - ROOT_OUTER_MARGIN,\n top: minTop - ROOT_OUTER_MARGIN,\n width: maxRight - minLeft + ROOT_OUTER_MARGIN * 2,\n height: maxBottom - minTop + ROOT_OUTER_MARGIN * 2,\n contentLeft: minLeft,\n contentTop: minTop,\n contentRight: maxRight,\n contentBottom: maxBottom,\n verticalCorridors: [...verticalCorridors].sort((a, b) => a - b),\n horizontalCorridors: [...horizontalCorridors].sort((a, b) => a - b),\n });\n}\n\nfunction containerBounds(containerId: GridContainerId, result: GridLayoutResult): RouterRect {\n const container = result.containers.get(containerId);\n if (!container) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing container layout \"${containerId}\"`);\n }\n if (containerId === ROOT_CONTAINER_ID) {\n const rootItems = [...result.itemMeta.values()].filter(\n ({ containerId: ownerContainerId }) => ownerContainerId === ROOT_CONTAINER_ID\n );\n if (rootItems.length > 0) {\n return {\n left: Math.min(...rootItems.map(({ cellLeft }) => cellLeft)) - ROOT_OUTER_MARGIN,\n right:\n Math.max(...rootItems.map(({ cellLeft, cellWidth }) => cellLeft + cellWidth)) +\n ROOT_OUTER_MARGIN,\n top: Math.min(...rootItems.map(({ cellTop }) => cellTop)) - ROOT_OUTER_MARGIN,\n bottom:\n Math.max(...rootItems.map(({ cellTop, cellHeight }) => cellTop + cellHeight)) +\n ROOT_OUTER_MARGIN,\n };\n }\n return {\n left: container.left,\n right: container.left + container.width,\n top: container.top,\n bottom: container.top + container.height,\n };\n }\n const owner = result.forest.nodeById.get(containerId);\n if (!owner) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing container owner \"${containerId}\"`);\n }\n const ownerBounds = routerRect(owner);\n return {\n left: ownerBounds.left + ROUTE_CLEARANCE_PX,\n right: ownerBounds.right - ROUTE_CLEARANCE_PX,\n top: ownerBounds.top + ROUTE_CLEARANCE_PX,\n bottom: ownerBounds.bottom - ROUTE_CLEARANCE_PX,\n };\n}\n\nfunction portalCoordinate(bounds: RouterRect, side: GridSide, interior: boolean): number {\n const boundary =\n side === 'left'\n ? bounds.left\n : side === 'right'\n ? bounds.right\n : side === 'top'\n ? bounds.top\n : bounds.bottom;\n const towardInterior = side === 'left' || side === 'top' ? 1 : -1;\n return boundary + towardInterior * ROUTE_CLEARANCE_PX * (interior ? 1 : -1);\n}\n\nfunction containerPortalRanges(\n containerId: GridContainerId,\n result: GridLayoutResult\n): PortalRange[] {\n const ranges: PortalRange[] = [];\n if (containerId !== ROOT_CONTAINER_ID) {\n const owner = result.forest.nodeById.get(containerId);\n if (owner) {\n const bounds = routerRect(owner);\n ranges.push(\n ...derivePortalRanges(containerId, bounds, owner.groupTitleRect).map((range) => ({\n ...range,\n coordinate: portalCoordinate(bounds, range.side, true),\n }))\n );\n }\n }\n for (const child of result.forest.childrenByParent.get(containerId) ?? []) {\n if (!child.isGroup) {\n continue;\n }\n const bounds = routerRect(child);\n ranges.push(\n ...derivePortalRanges(child.id, bounds, child.groupTitleRect).map((range) => ({\n ...range,\n coordinate: portalCoordinate(bounds, range.side, false),\n }))\n );\n }\n return ranges;\n}\n\nexport function buildRoutingContext(\n containerIds: readonly GridContainerId[],\n result: GridLayoutResult,\n metrics: GridRoutingInstrumentation | undefined,\n options: GridRoutingTestOptions\n): GridRoutingContext {\n // Build each immutable container topology once. Per-edge endpoints are added later as cheap\n // overlays, avoiding repeated obstacle sweeps for large diagrams.\n const context: GridRoutingContext = {\n topologies: new Map(),\n fallbackContainers: new Map(),\n searchBudget: { expandedStates: 0 },\n searchBudgetWarningEmitted: false,\n baseEstimatedBytes: 0,\n metrics,\n };\n let estimatedBytes = 0;\n for (const containerId of [...new Set(containerIds)].sort()) {\n const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(\n (node) => !isEdgeLabelNode(node)\n );\n const title = result.forest.nodeById.get(containerId)?.groupTitleRect;\n try {\n const topology = buildContainerRoutingTopology(\n {\n containerId,\n bounds: containerBounds(containerId, result),\n obstacles: children.map((node) => ({ id: node.id, bounds: routerRect(node) })),\n titleExclusions: title\n ? [{ id: `${containerId}:title`, bounds: { ...title } }]\n : undefined,\n portalRanges: containerPortalRanges(containerId, result),\n },\n { caps: options.topologyCaps }\n );\n const invocationMemoryCap =\n options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES;\n if (estimatedBytes + topology.estimatedBytes > invocationMemoryCap) {\n // Keep the invocation-wide cap honest: an individually valid topology may still exceed the\n // aggregate budget when combined with topologies already retained by this routing session.\n context.fallbackContainers.set(containerId, 'estimated_memory_cap');\n continue;\n }\n estimatedBytes += topology.estimatedBytes;\n context.baseEstimatedBytes = estimatedBytes;\n context.topologies.set(containerId, topology);\n if (metrics) {\n metrics.containersBuilt++;\n metrics.baseTopologyBuilds++;\n metrics.baseVertices += topology.vertices.length;\n metrics.baseAdjacencyEntries += topology.adjacencyEntries;\n metrics.buildSweepEvents += topology.seedCount * 4 + topology.obstacles.length * 4;\n metrics.estimatedBytes = estimatedBytes;\n }\n } catch (error) {\n if (!(error instanceof GridRoutingResourceLimitError)) {\n throw error;\n }\n context.fallbackContainers.set(containerId, error.reason);\n }\n }\n return context;\n}\n\nexport function validatedCompatibilitySegment(\n edgeId: string,\n containerId: GridContainerId,\n start: SegmentAttachment,\n end: SegmentAttachment,\n route: () => Point[],\n result: GridLayoutResult,\n metrics?: GridRoutingInstrumentation\n): Point[] {\n const points = route();\n if (metrics) {\n metrics.compatibilitySegments++;\n }\n if (validateContainerSegment(points, start.ownerId, end.ownerId, containerId, result)) {\n return points;\n }\n if (metrics) {\n metrics.compatibilityValidationFailures++;\n metrics.routesImpossible++;\n }\n throw gridError('GRID_ROUTE_NOT_FOUND', `Invalid compatibility route for \"${edgeId}\"`, {\n edgeId,\n containerId,\n });\n}\n\nexport function compatibilityLcaAttachments(\n plan: EdgeRoutePlan,\n result: GridLayoutResult,\n demandCoords: Map<string, number>\n): { start: SegmentAttachment; end: SegmentAttachment } {\n const sourceFinal = plan.source.chain.at(-1)!;\n const targetFinal = plan.target.chain.at(-1)!;\n const finalAttachment = (\n endpoint: typeof plan.source,\n final: (typeof plan.source.chain)[number]\n ): SegmentAttachment => ({\n ownerId: final.ownerId,\n ...(endpoint.finalKind === 'boundary'\n ? boundaryAttachment(plan.lcaContainerId, final.side, final.demandKey, result, demandCoords)\n : itemAttachment(\n final.ownerId,\n final.side,\n final.demandKey,\n plan.lcaContainerId,\n result,\n demandCoords\n )),\n });\n return {\n start: finalAttachment(plan.source, sourceFinal),\n end: finalAttachment(plan.target, targetFinal),\n };\n}\n\nexport interface CompatibilitySegmentAttachments {\n containerId: GridContainerId;\n start: SegmentAttachment;\n end: SegmentAttachment;\n}\n\nexport function compatibilityHierarchyAttachments(\n endpoint: EdgeEndpointPlan,\n result: GridLayoutResult,\n demandCoords: Map<string, number>\n): CompatibilitySegmentAttachments[] {\n return endpoint.chain.slice(0, -1).map((from, index) => {\n const to = endpoint.chain[index + 1];\n return {\n containerId: to.ownerId,\n start: {\n ownerId: from.ownerId,\n ...itemAttachment(\n from.ownerId,\n from.side,\n from.demandKey,\n to.ownerId,\n result,\n demandCoords\n ),\n },\n end: {\n ownerId: to.ownerId,\n ...boundaryAttachment(to.ownerId, to.side, to.demandKey, result, demandCoords),\n },\n };\n });\n}\n\nfunction compatibilityPlanIsValid(\n plan: EdgeRoutePlan,\n result: GridLayoutResult,\n demandCoords: Map<string, number>\n): boolean {\n const segmentIsValid = (\n containerId: GridContainerId,\n start: SegmentAttachment,\n end: SegmentAttachment\n ): boolean =>\n validateContainerSegment(\n routeWithinContainer(containerId, result, start, end, plan.laneIndex),\n start.ownerId,\n end.ownerId,\n containerId,\n result\n );\n for (const endpoint of [plan.source, plan.target]) {\n for (const { containerId, start, end } of compatibilityHierarchyAttachments(\n endpoint,\n result,\n demandCoords\n )) {\n if (!segmentIsValid(containerId, start, end)) {\n return false;\n }\n }\n }\n const attachments = compatibilityLcaAttachments(plan, result, demandCoords);\n return segmentIsValid(plan.lcaContainerId, attachments.start, attachments.end);\n}\n\nexport /*\n * Grid routing currently uses two algorithms:\n *\n * - `routeWithinContainer()` is the deterministic corridor router. During normal rendering, an\n * ordinary unbundled same-container edge uses it as a fast path when its endpoint ports are\n * legal, the complete route passes measured-geometry validation, and its length equals the\n * Manhattan lower bound. This avoids building a visibility topology and running A* for\n * routes that sparse search cannot improve.\n * - The sparse visibility router handles self-loops, bundles, ordinary routes that fail the\n * fast path, and hierarchy routes that need alternative portals or obstacle-aware search.\n *\n * Test-only topology/search caps and dual-route comparison disable the fast path intentionally:\n * those modes must exercise sparse topology, search, and fallback behavior. Normal router and\n * performance tests cover the production fast path separately.\n *\n * Hierarchy routing is still partially migrated. Bundles, routes whose two endpoints have no\n * unrelated incident edges, and plans whose corridor route fails validation use sparse routing\n * for every hierarchy-chain segment. Other single hierarchy edges may retain validated\n * corridor segments when at least one endpoint is shared with another edge.\n * Group-to-descendant routes always use sparse routing for their LCA segment, even when their\n * ascent or descent chain still uses corridor routing. Defined sparse resource-limit failures\n * also use the corridor route as a fallback, but only after that route passes the same geometry\n * and pair-separation validation.\n *\n * Finishing the migration requires sparse routing to handle the remaining mixed-demand\n * hierarchy segments without introducing shared subpaths or crossings, and to meet the large\n * graph performance target without the common-edge fast path. It also requires generated\n * nested hierarchy, label, loop, bundle, and fallback coverage plus release-level validation.\n * Only then can `routeWithinContainer()`, corridor metadata, compatibility/fallback\n * instrumentation, and their obsolete tests be removed.\n */\nfunction prepareRoutingModes(\n prepared: PreparedEdgeRoutes,\n result: GridLayoutResult,\n metrics: GridRoutingInstrumentation | undefined,\n options: GridRoutingTestOptions\n): PreparedRoutingModes {\n // Classify every plan before building topologies: proven minimal corridor routes avoid sparse\n // setup, while only containers needed by sparse LCA, hierarchy, or loop segments are materialized.\n const {\n plans,\n eligiblePlans,\n eligibleIds,\n demandCoords,\n endpointCandidatesByEdge,\n endpointIncidentCounts,\n coordinatedEndpointIds,\n } = prepared;\n const hasIsolatedEndpoints = (plan: EdgeRoutePlan): boolean =>\n (endpointIncidentCounts.get(plan.edge.start!) ?? 0) === plan.bundleSize &&\n (endpointIncidentCounts.get(plan.edge.end!) ?? 0) === plan.bundleSize;\n const hasAncestorEndpoint = (plan: EdgeRoutePlan): boolean => {\n const source = result.forest.nodeById.get(plan.edge.start!);\n const target = result.forest.nodeById.get(plan.edge.end!);\n return Boolean(\n source &&\n target &&\n ((source.isGroup && isAncestorGroup(source.id, target, result.forest.nodeById)) ||\n (target.isGroup && isAncestorGroup(target.id, source, result.forest.nodeById)))\n );\n };\n const compatibilityFastRoutes = new Map<string, Point[]>();\n const routeOccupancy = new Map<GridContainerId, RouteOccupancyIndex>();\n const overlapAvoidanceEnabled = plans.length <= MAX_PLANS_FOR_OVERLAP_AVOIDANCE;\n const compatibilityFastPathEnabled =\n options.topologyCaps === undefined &&\n options.searchCaps === undefined &&\n options.onDualRouteComparison === undefined;\n for (const plan of compatibilityFastPathEnabled ? eligiblePlans : []) {\n if (coordinatedEndpointIds.has(plan.edge.id)) {\n continue;\n }\n const candidates = endpointCandidatesByEdge.get(plan.edge.id);\n if (plan.bundleSize !== 1 || !candidates?.sources.length || !candidates.targets.length) {\n continue;\n }\n const source = result.forest.nodeById.get(plan.edge.start!);\n const target = result.forest.nodeById.get(plan.edge.end!);\n if (!source || !target) {\n continue;\n }\n const attachments = compatibilityLcaAttachments(plan, result, demandCoords);\n const route = routeWithinContainer(\n plan.lcaContainerId,\n result,\n attachments.start,\n attachments.end,\n plan.laneIndex\n );\n const normalized = normalizePolyline(route);\n const first = normalized.points[0];\n const last = normalized.points.at(-1);\n if (!first || !last) {\n continue;\n }\n const sourceCandidate = candidates.sources.find(\n ({ port }) => port.x === first.x && port.y === first.y\n );\n const targetCandidate = candidates.targets.find(\n ({ port }) => port.x === last.x && port.y === last.y\n );\n if (!sourceCandidate || !targetCandidate) {\n continue;\n }\n if (metrics) {\n metrics.compatibilityFastPathAttempts++;\n }\n const lowerBoundLength = Math.abs(first.x - last.x) + Math.abs(first.y - last.y);\n if (!validateSameContainerRoute(route, source, target, plan.lcaContainerId, result)) {\n if (metrics) {\n metrics.compatibilityFastPathValidationFailures++;\n }\n continue;\n }\n if (manhattanLength(normalized.points) !== lowerBoundLength) {\n if (metrics) {\n metrics.compatibilityFastPathNonMinimalRoutes++;\n }\n continue;\n }\n // Small layouts demote a route that runs close and parallel to an earlier edge to sparse\n // routing. Large layouts keep the fast path to stay search-free within the performance\n // contract, nudging the route sideways when possible.\n let occupancy = routeOccupancy.get(plan.lcaContainerId);\n if (!occupancy) {\n occupancy = new RouteOccupancyIndex();\n routeOccupancy.set(plan.lcaContainerId, occupancy);\n }\n const conflicting = occupancy.conflictsWithRoute(normalized.points, plan.pairKey);\n if (conflicting && overlapAvoidanceEnabled) {\n // The sparse router can choose other ports and corridors, which reads better than a nudge.\n continue;\n }\n const separated = separateRouteFromOccupied(\n normalized.points,\n occupancy,\n plan.pairKey,\n (candidate) =>\n terminalStubsAreLongEnough(candidate) &&\n manhattanLength(candidate) === lowerBoundLength &&\n validateSameContainerRoute(candidate, source, target, plan.lcaContainerId, result)\n );\n const finalRoute = separated ?? route;\n occupancy.add(finalRoute, plan.pairKey);\n compatibilityFastRoutes.set(plan.edge.id, finalRoute);\n }\n const sparseCandidate = (plan: EdgeRoutePlan): boolean =>\n !eligibleIds.has(plan.edge.id) &&\n plan.edge.start !== plan.edge.end &&\n (plan.bundleSize > 1 ||\n hasIsolatedEndpoints(plan) ||\n !compatibilityPlanIsValid(plan, result, demandCoords));\n const planningOccupancy = new Map<GridContainerId, RouteOccupancyIndex>();\n const overlappingHierarchyIds = new Set<string>();\n if (overlapAvoidanceEnabled) {\n for (const plan of prepared.orderedPlans) {\n if (\n eligibleIds.has(plan.edge.id) ||\n plan.edge.start === plan.edge.end ||\n hasAncestorEndpoint(plan) ||\n sparseCandidate(plan)\n ) {\n continue;\n }\n const attachments = compatibilityLcaAttachments(plan, result, demandCoords);\n const route = routeWithinContainer(\n plan.lcaContainerId,\n result,\n attachments.start,\n attachments.end,\n plan.laneIndex\n );\n let occupancy = planningOccupancy.get(plan.lcaContainerId);\n if (!occupancy) {\n occupancy = new RouteOccupancyIndex();\n planningOccupancy.set(plan.lcaContainerId, occupancy);\n }\n if (occupancy.conflictsWithRoute(route, plan.pairKey)) {\n overlappingHierarchyIds.add(plan.edge.id);\n } else {\n occupancy.add(route, plan.pairKey);\n }\n }\n }\n const sparseHierarchyIds = new Set([\n ...plans.filter(sparseCandidate).map(({ edge }) => edge.id),\n ...overlappingHierarchyIds,\n ]);\n const sparseLcaIds = new Set([\n ...sparseHierarchyIds,\n ...plans.filter(hasAncestorEndpoint).map(({ edge }) => edge.id),\n ]);\n const routedContainerIds = plans\n .filter(\n (plan) =>\n (eligibleIds.has(plan.edge.id) && !compatibilityFastRoutes.has(plan.edge.id)) ||\n sparseLcaIds.has(plan.edge.id) ||\n plan.edge.start === plan.edge.end\n )\n .flatMap((plan) => [\n plan.lcaContainerId,\n ...plan.source.chain.slice(1).map(({ ownerId }) => ownerId),\n ...plan.target.chain.slice(1).map(({ ownerId }) => ownerId),\n ]);\n return {\n overlapAvoidanceEnabled,\n compatibilityFastRoutes,\n sparseHierarchyIds,\n sparseLcaIds,\n routedContainerIds,\n routeOccupancy,\n };\n}\n", "import type { Point } from '../../../types.js';\nimport { normalizePolyline, segmentsCross } from '../layout-utils/geometry.js';\nimport { manhattanLength } from '../layout-utils/helpers.js';\n\n// Instrumentation doubles as observable behavior for retries. Work counters are cumulative, while\n// committed-output counters must roll back with a failed bundle attempt.\nexport type GridRoutingFallbackReason =\n | 'vertex_cap'\n | 'adjacency_cap'\n | 'estimated_memory_cap'\n | 'search_state_cap'\n | 'label_index_work_cap'\n | 'label_placement_exhausted';\n\nexport interface GridRouteInstrumentation {\n edgeId: string;\n routeOrder: number;\n laneOffset: number;\n routeLength: number;\n bendCount: number;\n crossingCount: number;\n sharedLength: number;\n boundaryTransitionCount: number;\n routeSignature: string;\n}\n\nexport interface GridRoutingInstrumentation {\n containersBuilt: number;\n baseTopologyBuilds: number;\n baseVertices: number;\n baseAdjacencyEntries: number;\n buildSweepEvents: number;\n endpointOverlayBuilds: number;\n endpointOverlayVertices: number;\n hierarchyPortalPairs: number;\n hierarchyPortalTransitionLength: number;\n hierarchyPortalAlternativeAttempts: number;\n hierarchyPortalAlternativeSelections: number;\n hierarchyBoundaryTransitions: number;\n labelOverlayBuilds: number;\n labelOverlayVertices: number;\n labelSpacingEdgesExamined: number;\n labelSpacingEligibleEdges: number;\n labelSpacingBoundariesExpanded: number;\n labelSpacingPixelsAdded: number;\n labelAwareSelfLoopCandidates: number;\n labelAwareSelfLoopsCommitted: number;\n labelAwareSelfLoopFallbacks: number;\n searches: number;\n expandedStates: number;\n maxOpenSet: number;\n routesFound: number;\n routesImpossible: number;\n resourceLimitFallbacks: number;\n fallbackReasons: Record<GridRoutingFallbackReason, number>;\n fallbackValidationFailures: number;\n compatibilitySegments: number;\n compatibilityFastPathAttempts: number;\n compatibilityFastPaths: number;\n compatibilityFastPathValidationFailures: number;\n compatibilityFastPathNonMinimalRoutes: number;\n compatibilityRecoveries: number;\n compatibilityValidationFailures: number;\n bundleSeparationRelaxations: number;\n routeLength: number;\n bendCount: number;\n crossingCount: number;\n sharedLength: number;\n estimatedBytes: number;\n searchWorkspaceBytes: number;\n routeOrder: string[];\n routes: GridRouteInstrumentation[];\n}\n\nexport const gridRoutingMetricDisposition = {\n containersBuilt: 'cumulative',\n baseTopologyBuilds: 'cumulative',\n baseVertices: 'cumulative',\n baseAdjacencyEntries: 'cumulative',\n buildSweepEvents: 'cumulative',\n endpointOverlayBuilds: 'cumulative',\n endpointOverlayVertices: 'cumulative',\n hierarchyPortalPairs: 'transactional',\n hierarchyPortalTransitionLength: 'transactional',\n hierarchyPortalAlternativeAttempts: 'cumulative',\n hierarchyPortalAlternativeSelections: 'transactional',\n hierarchyBoundaryTransitions: 'transactional',\n labelOverlayBuilds: 'cumulative',\n labelOverlayVertices: 'cumulative',\n labelSpacingEdgesExamined: 'cumulative',\n labelSpacingEligibleEdges: 'cumulative',\n labelSpacingBoundariesExpanded: 'cumulative',\n labelSpacingPixelsAdded: 'cumulative',\n labelAwareSelfLoopCandidates: 'cumulative',\n labelAwareSelfLoopsCommitted: 'transactional',\n labelAwareSelfLoopFallbacks: 'cumulative',\n searches: 'cumulative',\n expandedStates: 'cumulative',\n maxOpenSet: 'cumulative',\n routesFound: 'transactional',\n routesImpossible: 'transactional',\n resourceLimitFallbacks: 'cumulative',\n fallbackReasons: 'cumulative',\n fallbackValidationFailures: 'cumulative',\n compatibilitySegments: 'transactional',\n compatibilityFastPathAttempts: 'cumulative',\n compatibilityFastPaths: 'cumulative',\n compatibilityFastPathValidationFailures: 'cumulative',\n compatibilityFastPathNonMinimalRoutes: 'cumulative',\n compatibilityRecoveries: 'transactional',\n compatibilityValidationFailures: 'cumulative',\n bundleSeparationRelaxations: 'transactional',\n routeLength: 'transactional',\n bendCount: 'transactional',\n crossingCount: 'transactional',\n sharedLength: 'transactional',\n estimatedBytes: 'cumulative',\n searchWorkspaceBytes: 'cumulative',\n routeOrder: 'transactional',\n routes: 'transactional',\n} as const satisfies Record<keyof GridRoutingInstrumentation, 'transactional' | 'cumulative'>;\n\n// Deriving checkpoint keys from the exhaustive disposition map forces every new metric to declare\n// whether retries preserve the work or restore the committed result.\ntype TransactionalGridRoutingMetric = {\n [K in keyof typeof gridRoutingMetricDisposition]: (typeof gridRoutingMetricDisposition)[K] extends 'transactional'\n ? K\n : never;\n}[keyof typeof gridRoutingMetricDisposition];\n\ntype TransactionalGridRoutingValueMetric = Exclude<\n TransactionalGridRoutingMetric,\n 'routeOrder' | 'routes'\n>;\n\nconst transactionalGridRoutingValueMetrics = (\n Object.keys(gridRoutingMetricDisposition) as (keyof GridRoutingInstrumentation)[]\n).filter(\n (key): key is TransactionalGridRoutingValueMetric =>\n gridRoutingMetricDisposition[key] === 'transactional' &&\n key !== 'routeOrder' &&\n key !== 'routes'\n);\n\nexport interface GridRoutingInstrumentationCheckpoint {\n routeOrderLength: number;\n routesLength: number;\n values: Pick<GridRoutingInstrumentation, TransactionalGridRoutingValueMetric>;\n}\n\nexport function createGridRoutingInstrumentationCheckpoint(\n metrics: GridRoutingInstrumentation\n): GridRoutingInstrumentationCheckpoint {\n // Route arrays are append-only during an attempt, so lengths are sufficient and avoid cloning\n // potentially large per-edge records on every bundle retry.\n return {\n routeOrderLength: metrics.routeOrder.length,\n routesLength: metrics.routes.length,\n values: Object.fromEntries(\n transactionalGridRoutingValueMetrics.map((key) => [key, metrics[key]])\n ) as GridRoutingInstrumentationCheckpoint['values'],\n };\n}\n\nexport function restoreGridRoutingInstrumentationCheckpoint(\n metrics: GridRoutingInstrumentation,\n checkpoint: GridRoutingInstrumentationCheckpoint\n): void {\n metrics.routeOrder.length = checkpoint.routeOrderLength;\n metrics.routes.length = checkpoint.routesLength;\n Object.assign(metrics, checkpoint.values);\n}\n\nexport function createGridRoutingInstrumentation(): GridRoutingInstrumentation {\n return {\n containersBuilt: 0,\n baseTopologyBuilds: 0,\n baseVertices: 0,\n baseAdjacencyEntries: 0,\n buildSweepEvents: 0,\n endpointOverlayBuilds: 0,\n endpointOverlayVertices: 0,\n hierarchyPortalPairs: 0,\n hierarchyPortalTransitionLength: 0,\n hierarchyPortalAlternativeAttempts: 0,\n hierarchyPortalAlternativeSelections: 0,\n hierarchyBoundaryTransitions: 0,\n labelOverlayBuilds: 0,\n labelOverlayVertices: 0,\n labelSpacingEdgesExamined: 0,\n labelSpacingEligibleEdges: 0,\n labelSpacingBoundariesExpanded: 0,\n labelSpacingPixelsAdded: 0,\n labelAwareSelfLoopCandidates: 0,\n labelAwareSelfLoopsCommitted: 0,\n labelAwareSelfLoopFallbacks: 0,\n searches: 0,\n expandedStates: 0,\n maxOpenSet: 0,\n routesFound: 0,\n routesImpossible: 0,\n resourceLimitFallbacks: 0,\n fallbackReasons: {\n vertex_cap: 0,\n adjacency_cap: 0,\n estimated_memory_cap: 0,\n search_state_cap: 0,\n label_index_work_cap: 0,\n label_placement_exhausted: 0,\n },\n fallbackValidationFailures: 0,\n compatibilitySegments: 0,\n compatibilityFastPathAttempts: 0,\n compatibilityFastPaths: 0,\n compatibilityFastPathValidationFailures: 0,\n compatibilityFastPathNonMinimalRoutes: 0,\n compatibilityRecoveries: 0,\n compatibilityValidationFailures: 0,\n bundleSeparationRelaxations: 0,\n routeLength: 0,\n bendCount: 0,\n crossingCount: 0,\n sharedLength: 0,\n estimatedBytes: 0,\n searchWorkspaceBytes: 0,\n routeOrder: [],\n routes: [],\n };\n}\n\nfunction intervalOverlap(\n firstStart: number,\n firstEnd: number,\n secondStart: number,\n secondEnd: number\n): number {\n return Math.max(\n 0,\n Math.min(Math.max(firstStart, firstEnd), Math.max(secondStart, secondEnd)) -\n Math.max(Math.min(firstStart, firstEnd), Math.min(secondStart, secondEnd))\n );\n}\n\nfunction sharedSegmentLength(first: Point[], second: Point[]): number {\n const firstSegments = normalizePolyline(first).segments;\n const secondSegments = normalizePolyline(second).segments;\n let total = 0;\n\n for (const a of firstSegments) {\n for (const b of secondSegments) {\n if (a.orientation !== b.orientation) {\n continue;\n }\n if (a.orientation === 'H' && a.a.y === b.a.y) {\n total += intervalOverlap(a.a.x, a.b.x, b.a.x, b.b.x);\n } else if (a.orientation === 'V' && a.a.x === b.a.x) {\n total += intervalOverlap(a.a.y, a.b.y, b.a.y, b.b.y);\n }\n }\n }\n return total;\n}\n\nexport function recordGridRoute(\n metrics: GridRoutingInstrumentation,\n edgeId: string,\n points: Point[],\n previousRoutes: readonly Point[][],\n boundaryTransitionCount = 0,\n laneOffset = 0\n): void {\n // Quality metrics compare only against previously committed routes, matching visible route order\n // and avoiding double-counting pairs.\n const normalized = normalizePolyline(points);\n let crossingCount = 0;\n let sharedLength = 0;\n\n for (const previous of previousRoutes) {\n const previousSegments = normalizePolyline(previous).segments;\n for (const segment of normalized.segments) {\n for (const previousSegment of previousSegments) {\n if (segmentsCross(segment, previousSegment)) {\n crossingCount++;\n }\n }\n }\n sharedLength += sharedSegmentLength(normalized.points, previous);\n }\n\n const route: GridRouteInstrumentation = {\n edgeId,\n routeOrder: metrics.routes.length,\n laneOffset,\n routeLength: manhattanLength(normalized.points),\n bendCount: normalized.bends,\n crossingCount,\n sharedLength,\n boundaryTransitionCount,\n routeSignature: JSON.stringify(normalized.points),\n };\n metrics.routeOrder.push(edgeId);\n metrics.routes.push(route);\n metrics.routesFound++;\n metrics.routeLength += route.routeLength;\n metrics.bendCount += route.bendCount;\n metrics.crossingCount += route.crossingCount;\n metrics.sharedLength += route.sharedLength;\n metrics.hierarchyBoundaryTransitions += boundaryTransitionCount;\n}\n", "import { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type {\n ContainerRoutingTopology,\n GridOrientation,\n GridSide,\n RouterPoint,\n RouterVertex,\n} from './types.js';\n\n// A* minimizes this tuple lexicographically. Length and bends dominate hierarchy transitions and\n// endpoint preference, which are deterministic tie-breakers rather than weighted approximations.\nexport type RouterTupleCost = [\n length: number,\n bends: number,\n boundaryTransitions: number,\n endpointCandidateRank: number,\n];\n\nexport interface RouterSearchResult {\n points: RouterPoint[];\n vertexIds: number[];\n cost: RouterTupleCost;\n}\n\nexport interface RouterSearchCaps {\n maxExpandedStates?: number;\n maxInvocationExpandedStates?: number;\n maxEstimatedBytes?: number;\n}\n\nexport interface RouterSearchBudget {\n expandedStates: number;\n}\n\nexport interface RouterSearchOptions {\n metrics?: GridRoutingInstrumentation;\n caps?: RouterSearchCaps;\n endpointCandidateRank?: number;\n recordOutcome?: boolean;\n budget?: RouterSearchBudget;\n initialOrientation?: GridOrientation;\n initialSide?: GridSide;\n initialLength?: number;\n targetOrientation?: GridOrientation;\n targetSide?: GridSide;\n targetLength?: number;\n topologyValidated?: boolean;\n workspace?: RouterSearchWorkspace;\n heuristic?: 'bend-aware' | 'zero';\n queueOrder?: 'canonical' | 'reverse';\n estimatedBytesBase?: number;\n arcAllowed?: (from: RouterPoint, to: RouterPoint) => boolean;\n}\n\nconst DEFAULT_MAX_EDGE_STATES = 100_000;\nconst DEFAULT_MAX_INVOCATION_STATES = 2_000_000;\n\nexport class RouterSearchWorkspace {\n // Typed arrays are retained across searches to avoid allocating object-heavy state graphs for\n // every endpoint candidate pair. State capacity grows geometrically and never shrinks mid-session.\n stateVertices = new Int32Array(256);\n orientations = new Uint8Array(256);\n gLengths = new Float64Array(256);\n gBends = new Float64Array(256);\n gBoundaryTransitions = new Float64Array(256);\n fLengths = new Float64Array(256);\n fBends = new Float64Array(256);\n predecessors = new Int32Array(256);\n depths = new Int32Array(256);\n ancestor4 = new Int32Array(256);\n best = new Int32Array(256);\n heapChildren = new Int32Array(256);\n heapSiblings = new Int32Array(256);\n heapPairs: number[] = [];\n touchedBestIndices: number[] = [];\n\n constructor() {\n this.best.fill(-1);\n }\n\n reset(vertexCount: number): void {\n const bestLength = vertexCount * 3;\n if (this.best.length < bestLength) {\n this.best = new Int32Array(bestLength);\n this.best.fill(-1);\n } else {\n for (const index of this.touchedBestIndices) {\n this.best[index] = -1;\n }\n }\n this.touchedBestIndices.length = 0;\n this.heapPairs.length = 0;\n }\n\n setBest(index: number, state: number): void {\n if (this.best[index] < 0) {\n this.touchedBestIndices.push(index);\n }\n this.best[index] = state;\n }\n\n ensureStateCapacity(required: number): void {\n if (this.stateVertices.length >= required) {\n return;\n }\n const capacity = Math.max(required, this.stateVertices.length * 2);\n this.stateVertices = growTypedArray(this.stateVertices, capacity);\n this.orientations = growTypedArray(this.orientations, capacity);\n this.gLengths = growTypedArray(this.gLengths, capacity);\n this.gBends = growTypedArray(this.gBends, capacity);\n this.gBoundaryTransitions = growTypedArray(this.gBoundaryTransitions, capacity);\n this.fLengths = growTypedArray(this.fLengths, capacity);\n this.fBends = growTypedArray(this.fBends, capacity);\n this.predecessors = growTypedArray(this.predecessors, capacity);\n this.depths = growTypedArray(this.depths, capacity);\n this.ancestor4 = growTypedArray(this.ancestor4, capacity);\n this.heapChildren = growTypedArray(this.heapChildren, capacity);\n this.heapSiblings = growTypedArray(this.heapSiblings, capacity);\n }\n\n estimatedBytes(): number {\n return (\n this.stateVertices.byteLength +\n this.orientations.byteLength +\n this.gLengths.byteLength +\n this.gBends.byteLength +\n this.gBoundaryTransitions.byteLength +\n this.fLengths.byteLength +\n this.fBends.byteLength +\n this.predecessors.byteLength +\n this.depths.byteLength +\n this.ancestor4.byteLength +\n this.best.byteLength +\n this.heapChildren.byteLength +\n this.heapSiblings.byteLength +\n (this.heapPairs.length + this.touchedBestIndices.length) * 8\n );\n }\n}\n\nexport function assertSearchBudgetAvailable(\n options: Pick<RouterSearchOptions, 'metrics' | 'caps' | 'budget'>\n): void {\n const edgeCap = options.caps?.maxExpandedStates ?? DEFAULT_MAX_EDGE_STATES;\n const invocationCap = options.caps?.maxInvocationExpandedStates ?? DEFAULT_MAX_INVOCATION_STATES;\n const invocationStart = options.budget?.expandedStates ?? options.metrics?.expandedStates ?? 0;\n if (edgeCap > 0 && invocationStart < invocationCap) {\n return;\n }\n throw new GridRoutingResourceLimitError(\n 'search_state_cap',\n 'Grid routing search-state cap exceeded',\n invocationStart >= invocationCap ? 'invocation' : 'edge'\n );\n}\n\nfunction growTypedArray<T extends Int32Array | Uint8Array | Float64Array>(\n values: T,\n capacity: number\n): T {\n const grown = new (values.constructor as new (length: number) => T)(capacity);\n grown.set(values);\n return grown;\n}\nexport function compareTupleCost(a: RouterTupleCost, b: RouterTupleCost): number {\n for (let index = 0; index < 4; index++) {\n if (a[index] < b[index]) {\n return -1;\n }\n if (a[index] > b[index]) {\n return 1;\n }\n }\n return 0;\n}\n\nfunction minimumBends(\n dx: number,\n dy: number,\n incomingOrientation?: GridOrientation,\n targetOrientation?: GridOrientation\n): number {\n if (dx === 0 && dy === 0) {\n return incomingOrientation && targetOrientation\n ? Number(incomingOrientation !== targetOrientation)\n : 0;\n }\n if (dx === 0) {\n return (\n (incomingOrientation ? Number(incomingOrientation !== 'V') : 0) +\n (targetOrientation ? Number(targetOrientation !== 'V') : 0)\n );\n }\n if (dy === 0) {\n return (\n (incomingOrientation ? Number(incomingOrientation !== 'H') : 0) +\n (targetOrientation ? Number(targetOrientation !== 'H') : 0)\n );\n }\n return Math.min(\n (incomingOrientation ? Number(incomingOrientation !== 'H') : 0) +\n 1 +\n (targetOrientation ? Number(targetOrientation !== 'V') : 0),\n (incomingOrientation ? Number(incomingOrientation !== 'V') : 0) +\n 1 +\n (targetOrientation ? Number(targetOrientation !== 'H') : 0)\n );\n}\n\ntype OrientationOrdinal = 0 | 1 | 2;\n\nfunction orientationOrdinal(orientation: GridOrientation | undefined): OrientationOrdinal {\n return orientation === undefined ? 0 : orientation === 'H' ? 1 : 2;\n}\n\nfunction movesTowardOwner(from: RouterPoint, to: RouterPoint, side: GridSide): boolean {\n return side === 'left'\n ? from.y === to.y && to.x > from.x\n : side === 'right'\n ? from.y === to.y && to.x < from.x\n : side === 'top'\n ? from.x === to.x && to.y > from.y\n : from.x === to.x && to.y < from.y;\n}\n\nfunction stateIndex(vertexId: number, orientation: GridOrientation | undefined): number {\n return vertexId * 3 + orientationOrdinal(orientation);\n}\n\nfunction normalizePoints(points: readonly RouterPoint[]): RouterPoint[] {\n const result: RouterPoint[] = [];\n for (const point of points) {\n const previous = result.at(-1);\n if (previous && previous.x === point.x && previous.y === point.y) {\n continue;\n }\n const beforePrevious = result.at(-2);\n if (\n beforePrevious &&\n previous &&\n ((beforePrevious.x === previous.x && previous.x === point.x) ||\n (beforePrevious.y === previous.y && previous.y === point.y))\n ) {\n result[result.length - 1] = { ...point };\n } else {\n result.push({ ...point });\n }\n }\n return result;\n}\n\nfunction reconstruct(\n stateId: number,\n stateVertices: ArrayLike<number>,\n predecessors: ArrayLike<number>,\n cost: RouterTupleCost,\n vertexAt: (id: number) => RouterVertex\n): RouterSearchResult {\n const vertexIds: number[] = [];\n let current = stateId;\n while (current >= 0) {\n vertexIds.push(stateVertices[current]);\n current = predecessors[current];\n }\n vertexIds.reverse();\n return {\n points: normalizePoints(vertexIds.map((id) => vertexAt(id).point)),\n vertexIds,\n cost,\n };\n}\n\nfunction validateSearchTopology(\n topology: Pick<ContainerRoutingTopology, 'vertices' | 'adjacency'>\n): void {\n for (const vertex of topology.vertices) {\n if (\n vertex.id < 0 ||\n topology.vertices[vertex.id] !== vertex ||\n !Number.isFinite(vertex.point.x) ||\n !Number.isFinite(vertex.point.y)\n ) {\n throw new Error('Malformed grid routing vertex');\n }\n for (const arc of topology.adjacency.get(vertex.id) ?? []) {\n const target = topology.vertices[arc.to];\n const aligned =\n target &&\n (arc.orientation === 'H'\n ? vertex.point.y === target.point.y\n : vertex.point.x === target.point.x);\n const length = target\n ? Math.abs(vertex.point.x - target.point.x) + Math.abs(vertex.point.y - target.point.y)\n : Number.NaN;\n if (\n arc.from !== vertex.id ||\n !aligned ||\n !Number.isFinite(arc.length) ||\n arc.length <= 0 ||\n arc.length !== length\n ) {\n throw new Error('Malformed grid routing arc');\n }\n }\n }\n}\n\nfunction search(\n topology: Pick<ContainerRoutingTopology, 'vertices' | 'adjacency'> &\n Partial<\n Pick<\n ContainerRoutingTopology,\n | 'adjacencyByVertex'\n | 'searchAdjacencyByVertex'\n | 'vertexCount'\n | 'getVertex'\n | 'getSearchArcs'\n >\n >,\n sourceId: number,\n targetId: number,\n options: RouterSearchOptions\n): RouterSearchResult | undefined {\n const vertexAt = (id: number): RouterVertex => {\n const vertex = topology.getVertex?.(id) ?? topology.vertices[id];\n if (!vertex) {\n throw new Error(`Missing grid routing vertex ${id}`);\n }\n return vertex;\n };\n const source = vertexAt(sourceId);\n const target = vertexAt(targetId);\n if (!options.topologyValidated) {\n validateSearchTopology(topology);\n }\n\n const metrics = options.metrics;\n if (metrics) {\n metrics.searches++;\n }\n assertSearchBudgetAvailable(options);\n const workspace = options.workspace ?? new RouterSearchWorkspace();\n workspace.reset(topology.vertexCount ?? topology.vertices.length);\n let stateVertices = workspace.stateVertices;\n let orientations = workspace.orientations;\n let gLengths = workspace.gLengths;\n let gBends = workspace.gBends;\n let gBoundaryTransitions = workspace.gBoundaryTransitions;\n let fLengths = workspace.fLengths;\n let fBends = workspace.fBends;\n let predecessors = workspace.predecessors;\n let depths = workspace.depths;\n let ancestor4 = workspace.ancestor4;\n let heapChildren = workspace.heapChildren;\n let heapSiblings = workspace.heapSiblings;\n const best = workspace.best;\n const heapPairs = workspace.heapPairs;\n let stateCount = 1;\n const endpointCandidateRank = options.endpointCandidateRank ?? 0;\n const useBendHeuristic = options.heuristic !== 'zero';\n function nonCostOrder(a: number, b: number): number {\n return (\n stateVertices[a] - stateVertices[b] ||\n orientations[a] - orientations[b] ||\n predecessors[a] - predecessors[b] ||\n a - b\n );\n }\n function compareStates(a: number, b: number): number {\n return (\n fLengths[a] - fLengths[b] ||\n fBends[a] - fBends[b] ||\n gBoundaryTransitions[a] - gBoundaryTransitions[b] ||\n (options.queueOrder === 'reverse' ? -nonCostOrder(a, b) : nonCostOrder(a, b))\n );\n }\n function compareChains(a: number, b: number): number {\n // Equal-cost states choose the lexicographically smaller predecessor chain. Four-level jump\n // pointers reduce the common-prefix walk without retaining full paths per state.\n if (a === b) {\n return 0;\n }\n if (a < 0) {\n return -1;\n }\n if (b < 0) {\n return 1;\n }\n const aDepth = depths[a];\n const bDepth = depths[b];\n let alignedA = a;\n let alignedB = b;\n while (depths[alignedA] > depths[alignedB]) {\n alignedA = predecessors[alignedA];\n }\n while (depths[alignedB] > depths[alignedA]) {\n alignedB = predecessors[alignedB];\n }\n if (alignedA === alignedB) {\n return aDepth - bDepth;\n }\n while (\n ancestor4[alignedA] >= 0 &&\n ancestor4[alignedB] >= 0 &&\n ancestor4[alignedA] !== ancestor4[alignedB]\n ) {\n alignedA = ancestor4[alignedA];\n alignedB = ancestor4[alignedB];\n }\n while (predecessors[alignedA] !== predecessors[alignedB]) {\n alignedA = predecessors[alignedA];\n alignedB = predecessors[alignedB];\n }\n return (\n stateVertices[alignedA] - stateVertices[alignedB] ||\n orientations[alignedA] - orientations[alignedB]\n );\n }\n let heapRoot = -1;\n let heapSize = 0;\n // A pairing heap supports cheap melds in flat arrays, preserving workspace reuse and avoiding one\n // allocation per queue node.\n function heapMeld(first: number, second: number): number {\n if (first < 0) {\n return second;\n }\n if (second < 0) {\n return first;\n }\n if (compareStates(first, second) <= 0) {\n heapSiblings[second] = heapChildren[first];\n heapChildren[first] = second;\n return first;\n }\n heapSiblings[first] = heapChildren[second];\n heapChildren[second] = first;\n return second;\n }\n const heapPush = (value: number): void => {\n heapChildren[value] = -1;\n heapSiblings[value] = -1;\n heapRoot = heapMeld(heapRoot, value);\n heapSize++;\n };\n const heapPop = (): number | undefined => {\n if (heapRoot < 0) {\n return undefined;\n }\n const first = heapRoot;\n heapPairs.length = 0;\n let child = heapChildren[first];\n while (child >= 0) {\n const next = heapSiblings[child];\n heapSiblings[child] = -1;\n heapPairs.push(child);\n child = next;\n }\n for (let index = 0; index + 1 < heapPairs.length; index += 2) {\n heapPairs[index >>> 1] = heapMeld(heapPairs[index], heapPairs[index + 1]);\n }\n let pairCount = Math.ceil(heapPairs.length / 2);\n if (heapPairs.length % 2 !== 0) {\n heapPairs[pairCount - 1] = heapPairs[heapPairs.length - 1];\n }\n heapRoot = -1;\n while (pairCount > 0) {\n heapRoot = heapMeld(heapPairs[--pairCount], heapRoot);\n }\n heapSize--;\n return first;\n };\n let expandedThisSearch = 0;\n const edgeCap = options.caps?.maxExpandedStates ?? DEFAULT_MAX_EDGE_STATES;\n const invocationCap = options.caps?.maxInvocationExpandedStates ?? DEFAULT_MAX_INVOCATION_STATES;\n const invocationStart = options.budget?.expandedStates ?? metrics?.expandedStates ?? 0;\n const recordWorkspaceBytes = (): void => {\n const bytes = workspace.estimatedBytes();\n const totalBytes = (options.estimatedBytesBase ?? 0) + bytes;\n if (metrics) {\n metrics.searchWorkspaceBytes = Math.max(metrics.searchWorkspaceBytes, bytes);\n metrics.estimatedBytes = Math.max(metrics.estimatedBytes, totalBytes);\n }\n if (totalBytes > (options.caps?.maxEstimatedBytes ?? Number.POSITIVE_INFINITY)) {\n throw new GridRoutingResourceLimitError(\n 'estimated_memory_cap',\n 'Grid routing search workspace memory cap exceeded'\n );\n }\n };\n recordWorkspaceBytes();\n const commitExpandedStates = (): void => {\n // Charge states once on every exit path, including cap exceptions, so the invocation-wide\n // budget cannot be reset by trying another candidate pair.\n if (options.budget) {\n options.budget.expandedStates += expandedThisSearch;\n }\n if (metrics) {\n metrics.expandedStates += expandedThisSearch;\n }\n };\n const initialLength = options.initialLength ?? 0;\n stateVertices[0] = sourceId;\n orientations[0] = orientationOrdinal(options.initialOrientation);\n gLengths[0] = initialLength;\n gBends[0] = 0;\n gBoundaryTransitions[0] = 0;\n const initialDx = Math.abs(source.point.x - target.point.x);\n const initialDy = Math.abs(source.point.y - target.point.y);\n fLengths[0] = initialLength + (useBendHeuristic ? initialDx + initialDy : 0);\n fBends[0] = useBendHeuristic\n ? minimumBends(initialDx, initialDy, options.initialOrientation, options.targetOrientation)\n : 0;\n predecessors[0] = -1;\n depths[0] = 1;\n ancestor4[0] = -1;\n workspace.setBest(stateIndex(sourceId, options.initialOrientation), 0);\n heapPush(0);\n if (metrics) {\n metrics.maxOpenSet = Math.max(metrics.maxOpenSet, heapSize);\n }\n let bestGoalState = -1;\n let bestGoalCost: RouterTupleCost | undefined;\n const considerGoal = (state: number): void => {\n const completedCost: RouterTupleCost = [\n gLengths[state] + (options.targetLength ?? 0),\n gBends[state] +\n (options.targetOrientation !== undefined &&\n orientations[state] !== 0 &&\n orientationOrdinal(options.targetOrientation) !== orientations[state]\n ? 1\n : 0),\n gBoundaryTransitions[state],\n endpointCandidateRank,\n ];\n if (\n !bestGoalCost ||\n compareTupleCost(completedCost, bestGoalCost) < 0 ||\n (compareTupleCost(completedCost, bestGoalCost) === 0 &&\n compareChains(state, bestGoalState) < 0)\n ) {\n bestGoalState = state;\n bestGoalCost = completedCost;\n }\n };\n const relaxArc = (\n current: number,\n currentPoint: RouterPoint,\n to: number,\n orientation: OrientationOrdinal,\n arcLength: number,\n boundaryTransitions: number\n ): void => {\n const nextPoint = vertexAt(to).point;\n if (options.arcAllowed && !options.arcAllowed(currentPoint, nextPoint)) {\n return;\n }\n if (\n options.initialSide &&\n predecessors[current] < 0 &&\n movesTowardOwner(currentPoint, nextPoint, options.initialSide)\n ) {\n return;\n }\n if (\n options.targetSide &&\n to === targetId &&\n movesTowardOwner(target.point, currentPoint, options.targetSide)\n ) {\n return;\n }\n const index = to * 3 + orientation;\n const previous = best[index];\n const length = gLengths[current] + arcLength;\n const bends =\n gBends[current] +\n (orientations[current] !== 0 && orientations[current] !== orientation ? 1 : 0);\n const nextBoundaryTransitions = gBoundaryTransitions[current] + boundaryTransitions;\n const previousComparison =\n previous >= 0\n ? length - gLengths[previous] ||\n bends - gBends[previous] ||\n nextBoundaryTransitions - gBoundaryTransitions[previous]\n : -1;\n if (\n previous >= 0 &&\n (previousComparison > 0 ||\n (previousComparison === 0 && compareChains(current, predecessors[previous]) >= 0))\n ) {\n return;\n }\n const candidate = stateCount++;\n if (stateCount > stateVertices.length) {\n workspace.ensureStateCapacity(stateCount);\n stateVertices = workspace.stateVertices;\n orientations = workspace.orientations;\n gLengths = workspace.gLengths;\n gBends = workspace.gBends;\n gBoundaryTransitions = workspace.gBoundaryTransitions;\n fLengths = workspace.fLengths;\n fBends = workspace.fBends;\n predecessors = workspace.predecessors;\n depths = workspace.depths;\n ancestor4 = workspace.ancestor4;\n heapChildren = workspace.heapChildren;\n heapSiblings = workspace.heapSiblings;\n recordWorkspaceBytes();\n }\n stateVertices[candidate] = to;\n orientations[candidate] = orientation;\n gLengths[candidate] = length;\n gBends[candidate] = bends;\n gBoundaryTransitions[candidate] = nextBoundaryTransitions;\n const candidateDx = Math.abs(nextPoint.x - target.point.x);\n const candidateDy = Math.abs(nextPoint.y - target.point.y);\n fLengths[candidate] = length + (useBendHeuristic ? candidateDx + candidateDy : 0);\n fBends[candidate] =\n bends +\n (useBendHeuristic\n ? minimumBends(\n candidateDx,\n candidateDy,\n orientation === 1 ? 'H' : 'V',\n options.targetOrientation\n )\n : 0);\n predecessors[candidate] = current;\n depths[candidate] = depths[current] + 1;\n const parent2 = predecessors[current];\n const parent3 = parent2 >= 0 ? predecessors[parent2] : -1;\n ancestor4[candidate] = parent3 >= 0 ? predecessors[parent3] : -1;\n workspace.setBest(index, candidate);\n heapPush(candidate);\n };\n\n while (heapSize > 0) {\n const next = heapRoot;\n // The queue is ordered by the same admissible tuple prefix as the goal. Once its best state is\n // worse than the best goal, no remaining state can improve the result.\n if (\n bestGoalCost &&\n (fLengths[next] - bestGoalCost[0] ||\n fBends[next] - bestGoalCost[1] ||\n gBoundaryTransitions[next] - bestGoalCost[2] ||\n endpointCandidateRank - bestGoalCost[3]) > 0\n ) {\n break;\n }\n const current = heapPop()!;\n if (best[stateVertices[current] * 3 + orientations[current]] !== current) {\n continue;\n }\n if (expandedThisSearch >= edgeCap || invocationStart + expandedThisSearch >= invocationCap) {\n if (bestGoalState >= 0 && bestGoalCost) {\n if (metrics && options.recordOutcome !== false) {\n metrics.routesFound++;\n }\n commitExpandedStates();\n return reconstruct(bestGoalState, stateVertices, predecessors, bestGoalCost, vertexAt);\n }\n commitExpandedStates();\n const searchStateScope =\n invocationStart + expandedThisSearch >= invocationCap ? 'invocation' : 'edge';\n throw new GridRoutingResourceLimitError(\n 'search_state_cap',\n 'Grid routing search-state cap exceeded',\n searchStateScope\n );\n }\n expandedThisSearch++;\n\n if (stateVertices[current] === targetId) {\n considerGoal(current);\n continue;\n }\n\n const vertexId = stateVertices[current];\n const currentPoint = vertexAt(vertexId).point;\n const compactArcs =\n topology.getSearchArcs?.(vertexId) ?? topology.searchAdjacencyByVertex?.[vertexId];\n if (compactArcs) {\n for (const arc of compactArcs) {\n relaxArc(\n current,\n currentPoint,\n arc.to,\n arc.orientationOrdinal,\n arc.length,\n arc.boundaryTransitions\n );\n }\n } else {\n for (const arc of topology.adjacencyByVertex?.[vertexId] ??\n topology.adjacency.get(vertexId) ??\n []) {\n relaxArc(\n current,\n currentPoint,\n arc.to,\n orientationOrdinal(arc.orientation),\n arc.length,\n arc.kind === 'portal' ? 1 : 0\n );\n }\n }\n if (metrics) {\n metrics.maxOpenSet = Math.max(metrics.maxOpenSet, heapSize);\n }\n }\n\n if (bestGoalState < 0 || !bestGoalCost) {\n commitExpandedStates();\n if (metrics && options.recordOutcome !== false) {\n metrics.routesImpossible++;\n }\n return undefined;\n }\n if (metrics && options.recordOutcome !== false) {\n metrics.routesFound++;\n }\n commitExpandedStates();\n return reconstruct(bestGoalState, stateVertices, predecessors, bestGoalCost, vertexAt);\n}\n\nexport function findShortestRoute(\n topology: Pick<ContainerRoutingTopology, 'vertices' | 'adjacency'> &\n Partial<\n Pick<\n ContainerRoutingTopology,\n | 'adjacencyByVertex'\n | 'searchAdjacencyByVertex'\n | 'vertexCount'\n | 'getVertex'\n | 'getSearchArcs'\n >\n >,\n sourceId: number,\n targetId: number,\n options: RouterSearchOptions = {}\n): RouterSearchResult | undefined {\n return search(topology, sourceId, targetId, options);\n}\n", "import { log } from '../../../logger.js';\nimport type { Point } from '../../../types.js';\nimport type { Node } from '../../types.js';\nimport { normalizePolyline } from '../layout-utils/geometry.js';\nimport { manhattanLength, rectForNode } from '../layout-utils/helpers.js';\nimport type { GridRoutingTestOptions } from './router.js';\nimport type { RouteOccupancyIndex } from './routerOccupancy.js';\nimport {\n SELF_LOOP_PORT_GAP,\n SELF_LOOP_PORT_OFFSET_STEP,\n areExactlyAxisAligned,\n labelAwareSelfLoopCandidates,\n orderedSelfLoopSides,\n routeObstacleClearSelfLoop,\n type SegmentAttachment,\n type SegmentAttachmentAlternative,\n} from './routerCompatibility.js';\nimport {\n endpointPairLowerBound,\n pairArcAllowed,\n routeHasDistinctPairPorts,\n routeSatisfiesPairConstraints,\n validateContainerSegment,\n validateSameContainerRoute,\n} from './routerConstraint.js';\nimport {\n TERMINAL_APPROACH_PX,\n sideInterval,\n sideOrder,\n type EdgeRoutePlan,\n type EndpointCandidate,\n} from './routerPlanning.js';\nimport { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingFallbackReason } from './routerInstrumentation.js';\nimport {\n assertSearchBudgetAvailable,\n compareTupleCost,\n findShortestRoute,\n type RouterSearchResult,\n type RouterSearchWorkspace,\n type RouterTupleCost,\n} from './routerSearch.js';\nimport {\n buildEndpointRoutingOverlay,\n DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n routingPointKey,\n type EndpointOverlayScratch,\n} from './routerTopology.js';\nimport type {\n GridContainerId,\n GridLayoutResult,\n GridOrientation,\n GridRoutingContext,\n GridSide,\n RouterPoint,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError } from './types.js';\n\n// Sparse routing overlays edge-specific endpoints onto immutable container visibility graphs, then\n// validates every result before it can replace the deterministic corridor route.\nconst ROUTER_DEBUG_KEY = 'grid-router';\n\nfunction recordFallback(\n context: GridRoutingContext,\n reason: GridRoutingFallbackReason,\n edgeId: string,\n containerId: GridContainerId,\n searchStateScope?: GridRoutingResourceLimitError['searchStateScope']\n): void {\n if (context.metrics) {\n context.metrics.resourceLimitFallbacks++;\n context.metrics.fallbackReasons[reason]++;\n }\n log.debug(ROUTER_DEBUG_KEY, 'GRID_ROUTING_RESOURCE_FALLBACK', {\n edgeId,\n containerId,\n reason,\n });\n if (\n reason === 'search_state_cap' &&\n searchStateScope === 'invocation' &&\n !context.searchBudgetWarningEmitted\n ) {\n context.searchBudgetWarningEmitted = true;\n log.warn(ROUTER_DEBUG_KEY, 'GRID_ROUTING_INVOCATION_SEARCH_BUDGET_EXHAUSTED', {\n edgeId,\n containerId,\n expandedStates: context.searchBudget.expandedStates,\n });\n }\n}\n\ninterface ValidatedFallbackOptions<T> {\n context: GridRoutingContext;\n reason: GridRoutingFallbackReason;\n edgeId: string;\n containerId: GridContainerId;\n searchStateScope?: GridRoutingResourceLimitError['searchStateScope'];\n route: () => T;\n isValid: (fallback: T) => boolean;\n includeContainerIdInError?: boolean;\n}\n\nfunction runValidatedFallback<T>({\n context,\n reason,\n edgeId,\n containerId,\n searchStateScope,\n route,\n isValid,\n includeContainerIdInError,\n}: ValidatedFallbackOptions<T>): T {\n const fallback = route();\n recordFallback(context, reason, edgeId, containerId, searchStateScope);\n if (isValid(fallback)) {\n return fallback;\n }\n if (context.metrics) {\n context.metrics.fallbackValidationFailures++;\n }\n throw gridError('GRID_ROUTE_NOT_FOUND', `Invalid legacy fallback for \"${edgeId}\"`, {\n edgeId,\n ...(includeContainerIdInError ? { containerId } : {}),\n reason,\n });\n}\n\n/*\n * TODO: Consider an opt-in `grid.routingPolicy: 'best-effort'` mode while keeping validated\n * routing as the default.\n *\n * A minimal implementation could catch recoverable per-edge routing exhaustion after both the\n * sparse router and validated compatibility route fail, then construct a deterministic orthogonal\n * dogleg between the measured source and target bounds. Self-loops would need a similarly\n * deterministic rectangular loop. The fallback could cross protected geometry or share bundle\n * lanes, but it must still use finite coordinates, preserve valid endpoints, avoid partially\n * committed state, and emit a warning containing the edge id and original failure reason.\n *\n * A production-quality implementation would need:\n * - Explicit classification of recoverable geometry exhaustion versus malformed input and internal\n * invariants. Invalid coordinates, containment, measurements, endpoints, and topology state must\n * remain errors in every mode.\n * - Transactional per-edge fallback that updates pair-route, portal, instrumentation, and retry\n * state consistently.\n * - Documented constraints that best-effort routing may relax, with deterministic output and\n * observable warnings or metrics for every degraded edge.\n * - A matching label policy that restores provisional label-routing state before placing a label\n * at a deterministic fallback position or omitting it.\n * - Tests for both policies using the same production paths, including hierarchy routes,\n * self-loops, bundles, resource-limit fallbacks, and label-placement exhaustion.\n */\nexport function sparseSameContainerRoute(\n plan: EdgeRoutePlan,\n sources: readonly EndpointCandidate[],\n targets: readonly EndpointCandidate[],\n source: Node,\n target: Node,\n legacyRoute: () => Point[],\n result: GridLayoutResult,\n context: GridRoutingContext,\n searchWorkspace: RouterSearchWorkspace,\n overlayScratch: EndpointOverlayScratch,\n options: GridRoutingTestOptions,\n pairRoutes: readonly (readonly Point[])[],\n occupied?: {\n index: RouteOccupancyIndex;\n pairKey: string;\n prioritizeEndpointCandidates?: boolean;\n }\n): Point[] {\n const fallbackReason = context.fallbackContainers.get(plan.lcaContainerId);\n if (fallbackReason) {\n return runValidatedFallback({\n context,\n reason: fallbackReason,\n edgeId: plan.edge.id,\n containerId: plan.lcaContainerId,\n route: legacyRoute,\n isValid: (legacy) =>\n validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result) &&\n (plan.bundleSize <= 1 || routeSatisfiesPairConstraints(legacy, pairRoutes)),\n });\n }\n const topology = context.topologies.get(plan.lcaContainerId);\n if (!topology) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing routing topology \"${plan.lcaContainerId}\"`);\n }\n if (sources.length === 0 || targets.length === 0) {\n if (context.metrics) {\n context.metrics.routesImpossible++;\n }\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n plan.bundleSize > 1\n ? `No distinct lane route for \"${plan.edge.id}\"`\n : `No legal endpoint candidates for \"${plan.edge.id}\"`,\n { edgeId: plan.edge.id }\n );\n }\n\n let best: { result: RouterSearchResult; points: Point[] } | undefined;\n let searchCap: GridRoutingResourceLimitError | undefined;\n const pairs = sources\n .flatMap((sourceCandidate) =>\n targets.map((targetCandidate) => {\n const pairRank = sourceCandidate.rank * targets.length + targetCandidate.rank;\n const [length, bends] = endpointPairLowerBound(sourceCandidate, targetCandidate);\n const lowerCost: RouterTupleCost = [length, bends, 0, pairRank];\n return { sourceCandidate, targetCandidate, pairRank, lowerCost };\n })\n )\n .sort(\n (a, b) =>\n compareTupleCost(a.lowerCost, b.lowerCost) ||\n sideOrder(a.sourceCandidate.side) - sideOrder(b.sourceCandidate.side) ||\n sideOrder(a.targetCandidate.side) - sideOrder(b.targetCandidate.side)\n );\n\n // Candidate pairs are ordered by an admissible lower bound. Once a completed route is no worse\n // than that bound, neither this pair nor any remaining pair can improve the current best.\n const searchPairs = (\n avoidOccupied: boolean,\n mode: 'all' | 'preferred' | 'assigned-side' = 'all'\n ): void => {\n const arcAllowed: ((from: RouterPoint, to: RouterPoint) => boolean) | undefined =\n plan.bundleSize > 1 || avoidOccupied\n ? (from, to) =>\n (plan.bundleSize <= 1 || pairArcAllowed(from, to, pairRoutes)) &&\n !(avoidOccupied && occupied!.index.conflictsWithArc(from, to, occupied!.pairKey))\n : undefined;\n for (const { sourceCandidate, targetCandidate, pairRank, lowerCost } of pairs) {\n if (mode === 'preferred' && pairRank !== 0) {\n continue;\n }\n if (\n mode === 'assigned-side' &&\n (sourceCandidate.onAssignedSide === false || targetCandidate.onAssignedSide === false)\n ) {\n continue;\n }\n if (best && compareTupleCost(best.result.cost, lowerCost) <= 0) {\n break;\n }\n try {\n assertSearchBudgetAvailable({\n metrics: context.metrics,\n caps: options.searchCaps,\n budget: context.searchBudget,\n });\n const overlay = buildEndpointRoutingOverlay(\n topology,\n sourceCandidate.connect,\n targetCandidate.connect,\n context.metrics,\n overlayScratch,\n plan.bundleSize > 1 &&\n (sourceCandidate.connect.x === targetCandidate.connect.x ||\n sourceCandidate.connect.y === targetCandidate.connect.y)\n ? [\n {\n x: (sourceCandidate.connect.x + targetCandidate.connect.x) / 2,\n y: (sourceCandidate.connect.y + targetCandidate.connect.y) / 2,\n },\n ]\n : []\n );\n const liveEstimatedBytes =\n context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes;\n if (\n liveEstimatedBytes >\n (options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES)\n ) {\n throw new GridRoutingResourceLimitError(\n 'estimated_memory_cap',\n 'Grid routing estimated_memory_cap exceeded'\n );\n }\n if (context.metrics) {\n context.metrics.estimatedBytes = Math.max(\n context.metrics.estimatedBytes,\n liveEstimatedBytes\n );\n }\n const sourceId = overlay.pointVertexIds.get(routingPointKey(sourceCandidate.connect));\n const targetId = overlay.pointVertexIds.get(routingPointKey(targetCandidate.connect));\n if (sourceId === undefined || targetId === undefined) {\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n `Endpoint projection is missing from the routing overlay for \"${plan.edge.id}\"`,\n {\n edgeId: plan.edge.id,\n containerId: plan.lcaContainerId,\n source: sourceCandidate.connect,\n target: targetCandidate.connect,\n }\n );\n }\n const sourceOrientation: GridOrientation =\n sourceCandidate.side === 'left' || sourceCandidate.side === 'right' ? 'H' : 'V';\n const targetOrientation: GridOrientation =\n targetCandidate.side === 'left' || targetCandidate.side === 'right' ? 'H' : 'V';\n const resultForPair = findShortestRoute(overlay, sourceId, targetId, {\n metrics: context.metrics,\n caps: {\n ...options.searchCaps,\n maxEstimatedBytes:\n options.searchCaps?.maxEstimatedBytes ??\n options.topologyCaps?.maxEstimatedBytes ??\n DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n },\n endpointCandidateRank: pairRank,\n recordOutcome: false,\n budget: context.searchBudget,\n initialOrientation: sourceOrientation,\n initialLength: TERMINAL_APPROACH_PX,\n targetOrientation,\n targetLength: TERMINAL_APPROACH_PX,\n topologyValidated: true,\n workspace: searchWorkspace,\n estimatedBytesBase: liveEstimatedBytes,\n arcAllowed,\n });\n if (!resultForPair) {\n continue;\n }\n const points = normalizePolyline([\n sourceCandidate.port,\n ...resultForPair.points,\n targetCandidate.port,\n ]).points;\n if (!validateSameContainerRoute(points, source, target, plan.lcaContainerId, result)) {\n continue;\n }\n if (plan.bundleSize > 1 && !routeSatisfiesPairConstraints(points, pairRoutes)) {\n continue;\n }\n if (avoidOccupied && occupied!.index.conflictsWithRoute(points, occupied!.pairKey)) {\n continue;\n }\n if (!best || compareTupleCost(resultForPair.cost, best.result.cost) < 0) {\n best = { result: resultForPair, points };\n searchCap = undefined;\n }\n } catch (error) {\n if (!(error instanceof GridRoutingResourceLimitError)) {\n throw error;\n }\n if (best) {\n break;\n }\n searchCap = error;\n break;\n }\n }\n };\n // Prefer a route that does not share a corridor with another edge. Sharing is the last resort,\n // so a failed constrained search retries without it instead of reporting no route.\n const avoidOccupied = occupied !== undefined && occupied.index.size > 0;\n if (occupied?.prioritizeEndpointCandidates) {\n // The assigned ports win unless another pair on the same sides at coordinated owners is cheaper,\n // which avoids accepting a legal but contorted route for the assigned ports.\n searchPairs(avoidOccupied, 'preferred');\n searchPairs(avoidOccupied, 'assigned-side');\n }\n if (!best) {\n searchPairs(avoidOccupied);\n }\n if (!best && !searchCap && occupied !== undefined && occupied.index.size > 0) {\n searchPairs(false);\n }\n if (searchCap) {\n // Resource caps select the compatibility route only after it passes the same geometry and bundle\n // constraints; caps never weaken correctness.\n return runValidatedFallback({\n context,\n reason: searchCap.reason,\n edgeId: plan.edge.id,\n containerId: plan.lcaContainerId,\n searchStateScope: searchCap.searchStateScope,\n route: legacyRoute,\n isValid: (legacy) =>\n validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result) &&\n (plan.bundleSize <= 1 || routeSatisfiesPairConstraints(legacy, pairRoutes)),\n });\n }\n if (!best) {\n if (context.metrics) {\n context.metrics.routesImpossible++;\n }\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n plan.bundleSize > 1\n ? `No distinct lane route for \"${plan.edge.id}\"`\n : `No cell-aware route for \"${plan.edge.id}\"`,\n {\n edgeId: plan.edge.id,\n }\n );\n }\n if (options.onDualRouteComparison) {\n const legacy = legacyRoute();\n const sparseNormalized = normalizePolyline(best.points);\n const legacyNormalized = normalizePolyline(legacy);\n options.onDualRouteComparison({\n edgeId: plan.edge.id,\n sparse: {\n valid: true,\n length: manhattanLength(sparseNormalized.points),\n bends: sparseNormalized.bends,\n },\n legacy: {\n valid: validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result),\n length: manhattanLength(legacyNormalized.points),\n bends: legacyNormalized.bends,\n },\n });\n }\n return best.points;\n}\n\nfunction selfLoopAttachments(\n owner: Node,\n side: GridSide,\n index: number\n): { start: EndpointCandidate; target: EndpointCandidate } | undefined {\n const interval = sideInterval(owner, side);\n if (!interval || interval.high - interval.low < SELF_LOOP_PORT_GAP) {\n return undefined;\n }\n const rect = rectForNode(owner);\n const center = (interval.low + interval.high) / 2;\n const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;\n const coordinates = [\n center - SELF_LOOP_PORT_GAP / 2 - portOffset,\n center + SELF_LOOP_PORT_GAP / 2 + portOffset,\n ];\n if (coordinates[0] < interval.low || coordinates[1] > interval.high) {\n return undefined;\n }\n const candidate = (coordinate: number): EndpointCandidate => {\n const port =\n side === 'left' || side === 'right'\n ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n return {\n ownerId: owner.id,\n side,\n port,\n connect: {\n x:\n port.x +\n (side === 'left' ? -TERMINAL_APPROACH_PX : side === 'right' ? TERMINAL_APPROACH_PX : 0),\n y:\n port.y +\n (side === 'top' ? -TERMINAL_APPROACH_PX : side === 'bottom' ? TERMINAL_APPROACH_PX : 0),\n },\n rank: 0,\n };\n };\n return { start: candidate(coordinates[0]), target: candidate(coordinates[1]) };\n}\n\nexport function sparseSelfLoopRoute(\n plan: EdgeRoutePlan,\n owner: Node,\n result: GridLayoutResult,\n context: GridRoutingContext,\n searchWorkspace: RouterSearchWorkspace,\n overlayScratch: EndpointOverlayScratch | undefined,\n ownerSideCounts: Map<string, number>,\n selfLoopCounts: Map<string, number>,\n pairRoutes: readonly (readonly Point[])[],\n options: GridRoutingTestOptions\n): { points: Point[]; side: GridSide; index: number } {\n // Try sides in load order and reserve progressively wider port pairs for repeated loops on the\n // same side.\n const containerId = owner.parentId ?? ROOT_CONTAINER_ID;\n const labelRequirement = result.labelRequirements.selfLoops.get(plan.edge.id);\n const fallbackReason = context.fallbackContainers.get(containerId);\n const legacyRoute = (): { points: Point[]; side: GridSide; index: number } =>\n routeObstacleClearSelfLoop(\n owner,\n ownerSideCounts,\n selfLoopCounts,\n result,\n labelRequirement,\n context.metrics\n );\n if (fallbackReason) {\n const fallback = runValidatedFallback({\n context,\n reason: fallbackReason,\n edgeId: plan.edge.id,\n containerId,\n route: legacyRoute,\n isValid: (legacy) =>\n validateSameContainerRoute(legacy.points, owner, owner, containerId, result) &&\n routeSatisfiesPairConstraints(legacy.points, pairRoutes),\n });\n if (labelRequirement && context.metrics) {\n context.metrics.labelAwareSelfLoopsCommitted++;\n }\n return fallback;\n }\n const topology = context.topologies.get(containerId);\n if (!topology || !overlayScratch) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing routing topology \"${containerId}\"`);\n }\n const orderedSides = orderedSelfLoopSides(owner, ownerSideCounts, selfLoopCounts);\n if (labelRequirement) {\n for (const side of orderedSides) {\n const index = selfLoopCounts.get(`${owner.id}:${side}`) ?? 0;\n const rect = rectForNode(owner);\n const demandCoord = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n const candidates = labelAwareSelfLoopCandidates(\n owner,\n side,\n index,\n demandCoord,\n labelRequirement\n );\n if (context.metrics) {\n context.metrics.labelAwareSelfLoopCandidates += candidates.length;\n }\n for (const points of candidates) {\n if (\n validateSameContainerRoute(points, owner, owner, containerId, result) &&\n routeSatisfiesPairConstraints(points, pairRoutes)\n ) {\n if (context.metrics) {\n context.metrics.labelAwareSelfLoopsCommitted++;\n }\n return { points, side, index };\n }\n }\n }\n if (context.metrics) {\n context.metrics.labelAwareSelfLoopFallbacks++;\n }\n }\n for (const side of orderedSides) {\n const index = selfLoopCounts.get(`${owner.id}:${side}`) ?? 0;\n const attachments = selfLoopAttachments(owner, side, index);\n if (!attachments) {\n continue;\n }\n const { start, target } = attachments;\n try {\n assertSearchBudgetAvailable({\n metrics: context.metrics,\n caps: options.searchCaps,\n budget: context.searchBudget,\n });\n const overlay = buildEndpointRoutingOverlay(\n topology,\n start.connect,\n target.connect,\n context.metrics,\n overlayScratch,\n [\n {\n x: (start.connect.x + target.connect.x) / 2,\n y: (start.connect.y + target.connect.y) / 2,\n },\n ]\n );\n const sourceId = overlay.pointVertexIds.get(routingPointKey(start.connect));\n const targetId = overlay.pointVertexIds.get(routingPointKey(target.connect));\n if (sourceId === undefined || targetId === undefined) {\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n `Self-loop endpoint projection is missing from the routing overlay for \"${plan.edge.id}\"`,\n {\n edgeId: plan.edge.id,\n containerId,\n source: start.connect,\n target: target.connect,\n side,\n }\n );\n }\n const orientation: GridOrientation = side === 'left' || side === 'right' ? 'H' : 'V';\n const route = findShortestRoute(overlay, sourceId, targetId, {\n metrics: context.metrics,\n caps: {\n ...options.searchCaps,\n maxEstimatedBytes:\n options.searchCaps?.maxEstimatedBytes ??\n options.topologyCaps?.maxEstimatedBytes ??\n DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n },\n recordOutcome: false,\n budget: context.searchBudget,\n initialOrientation: orientation,\n initialSide: side,\n initialLength: TERMINAL_APPROACH_PX,\n targetOrientation: orientation,\n targetSide: side,\n targetLength: TERMINAL_APPROACH_PX,\n topologyValidated: true,\n workspace: searchWorkspace,\n estimatedBytesBase:\n context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes,\n arcAllowed: (from, to) => pairArcAllowed(from, to, pairRoutes),\n });\n if (!route) {\n continue;\n }\n const points = normalizePolyline([start.port, ...route.points, target.port]).points;\n if (\n validateSameContainerRoute(points, owner, owner, containerId, result) &&\n routeSatisfiesPairConstraints(points, pairRoutes)\n ) {\n return {\n points,\n side,\n index,\n };\n }\n } catch (error) {\n if (!(error instanceof GridRoutingResourceLimitError)) {\n throw error;\n }\n const fallback = runValidatedFallback({\n context,\n reason: error.reason,\n edgeId: plan.edge.id,\n containerId,\n searchStateScope: error.searchStateScope,\n route: legacyRoute,\n isValid: (legacy) =>\n validateSameContainerRoute(legacy.points, owner, owner, containerId, result) &&\n routeSatisfiesPairConstraints(legacy.points, pairRoutes),\n });\n if (labelRequirement && context.metrics) {\n context.metrics.labelAwareSelfLoopsCommitted++;\n }\n return fallback;\n }\n }\n if (context.metrics) {\n context.metrics.routesImpossible++;\n }\n throw gridError('GRID_ROUTE_NOT_FOUND', `No distinct self-loop route for \"${plan.edge.id}\"`, {\n edgeId: plan.edge.id,\n nodeId: owner.id,\n });\n}\n\nexport function sparseContainerSegment(\n edgeId: string,\n containerId: GridContainerId,\n start: SegmentAttachment,\n end: SegmentAttachment,\n legacyRoute: () => Point[],\n result: GridLayoutResult,\n context: GridRoutingContext,\n searchWorkspace: RouterSearchWorkspace,\n overlayScratch: EndpointOverlayScratch | undefined,\n options: GridRoutingTestOptions,\n pairRoutes: readonly (readonly Point[])[] = [],\n endAlternatives: () => readonly SegmentAttachmentAlternative[] = () => [],\n startAlternatives: () => readonly SegmentAttachmentAlternative[] = () => [],\n allowSharedPairCorridors = false,\n occupied?: { index: RouteOccupancyIndex; pairKey: string }\n): Point[] {\n const fallbackReason = context.fallbackContainers.get(containerId);\n if (fallbackReason) {\n return runValidatedFallback({\n context,\n reason: fallbackReason,\n edgeId,\n containerId,\n route: legacyRoute,\n isValid: (legacy) =>\n validateContainerSegment(legacy, start.ownerId, end.ownerId, containerId, result) &&\n routeSatisfiesPairConstraints(legacy, pairRoutes),\n includeContainerIdInError: true,\n });\n }\n const topology = context.topologies.get(containerId);\n if (!topology || !overlayScratch) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing routing topology \"${containerId}\"`);\n }\n const attempts: {\n start: SegmentAttachment;\n end: SegmentAttachment;\n select: readonly (() => void)[];\n }[] = [{ start, end, select: [] }];\n // Alternatives are generated lazily only after the selected attachments fail. Their `select`\n // callbacks commit portal-coordinate changes after a complete route validates.\n let alternativesAdded = false;\n const appendAlternatives = (): void => {\n if (alternativesAdded) {\n return;\n }\n alternativesAdded = true;\n const starts = startAlternatives();\n const ends = endAlternatives();\n attempts.push(\n ...ends.map((alternative) => ({\n start,\n end: alternative.attachment,\n select: [alternative.select],\n })),\n ...starts.map((alternative) => ({\n start: alternative.attachment,\n end,\n select: [alternative.select],\n })),\n ...starts.flatMap((startAlternative) =>\n ends.map((endAlternative) => ({\n start: startAlternative.attachment,\n end: endAlternative.attachment,\n select: [startAlternative.select, endAlternative.select],\n }))\n )\n );\n };\n // Prefer attachments and corridors that do not run along another edge. Sharing is the last\n // resort, so a failed constrained pass retries without it.\n const passes = occupied !== undefined && occupied.index.size > 0 ? [true, false] : [false];\n try {\n for (const avoidOccupied of passes) {\n for (const [attemptIndex, attempt] of attempts.entries()) {\n const attemptedStart = attempt.start;\n const attemptedEnd = attempt.end;\n if (attemptIndex > 0 && context.metrics) {\n context.metrics.hierarchyPortalAlternativeAttempts++;\n }\n const aligned = areExactlyAxisAligned(attemptedStart.connect, attemptedEnd.connect);\n if (aligned) {\n const direct = normalizePolyline([\n attemptedStart.port,\n attemptedStart.connect,\n attemptedEnd.connect,\n attemptedEnd.port,\n ]).points;\n if (\n validateContainerSegment(\n direct,\n attemptedStart.ownerId,\n attemptedEnd.ownerId,\n containerId,\n result\n ) &&\n routeSatisfiesPairConstraints(direct, pairRoutes) &&\n !(avoidOccupied && occupied!.index.conflictsWithRoute(direct, occupied!.pairKey))\n ) {\n for (const select of attempt.select) {\n select();\n }\n if (attemptIndex > 0 && context.metrics) {\n context.metrics.hierarchyPortalAlternativeSelections++;\n }\n return direct;\n }\n }\n assertSearchBudgetAvailable({\n metrics: context.metrics,\n caps: options.searchCaps,\n budget: context.searchBudget,\n });\n const overlay = buildEndpointRoutingOverlay(\n topology,\n attemptedStart.connect,\n attemptedEnd.connect,\n context.metrics,\n overlayScratch\n );\n const liveEstimatedBytes =\n context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes;\n if (\n liveEstimatedBytes >\n (options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES)\n ) {\n throw new GridRoutingResourceLimitError(\n 'estimated_memory_cap',\n 'Grid routing estimated_memory_cap exceeded'\n );\n }\n const sourceId = overlay.pointVertexIds.get(routingPointKey(attemptedStart.connect));\n const targetId = overlay.pointVertexIds.get(routingPointKey(attemptedEnd.connect));\n if (sourceId === undefined || targetId === undefined) {\n if (attemptIndex === 0) {\n appendAlternatives();\n }\n continue;\n }\n const route = findShortestRoute(overlay, sourceId, targetId, {\n metrics: context.metrics,\n caps: {\n ...options.searchCaps,\n maxEstimatedBytes:\n options.searchCaps?.maxEstimatedBytes ??\n options.topologyCaps?.maxEstimatedBytes ??\n DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n },\n recordOutcome: false,\n budget: context.searchBudget,\n initialOrientation:\n attemptedStart.side === 'left' || attemptedStart.side === 'right' ? 'H' : 'V',\n initialSide: attemptedStart.side,\n initialLength:\n Math.abs(attemptedStart.port.x - attemptedStart.connect.x) +\n Math.abs(attemptedStart.port.y - attemptedStart.connect.y),\n targetOrientation:\n attemptedEnd.side === 'left' || attemptedEnd.side === 'right' ? 'H' : 'V',\n targetSide: attemptedEnd.side,\n targetLength:\n Math.abs(attemptedEnd.port.x - attemptedEnd.connect.x) +\n Math.abs(attemptedEnd.port.y - attemptedEnd.connect.y),\n topologyValidated: true,\n workspace: searchWorkspace,\n estimatedBytesBase: liveEstimatedBytes,\n arcAllowed:\n pairRoutes.length > 0 || avoidOccupied\n ? (from, to) =>\n (pairRoutes.length === 0 || pairArcAllowed(from, to, pairRoutes)) &&\n !(avoidOccupied && occupied!.index.conflictsWithArc(from, to, occupied!.pairKey))\n : undefined,\n });\n if (!route) {\n if (attemptIndex === 0) {\n appendAlternatives();\n }\n continue;\n }\n const points = normalizePolyline([\n attemptedStart.port,\n ...route.points,\n attemptedEnd.port,\n ]).points;\n if (\n !validateContainerSegment(\n points,\n attemptedStart.ownerId,\n attemptedEnd.ownerId,\n containerId,\n result\n ) ||\n !routeSatisfiesPairConstraints(points, pairRoutes) ||\n (avoidOccupied && occupied!.index.conflictsWithRoute(points, occupied!.pairKey))\n ) {\n if (attemptIndex === 0) {\n appendAlternatives();\n }\n continue;\n }\n for (const select of attempt.select) {\n select();\n }\n if (attemptIndex > 0 && context.metrics) {\n context.metrics.hierarchyPortalAlternativeSelections++;\n }\n return points;\n }\n }\n } catch (error) {\n if (!(error instanceof GridRoutingResourceLimitError)) {\n throw error;\n }\n return runValidatedFallback({\n context,\n reason: error.reason,\n edgeId,\n containerId,\n searchStateScope: error.searchStateScope,\n route: legacyRoute,\n isValid: (legacy) =>\n validateContainerSegment(legacy, start.ownerId, end.ownerId, containerId, result) &&\n routeSatisfiesPairConstraints(legacy, pairRoutes),\n includeContainerIdInError: true,\n });\n }\n const compatibility = legacyRoute();\n // Exhausted sparse geometry may recover through the corridor router. Bundled hierarchy segments\n // can share interior corridors only when their endpoint ports remain distinct.\n if (\n validateContainerSegment(compatibility, start.ownerId, end.ownerId, containerId, result) &&\n (routeSatisfiesPairConstraints(compatibility, pairRoutes) ||\n (allowSharedPairCorridors && routeHasDistinctPairPorts(compatibility, pairRoutes)))\n ) {\n if (context.metrics) {\n context.metrics.compatibilitySegments++;\n context.metrics.compatibilityRecoveries++;\n }\n return compatibility;\n }\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n `No hierarchy route for \"${edgeId}\" in \"${containerId}\" from ${routingPointKey(start.connect)} to ${routingPointKey(end.connect)}`,\n { edgeId, containerId }\n );\n}\n", "import type { Point } from '../../../types.js';\nimport type { Edge, LayoutData } from '../../types.js';\nimport { clamp, rectForNode } from '../layout-utils/helpers.js';\nimport type { GridRoutingTestOptions } from './router.js';\nimport {\n boundedAlternativePortalCoordinates,\n buildRoutingContext,\n combinePointChains,\n compatibilityHierarchyAttachments,\n compatibilityLcaAttachments,\n groupBoundaryEndpointAttachment,\n itemAttachment,\n portalAttachment,\n prepareRoutingModes,\n reversePoints,\n rootContainerMeta,\n routeWithinContainer,\n validatedCompatibilitySegment,\n type PreparedRoutingModes,\n type SegmentAttachment,\n type SegmentAttachmentAlternative,\n} from './routerCompatibility.js';\nimport {\n isPairSeparationError,\n routeHasDistinctPairPorts,\n routeSatisfiesPairConstraints,\n routerRect,\n} from './routerConstraint.js';\nimport {\n ownerGroupTitle,\n ownerSideKey,\n prepareEdgeRoutes,\n sideInterval,\n type EdgeEndpointEntry,\n type EdgeEndpointPlan,\n type EdgeRoutePlan,\n type PreparedEdgeRoutes,\n} from './routerPlanning.js';\nimport {\n createGridRoutingInstrumentationCheckpoint,\n recordGridRoute,\n restoreGridRoutingInstrumentationCheckpoint,\n type GridRoutingInstrumentation,\n type GridRoutingInstrumentationCheckpoint,\n} from './routerInstrumentation.js';\nimport { RouteOccupancyIndex } from './routerOccupancy.js';\nimport { RouterSearchWorkspace } from './routerSearch.js';\nimport {\n sparseContainerSegment,\n sparseSameContainerRoute,\n sparseSelfLoopRoute,\n} from './routerSparse.js';\nimport { buildPairedPortal, derivePortalRanges, EndpointOverlayScratch } from './routerTopology.js';\nimport type {\n GridContainerId,\n GridLayoutResult,\n GridRoutingContext,\n PairedPortal,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError } from './types.js';\n\n// The session is the transaction boundary for one routing invocation. It owns mutable reservations,\n// reusable search memory, and retry state while the base layout geometry remains read-only.\ninterface BundleEdgeCheckpoint {\n edge: Edge;\n // Geometry and its rendering contract commit together; retries must not leak either half.\n points: Edge['points'];\n curve: Edge['curve'];\n cornerRadius: Edge['cornerRadius'];\n}\n\ninterface BundleCheckpoint {\n pairKey: string;\n occupancy: { index: RouteOccupancyIndex; size: number } | undefined;\n pairRoutes: Point[][] | undefined;\n demandKeys: string[];\n pairedPortals: Map<string, PairedPortal>;\n demandCoords: Map<string, number>;\n edges: BundleEdgeCheckpoint[];\n instrumentedRoutesLength: number | undefined;\n metrics: GridRoutingInstrumentationCheckpoint | undefined;\n}\n\nfunction createBundleCheckpoint(\n pairPlans: readonly EdgeRoutePlan[],\n pairRoutes: ReadonlyMap<string, Point[][]>,\n pairedPortals: ReadonlyMap<string, PairedPortal>,\n demandCoords: ReadonlyMap<string, number>,\n instrumentedRoutes: readonly Point[][] | undefined,\n metrics: GridRoutingInstrumentation | undefined,\n routeOccupancy: ReadonlyMap<GridContainerId, RouteOccupancyIndex>\n): BundleCheckpoint {\n // Snapshot only state a failed bundle can mutate. Topologies and prepared plans are immutable and\n // intentionally shared across attempts.\n const pairKey = pairPlans[0].pairKey;\n const committedPairRoutes = pairRoutes.get(pairKey);\n const demandKeys = [\n ...new Set(\n pairPlans.flatMap((plan) =>\n [...plan.source.chain, ...plan.target.chain].map(({ demandKey }) => demandKey)\n )\n ),\n ];\n const bundlePairedPortals = new Map<string, PairedPortal>();\n const bundleDemandCoords = new Map<string, number>();\n for (const demandKey of demandKeys) {\n const portal = pairedPortals.get(demandKey);\n if (portal) {\n bundlePairedPortals.set(demandKey, portal);\n }\n const coordinate = demandCoords.get(demandKey);\n if (coordinate !== undefined) {\n bundleDemandCoords.set(demandKey, coordinate);\n }\n }\n // Pair members share endpoints, so they share one LCA container and one occupancy index.\n const occupancyIndex = routeOccupancy.get(pairPlans[0].lcaContainerId);\n return {\n pairKey,\n occupancy: occupancyIndex ? { index: occupancyIndex, size: occupancyIndex.size } : undefined,\n pairRoutes: committedPairRoutes ? [...committedPairRoutes] : undefined,\n demandKeys,\n pairedPortals: bundlePairedPortals,\n demandCoords: bundleDemandCoords,\n edges: pairPlans.map(({ edge }) => ({\n edge,\n points: edge.points,\n curve: edge.curve,\n cornerRadius: edge.cornerRadius,\n })),\n instrumentedRoutesLength: instrumentedRoutes?.length,\n metrics: metrics ? createGridRoutingInstrumentationCheckpoint(metrics) : undefined,\n };\n}\n\nfunction restoreBundleCheckpoint(\n checkpoint: BundleCheckpoint,\n pairRoutes: Map<string, Point[][]>,\n pairedPortals: Map<string, PairedPortal>,\n demandCoords: Map<string, number>,\n instrumentedRoutes: Point[][] | undefined,\n metrics: GridRoutingInstrumentation | undefined\n): void {\n checkpoint.occupancy?.index.truncate(checkpoint.occupancy.size);\n if (checkpoint.pairRoutes) {\n pairRoutes.set(checkpoint.pairKey, [...checkpoint.pairRoutes]);\n } else {\n pairRoutes.delete(checkpoint.pairKey);\n }\n for (const demandKey of checkpoint.demandKeys) {\n const portal = checkpoint.pairedPortals.get(demandKey);\n if (portal) {\n pairedPortals.set(demandKey, portal);\n } else {\n pairedPortals.delete(demandKey);\n }\n const coordinate = checkpoint.demandCoords.get(demandKey);\n if (coordinate !== undefined) {\n demandCoords.set(demandKey, coordinate);\n } else {\n demandCoords.delete(demandKey);\n }\n }\n for (const edgeCheckpoint of checkpoint.edges) {\n edgeCheckpoint.edge.points = edgeCheckpoint.points;\n edgeCheckpoint.edge.curve = edgeCheckpoint.curve;\n edgeCheckpoint.edge.cornerRadius = edgeCheckpoint.cornerRadius;\n }\n if (instrumentedRoutes && checkpoint.instrumentedRoutesLength !== undefined) {\n instrumentedRoutes.length = checkpoint.instrumentedRoutesLength;\n }\n if (metrics && checkpoint.metrics) {\n restoreGridRoutingInstrumentationCheckpoint(metrics, checkpoint.metrics);\n }\n}\n\nexport class GridEdgeRoutingSession {\n private prepared!: PreparedEdgeRoutes;\n private modes!: PreparedRoutingModes;\n private routingContext!: GridRoutingContext;\n private readonly searchWorkspace = new RouterSearchWorkspace();\n private endpointOverlayScratch!: Map<GridContainerId, EndpointOverlayScratch>;\n private readonly pairedPortals = new Map<string, PairedPortal>();\n private readonly ownerSideCounts = new Map<string, number>();\n private instrumentedRoutes!: Point[][] | undefined;\n private readonly selfLoopCounts = new Map<string, number>();\n private readonly pairRoutes = new Map<string, Point[][]>();\n private routed = false;\n\n constructor(\n private readonly layout: LayoutData,\n private readonly result: GridLayoutResult,\n private readonly metrics: GridRoutingInstrumentation | undefined,\n private readonly options: GridRoutingTestOptions\n ) {}\n\n route(): void {\n if (this.routed) {\n throw new Error('Grid edge routing session can only be run once');\n }\n this.routed = true;\n this.prepare();\n\n // Pair insertion order follows the already canonical plan order; Map preserves that order when\n // bundles are routed as indivisible retry units.\n const plansByPair = new Map<string, EdgeRoutePlan[]>();\n for (const plan of this.prepared.orderedPlans) {\n const pairPlans = plansByPair.get(plan.pairKey) ?? [];\n pairPlans.push(plan);\n plansByPair.set(plan.pairKey, pairPlans);\n }\n for (const pairPlans of plansByPair.values()) {\n this.routeBundle(pairPlans);\n }\n }\n\n private prepare(): void {\n // Preparation is front-loaded so routing attempts never observe partially built planning or\n // topology state.\n rootContainerMeta(this.result);\n this.prepared = prepareEdgeRoutes(this.layout, this.result);\n\n this.modes = prepareRoutingModes(this.prepared, this.result, this.metrics, this.options);\n this.routingContext = buildRoutingContext(\n this.modes.routedContainerIds,\n this.result,\n this.metrics,\n this.options\n );\n this.endpointOverlayScratch = new Map(\n [...this.routingContext.topologies].map(([containerId, topology]) => [\n containerId,\n new EndpointOverlayScratch(topology),\n ])\n );\n this.instrumentedRoutes = this.metrics ? [] : undefined;\n const countedDemandKeys = new Set<string>();\n for (const plan of this.prepared.orderedPlans) {\n if (plan.edge.start === plan.edge.end) {\n continue;\n }\n for (const entry of [...plan.source.chain, ...plan.target.chain]) {\n if (countedDemandKeys.has(entry.demandKey)) {\n continue;\n }\n countedDemandKeys.add(entry.demandKey);\n const key = ownerSideKey(entry.ownerId, entry.side);\n this.ownerSideCounts.set(key, (this.ownerSideCounts.get(key) ?? 0) + 1);\n }\n }\n }\n\n private pairedPortal(entry: EdgeEndpointEntry): PairedPortal {\n const existing = this.pairedPortals.get(entry.demandKey);\n if (existing) {\n return existing;\n }\n const owner = this.result.forest.nodeById.get(entry.ownerId);\n if (!owner?.isGroup) {\n throw gridError('GRID_ROUTE_NOT_FOUND', `Missing portal owner \"${entry.ownerId}\"`);\n }\n const rect = routerRect(owner);\n const coordinate =\n this.prepared.demandCoords.get(entry.demandKey) ??\n (entry.side === 'left' || entry.side === 'right'\n ? (rect.top + rect.bottom) / 2\n : (rect.left + rect.right) / 2);\n const range = derivePortalRanges(entry.ownerId, rect, owner.groupTitleRect).find(\n ({ side }) => side === entry.side\n );\n if (!range) {\n throw gridError(\n 'GRID_ROUTE_NOT_FOUND',\n `No legal ${entry.side} portal for \"${entry.ownerId}\"`\n );\n }\n const portal = buildPairedPortal(\n entry.ownerId,\n rect,\n owner.groupTitleRect ? { ...owner.groupTitleRect } : undefined,\n entry.side,\n clamp(coordinate, range.low, range.high)\n );\n this.pairedPortals.set(entry.demandKey, portal);\n if (this.metrics) {\n this.metrics.hierarchyPortalPairs++;\n this.metrics.hierarchyPortalTransitionLength += portal.transition.length;\n }\n return portal;\n }\n\n private alternativePairedPortals(\n entry: EdgeEndpointEntry,\n interior = true\n ): SegmentAttachmentAlternative[] {\n const selected = this.pairedPortal(entry);\n const owner = this.result.forest.nodeById.get(entry.ownerId);\n if (!owner?.isGroup) {\n return [];\n }\n const rect = routerRect(owner);\n const range = derivePortalRanges(entry.ownerId, rect, owner.groupTitleRect).find(\n ({ side }) => side === entry.side\n );\n if (!range) {\n return [];\n }\n const container = this.result.containers.get(owner.id);\n const corridors =\n entry.side === 'left' || entry.side === 'right'\n ? container?.horizontalCorridors\n : container?.verticalCorridors;\n // Keep retries bounded and deterministic: nearby established corridors are preferred, with\n // range endpoints available when the originally selected portal blocks a hierarchy segment.\n return boundedAlternativePortalCoordinates(\n selected.tangentialCoordinate,\n range.low,\n range.high,\n corridors ?? []\n ).map((coordinate) => {\n const portal = buildPairedPortal(\n entry.ownerId,\n rect,\n owner.groupTitleRect ? { ...owner.groupTitleRect } : undefined,\n entry.side,\n coordinate\n );\n return {\n attachment: portalAttachment(portal, interior),\n select: () => {\n this.pairedPortals.set(entry.demandKey, portal);\n this.prepared.demandCoords.set(entry.demandKey, coordinate);\n },\n };\n });\n }\n\n private itemSegmentAttachment(\n entry: EdgeEndpointEntry,\n containerId: GridContainerId\n ): SegmentAttachment {\n return {\n ownerId: entry.ownerId,\n ...itemAttachment(\n entry.ownerId,\n entry.side,\n entry.demandKey,\n containerId,\n this.result,\n this.prepared.demandCoords\n ),\n };\n }\n\n private alternativeItemAttachments(\n plan: EdgeRoutePlan,\n entry: EdgeEndpointEntry,\n containerId: GridContainerId\n ): SegmentAttachmentAlternative[] {\n const current = this.itemSegmentAttachment(entry, containerId);\n const owner = this.result.forest.nodeById.get(entry.ownerId);\n if (!owner) {\n return [];\n }\n return (['right', 'bottom', 'left', 'top'] as const)\n .filter((side) => side !== current.side && !(side === 'top' && ownerGroupTitle(owner)))\n .map((side) => {\n const interval = sideInterval(owner, side);\n if (!interval) {\n return undefined;\n }\n const rect = rectForNode(owner);\n const center = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n const coordinate = Math.max(\n interval.low,\n Math.min(interval.high, center + plan.laneOffset)\n );\n return {\n ownerId: entry.ownerId,\n ...itemAttachment(\n entry.ownerId,\n side,\n entry.demandKey,\n containerId,\n this.result,\n this.prepared.demandCoords,\n coordinate\n ),\n };\n })\n .filter((attachment): attachment is SegmentAttachment => attachment !== undefined)\n .slice(0, 3)\n .map((attachment) => ({\n attachment,\n select: () => undefined,\n }));\n }\n\n private routePlan(plan: EdgeRoutePlan, allowHierarchyRelaxation = true): void {\n // A plan is routed in three phases: source ascent, one LCA-container segment, and reversed\n // target descent. The chains are committed only after the combined route satisfies pair rules.\n const result = this.result;\n const routingContext = this.routingContext;\n const searchWorkspace = this.searchWorkspace;\n const endpointOverlayScratch = this.endpointOverlayScratch;\n const demandCoords = this.prepared.demandCoords;\n const ownerSideCounts = this.ownerSideCounts;\n const selfLoopCounts = this.selfLoopCounts;\n const pairRoutes = this.pairRoutes;\n const instrumentedRoutes = this.instrumentedRoutes;\n const metrics = this.metrics;\n const options = this.options;\n const eligibleIds = this.prepared.eligibleIds;\n const endpointCandidatesByEdge = this.prepared.endpointCandidatesByEdge;\n const compatibilityFastRoutes = this.modes.compatibilityFastRoutes;\n const sparseHierarchyIds = this.modes.sparseHierarchyIds;\n const sparseLcaIds = this.modes.sparseLcaIds;\n const edge = plan.edge;\n const sourceNode = edge.start ? result.forest.nodeById.get(edge.start) : undefined;\n const targetNode = edge.end ? result.forest.nodeById.get(edge.end) : undefined;\n if (!sourceNode || !targetNode) {\n throw gridError('GRID_MISSING_ENDPOINT', `Missing endpoint for edge \"${edge.id}\"`, {\n edgeId: edge.id,\n });\n }\n\n if (sourceNode.id === targetNode.id) {\n const committedPairRoutes = pairRoutes.get(plan.pairKey) ?? [];\n const { points, side, index } = sparseSelfLoopRoute(\n plan,\n sourceNode,\n result,\n routingContext,\n searchWorkspace,\n endpointOverlayScratch.get(sourceNode.parentId ?? ROOT_CONTAINER_ID),\n ownerSideCounts,\n selfLoopCounts,\n committedPairRoutes,\n options\n );\n const countKey = `${sourceNode.id}:${side}`;\n selfLoopCounts.set(countKey, index + 1);\n edge.points = points;\n // The router owns the polyline; attach its curve contract at the same commit boundary.\n edge.curve = result.config.curve;\n edge.cornerRadius = result.config.edgeCornerRadius;\n committedPairRoutes.push(points);\n pairRoutes.set(plan.pairKey, committedPairRoutes);\n if (metrics && instrumentedRoutes) {\n recordGridRoute(metrics, edge.id, points, instrumentedRoutes, 0, plan.laneOffset);\n instrumentedRoutes.push(points);\n }\n return;\n }\n\n const sourceFinal = plan.source.chain[plan.source.chain.length - 1];\n const targetFinal = plan.target.chain[plan.target.chain.length - 1];\n const useSparseLca = sparseLcaIds.has(edge.id);\n const compatibilityLca = useSparseLca\n ? undefined\n : compatibilityLcaAttachments(plan, result, demandCoords);\n const lcaStart: SegmentAttachment = compatibilityLca\n ? compatibilityLca.start\n : plan.source.finalKind === 'boundary'\n ? groupBoundaryEndpointAttachment(\n sourceFinal.ownerId,\n sourceFinal.side,\n sourceFinal.demandKey,\n result,\n demandCoords\n )\n : plan.source.chain.length > 1\n ? portalAttachment(this.pairedPortal(sourceFinal), false)\n : this.itemSegmentAttachment(sourceFinal, plan.lcaContainerId);\n const lcaEnd: SegmentAttachment = compatibilityLca\n ? compatibilityLca.end\n : plan.target.finalKind === 'boundary'\n ? groupBoundaryEndpointAttachment(\n targetFinal.ownerId,\n targetFinal.side,\n targetFinal.demandKey,\n result,\n demandCoords\n )\n : plan.target.chain.length > 1\n ? portalAttachment(this.pairedPortal(targetFinal), false)\n : this.itemSegmentAttachment(targetFinal, plan.lcaContainerId);\n let legacyLcaPoints: Point[] | undefined;\n const legacyRoute = () =>\n (legacyLcaPoints ??= routeWithinContainer(\n plan.lcaContainerId,\n result,\n lcaStart,\n lcaEnd,\n plan.laneIndex\n ));\n const compatibilityFastRoute = compatibilityFastRoutes.get(edge.id);\n const lcaPoints = compatibilityFastRoute\n ? (() => {\n if (metrics) {\n metrics.compatibilityFastPaths++;\n }\n return compatibilityFastRoute;\n })()\n : eligibleIds.has(edge.id)\n ? sparseSameContainerRoute(\n plan,\n endpointCandidatesByEdge.get(edge.id)!.sources,\n endpointCandidatesByEdge.get(edge.id)!.targets,\n sourceNode,\n targetNode,\n legacyRoute,\n result,\n routingContext,\n searchWorkspace,\n endpointOverlayScratch.get(plan.lcaContainerId)!,\n options,\n pairRoutes.get(plan.pairKey) ?? [],\n {\n index: this.occupancyFor(plan.lcaContainerId),\n pairKey: plan.pairKey,\n prioritizeEndpointCandidates: this.prepared.coordinatedEndpointIds.has(edge.id),\n }\n )\n : useSparseLca\n ? sparseContainerSegment(\n edge.id,\n plan.lcaContainerId,\n lcaStart,\n lcaEnd,\n legacyRoute,\n result,\n routingContext,\n searchWorkspace,\n endpointOverlayScratch.get(plan.lcaContainerId),\n options,\n pairRoutes.get(plan.pairKey) ?? [],\n () =>\n plan.target.finalKind === 'item' && plan.target.chain.length > 1\n ? this.alternativePairedPortals(targetFinal, false)\n : [],\n () =>\n plan.source.finalKind === 'item' && plan.source.chain.length > 1\n ? this.alternativePairedPortals(sourceFinal, false)\n : [],\n plan.bundleSize > 1,\n this.modes.overlapAvoidanceEnabled\n ? { index: this.occupancyFor(plan.lcaContainerId), pairKey: plan.pairKey }\n : undefined\n )\n : validatedCompatibilitySegment(\n edge.id,\n plan.lcaContainerId,\n lcaStart,\n lcaEnd,\n legacyRoute,\n result,\n metrics\n );\n\n const routeHierarchyChain = (endpoint: EdgeEndpointPlan, chains: Point[][]): void => {\n if (!sparseHierarchyIds.has(edge.id)) {\n for (const { containerId, start, end } of compatibilityHierarchyAttachments(\n endpoint,\n result,\n demandCoords\n )) {\n chains.push(\n validatedCompatibilitySegment(\n edge.id,\n containerId,\n start,\n end,\n () => routeWithinContainer(containerId, result, start, end, plan.laneIndex),\n result,\n metrics\n )\n );\n }\n return;\n }\n for (let index = 0; index < endpoint.chain.length - 1; index++) {\n const from = endpoint.chain[index];\n const to = endpoint.chain[index + 1];\n const start =\n index === 0\n ? this.itemSegmentAttachment(from, to.ownerId)\n : portalAttachment(this.pairedPortal(from), false);\n const end = portalAttachment(this.pairedPortal(to), true);\n chains.push(\n sparseContainerSegment(\n edge.id,\n to.ownerId,\n start,\n end,\n () => routeWithinContainer(to.ownerId, result, start, end, plan.laneIndex),\n result,\n routingContext,\n searchWorkspace,\n endpointOverlayScratch.get(to.ownerId),\n options,\n pairRoutes.get(plan.pairKey) ?? [],\n () => this.alternativePairedPortals(to),\n () => (index === 0 ? this.alternativeItemAttachments(plan, from, to.ownerId) : []),\n plan.bundleSize > 1\n )\n );\n }\n };\n const sourceChains: Point[][] = [];\n const targetChains: Point[][] = [];\n routeHierarchyChain(plan.source, sourceChains);\n routeHierarchyChain(plan.target, targetChains);\n\n const points = combinePointChains([\n ...sourceChains,\n lcaPoints,\n ...targetChains.reverse().map((chain) => reversePoints(chain)),\n ]);\n const committedPairRoutes = pairRoutes.get(plan.pairKey) ?? [];\n const satisfiesPairConstraints = routeSatisfiesPairConstraints(points, committedPairRoutes);\n const relaxHierarchySeparation =\n !satisfiesPairConstraints &&\n plan.bundleSize > 1 &&\n plan.source.chain.length + plan.target.chain.length > 2 &&\n routeHasDistinctPairPorts(points, committedPairRoutes);\n if (\n plan.bundleSize > 1 &&\n !satisfiesPairConstraints &&\n (!relaxHierarchySeparation || !allowHierarchyRelaxation)\n ) {\n if (metrics) {\n metrics.routesImpossible++;\n }\n throw gridError('GRID_ROUTE_NOT_FOUND', `No distinct lane route for \"${edge.id}\"`, {\n edgeId: edge.id,\n reason: relaxHierarchySeparation ? 'pair-separation' : 'no-distinct-route',\n });\n }\n if (relaxHierarchySeparation && metrics) {\n metrics.bundleSeparationRelaxations++;\n }\n edge.points = points;\n // Publish style only after the route satisfies terminal and pair-separation invariants.\n edge.curve = result.config.curve;\n edge.cornerRadius = result.config.edgeCornerRadius;\n committedPairRoutes.push(points);\n pairRoutes.set(plan.pairKey, committedPairRoutes);\n // Fast routes were registered while routing modes were prepared.\n if (!compatibilityFastRoute) {\n this.occupancyFor(plan.lcaContainerId).add(lcaPoints, plan.pairKey);\n }\n if (metrics && instrumentedRoutes) {\n const boundaryTransitionCount = plan.source.chain.length + plan.target.chain.length - 2;\n recordGridRoute(\n metrics,\n edge.id,\n points,\n instrumentedRoutes,\n boundaryTransitionCount,\n plan.laneOffset\n );\n instrumentedRoutes.push(points);\n }\n }\n\n private occupancyFor(containerId: GridContainerId): RouteOccupancyIndex {\n let occupancy = this.modes.routeOccupancy.get(containerId);\n if (!occupancy) {\n occupancy = new RouteOccupancyIndex();\n this.modes.routeOccupancy.set(containerId, occupancy);\n }\n return occupancy;\n }\n\n private createBundleCheckpoint(pairPlans: readonly EdgeRoutePlan[]): BundleCheckpoint {\n this.occupancyFor(pairPlans[0].lcaContainerId);\n return createBundleCheckpoint(\n pairPlans,\n this.pairRoutes,\n this.pairedPortals,\n this.prepared.demandCoords,\n this.instrumentedRoutes,\n this.metrics,\n this.modes.routeOccupancy\n );\n }\n\n private restoreBundleCheckpoint(checkpoint: BundleCheckpoint): void {\n restoreBundleCheckpoint(\n checkpoint,\n this.pairRoutes,\n this.pairedPortals,\n this.prepared.demandCoords,\n this.instrumentedRoutes,\n this.metrics\n );\n }\n\n private routeBundle(pairPlans: EdgeRoutePlan[]): void {\n // Small bundles first require strict pair separation. If that fails only because hierarchy\n // interiors overlap, restore the whole bundle and retry with that separation relaxed while\n // preserving distinct endpoint ports.\n const canAttemptStrictSeparation =\n pairPlans.length > 1 &&\n pairPlans.length <= 8 &&\n pairPlans.every(({ edge }) => edge.start !== edge.end);\n if (!canAttemptStrictSeparation) {\n for (const plan of pairPlans) {\n this.routePlan(plan);\n }\n return;\n }\n // A bundle is the retry unit because earlier siblings reserve pair corridors and portals for\n // later ones. Restore every transactional structure before relaxing separation. The cumulative\n // search budget intentionally retains work performed by the discarded attempt.\n const checkpoint = this.createBundleCheckpoint(pairPlans);\n let initialError: unknown;\n try {\n for (const plan of pairPlans) {\n this.routePlan(plan, false);\n }\n return;\n } catch (error) {\n initialError = error;\n this.restoreBundleCheckpoint(checkpoint);\n }\n\n if (!isPairSeparationError(initialError)) {\n throw initialError;\n }\n for (const plan of pairPlans) {\n this.routePlan(plan);\n }\n }\n}\n", "import type { LayoutData } from '../../types.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type { RouterSearchCaps } from './routerSearch.js';\nimport { GridEdgeRoutingSession } from './routerSession.js';\nimport type { TopologyResourceCaps } from './routerTopology.js';\nimport type { GridLayoutResult } from './types.js';\n\n// Public routing facade. The implementation is split by phase so callers only depend on the\n// stable options and compatibility exports that predate the module extraction.\nexport {\n areExactlyAxisAligned,\n boundedAlternativePortalCoordinates,\n} from './routerCompatibility.js';\nexport { validateSameContainerRoute } from './routerConstraint.js';\nexport { assignCompactPortalCoordinates } from './routerPlanning.js';\n\nexport interface GridRoutingDualRouteComparison {\n edgeId: string;\n sparse: { valid: boolean; length: number; bends: number };\n legacy: { valid: boolean; length: number; bends: number };\n}\n\nexport interface GridRoutingOptions {\n // Caps are also test seams, so enabling them deliberately bypasses compatibility fast paths.\n topologyCaps?: TopologyResourceCaps;\n searchCaps?: RouterSearchCaps;\n}\n\n/** @internal */\nexport interface GridRoutingTestOptions extends GridRoutingOptions {\n onDualRouteComparison?: (comparison: GridRoutingDualRouteComparison) => void;\n}\n\nexport function routeGridEdges(\n layout: LayoutData,\n result: GridLayoutResult,\n metrics?: GridRoutingInstrumentation,\n options?: GridRoutingOptions\n): void;\nexport function routeGridEdges(\n layout: LayoutData,\n result: GridLayoutResult,\n metrics?: GridRoutingInstrumentation,\n options: GridRoutingTestOptions = {}\n): void {\n // A fresh session owns every mutable routing structure and commits routes in deterministic order.\n new GridEdgeRoutingSession(layout, result, metrics, options).route();\n}\n", "import type { LayoutData, Node } from '../../types.js';\nimport { positionGridEdgeLabels } from './edgeLabels.js';\nimport { buildGridForest } from './groups.js';\nimport { buildGridLabelRequirements, deriveGridContainerLabelGaps } from './labelSpacing.js';\nimport {\n buildGridSourceOrder,\n readGridConfig,\n resolveGridPlacements,\n validateGridPlacementMap,\n} from './placement.js';\nimport { routeGridEdges, type GridRoutingTestOptions } from './router.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport {\n GRID_DEFAULTS,\n ROOT_CONTAINER_ID,\n type GridContainerId,\n type GridContainerLayoutMeta,\n type GridItemLayoutMeta,\n type GridForest,\n type GridLayoutResult,\n type GridLayoutData,\n gridError,\n isEdgeLabelNode,\n isFinitePositiveNumber,\n} from './types.js';\n\n/*\n * Computes grid geometry in two coordinate systems:\n *\n * 1. Each container lays out its direct children in local coordinates, children-first.\n * 2. A top-down pass translates those local results into absolute diagram coordinates.\n *\n * The public entry point runs both phases on a clone and commits only after the complete geometry\n * succeeds, so invalid input cannot leave the caller's graph partially positioned.\n */\nconst GROUP_ROUTING_GUTTER = 24;\nconst GROUP_ROUTING_CLEARANCE = 20;\n\nfunction titleBandFor(node: Node, titleGap: number): number {\n if (!node.label || !node.labelBBox || !(node.labelBBox.height > 0)) {\n return 0;\n }\n return node.labelBBox.height + titleGap;\n}\n\nfunction ensureMeasuredNode(node: Node): void {\n if (!isFinitePositiveNumber(node.width) || !isFinitePositiveNumber(node.height)) {\n throw gridError(\n 'GRID_MISSING_MEASUREMENT',\n `Node \"${node.id}\" must have width and height greater than 0 (width: ${node.width}, height: ${node.height})`,\n {\n nodeId: node.id,\n width: node.width,\n height: node.height,\n }\n );\n }\n}\n\nfunction measureChild(node: Node): { width: number; height: number } {\n ensureMeasuredNode(node);\n return { width: node.width!, height: node.height! };\n}\n\nfunction layoutContainer(\n containerId: GridContainerId,\n result: GridLayoutResult,\n containers: Map<GridContainerId, GridContainerLayoutMeta>,\n itemMeta: Map<string, GridItemLayoutMeta>,\n metrics?: GridRoutingInstrumentation\n): void {\n const { forest, config, sourceOrder } = result;\n const group = containerId === ROOT_CONTAINER_ID ? undefined : forest.groupById.get(containerId);\n const padding = group ? Math.max(group.padding ?? 0, config.containerPadding) : 0;\n const titleBand = group ? titleBandFor(group, config.titleGap) : 0;\n const routingGutter = group ? GROUP_ROUTING_GUTTER : 0;\n const contentTop = group ? padding + titleBand + routingGutter : 0;\n\n const directItems = (forest.childrenByParent.get(containerId) ?? []).filter(\n (node) => !isEdgeLabelNode(node)\n );\n\n const { cells } = resolveGridPlacements(directItems, sourceOrder, config);\n const cellEntries = [...cells.values()].sort((a, b) => a.row - b.row || a.column - b.column);\n\n // A cell may contain an authored vertical stack. Columns and rows are sized from the largest\n // complete stack in that track, which keeps neighboring cells aligned.\n const columnWidths = new Map<number, number>();\n const rowHeights = new Map<number, number>();\n const rows = new Set<number>();\n const columns = new Set<number>();\n\n for (const cell of cellEntries) {\n let stackWidth = 0;\n let stackHeight = 0;\n for (const placement of cell.items) {\n const size = measureChild(placement.item);\n stackWidth = Math.max(stackWidth, size.width);\n stackHeight += size.height;\n }\n if (cell.items.length > 1) {\n stackHeight += config.cellGap * (cell.items.length - 1);\n }\n cell.width = stackWidth;\n cell.height = stackHeight;\n rows.add(cell.row);\n columns.add(cell.column);\n columnWidths.set(cell.column, Math.max(columnWidths.get(cell.column) ?? 0, stackWidth));\n rowHeights.set(cell.row, Math.max(rowHeights.get(cell.row) ?? 0, stackHeight));\n }\n\n const sortedRows = [...rows].sort((a, b) => a - b);\n const sortedColumns = [...columns].sort((a, b) => a - b);\n const labelGaps = deriveGridContainerLabelGaps(\n result.labelRequirements.byContainer.get(containerId) ?? [],\n cells,\n rowHeights,\n columnWidths,\n sortedRows,\n sortedColumns,\n config.rowGap,\n config.columnGap,\n metrics\n );\n const rowGapAfter = (row: number) => Math.max(config.rowGap, labelGaps.rowGapAfter.get(row) ?? 0);\n const columnGapAfter = (column: number) =>\n Math.max(config.columnGap, labelGaps.columnGapAfter.get(column) ?? 0);\n if (metrics) {\n for (const gap of labelGaps.rowGapAfter.values()) {\n if (gap > config.rowGap) {\n metrics.labelSpacingBoundariesExpanded++;\n metrics.labelSpacingPixelsAdded += gap - config.rowGap;\n }\n }\n for (const gap of labelGaps.columnGapAfter.values()) {\n if (gap > config.columnGap) {\n metrics.labelSpacingBoundariesExpanded++;\n metrics.labelSpacingPixelsAdded += gap - config.columnGap;\n }\n }\n }\n\n const contentWidth = sortedColumns.reduce(\n (total, column, index) =>\n total +\n (columnWidths.get(column) ?? 0) +\n (index < sortedColumns.length - 1 ? columnGapAfter(column) : 0),\n 0\n );\n // A title sets the minimum group width. If it is wider than the content and its insets,\n // center the occupied tracks so the extra horizontal space is split evenly on both sides.\n const width = group\n ? Math.max(\n contentWidth + (padding + routingGutter) * 2,\n (group.labelBBox?.width ?? 0) + padding * 2\n )\n : contentWidth;\n const contentLeft = group ? (width - contentWidth) / 2 : 0;\n\n const columnOrigins = new Map<number, number>();\n let xCursor = contentLeft;\n for (const [index, column] of sortedColumns.entries()) {\n columnOrigins.set(column, xCursor);\n xCursor +=\n (columnWidths.get(column) ?? 0) +\n (index < sortedColumns.length - 1 ? columnGapAfter(column) : 0);\n }\n\n const rowOrigins = new Map<number, number>();\n let yCursor = contentTop;\n for (const [index, row] of sortedRows.entries()) {\n rowOrigins.set(row, yCursor);\n yCursor += (rowHeights.get(row) ?? 0) + (index < sortedRows.length - 1 ? rowGapAfter(row) : 0);\n }\n const gridHeight = sortedRows.length ? yCursor - contentTop : 0;\n\n const outerLeftCorridor = group\n ? contentLeft - GROUP_ROUTING_CLEARANCE\n : -Math.max(config.columnGap / 2, GRID_DEFAULTS.containerPadding);\n const outerRightCorridor = group\n ? contentLeft + contentWidth + GROUP_ROUTING_CLEARANCE\n : contentLeft + contentWidth + Math.max(config.columnGap / 2, GRID_DEFAULTS.containerPadding);\n const outerTopCorridor = group\n ? contentTop - GROUP_ROUTING_CLEARANCE\n : -Math.max(config.rowGap / 2, GRID_DEFAULTS.containerPadding);\n const outerBottomCorridor = group\n ? contentTop + gridHeight + GROUP_ROUTING_CLEARANCE\n : contentTop + gridHeight + Math.max(config.rowGap / 2, GRID_DEFAULTS.containerPadding);\n\n // Record the empty bands between tracks while geometry is available. The routing layer consumes\n // these coordinates later without needing to reconstruct placement decisions.\n const verticalCorridors = new Set<number>([outerLeftCorridor, outerRightCorridor]);\n const horizontalCorridors = new Set<number>([outerTopCorridor, outerBottomCorridor]);\n const leftCorridorByColumn = new Map<number, number>();\n const rightCorridorByColumn = new Map<number, number>();\n const topCorridorByRow = new Map<number, number>();\n const bottomCorridorByRow = new Map<number, number>();\n\n if (sortedColumns.length > 0) {\n leftCorridorByColumn.set(sortedColumns[0], outerLeftCorridor);\n rightCorridorByColumn.set(sortedColumns.at(-1)!, outerRightCorridor);\n }\n for (let index = 0; index < sortedColumns.length - 1; index++) {\n const current = sortedColumns[index];\n const next = sortedColumns[index + 1];\n const corridor =\n (columnOrigins.get(current)! + (columnWidths.get(current) ?? 0) + columnOrigins.get(next)!) /\n 2;\n verticalCorridors.add(corridor);\n rightCorridorByColumn.set(current, corridor);\n leftCorridorByColumn.set(next, corridor);\n }\n if (sortedRows.length > 0) {\n topCorridorByRow.set(sortedRows[0], outerTopCorridor);\n bottomCorridorByRow.set(sortedRows.at(-1)!, outerBottomCorridor);\n }\n for (let index = 0; index < sortedRows.length - 1; index++) {\n const current = sortedRows[index];\n const next = sortedRows[index + 1];\n const corridor =\n (rowOrigins.get(current)! + (rowHeights.get(current) ?? 0) + rowOrigins.get(next)!) / 2;\n horizontalCorridors.add(corridor);\n bottomCorridorByRow.set(current, corridor);\n topCorridorByRow.set(next, corridor);\n }\n\n for (const cell of cellEntries) {\n const cellLeft = columnOrigins.get(cell.column) ?? contentLeft;\n const cellTop = rowOrigins.get(cell.row) ?? contentTop;\n const cellWidth = columnWidths.get(cell.column) ?? cell.width;\n const cellHeight = rowHeights.get(cell.row) ?? cell.height;\n const verticalFactor =\n cell.verticalAlign === 'top' ? 0 : cell.verticalAlign === 'bottom' ? 1 : 0.5;\n const stackTop = cellTop + (cellHeight - cell.height) * verticalFactor;\n\n let itemTop = stackTop;\n for (const [itemIndex, placement] of cell.items.entries()) {\n const { width, height } = measureChild(placement.item);\n const horizontalFactor =\n placement.horizontalAlign === 'left' ? 0 : placement.horizontalAlign === 'right' ? 1 : 0.5;\n const itemLeft = cellLeft + (cellWidth - width) * horizontalFactor;\n placement.item.x = itemLeft + width / 2;\n placement.item.y = itemTop + height / 2;\n const topCorridorY =\n itemIndex > 0\n ? itemTop - config.cellGap / 2\n : (topCorridorByRow.get(cell.row) ?? outerTopCorridor);\n const bottomCorridorY =\n itemIndex < cell.items.length - 1\n ? itemTop + height + config.cellGap / 2\n : (bottomCorridorByRow.get(cell.row) ?? outerBottomCorridor);\n if (itemIndex > 0) {\n horizontalCorridors.add(topCorridorY);\n }\n if (itemIndex < cell.items.length - 1) {\n horizontalCorridors.add(bottomCorridorY);\n }\n\n itemMeta.set(placement.item.id, {\n containerId,\n row: cell.row,\n column: cell.column,\n cellLeft,\n cellTop,\n cellWidth,\n cellHeight,\n leftCorridorX: leftCorridorByColumn.get(cell.column) ?? outerLeftCorridor,\n rightCorridorX: rightCorridorByColumn.get(cell.column) ?? outerRightCorridor,\n topCorridorY,\n bottomCorridorY,\n });\n\n itemTop += height + config.cellGap;\n }\n }\n\n const height = group ? gridHeight + titleBand + (padding + routingGutter) * 2 : gridHeight;\n\n containers.set(containerId, {\n id: containerId,\n left: 0,\n top: 0,\n width,\n height,\n contentLeft,\n contentTop,\n contentRight: group ? contentLeft + contentWidth : contentWidth,\n contentBottom: group ? contentTop + gridHeight : gridHeight,\n verticalCorridors: [...verticalCorridors].sort((a, b) => a - b),\n horizontalCorridors: [...horizontalCorridors].sort((a, b) => a - b),\n });\n\n if (group) {\n group.width = width;\n group.height = height;\n group.x = width / 2;\n group.y = height / 2;\n if (titleBand > 0) {\n group.groupTitleRect = {\n left: 0,\n right: width,\n top: 0,\n bottom: padding + titleBand,\n };\n } else {\n delete group.groupTitleRect;\n }\n }\n}\n\nfunction translateRect(\n rect: NonNullable<Node['groupTitleRect']>,\n dx: number,\n dy: number\n): NonNullable<Node['groupTitleRect']> {\n return {\n left: rect.left + dx,\n right: rect.right + dx,\n top: rect.top + dy,\n bottom: rect.bottom + dy,\n };\n}\n\nfunction materializeAbsoluteGeometry(result: GridLayoutResult): void {\n const { forest, containers, itemMeta } = result;\n\n // Container layout is local to its parent. Walk top-down with accumulated offsets so nodes,\n // title rectangles, cell metadata, and routing corridors all move as one coordinate system.\n interface ShiftFrame {\n containerId: GridContainerId;\n offsetX: number;\n offsetY: number;\n children: Node[];\n nextChildIndex: number;\n entered: boolean;\n }\n\n const stack: ShiftFrame[] = [\n {\n containerId: ROOT_CONTAINER_ID,\n offsetX: 0,\n offsetY: 0,\n children: forest.childrenByParent.get(ROOT_CONTAINER_ID) ?? [],\n nextChildIndex: 0,\n entered: false,\n },\n ];\n\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n\n if (!frame.entered) {\n frame.entered = true;\n const container = containers.get(frame.containerId);\n if (container) {\n container.left += frame.offsetX;\n container.top += frame.offsetY;\n container.contentLeft += frame.offsetX;\n container.contentRight += frame.offsetX;\n container.contentTop += frame.offsetY;\n container.contentBottom += frame.offsetY;\n container.verticalCorridors = container.verticalCorridors.map(\n (value) => value + frame.offsetX\n );\n container.horizontalCorridors = container.horizontalCorridors.map(\n (value) => value + frame.offsetY\n );\n }\n }\n\n const child = frame.children[frame.nextChildIndex];\n if (!child) {\n stack.pop();\n continue;\n }\n frame.nextChildIndex += 1;\n\n if (isEdgeLabelNode(child)) {\n continue;\n }\n\n const meta = itemMeta.get(child.id);\n if (meta) {\n meta.cellLeft += frame.offsetX;\n meta.cellTop += frame.offsetY;\n meta.leftCorridorX += frame.offsetX;\n meta.rightCorridorX += frame.offsetX;\n meta.topCorridorY += frame.offsetY;\n meta.bottomCorridorY += frame.offsetY;\n }\n\n child.x = (child.x ?? 0) + frame.offsetX;\n child.y = (child.y ?? 0) + frame.offsetY;\n\n if (!child.isGroup) {\n continue;\n }\n\n if (child.groupTitleRect) {\n child.groupTitleRect = translateRect(\n child.groupTitleRect,\n child.x - (child.width ?? 0) / 2,\n child.y - (child.height ?? 0) / 2\n );\n }\n\n stack.push({\n containerId: child.id,\n offsetX: child.x - (child.width ?? 0) / 2,\n offsetY: child.y - (child.height ?? 0) / 2,\n children: forest.childrenByParent.get(child.id) ?? [],\n nextChildIndex: 0,\n entered: false,\n });\n }\n}\n\nfunction commitGridGeometry(source: LayoutData, target: LayoutData): void {\n // Preserve caller-owned node and edge identities. Downstream renderers may already hold\n // references to these objects, so only calculated geometry is copied from the working graph.\n const sourceNodeById = new Map(source.nodes.map((node) => [node.id, node]));\n for (const targetNode of target.nodes) {\n const sourceNode = sourceNodeById.get(targetNode.id);\n if (!sourceNode) {\n continue;\n }\n targetNode.x = sourceNode.x;\n targetNode.y = sourceNode.y;\n targetNode.width = sourceNode.width;\n targetNode.height = sourceNode.height;\n if (sourceNode.groupTitleRect) {\n targetNode.groupTitleRect = { ...sourceNode.groupTitleRect };\n } else {\n delete targetNode.groupTitleRect;\n }\n }\n\n const sourceEdgeById = new Map(source.edges.map((edge) => [edge.id, edge]));\n for (const targetEdge of target.edges) {\n const sourceEdge = sourceEdgeById.get(targetEdge.id);\n if (!sourceEdge) {\n continue;\n }\n targetEdge.points = sourceEdge.points?.map((point) => ({ ...point }));\n targetEdge.curve = sourceEdge.curve;\n targetEdge.cornerRadius = sourceEdge.cornerRadius;\n targetEdge.portClipping = 'outline-orthogonal';\n targetEdge.skipCornerFix = sourceEdge.curve === 'linear';\n }\n}\n\nfunction cloneGridLayoutData(data: GridLayoutData): GridLayoutData {\n return {\n ...data,\n nodes: data.nodes.map((node) => ({\n ...node,\n labelBBox: node.labelBBox ? { ...node.labelBBox } : node.labelBBox,\n groupTitleRect: node.groupTitleRect ? { ...node.groupTitleRect } : node.groupTitleRect,\n })),\n edges: data.edges.map((edge) => ({\n ...edge,\n points: edge.points?.map((point) => ({ ...point })),\n })),\n };\n}\n\nfunction rebindGridForest(forest: GridForest, nodes: Node[]): GridForest {\n // The calculation forest points at cloned nodes. Rebuild each collection against the committed\n // caller-owned nodes before exposing the result to later routing and rendering phases.\n const nodeById = new Map(nodes.map((node) => [node.id, node]));\n const originalNode = (node: Node): Node => {\n const original = nodeById.get(node.id);\n if (!original) {\n throw new Error(`Missing committed grid node \"${node.id}\"`);\n }\n return original;\n };\n const originalGroup = (group: Node & { isGroup: true }): Node & { isGroup: true } => {\n const original = originalNode(group);\n if (!original.isGroup) {\n throw new Error(`Committed grid node \"${group.id}\" is no longer a group`);\n }\n return original as Node & { isGroup: true };\n };\n\n return {\n nodeById,\n groupById: new Map(\n [...forest.groupById].map(([groupId, group]) => [groupId, originalGroup(group)])\n ),\n childrenByParent: new Map(\n [...forest.childrenByParent].map(([parentId, children]) => [\n parentId,\n children.map(originalNode),\n ])\n ),\n rootChildren: forest.rootChildren.map(originalNode),\n postOrderGroups: forest.postOrderGroups.map(originalGroup),\n helperNodeIds: new Set(forest.helperNodeIds),\n };\n}\n\nfunction runGridLayoutCoreInPlace(\n data: GridLayoutData,\n options: GridLayoutCoreInternalOptions\n): GridLayoutResult {\n const forest = buildGridForest(data.nodes);\n const config = readGridConfig(data);\n const sourceOrder = buildGridSourceOrder(data.nodes.filter((node) => !isEdgeLabelNode(node)));\n validateGridPlacementMap(\n data.nodes.filter((node) => !isEdgeLabelNode(node)),\n config\n );\n\n const result: GridLayoutResult = {\n forest,\n config,\n containers: new Map(),\n itemMeta: new Map(),\n sourceOrder,\n labelRequirements: buildGridLabelRequirements(data, forest, options.metrics),\n };\n\n // Post-order is the key sizing invariant: a group becomes a measured child only after all of its\n // descendants have established the group's final width and height.\n for (const group of forest.postOrderGroups) {\n layoutContainer(group.id, result, result.containers, result.itemMeta, options.metrics);\n }\n layoutContainer(ROOT_CONTAINER_ID, result, result.containers, result.itemMeta, options.metrics);\n materializeAbsoluteGeometry(result);\n // Routing consumes absolute node bounds and corridor coordinates, so it must run after the\n // children-first sizing and top-down translation phases have both completed.\n routeGridEdges(data, result, options.metrics, options.routing);\n // Labels consume final routes and may transactionally reroute them, so they are the last layout\n // phase before the working copy is committed to the render model.\n positionGridEdgeLabels(data, undefined, options.metrics);\n return result;\n}\n\n/** @internal */\nexport interface GridLayoutCoreInternalOptions {\n metrics?: GridRoutingInstrumentation;\n routing?: GridRoutingTestOptions;\n}\n\nexport function runGridLayoutCore(\n data4Layout: LayoutData,\n options: GridLayoutCoreInternalOptions = {}\n): GridLayoutResult {\n const data = data4Layout;\n\n // Routing and label placement are transactional: a failed recovery must not leave partial\n // coordinates on the shared render model. Commit only the geometry from a complete run.\n const working = cloneGridLayoutData(data);\n const result = runGridLayoutCoreInPlace(working, options);\n commitGridGeometry(working, data);\n return {\n ...result,\n forest: rebindGridForest(result.forest, data.nodes),\n };\n}\n", "import {\n applyLineJumpsToSvg,\n normalizeLineHops,\n type EdgeGeom,\n} from '../../rendering-elements/lineJump.js';\nimport type { LayoutData } from '../../types.js';\nimport type { CommonLayoutPaintContext } from '../common/index.js';\n\ninterface EdgePaintGroups {\n groups: { edgePaths: Parameters<typeof applyLineJumpsToSvg>[0] };\n}\n\nexport function applyGridLineJumps(\n data: LayoutData,\n { measure }: CommonLayoutPaintContext<unknown, EdgePaintGroups>\n): void {\n const lineHops = normalizeLineHops(data.config.grid?.lineHops);\n if (lineHops === false) {\n return;\n }\n\n const edges = data.edges\n .filter(\n (edge): edge is typeof edge & { points: EdgeGeom['points'] } =>\n Array.isArray(edge.points) && edge.points.length >= 2\n )\n .map((edge) => ({\n id: edge.id,\n points: edge.points,\n curve: edge.curve,\n cornerRadius: edge.cornerRadius,\n arrowTypeStart: edge.arrowTypeStart,\n arrowTypeEnd: edge.arrowTypeEnd,\n }));\n\n applyLineJumpsToSvg(measure.groups.edgePaths, edges, {\n enabled: true,\n jumpRadius: 6,\n jumpStyle: lineHops,\n });\n}\n", "import { createCommonLayoutRenderer } from '../common/index.js';\nimport { prepareGridLayout } from './edgeLabels.js';\nimport { runGridLayoutCore } from './layoutCore.js';\nimport { applyGridLineJumps } from './lineHops.js';\n\n// Keep this adapter deliberately small: the common renderer owns the public render lifecycle,\n// while grid-specific preparation and layout remain reusable by DDLT and focused tests.\nexport { prepareGridLayout, runGridLayoutCore };\n\nexport const render = createCommonLayoutRenderer({\n prepareLayout: prepareGridLayout,\n runLayoutCore: (data4Layout) => runGridLayoutCore(data4Layout),\n afterPaint: applyGridLineJumps,\n});\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,gBAAgB;AAuBtB,SAAS,mBAAmB,GAAU,GAAU,YAAY,eAAgC;AACjG,QAAM,KAAK,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC;AAC7B,QAAM,KAAK,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC;AAC7B,MAAI,MAAM,aAAa,MAAM,WAAW;AACtC,WAAO;AAAA,EACT;AACA,MAAI,MAAM,WAAW;AACnB,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAVgB;AAaT,SAAS,mBAAmB,QAAiB,YAAY,eAA0B;AACxF,QAAM,WAAsB,CAAC;AAC7B,WAAS,IAAI,GAAG,IAAI,OAAO,SAAS,GAAG,KAAK;AAC1C,UAAM,IAAI,OAAO,CAAC;AAClB,UAAM,IAAI,OAAO,IAAI,CAAC;AACtB,aAAS,KAAK,EAAE,GAAG,GAAG,aAAa,mBAAmB,GAAG,GAAG,SAAS,EAAE,CAAC;AAAA,EAC1E;AACA,SAAO;AACT;AARgB;AAWT,SAAS,eAAe,UAAqB,YAAY,eAA0B;AACxF,MAAI,SAAS,WAAW,GAAG;AACzB,WAAO,CAAC;AAAA,EACV;AACA,QAAM,SAAoB,CAAC;AAC3B,MAAI,UAAU,EAAE,GAAG,SAAS,CAAC,EAAE;AAE/B,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,OAAO,SAAS,CAAC;AAEvB,QAAI,KAAK,gBAAgB,KAAK;AAC5B;AAAA,IACF;AACA,QAAI,QAAQ,gBAAgB,KAAK;AAC/B,gBAAU,EAAE,GAAG,KAAK;AACpB;AAAA,IACF;AAE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;AAAA,EACF;AAEA,QAAM,QAAQ,KAAK,MAChB;AAAA,IACC,CAAC,SACC,MAAM,QAAQ,KAAK,MAAM,KAAK,KAAK,OAAO,UAAU;AAAA,EACxD,EACC,IAAI,CAAC,UAAU;AAAA,IACd,IAAI,KAAK;AAAA,IACT,QAAQ,KAAK;AAAA,IACb,OAAO,KAAK;AAAA,IACZ,cAAc,KAAK;AAAA,IACnB,gBAAgB,KAAK;AAAA,IACrB,cAAc,KAAK;AAAA,EACrB,EAAE;AAEJ,sBAAoB,QAAQ,OAAO,WAAW,OAAO;AAAA,IACnD,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,WAAW;AAAA,EACb,CAAC;AACH;AA5BgB;;;ACHT,IAAM,SAAS,2BAA2B;AAAA,EAC/C,eAAe;AAAA,EACf,eAAe,wBAAC,gBAAgB,kBAAkB,WAAW,GAA9C;AAAA,EACf,YAAY;AACd,CAAC;",
"names": ["normalizePolyline", "normalizePolyline", "alongPadding", "preferred", "entry", "exit", "low", "high", "_a", "hit", "tangentialCoordinate", "candidateSegments", "avoidOccupied", "committedPairRoutes", "points", "width", "height"]
}