@molecule/api-uptime-molecule

Provider bond · uptime · API (Node) · v1.2.0 · Apache-2.0

molecule.dev hosted uptime — probe a URL from molecule’s vantage point, billed to your project, no vendor account

npm install @molecule/api-uptime-molecule

npm · Source on GitHub · Implements @molecule/api-uptime

How it works

@molecule/api-uptime-molecule is a provider bond on the API (Node) side: it implements the uptime core interface (@molecule/api-uptime) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

Works with: @molecule/api-secrets, @molecule/api-uptime

Secrets: MOLECULE_API_KEY

Reference

molecule.dev hosted uptime — probe a URL from molecule’s vantage point, billed to your project, no vendor account

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.ts JSDoc, not this file.

Type

provider

Installation

npm install @molecule/api-uptime-molecule @molecule/api-uptime @molecule/api-secrets

API

Interfaces

MoleculeUptimeConfig

Options for createProvider(). Every field falls back to its env var.

interface MoleculeUptimeConfig {
  /**
   * A molecule project API key (`mk_…`) or the in-sandbox token (`mbk_…`),
   * scope `broker` or `broker:uptime`. Defaults to
   * `process.env.MOLECULE_API_KEY`.
   */
  apiKey?: string

  /**
   * The hosted services base URL. Defaults to
   * `process.env.MOLECULE_SERVICES_URL`, then
   * `https://api.molecule.dev/api/v1/services`.
   */
  servicesUrl?: string

  /** Per-call HTTP timeout in milliseconds. Defaults to `45_000` — the probe's own `timeoutMs` (at most 30,000) plus redirect and network slack. */
  timeoutMs?: number
}

UptimeMonitorView

One scheduled monitor: a probe spec the platform runs on an interval from molecule.dev, with its latest verdict and schedule state. The push subscription keys are never returned.

interface UptimeMonitorView {
  id: string
  url: string
  /** The validated probe spec the platform executes (url, method, timeoutMs, expectStatus, expectText, degradedLatencyMs). */
  spec: {
    url: string
    method?: 'GET' | 'HEAD'
    timeoutMs?: number
    expectStatus?: number
    expectText?: string
    degradedLatencyMs?: number
  }
  intervalSeconds: number
  /** Whether a web-push subscription is attached for down/recovery alerts. */
  alerting: boolean
  paused: boolean
  lastStatus: 'operational' | 'degraded' | 'down' | null
  lastCheckedAt: string | null
  nextRunAt: string
  consecutiveFails: number
  lastAlertAt: string | null
  createdAt: string
}

ScheduleMonitorInput

What scheduleMonitor() accepts: the probe spec plus the schedule.

interface ScheduleMonitorInput {
  /** Update an existing monitor instead of creating one (every field resupplied; execution state resets). */
  id?: string
  url: string
  /** Whole seconds between runs: 60–86,400. */
  intervalSeconds: number
  method?: 'GET' | 'HEAD'
  timeoutMs?: number
  expectStatus?: number
  expectText?: string
  degradedLatencyMs?: number
  /** A browser push subscription created with molecule.dev's VAPID key (from `push/vapid-key`); attach or replace down/recovery alerting. `null` removes it. */
  alertPush?: { endpoint: string; keys: { p256dh: string; auth: string } } | null
  paused?: boolean
}

UptimeCheckView

One stored check of a scheduled monitor.

interface UptimeCheckView {
  checkedAt: string
  status: 'operational' | 'degraded' | 'down'
  latencyMs: number | null
  httpStatus: number | null
  message: string | null
}

Classes

MoleculeServiceError

Error thrown for a refused or failed hosted-service call.

class MoleculeServiceError extends Error {
  /** HTTP status from molecule.dev. */
  readonly status: number
  /** Stable error key from molecule.dev. */
  readonly errorKey: string | undefined

  /**
   * Create the error.
   *
   * @param message - Human-readable message.
   * @param status - HTTP status.
   * @param errorKey - Stable error key, when the service sent one.
   * @param cause - The underlying error, if any.
   */
  constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
    super(message, cause === undefined ? undefined : { cause })
    this.name = 'MoleculeServiceError'
    this.status = status
    this.errorKey = errorKey
  }
}

