@molecule/api-uptime
Core interface · uptime · API (Node) · v1.1.0 · Apache-2.0
Abstract uptime interface — probe an http(s) URL for status, latency and TLS expiry — bond in-process fetch or molecule.dev’s hosted service
npm install @molecule/api-uptimeHow it works
@molecule/api-uptime is the uptime core interface on the API (Node) side: the API your app calls, with no vendor inside.
Choose the implementation by bonding one of its 2 providers: @molecule/api-uptime-fetch, @molecule/api-uptime-molecule.
import { setProvider, probe } from '@molecule/api-uptime'
import { provider as uptimeFetch } from '@molecule/api-uptime-fetch'
setProvider(uptimeFetch)
const result = await probe({
url: 'https://api.example.com/health',
expectText: '"ok"',
})
console.log(result.status, result.latencyMs, result.tls?.daysRemaining)Providers (2): @molecule/api-uptime-fetch, @molecule/api-uptime-molecule
Works with: @molecule/api-bond, @molecule/api-i18n
Reference
Provider-agnostic uptime interface for molecule.dev — probe an http(s) URL
and get a verdict: operational, degraded or down, with latency, the
final HTTP status, redirect count and the TLS certificate's remaining
lifetime.
Defines the UptimeProvider interface for availability checks. Bond
packages (an in-process fetch with verified dialing, molecule.dev hosted)
implement this interface. Application code uses the probe convenience
function, which delegates to the bonded provider.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { setProvider, probe } from '@molecule/api-uptime'
import { provider as uptimeFetch } from '@molecule/api-uptime-fetch'
setProvider(uptimeFetch)
const result = await probe({
url: 'https://api.example.com/health',
expectText: '"ok"',
})
console.log(result.status, result.latencyMs, result.tls?.daysRemaining)
Type
core
Installation
npm install @molecule/api-uptime @molecule/api-bond @molecule/api-i18n
API
Interfaces
UptimeTlsInfo
The TLS certificate of the final hop's connection (https only).
interface UptimeTlsInfo {
/** Certificate subject common name, when present. */
subject?: string
/** Issuing certificate authority's organization, when present. */
issuer?: string
/** Not-after date, ISO 8601. */
validTo: string
/** Whole days from the probe until `validTo` (negative when already expired). */
daysRemaining: number
}
UptimeProbeSpec
One uptime probe: request a URL from the provider's vantage point and
judge the answer. The spec is the whole contract — everything is optional
except url, and every field is validated before any connection.
interface UptimeProbeSpec {
/** The target, absolute `http:`/`https:`, at most 2,048 characters. */
url: string
/** `GET` (default) or `HEAD`. `HEAD` cannot carry `expectText`. */
method?: UptimeMethod
/**
* Milliseconds allowed for the WHOLE probe — every redirect hop, the body
* read included (1,000–30,000; default 10,000). Exceeding it is `down`.
*/
timeoutMs?: number
/**
* The status the target must return. When given, ONLY this status is
* `operational` and any other is `down`; when absent, 2xx is `operational`,
* 3xx `degraded` (the probe followed up to 3 redirects and still ended on
* one), 4xx/5xx `down`.
*/
expectStatus?: number
/**
* Text that must appear in the response body (GET only, first 1 MB).
* Case-sensitive substring. Not found → `down`.
*/
expectText?: string
/**
* A successful probe slower than this many milliseconds (0–30,000; default
* 2,000) is `degraded` instead of `operational`.
*/
degradedLatencyMs?: number
}
UptimeProbeResult
The outcome of one probe. A down site is a SUCCESSFUL probe — the call
answered the question — so providers resolve with it instead of throwing;
a thrown error means the probe itself could not run.
interface UptimeProbeResult {
/** The availability verdict. */
status: UptimeStatus
/** ISO 8601 timestamp of when the probe completed. */
checkedAt: string
/** The requested `url`. */
url: string
/** The `method` the probe used (its default, when the spec omitted it). */
method?: UptimeMethod
/** The URL after redirects, when the target redirected. */
finalUrl?: string
/** How many redirects were followed (0 when none). */
redirects?: number
/** The final response's HTTP status, when one arrived. */
httpStatus?: number
/** Whole milliseconds from probe start to the response being fully read. */
latencyMs?: number
/** The final hop's TLS certificate (https only). */
tls?: UptimeTlsInfo
/**
* A few response headers of the final hop — `content-type`, `server`,
* `content-length` and `location` only, when present.
*/
headers?: Record<string, string>
/** Response-body bytes actually read (capped; 0 for `HEAD`). */
bodyBytesRead?: number
/** When `expectText` was given: whether it appeared. */
expectTextMatched?: boolean
/** Human-readable reason for a `down`/`degraded` verdict. */
message?: string
}
UptimeProvider
Uptime provider interface. All uptime providers must implement this. Bond packages (in-process fetch, molecule.dev hosted, …) provide concrete implementations.
interface UptimeProvider {
/**
* Probes one URL and resolves with the verdict.
*
* @param spec - What to probe and how to judge it.
* @returns The probe's outcome — `down` included.
* @throws {Error} When the spec is invalid or the provider cannot probe.
*/
probe(spec: UptimeProbeSpec): Promise<UptimeProbeResult>
}
ProbeObservation
The observed facts one hop left behind — the input to deriveProbeStatus.
interface ProbeObservation {
/** Connection/DNS/TLS/timeout failure text, when the probe never got a response. */
failure?: string
/** The final response's HTTP status, when one arrived. */
httpStatus?: number
/** Whether `expectText` appeared (only when the spec carried it). */
expectTextMatched?: boolean
/** Whole milliseconds the probe took. */
latencyMs?: number
}
Types
UptimeStatus
Availability verdict for one probe.
type UptimeStatus = 'operational' | 'degraded' | 'down'
UptimeMethod
How to request the target. HEAD cannot carry expectText (no body).
type UptimeMethod = 'GET' | 'HEAD'
NormalizedUptimeProbeSpec
The spec after validation: every optional field at its default.
type NormalizedUptimeProbeSpec = Required<
Pick<UptimeProbeSpec, 'url' | 'method' | 'timeoutMs' | 'degradedLatencyMs'>
> &
Pick<UptimeProbeSpec, 'expectStatus' | 'expectText'>
Functions
setProvider(provider)
Registers an uptime provider as the active singleton. Called by bond packages during application startup.
function setProvider(provider: UptimeProvider): void
provider— The uptime provider implementation to bond.
getProvider()
Retrieves the bonded uptime provider, throwing if none is configured.
function getProvider(): UptimeProvider
Returns: The bonded uptime provider.
hasProvider()
Checks whether an uptime provider is currently bonded.
function hasProvider(): boolean
Returns: true if an uptime provider is bonded.
probe(spec)
Probes a URL through the bonded provider.
function probe(spec: UptimeProbeSpec): Promise<UptimeProbeResult>
spec— What to probe and how to judge it (urlrequired).
Returns: The probe's outcome — a down site included.
isPublicIpv4(ip)
True when an IPv4 address is public unicast — the only thing we dial.
function isPublicIpv4(ip: string): boolean
ipv6ToBytes(ip)
Parse an IPv6 address into its 16 bytes, or null when the text is not one.
Handles the compressed (::) form, leading zeros inside a group, and a
trailing dotted-quad pair (::ffff:1.2.3.4, which a caller may hand us even
though the URL parser and getnameinfo both emit the hex spelling). The
brackets a URL hostname carries are NOT accepted: a length-16 result is the
only thing isPublicIpv6 will act on, so anything it cannot read
refuses (fail closed) rather than being matched as text.
function ipv6ToBytes(ip: unknown): number[] | null
ip— The address text.
Returns: 16 bytes, or null.
isPublicIpv6(ip)
True when an IPv6 address is public unicast — the only thing we dial.
The verdict is made on the PARSED BYTES, never on the address text. The
text form is not a property the guard can rely on: getnameinfo and the URL
parser both emit the canonical compressed spelling, so a prefix test written
against a padded spelling (2001:0000) never matches 2001:0:…, and the
IPv4-mapped test that only unwrapped a DOTTED-QUAD tail never fired at all —
::ffff:127.0.0.1 arrives as ::ffff:7f00:1, which the old checks read as
a public address.
function isPublicIpv6(ip: unknown): boolean
ip— The address text.
Returns: Whether the address may be dialled.
isDialable(addrs)
Every resolved address must be public unicast, or the target refuses.
function isDialable(addrs: dns.LookupAddress[]): boolean
resolvePublicAddress(hostname)
Resolves hostname and checks every address — the render server's
verifyTarget as a promise. Resolves the VERIFIED address the caller must
dial (never the hostname again: the dial re-resolving is the rebinding the
check exists to deny), or null when any address is not public unicast.
function resolvePublicAddress(hostname: string): Promise<{ address: string; family: number } | null>
hostname— The URL hostname (brackets stripped).
Returns: The verified address, or null on refusal / lookup failure.
validateProbeSpec(raw)
Validates a probe spec field by field. Unknown fields are IGNORED (the caller passes plain objects from JSON; extra keys carry no meaning here), wrong-typed known fields are refused — the hosted path rebuilds its body field by field upstream of this, so a smuggled provider option has no route in.
function validateProbeSpec(
raw: unknown,
): { ok: true; spec: NormalizedUptimeProbeSpec } | { ok: false; message: string }
raw— The untrusted spec.
Returns: The normalized spec, or the refusal message.
deriveProbeStatus(observation, spec)
Derives the verdict from the observation — the SAME rules for every bond:
- a failure (no response at all) is
down; expectStatus, when given, is the whole verdict: only it isoperational;- otherwise 2xx is
operational, 3xxdegraded(the redirect chain ended on a redirect — a loop, or more hops thanUPTIME_LIMITS.maxRedirects), 4xx/5xxdown; expectTextgiven but absent from the body isdown(the page loaded but is not the page the caller wanted — the classic "up but serving an error shell" false-positive uptime checks exist to catch);- an
operationalverdict slower thandegradedLatencyMsdegrades.
function deriveProbeStatus(
observation: ProbeObservation,
spec: NormalizedUptimeProbeSpec,
): { status: UptimeStatus; message?: string }
observation— What the probe saw.spec— The normalized spec the probe ran.
Returns: The verdict and, for non-operational ones, the reason.
Constants
UPTIME_LIMITS
Per-probe limits — mirrored by the hosted handler, the render machine and the -molecule bond.
const UPTIME_LIMITS: {
readonly maxUrlChars: 2048
readonly minTimeoutMs: 1000
readonly maxTimeoutMs: 30000
readonly defaultTimeoutMs: 10000
readonly maxExpectTextChars: 256
readonly defaultDegradedLatencyMs: 2000
readonly maxDegradedLatencyMs: 30000
readonly maxRedirects: 3
readonly maxBodyBytes: 1000000
}
Available Providers
| Provider | Package |
|---|---|
| Fetch (uptime) | @molecule/api-uptime-fetch |
| Molecule (hosted) | @molecule/api-uptime-molecule |
Injection Notes
Requirements
Peer dependencies:
@molecule/api-bond^1.0.1@molecule/api-i18n^1.0.1
Runtime Dependencies
-
@molecule/api-bond -
@molecule/api-i18n -
A
downsite is a SUCCESSFUL probe. The provider resolves with thedownverdict — the call answered the question. A thrown error means the probe itself could not run (invalid spec, provider misconfigured). -
Verdict rules (the same in every bond — see
deriveProbeStatus): a connection/DNS/TLS/timeout failure isdown;expectStatus, when given, is the whole verdict; otherwise 2xx isoperational, 3xxdegraded(the probe follows up to 3 redirects), 4xx/5xxdown;expectTextabsent from the first 1 MB of the body isdown; anoperationalprobe slower thandegradedLatencyMs(default 2,000) degrades. -
A
url:probe leaves YOUR server's network — an in-process bond dials what the URL names. The default dialing is VERIFIED (every resolved address must be public unicast — loopback, RFC 1918, link-local cloud metadata and every other non-global range refuse, and the probe dials the verified address, so DNS rebinding has nothing to switch to);allowPrivateTargets: truelifts that for probing hosts you know are yours — NEVER with a raw user-supplied URL (prefer the hosted molecule.dev bond there; it refuses private targets, period). -
Probe targets are untrusted INPUT, but responses are not executed and not parsed as markup: the body is read only to cap 1 MB and match
expectText. -
This is a point-in-time probe, NOT a monitor: nothing is scheduled and no history is kept. Call it on your own cadence (a cron in the app, an agent's loop) — or use it as the check a status page's renderer drives.