@shumoku/core · 0.5.0
TypeScript API
122 public functions generated from TypeScript and TSDoc.
absenceImpliesRetraction True when absence in a snapshot should be treated as evidence
(retract / mark stale). False when the snapshot 's absence is
meaningless because the node was deliberately not asked.
This is the *critical* anti-footgun call codex flagged: if we
post-filter excluded nodes out of a NetBox snapshot whose status
is `ok` (= absence trusted), the resolver would happily interpret
the missing entry as "NetBox says it 's gone". We never want that. addHttpWarning Add HTTP warning to connection result if URL uses insecure HTTP applyGraphEdits Writes the edits made to a drawn graph back into the model it was drawn from.
`drawn` is the graph as it was before the edits and `edited` as it is after; only what differs
between them is written. The configuration keeps what the graph cannot say, such as a node's
software or the host a VM runs on, and a field the graph draws from another (a product's name,
a link's speed) is kept as written until that field is edited. The layers of an edited element
are replaced, as the graph says all of them. Without an edit, the model itself is returned. applyThemeToCSS Apply theme to CSS variables asEntityId Trust-boundary cast — DB reads, registry mint, wire-format parse.
Use ONLY at: mint, DB row reads, HTTP param boundaries, and tests.
If you find yourself casting mid-logic, fix the signature above you instead. attachmentKey Stable merge / suppression key for an attachment. `access` is keyed per
protocol (SNMP and SSH are distinct slots); `metrics-binding` is keyed per
metrics source (two metrics sources can each bind one element — but ONE
binding per (source, element) is the invariant; extend with a role segment
if per-metric-role binding is ever needed, don't overload the slot); every
other kind keys by its `kind`. The resolver merges attachments by this key
(highest-priority contribution wins per key) and the human suppresses by it
(`suppressedAttachments`). One definition so merge and suppression never
disagree on what "the same attachment slot" means. bindingInterfaceName The best name to hand the plugin for an interface binding. Identity
(`ifName`) is the durable key; `interfaceName` is the migration / label
fallback. The poll-time resolution layer may refine this against the
source's live interface list, but a name is always derivable here. buildAlertTitle Display title: `"<alertname> - <host>"`, or just the name when no host. buildIdentity Build an `Identity` from raw parts, dropping empty values. Returns
`undefined` when nothing identifying was supplied (so callers don't stamp
an empty identity object that the resolver would treat as `unbound`). cableConnectorForStandard Derive the cable-end connector from the link's effective standard.
The model no longer stores `cable.connector` explicitly — call this
from display / validation code that needs the connector value. cableGradesForStandard Cable grades available given the link's standard. Returns an empty
array when grade isn't a meaningful axis (DAC / AOC) — the UI hides
the third select in that case. cableVariantsForPlug Cable variants for a plug — all standards reachable through that
cage form factor, ordered by speed. For RJ45 this includes 10M /
100M / 1G / 2.5G / 5G / 10G; for SFP+ it includes SR / LR / CR / AOC. checkNetwork Every issue in a written network, all at once: someone who writes from an example needs the
whole list, not the first mistake. An empty list means the network can be read. classifyIcon Classify a raw icon string into inline-SVG vs URL.
Inline content starts with `<` (either a bare `<path .../>` fragment
or a full `<svg>...</svg>` block). Anything else is treated as a URL,
including `data:` URIs. classifyStandardGroup No summary. combineLinkPresentation Compose an independent connection; style does not change endpoints or physical data. combineNetworkDocument Compose an independent graph for existing layout, renderer and editor consumers.
This checks the presentation boundary, not the entire topology schema. combineNodePresentation Compose an independent runtime node without changing stored payloads. combineSubgraphPresentation Compose an independent group with its display override. computeEffectivePolicy No summary. contrastRatio The WCAG contrast ratio of two colours. createTheme Create custom theme defaultCableGrade Default grade for a freshly-picked standard. Used when the user
picks/changes the cable medium and we want the third select to land
on a sensible value rather than empty. defaultStandardForCages Propose a sensible default standard given the cages on both ends. deriveMappingFromGraph Derive a legacy `MetricsMapping` from a resolved graph's bindings.
- Node host binding → `mapping.nodes[node.id]`.
- Link interface binding lives on a `NodePort`; we attribute it to the
link whose endpoint references that port, keyed `link.id || link-${i}`
to match the rest of the server (server.ts / topologies.ts).
Pure; never mutates the input. deriveStructure The structure a written network implies. A network is the `config` of a read model
(`readNetworkModel(yaml).config`); the result refers to it by its written ids. diagramTitle Everything a node or link says, one fact a line: what a title (tooltip) shows in full. drawingArcs How each vertex of a polyline is rounded, given the radius asked for at each (0 at the ends).
The arc is tangent to both runs, so a vertex turning through θ takes `r·tan(θ/2)` off each, at
most half of either run; where that does not fit, the radius is reduced to fit. A vertex that
is not rounded (an end, no radius, a run of no length, no turn) has no arc. This is the one
place a drawn corner is worked out; the renderer writes the arcs out and the layout samples them. drawingBoundary Where the network meets what lies beyond it, as ids the structure can measure from. The
drawing layer's own choice comes first; else the external or cloud nodes and the routing domains
that links reach, what the input itself says is outside; else the structure's candidates (where
the physical meets the virtual). A part of the
network that none of these reaches gets its own guess (`upstreamOf`), so it still has an up
and a down. drawNetwork Draws a model as a scene: the one entry from what is written (and what the layers add) to
where each box stands and how each line runs. The model is the truth; the scene is only its
projection, made fresh each time. effectiveLinkStandard No summary. effectivePlugCage Resolve the effective plug cage for an endpoint with the canonical priority:
explicit `plug.cage` > module's required cage > port.connectors[0]
(only when the port has a single connector — multi-connector combo
ports require an explicit choice on the link side). Returns undefined
when none are known. effectivePolicyForNode Convenience: compute the effective discovery policy for a node in
the context of a full `NetworkGraph`. Walks the graph 's subgraphs
once into a lookup map, then delegates to `computeEffectivePolicy`.
The resolver, the scheduler, and the API "GET effective policy for
this node" surface all need the same answer; they call this helper. endpointModule No summary. endpointPlugCage No summary. endpointStandard No summary. extractHost Host from the common label dialects, in priority order. filterAlertLabels Drop Alertmanager-internal labels (`__name__`, other `__…`). fittingLineTone The tone that tells the most lines apart over these backgrounds: of the lightnesses at which
every hue is seen, the one that leaves the most chroma. For writing a theme's `lineTone`. flattenObject Flatten an arbitrary upstream record into `DiscoveredMetric[]` for the
plugin "All metrics" passthrough panel.
This is the generic dumper every `HostsCapable` plugin should use instead
of hand-enumerating fields (which is how zabbix ended up coercing every
value to a number and dropping categorical attributes). Walk the object:
- object children join into the metric name with `_`
(`{ a: { b: 1 } }` with prefix `p` → `p_a_b`),
- array-of-primitives emits a `<name>_count`,
- array-of-objects emits a `<name>_count` then expands each element with a
`<key>_index` label,
- null / undefined / empty-string / non-finite leaves are skipped as noise.
Lifted verbatim (behavior-preserving) from the aruba-instant-on plugin,
which had the only correct generic implementation. formatReachMeters Format a meters value for UI display (1000+ → km). fromNetworkGraph Splits a drawn graph back into its configuration and layers: the inverse of `toNetworkGraph`
for what the configuration can say. A node drawn for a segment becomes the segment again. getDeviceIcon Get SVG icon content for a device type getNodeId Helper to get node ID from endpoint. Kept as a tiny accessor so callers
read intent ("the link's source node") rather than reaching into shape. getStandardSpec No summary. getThemeFromCSS Get theme from CSS variables groupCableVariants Group cable variants by `cableKind` for sectioned `<optgroup>` rendering. groupStandards Group a list of `StandardOption`s by their `group` for sectioned dropdowns. hasAlertsCapability No summary. hasAutoscanCapability No summary. hasConfigOptions Duck-type: can this plugin supply dynamic candidates for `optionsSource` fields? hasConnectionInfo Duck-type: does this plugin expose derived, display-only connection info? hasHostsCapability No summary. hasMetricsCapability No summary. hasNativeApi Duck-type check: does this plugin expose a native-API passthrough?
Intentionally not bound to a `DataSourceCapability` literal — this is a
developer-only escape hatch, not a product feature, so it stays off the
advertised capability list. hasTopologyCapability No summary. hueOf A colour's OKLCH hue, in degrees. interfaceMatchScore Score how well two normalized interface names match (0–1): same canonical
prefix, then port numbers compared right-to-left (rightmost = most specific). interfaceNamesMatch Whether two interface names denote the same physical port. Same canonical
prefix with aligning numbers (score ≥ 0.5), OR — for cross-vocabulary cases
like TTDB's speed-code `hg` vs Juniper `et-` where prefixes differ but the
port number is identical — the full number sequence matches. isExcluded True when the node should NOT be auto-touched by the scheduler or
by any source's discovery pass — convenience predicate that hides
the mode comparison from callers that just need a yes/no answer. isPluggableConnector No summary. isPoeCapableConnector No summary. isSecretProp A field is a write-only secret if it declares `secret: true`. `format:
'password'` is honoured too so external plugins that predate the flag keep
working; new schemas should set `secret: true`. issuesForTarget Filter issues whose target points at a specific field. Used by the UI. keyHash Stable string form of a key for use as a Map key. labelText A label line as drawn: the bold and line-break markup a label may carry is not text. layoutDrawing Lays a network out as a scene: where each box stands and how each line runs. `network` is the
configuration as written, `structure` what follows from it and the boundary points, and
`metrics` every length the drawing may use.
Every discrete choice is made from relations and indices before any coordinate, one stage after
another, and the coordinates are solved once for each axis at the end: the ranks (`ranksOf`)
from the flows, the left-to-right order of every rank (`layersOf`), the free space cut into
corridors (`corridorsOf`), each line's way through them (`routesOf`), the order of the lines
in each corridor (`tracksOf`), what the ports and corridors ask of the sizes (`needsOf`), and
the coordinates (`placeAll`). No stage reads a length to decide, so a font that measures a
little differently moves things a little and changes nothing else. lineColorCapacity The most colours a tone can tell apart. lineColors `count` colours of a tone, as `#rrggbb`: hues evenly spaced from the tone's, at the least chroma
that keeps them told apart. `undefined` when the tone has no room for that many. linkSpeedBps The nominal speed of a link (bits/sec): what its ends' standards name, else the `speedBps` the
link carries for a link that no standard describes. linkTitle No summary. mapAlertmanagerSeverity No summary. mapWithConcurrency Run `fn` over `items` with at most `limit` calls in flight at once,
preserving input order in the result array.
Replaces the two failure modes the audit found: unbounded `Promise.all`
fan-out (network-scan would open hundreds of SNMP sockets at once) and
fully sequential `await`-in-a-loop polling (zabbix walked hosts one by
one). A rejected `fn` rejects the whole call (like `Promise.all`); a
caller wanting partial results should catch inside `fn`. mediumFromGrade Derive the cable medium kind from a `CableGrade`. Twisted-pair
categories map to twisted-pair, OM3/4/5 → multi-mode fiber, OS1/2 →
single-mode fiber, DAC and AOC are their own mediums. mediumFromStandard Derive the cable medium implied by an Ethernet standard. Resolves
the standard via `STANDARD_SPECS` and maps `cableKind` + `fiberMode`
onto the unified `CableMedium` enum. mergeTheme Merge theme with overrides metricsBindingOf The metrics-binding attachment on an element, if any. When `activeSourceIds`
is given, only a binding whose `sourceId` is active counts — so a binding left
behind by a detached/removed metrics source stops driving the mapping. missingCapabilityMethods Declared capabilities whose required method is missing on a constructed
instance, formatted `"cap → method()"`. Empty array = compliant. Unknown
(open) capabilities are skipped. The registry calls this once at first
instantiate (decision 7) to catch a plugin that advertises a capability it
doesn't actually implement (C6). newId Generate a fresh unique ID for the given entity kind.
Collision probability for 10-char nanoid is negligible for editor-scale
workloads (~trillions of IDs before 1% collision chance). nodeContentScale The safe central rectangle inside each nonrectangular outline. nodeIdentityKeys Enumerate Node identity keys in priority order. The first match
wins during cluster lookup. Caller should also bind *every* key
to the resulting cluster after a match so subsequent observations
collapse correctly even if they only carry a weaker key. nodeIdentityQuality Coarse identity quality — surfaced in UI to warn users which
elements may detach from their metrics/observations across reboots.
Node: `stable` if chassisId + (mgmtIp or sysName), `weak` if any
single primary key, `unbound` otherwise.
Port: `stable` if ifName + (mac or ifIndex), `weak` if any single
key, `unbound` otherwise. normalizeInterfaceName Normalize an interface name to `{ prefix, numbers, sub }`. The numeric part is
split on `/`, `-`, or `:` so TTDB's dash form ("hg-0-0-0" → [0,0,0]) lines up
with the slash form ("hg/0/0/0" → [0,0,0]). normalizeMacKey Canonical spelling for a MAC-shaped identity key: lowercase, colon-separated.
Sources disagree on how to write the same wire address. Huawei NCE returns
`50-04-01-01-D5-50` in its device list and `CC:D8:1F:9F:D4:AB` in its LLDP
table; an SNMP walk of the very same switch yields `cc:d8:1f:9f:d4:ab`; Cisco
gear writes `ccd8.1f9f.d4ab`. Identity keys are matched as exact strings, so
without one canonical spelling a device arrives as two entities that never
merge — the failure is silent, which is what makes it worth normalizing here
rather than in each plugin.
Anything that is not twelve hex digits once separators are stripped is
returned untouched: `chassisId` is only sometimes a MAC (LLDP also permits
interface names and network addresses) and must survive as written. normalizePortConnector No summary. oklchToHex An OKLCH colour as `#rrggbb`. paperSizeToPixels Convert paper size to pixels at given DPI parseAlertmanagerAlerts Parse an Alertmanager response into core `Alert[]`, applying the standard
active/timeRange and minSeverity filters.
- Active alerts are always kept; resolved alerts are dropped when
`activeOnly`, otherwise dropped once older than `timeRange` (default 1h).
- Unparseable `startsAt` falls back to `now`; missing/unparseable `endsAt`
yields `undefined` (no bogus epoch-0 end time). parseNetworkPresentation Validate and copy unknown presentation data. plugFromCage Build a cage-only plug — the user picked a form factor without a module yet. plugFromStandard Build a plug from a chosen module standard. The plug carries only the
`module` — `cage` is intentionally omitted because it's derivable from
`module.standard` via `STANDARD_SPECS[std].cage`. Returns `undefined`
if the standard is unknown. plugProfileForStandard Resolve a standard to its plug profile (for prefilling the plug select). plugProfilesForConnectors Plug profiles compatible with the given port connectors. Empty
arrays are permissive (return all plugs); multi-connector combo
ports return the union of compatible plugs. portIdentityKeys Enumerate Port identity keys in priority order. Port matching
happens *within* a parent node cluster — the same `ifName` on a
different chassis is a different port. The caller is responsible
for that scoping; this list is just the per-port priority order. portIdentityQuality No summary. rateFromBps Writes a rate in bits/sec as the input does, such as `10G` or `100M`. reachForLink Effective reach in meters for a link, accounting for the cable grade.
Falls back to the standard's `maxReach_m` when the grade isn't set or
isn't in the registry's per-grade table. readNetworkModel Reads the YAML people write into a model that holds it as its configuration. A network that
cannot be read as written throws a `NetworkInputError` listing every issue in it. resolve Resolve the project's own graph against source snapshots, for callers that still hold graphs:
each graph is split into its configuration and layers, merged by `resolveNetwork`, and drawn
again. New callers should hold models and call `resolveNetwork` directly. resolveIcon Resolve the icon to render for a given spec. Returns the explicit
`spec.icon` if any; otherwise the bundled device-type fallback;
otherwise null. resolveNetwork Merge the project's own model with what every source observed into one model of the same
shape.
All contributions are equal and priority-ordered; the project is just the top priority.
Nodes are clustered by identity (any-key match, or a shared registry entity id) regardless of
priority, and then per field the highest-priority contribution that holds a value wins
(`priority desc, capturedAt desc`). Who won the label, type, product and group is recorded in
the observation layer's `fieldSources`; every node, port, group and link gets a `provenance`.
The merged network keeps a node's project id when the project wrote it, and gives a node only
sources found a synthesized `discovered:N` id. Each source's groups, segments, routing domains,
connections and redundancy sets are namespaced by its source id so they never collide.
See `apps/server/docs/design/topology-source-priority-merge.md`. sampleNetworkModel The sample with its drawing layer. sanitizeIconSvg No summary. sanitizeIconSvgWith No summary. separateLinkPresentation Split connection style from facts. Unstyled idless links are preserved. separateNetworkGraph Separate geometry, shape, styles, port placement and graph settings from facts.
Derived group bounds are discarded; physical records are copied unchanged. separateNodePresentation Split a structured-cloneable runtime node into independent storage values. separateSubgraphPresentation Split group style/direction from facts; discard runtime-derived bounds. severityAtLeast True when `severity` is at least as severe as `min`. severityRank Rank of a severity (unknown → `info`). sourceToGraph Builds the graph of what one source discovered, as the resolver merges it. specDeviceType Extract DeviceType from a spec (hardware and compute only). stampObserved Return a copy of `node` stamped with observation provenance, identity, and
sync metadata. Never mutates the input (callers build node lists with
`.map(stampObserved…)`). Existing identity/metadata are preserved and only
overlaid with the supplied values. standardsForConnectors Standards available given the connectors on each port. Used by the
editor's cascading "Standard" picker so the dropdown only offers
links that physically fit. Empty arrays are treated permissively —
we'd rather show too many than none.
For combo ports (multiple connectors), this returns the union: any
standard that fits at least one connector on each side qualifies.
Returned as one flat list; group via `option.group` if the UI wants
to split into sections. standardSpeedBps The speed (bits/sec) the standards of the plugs name: the slower when the two ends differ
(a BiDi link), the only one when one end names it, nothing when neither does. symmetricPlug Produce a symmetric plug spec for a link — both endpoints get the same
plug+module. Used by editor flows that default to symmetric links. toneFits Whether every hue of a lightness and chroma is shown by a screen and seen against every
background, checked every few degrees. toNetworkGraph Builds the graph that layout and the renderers draw from the configuration and its layers.
Sources are not read: Server merges them into the configuration first. validateAgainstSchema No summary. validateLinkCompatibility Validate a link against its endpoints, ports, and cable. Runs every
registered endpoint-level and link-level check; collects all issues
the UI / consumers can route to inline markers via `issuesForTarget`. validateTopologyIdentityContract Check whether what a topology plugin discovered satisfies the identity contract.
Returns arrays of violating node/port ids. Both arrays empty → contract met. writeNetworkModel Writes a model's configuration as the YAML people write. Its layers are not written.