MoleculeUptimeProvider

Uptime provider backed by molecule.dev's hosted service.

The hosted machine probes HTTP(S) targets from PUBLIC addresses only — loopback, private-network and link-local targets are refused before any connection — so a user-supplied URL cannot reach your network from molecule's render machine, and a probe of YOUR OWN site reads the public internet's view of it, not your process's.

class MoleculeUptimeProvider implements UptimeProvider {
  readonly name = 'molecule'

  private readonly apiKey: string
  private readonly servicesUrl: string
  private readonly timeoutMs: number

  /**
   * Create the provider.
   *
   * @param config - Options; each falls back to its env var.
   */
  constructor(config: MoleculeUptimeConfig = {}) {
    this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
    this.servicesUrl = resolveServicesUrl(
      config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
    )
    this.timeoutMs = config.timeoutMs ?? 45_000
  }

  /**
   * Probes one URL on the hosted service and returns the verdict.
   *
   * @param spec - What to probe and how to judge it.
   * @returns The probe's outcome — a `down` site included.
   */
  async probe(spec: UptimeProbeSpec): Promise<UptimeProbeResult> {
    // The service limits are mirrored LOCALLY (the core's validator is the
    // same contract the handler enforces), so a bad call never leaves the
    // process.
    const checked = validateProbeSpec(spec)
    if (!checked.ok) {
      throw new MoleculeServiceError(checked.message, 400, 'hostedServices.error.invalidInput')
    }
    return this.request('uptime/probe', checked.spec)
  }

  /**
   * Schedules (or updates) a recurring uptime monitor: the platform runs the
   * probe on your interval from molecule.dev and stores every verdict — read
   * them back with `monitorHistory`. At most 10 monitors per project.
   *
   * @param input - The probe spec, the interval and the optional alert subscription.
   * @returns The stored monitor.
   */
  async scheduleMonitor(input: ScheduleMonitorInput): Promise<UptimeMonitorView> {
    if (
      typeof input.intervalSeconds !== 'number' ||
      !Number.isInteger(input.intervalSeconds) ||
      input.intervalSeconds < MONITOR_LIMITS.minIntervalSeconds ||
      input.intervalSeconds > MONITOR_LIMITS.maxIntervalSeconds
    ) {
      throw new MoleculeServiceError(
        `"intervalSeconds" must be a whole number between ${MONITOR_LIMITS.minIntervalSeconds} and ${MONITOR_LIMITS.maxIntervalSeconds}.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    // The core validator IS the service contract; run it here so a bad spec
    // never leaves the process.
    const checked = validateProbeSpec(input)
    if (!checked.ok) {
      throw new MoleculeServiceError(checked.message, 400, 'hostedServices.error.invalidInput')
    }
    const body: Record<string, unknown> = {
      ...checked.spec,
      intervalSeconds: input.intervalSeconds,
    }
    if (input.id !== undefined) body.id = input.id
    if (input.alertPush !== undefined) body.alertPush = input.alertPush
    if (input.paused !== undefined) body.paused = input.paused
    const out = await this.request<{ monitor?: UptimeMonitorView }>('uptime/schedule', body)
    if (!out.monitor?.id) {
      throw new MoleculeServiceError(
        'molecule.dev returned no monitor.',
        502,
        'hostedServices.error.upstreamFailed',
      )
    }
    return out.monitor
  }

  /** Lists this project's scheduled monitors with their latest verdicts. */
  async listMonitors(): Promise<UptimeMonitorView[]> {
    const out = await this.request<{ monitors?: UptimeMonitorView[] }>('uptime/monitors', {})
    return out.monitors ?? []
  }

  /**
   * Reads one monitor's stored checks (newest first) with an uptime summary
   * over the returned window. Checks are kept 30 days.
   *
   * @param monitorId - The monitor's id (from `listMonitors`).
   * @param limit - At most 500 checks; default 100.
   */
  async monitorHistory(
    monitorId: string,
    limit = 100,
  ): Promise<{
    monitor: UptimeMonitorView
    checks: UptimeCheckView[]
    summary: {
      total: number
      operational: number
      degraded: number
      down: number
      uptimePercent: number | null
    }
  }> {
    if (!monitorId) {
      throw new MoleculeServiceError(
        '"monitorId" is required.',
        400,
        'hostedServices.error.invalidInput',
      )
    }
    if (!Number.isInteger(limit) || limit < 1 || limit > MONITOR_LIMITS.maxHistoryLimit) {
      throw new MoleculeServiceError(
        `"limit" must be a whole number between 1 and ${MONITOR_LIMITS.maxHistoryLimit}.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    return this.request('uptime/history', { monitorId, limit })
  }

  /** Deletes a scheduled monitor and its stored checks. */
  async removeMonitor(id: string): Promise<{ removed: boolean; id: string }> {
    if (!id) {
      throw new MoleculeServiceError('"id" is required.', 400, 'hostedServices.error.invalidInput')
    }
    return this.request('uptime/remove', { id })
  }

  /** One POST to the hosted service. */
  private async request<T>(path: string, body: Record<string, unknown>): Promise<T> {
    if (!this.apiKey) {
      throw new MoleculeServiceError(
        'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
        401,
        'hostedServices.error.tokenInvalid',
      )
    }
    const response = await fetch(`${this.servicesUrl}/${path}`, {
      method: 'POST',
      headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(this.timeoutMs),
    })
    const text = await response.text()
    let data: unknown
    try {
      data = text ? JSON.parse(text) : {}
    } catch (error) {
      throw new MoleculeServiceError(
        `molecule.dev returned ${response.status} with a non-JSON body.`,
        response.status,
        undefined,
        error,
      )
    }
    if (!response.ok) {
      const err = data as { error?: string; errorKey?: string }
      const hint = HINTS[response.status]
      throw new MoleculeServiceError(
        `molecule.dev ${path} failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
        response.status,
        err.errorKey,
      )
    }
    const result = data as T
    if (path === 'uptime/probe') {
      const probeResult = data as UptimeProbeResult
      if (typeof probeResult.status !== 'string' || typeof probeResult.checkedAt !== 'string') {
        throw new MoleculeServiceError(
          'molecule.dev returned no probe verdict.',
          502,
          'hostedServices.error.upstreamFailed',
        )
      }
    }
    return result
  }
}

Functions

createProvider(config)

Create a hosted uptime provider.

function createProvider(config?: MoleculeUptimeConfig): UptimeProvider
  • config — Options; each falls back to its env var.

Returns: A UptimeProvider backed by molecule.dev.

Constants

provider

The provider implementation (wire with setProvider).

const provider: UptimeProvider

DEFAULT_SERVICES_URL

Default hosted services base URL.

const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'

MONITOR_LIMITS

The schedule bounds the service enforces, mirrored locally.

const MONITOR_LIMITS: {
  readonly minIntervalSeconds: 60
  readonly maxIntervalSeconds: 86400
  readonly maxHistoryLimit: 500
}

uptimeMoleculeSecretDefinitions

Secret definitions required by the molecule.dev hosted uptime bond.

const uptimeMoleculeSecretDefinitions: SecretDefinition[]

Core Interface

Implements @molecule/api-uptime interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setProvider } from '@molecule/api-uptime'
import { provider } from '@molecule/api-uptime-molecule'

export function setupUptimeMolecule(): void {
  setProvider(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-uptime >=1.0.0
  • @molecule/api-secrets ^1.0.1

Environment Variables

  • MOLECULE_API_KEY (required) — molecule.dev project API key
    • Setup: Create one for your project with mlcl apikey create --project <id> --name <name> (keys start with mk_).
    • Get it here: https://www.molecule.dev
    • Example: mk_...

Runtime Dependencies

  • @molecule/api-uptime
  • @molecule/api-secrets