@zuke/prometheus
A typed client for the Prometheus HTTP API, for Zuke builds. `PrometheusTasks`
@zuke/prometheus on JSR ↗ 57 symbols
Symbols
interface PrometheusActiveTarget A target Prometheus is scraping.
| Member | Signature | Doc |
|---|---|---|
discoveredLabels | discoveredLabels: PrometheusLabels | The labels service discovery found, before relabelling. |
labels | labels: PrometheusLabels | The labels after relabelling. |
scrapePool | scrapePool: string | The scrape pool (the job) the target belongs to. |
scrapeUrl | scrapeUrl: string | The URL scraped. |
globalUrl? | globalUrl?: string | The URL as seen from outside, when the server reports it. |
lastError? | lastError?: string | The last scrape's error, "" when it succeeded. |
lastScrape? | lastScrape?: string | When the last scrape happened (RFC 3339). |
lastScrapeDuration? | lastScrapeDuration?: number | How long the last scrape took, in seconds. |
health | health: string | up, down or unknown. |
scrapeInterval? | scrapeInterval?: string | The scrape interval, such as "1m". |
scrapeTimeout? | scrapeTimeout?: string | The scrape timeout, such as "10s". |
interface PrometheusAlert An alert, active or pending, as the rules and alerts endpoints report it.
| Member | Signature | Doc |
|---|---|---|
labels | labels: PrometheusLabels | The alert's labels, alertname among them. |
annotations | annotations: PrometheusLabels | The alert's annotations. |
state | state: string | firing or pending (or inactive where a server reports it). |
activeAt? | activeAt?: string | When the alert became active (RFC 3339). |
value | value: number | The expression's value when the alert last evaluated. |
keepFiringSince? | keepFiringSince?: string | Until when it keeps firing after resolving, if keep_firing_for is set. |
interface PrometheusAlertingRule An alerting rule.
| Member | Signature | Doc |
|---|---|---|
type | type: alerting | The rule kind. |
duration | duration: number | The for duration, in seconds. |
annotations | annotations: PrometheusLabels | The rule's annotations. |
alerts? | alerts?: unknown | The rule's active alerts; absent when excludeAlerts was set (the server then sends "alerts": null, read as absent). |
state? | state?: string | The rule's state: firing, pending or inactive. |
interface PrometheusAlerts The active alerts.
| Member | Signature | Doc |
|---|---|---|
alerts | alerts: unknown | Every active alert. |
class PrometheusApiError extends Error Prometheus, or an HTTP layer in front of it, refused the call: a non-2xx status, or an envelope whose status is "error".
try {
await PrometheusTasks.query((s) => s.url(url).query("rate(x[5m]"));
} catch (error) {
if (error instanceof PrometheusApiError && error.errorType === "bad_data") {
// the expression did not parse
}
}| Member | Signature | Doc |
|---|---|---|
name | name: string | The error name. |
method | method: string | The HTTP method of the failing call. |
path | path: string | The endpoint path, such as /api/v1/query (never the base URL). |
status | status: number | The HTTP status of the answer. |
errorType | errorType: string | undefined | Prometheus's errorType (bad_data, execution, timeout, …), when sent. |
detail | detail: string | undefined | What went wrong: the envelope's error text, or — for an answer that was not a Prometheus envelope, such as a gateway's error page — the start of the body. Scrubbed of credentials and capped in length. |
interface PrometheusAwsAccessKey An explicit access key (set by PrometheusAwsSettings.accessKey).
| Member | Signature | Doc |
|---|---|---|
accessKeyId | accessKeyId: string | The access key id. |
secretAccessKey | secretAccessKey: string | The secret access key. |
sessionToken? | sessionToken?: string | The session token of temporary credentials. |
class PrometheusAwsSettings Settings for PrometheusConnectionSettings.sigv4(...).
| Member | Signature | Doc |
|---|---|---|
region | region(region: string): this | The workspace's region, such as us-east-1; defaults to AWS_REGION, then AWS_DEFAULT_REGION. |
profile | profile(name: string): this | Read static keys from this profile of the shared credentials and config files (~/.aws/credentials, ~/.aws/config) instead of searching the default chain. |
accessKey | accessKey(accessKeyId: string, secretAccessKey: string, sessionToken?: string): this | Sign with this access key instead of searching the default chain. |
region_? | region_?: string | The signing region (set by region). |
profile_? | profile_?: string | The shared-config profile (set by profile). |
accessKey_? | accessKey_?: PrometheusAwsAccessKey | An explicit access key (set by accessKey). |
type PrometheusAzureCredentialKind = default | clientSecret | workloadIdentity | managedIdentity Which credential to use: "default" picks one from the environment (see PrometheusConnectionSettings.azure); the others are explicit.
class PrometheusAzureSettings Settings for PrometheusConnectionSettings.azure(...).
| Member | Signature | Doc |
|---|---|---|
scope | scope(scope: string): this | The scope to request, replacing https://prometheus.monitor.azure.com/.default. |
tenantId | tenantId(id: string): this | The Microsoft Entra tenant (directory) id; defaults to AZURE_TENANT_ID. |
clientId | clientId(id: string): this | The application's client id — or, for a user-assigned managed identity, the identity's; defaults to AZURE_CLIENT_ID. |
authorityHost | authorityHost(url: string): this | The Microsoft Entra authority, such as https://login.microsoftonline.us for Azure Government; defaults to AZURE_AUTHORITY_HOST, then https://login.microsoftonline.com. |
clientSecret | clientSecret(secret?: string): this | Use a service principal's client secret (the client-credentials grant). The secret defaults to AZURE_CLIENT_SECRET. |
workloadIdentity | workloadIdentity(tokenFile?: string): this | Use workload identity federation: the Kubernetes service-account token in tokenFile (default AZURE_FEDERATED_TOKEN_FILE) is the client assertion, read afresh on every token request since it is rotated. |
managedIdentity | managedIdentity(clientId?: string): this | Use the managed identity of the VM, App Service or Functions app the build runs on. Pass a user-assigned identity's client id, or leave it out for clientId(...) / AZURE_CLIENT_ID, and failing those the system-assigned identity. |
credential_ | credential_: PrometheusAzureCredentialKind | The credential to use (set by the credential methods). |
scope_ | scope_: string | The scope requested (set by scope). |
tenantId_? | tenantId_?: string | The tenant (set by tenantId); else AZURE_TENANT_ID. |
clientId_? | clientId_?: string | The application or identity (set by clientId); else AZURE_CLIENT_ID. |
authorityHost_? | authorityHost_?: string | The authority (set by authorityHost); else AZURE_AUTHORITY_HOST. |
clientSecret_? | clientSecret_?: string | The client secret (set by clientSecret); else AZURE_CLIENT_SECRET. |
federatedTokenFile_? | federatedTokenFile_?: string | The federated token file (set by workloadIdentity); else AZURE_FEDERATED_TOKEN_FILE. |
interface PrometheusBuildInfo The server's build information. version is always present; the API notes the other properties may change between versions, so they are optional.
| Member | Signature | Doc |
|---|---|---|
version | version: string | The Prometheus version, such as "3.5.0". |
revision? | revision?: string | The VCS revision it was built from. |
branch? | branch?: string | The branch it was built from. |
buildUser? | buildUser?: string | Who built it. |
buildDate? | buildDate?: string | When it was built. |
goVersion? | goVersion?: string | The Go version it was built with. |
class PrometheusConnectionSettings The connection half of every Prometheus call's settings.
| Member | Signature | Doc |
|---|---|---|
url | url(url: string): this | The Prometheus base URL, such as https://prometheus.internal. A path or query string it carries — a proxy prefix, a tenant parameter — is kept, and the endpoint path is appended. Userinfo in the URL (https://user:pass@host) is taken off the URL and sent as basic auth. When the call carries any credential — a configured source, or that userinfo — the URL must be https: unless it is loopback, or ZUKE_ALLOW_INSECURE_URL is set, since a plaintext request hands the credential to anyone on the path. An unauthenticated URL may be plaintext, as an in-cluster http://prometheus.monitoring.svc:9090 usually is. |
bearerToken | bearerToken(token: string): this | Authenticate with Authorization: Bearer <token>. |
basicAuth | basicAuth(username: string, password: string): this | Authenticate with HTTP basic auth (Authorization: Basic …). |
header | header(name: string, value: string): this | Send a fixed header, such as a tenant id (X-Scope-OrgID). A plain header does not make the call credentialed, so an in-cluster http:// Mimir, Cortex or Thanos with a tenant header keeps working — except Authorization, Proxy-Authorization, Cookie, and a name core's URL redactor treats as credential-bearing (X-API-Key, X-Auth-Token: names containing key, token, secret, auth, pass and the like), which count as credentials. For an API key under any other name use secretHeader. The value is masked in errors either way (when eight or more characters long). |
secretHeader | secretHeader(name: string, value: string): this | Send a fixed header that carries a credential — an API key such as X-API-Key. Like bearerToken, it makes the call credentialed, so the URL must be https: unless it is loopback, and its value is masked in errors. |
credentials | credentials(source: PrometheusCredentials): this | Add a credential source: a function handed the outgoing request — method, full URL, headers so far, body bytes — and the connection's seams, that returns the headers to add. Sources run in the order configured, so put a request signer last. ``ts s.credentials(async (_request, { readTextFile }) => ({ authorization: Bearer ${(await readTextFile("/run/secrets/prom")).trim()}, })) `` |
google | google(configure?: Configure<PrometheusGoogleSettings>): this | Authenticate to Google Cloud Managed Service for Prometheus with an OAuth access token from Application Default Credentials — no gcloud needed. The search order is credentialsFile(...), else the file GOOGLE_APPLICATION_CREDENTIALS names; then gcloud's application_default_credentials.json; then the GCE / GKE metadata server. A file may be a service_account key, an authorized_user gcloud login, or an external_account workload identity federation configuration with a file or url subject-token source. The scope defaults to monitoring.read; the token is cached until shortly before it expires. ``ts s.url("https://monitoring.googleapis.com/v1/projects/my-project/location/global/prometheus") .google() `` |
azure | azure(configure?: Configure<PrometheusAzureSettings>): this | Authenticate to Azure Monitor managed service for Prometheus with a Microsoft Entra ID token for https://prometheus.monitor.azure.com/.default — no az needed. Unless a credential is chosen, the first the environment configures is used: client secret (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET), then workload identity (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_FEDERATED_TOKEN_FILE), then managed identity (App Service's IDENTITY_ENDPOINT, else the VM's IMDS). The token is cached until shortly before it expires. ``ts s.url("https://my-amw.eastus.prometheus.monitor.azure.com") .azure((a) => a.managedIdentity(clientId)) `` |
sigv4 | sigv4(configure?: Configure<PrometheusAwsSettings>): this | Sign every request with AWS Signature Version 4 for Amazon Managed Service for Prometheus (service aps) — no aws CLI needed. The region is region(...), else AWS_REGION / AWS_DEFAULT_REGION. Credentials come from accessKey(...) or profile(...) when set, else the chain: the AWS_ACCESS_KEY_ID environment, the shared files' profile, web identity (AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN), the ECS / EKS Pod Identity container endpoint, then EC2 IMDSv2. Configure it after any other source, so it signs the headers they add. ``ts s.url("https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-1234") .sigv4((a) => a.region("us-east-1")) `` |
requestTimeout | requestTimeout(duration: string | number): this | How long the call may take, end to end ("10s", or ms; default 30 s). Client-side: the query's own timeout parameter is separate. |
maxResponseBytes | maxResponseBytes(bytes: number): this | The largest response body to read, in bytes (default 64 MiB). A larger one fails the call rather than being buffered whole. |
signal | signal(signal: AbortSignal): this | A signal that cancels the call — a run's or a bake's own. |
fetch | fetch(fetcher: fetch): this | The fetch to use — the seam a test answers calls through. |
readEnv | readEnv(reader: unknown): this | The environment reader: consulted for ZUKE_ALLOW_INSECURE_URL and handed to credential sources. |
readTextFile | readTextFile(reader: unknown): this | The text-file reader handed to credential sources. |
now | now(clock: unknown): this | The clock handed to credential sources, in epoch milliseconds. |
url_? | url_?: string | The Prometheus base URL (set by url). |
credentials_ | credentials_: PrometheusCredentials[] | The credential sources, in the order they run (set by the auth setters). |
requestTimeout_ | requestTimeout_: number | The client-side timeout in ms (set by requestTimeout). |
maxResponseBytes_ | maxResponseBytes_: number | The response size cap in bytes (set by maxResponseBytes). |
signal_? | signal_?: AbortSignal | A caller's signal that cancels the call (set by signal). |
fetch_ | fetch_: fetch | The fetch to use (set by fetch); the global one by default. |
readEnv_ | readEnv_: unknown | The environment reader (set by readEnv). |
readTextFile_ | readTextFile_: unknown | The text-file reader credential sources use (set by readTextFile). |
now_ | now_: unknown | The clock, in epoch ms (set by now). |
type PrometheusCredentials = unknown A credential source: given the outgoing request and the context's seams, return the headers that authenticate it.
Sources run in the order they were configured, each seeing the headers the earlier ones added, and may not replace a header that is already present. Every returned value is treated as a secret and masked in errors (values shorter than eight characters excepted — see registerSecrets). A source that throws fails the call with a "./errors.ts".PrometheusRequestError whose message is scrubbed the same way. It is called once per request.
A source that caches — a token until its expiry — must keep that cache outside the settings lambda: the lambda runs on every call, so a source created inside it starts empty each time. Define the source once at module level (or key its cache in module state, as the built-in google, azure and sigv4 sources do) and pass that one function to credentials(...).
interface PrometheusCredentialsContext The seams a credential source reads the outside world through, so a source that reads an environment variable, a key file, the clock or a token endpoint is testable without any of them. Each is set on the connection settings (readEnv, readTextFile, now, fetch).
| Member | Signature | Doc |
|---|---|---|
readEnv | readEnv: unknown | Read an environment variable; undefined when unset or not permitted. |
readTextFile | readTextFile: unknown | Read a text file — a mounted token, a key, a credentials file. |
now | now: unknown | The current time in epoch milliseconds, for signing and token expiry. |
fetch | fetch: fetch | The fetch the call itself uses, for a source that exchanges tokens. |
signal | signal: AbortSignal | Aborts when the call times out or the caller's signal fires. |
interface PrometheusDroppedTarget A target relabelling dropped.
| Member | Signature | Doc |
|---|---|---|
discoveredLabels | discoveredLabels: PrometheusLabels | The labels service discovery found. |
scrapePool? | scrapePool?: string | The scrape pool, when the server reports it. |
type PrometheusDuration = string | number A duration an API parameter accepts: Prometheus duration text such as "5m", or a number of seconds (the API's float form).
class PrometheusExpressionSettings extends PrometheusConnectionSettings What an instant and a range query share: the expression and its limits.
| Member | Signature | Doc |
|---|---|---|
query | query(promql: string): this | The PromQL expression (query). |
timeout | timeout(duration: PrometheusDuration): this | The evaluation timeout (timeout), such as "30s" — capped by the server's -query.timeout. The client-side limit is requestTimeout. |
limit | limit(series: number): this | The most series to return (limit); 0 means no limit. |
lookbackDelta | lookbackDelta(duration: PrometheusDuration): this | Override the lookback period for this query (lookback_delta). |
httpMethod | httpMethod(method: PrometheusHttpMethod): this | Send the parameters as a POST form (the default) or in a GET URL. |
query_? | query_?: string | The PromQL expression (set by query). |
timeout_? | timeout_?: string | The evaluation timeout parameter (set by timeout). |
limit_? | limit_?: string | The series limit parameter (set by limit). |
lookbackDelta_? | lookbackDelta_?: string | The lookback-delta parameter (set by lookbackDelta). |
httpMethod_ | httpMethod_: PrometheusHttpMethod | The HTTP method (set by httpMethod); POST by default. |
interface PrometheusFloatSample An instant-vector element whose sample is a float (the API's value key).
| Member | Signature | Doc |
|---|---|---|
metric | metric: PrometheusLabels | The series' labels. |
timestamp | timestamp: number | The sample's time, in Unix seconds (fractional). |
value | value: number | The sample value; NaN, Infinity and -Infinity are kept as such. |
class PrometheusGoogleSettings Settings for PrometheusConnectionSettings.google(...).
| Member | Signature | Doc |
|---|---|---|
scopes | scopes(...scopes: string[]): this | The OAuth scopes to request, replacing the default https://www.googleapis.com/auth/monitoring.read. A gcloud user credential (authorized_user) carries the scopes it was granted at gcloud auth application-default login and ignores these. |
credentialsFile | credentialsFile(path: string): this | Read this credentials file — a service-account key, a gcloud user credential, or a workload identity federation configuration — instead of searching Application Default Credentials. |
quotaProject | quotaProject(project: string): this | The project charged for the request's quota, sent as x-goog-user-project. Defaults to the credentials file's quota_project_id, which gcloud auth application-default set-quota-project writes. |
scopes_ | scopes_: unknown | The OAuth scopes requested (set by scopes). |
credentialsFile_? | credentialsFile_?: string | An explicit credentials file (set by credentialsFile). |
quotaProject_? | quotaProject_?: string | The project billed for quota (set by quotaProject). |
type PrometheusHeaders = Readonly<Record<string, string>> Header names to values, as a credential source returns them.
interface PrometheusHistogram A native histogram value, the API's <histogram> placeholder.
| Member | Signature | Doc |
|---|---|---|
count | count: number | The count of observations. |
sum | sum: number | The sum of observations. |
buckets | buckets: unknown | The populated buckets; empty when the server sent none. |
interface PrometheusHistogramBucket One bucket of a native histogram: [<boundary_rule>, "<left>", "<right>", "<count>"].
| Member | Signature | Doc |
|---|---|---|
boundaryRule | boundaryRule: 0 | 1 | 2 | 3 | Which boundaries are inclusive: 0 open left, 1 open right, 2 open both, 3 closed both — the API's <boundary_rule>. |
lower | lower: number | The bucket's left boundary. |
upper | upper: number | The bucket's right boundary. |
count | count: number | The number of observations in the bucket. |
interface PrometheusHistogramPoint One native-histogram sample at a point in time: [<unix_time>, <histogram>].
| Member | Signature | Doc |
|---|---|---|
timestamp | timestamp: number | The sample's time, in Unix seconds (fractional). |
histogram | histogram: PrometheusHistogram | The histogram. |
interface PrometheusHistogramSample An instant-vector element whose sample is a native histogram (histogram).
| Member | Signature | Doc |
|---|---|---|
metric | metric: PrometheusLabels | The series' labels. |
timestamp | timestamp: number | The sample's time, in Unix seconds (fractional). |
histogram | histogram: PrometheusHistogram | The histogram. |
type PrometheusHttpMethod = GET | POST The HTTP method for an endpoint the API serves on both GET and POST.
type PrometheusLabels = Readonly<Record<string, string>> A label set: label name to label value, as the API's metric object.
class PrometheusLabelsSettings extends PrometheusSelectionSettings Settings for listing label names (/api/v1/labels).
| Member | Signature | Doc |
|---|---|---|
httpMethod | httpMethod(method: PrometheusHttpMethod): this | Send the parameters as a POST form (the default) or in a GET URL. |
httpMethod_ | httpMethod_: PrometheusHttpMethod | The HTTP method (set by httpMethod); POST by default. |
class PrometheusLabelValuesSettings extends PrometheusSelectionSettings Settings for one label's values (/api/v1/label/<label_name>/values).
| Member | Signature | Doc |
|---|---|---|
labelName | labelName(name: string): this | The label whose values to list. Any name is accepted: one outside the classic [a-zA-Z_:][a-zA-Z0-9_:]* form (a UTF-8 name such as http.status_code) is sent in the API's U__ value-encoding escape, so nothing in the name can reach the URL path as a separator. |
labelName_? | labelName_?: string | The label whose values to list (set by labelName). |
interface PrometheusMatrix A range vector: resultType: "matrix".
| Member | Signature | Doc |
|---|---|---|
resultType | resultType: matrix | The result type. |
result | result: unknown | One entry per series. |
class PrometheusMetadataSettings extends PrometheusConnectionSettings Settings for metric metadata (/api/v1/metadata).
| Member | Signature | Doc |
|---|---|---|
limit | limit(metrics: number): this | The most metrics to return (limit). |
limitPerMetric | limitPerMetric(entries: number): this | The most metadata entries per metric (limit_per_metric). |
metric | metric(name: string): this | Only this metric's metadata (metric). |
limit_? | limit_?: string | The metric limit (set by limit). |
limitPerMetric_? | limitPerMetric_?: string | The per-metric limit (set by limitPerMetric). |
metric_? | metric_?: string | The metric to filter for (set by metric). |
interface PrometheusMetricMetadata One metadata entry for a metric, as scraped from a target.
| Member | Signature | Doc |
|---|---|---|
type | type: string | The metric type: counter, gauge, histogram, summary, unknown, … |
help | help: string | The # HELP text. |
unit | unit: string | The unit, or "". |
interface PrometheusOutgoingRequest The outgoing request a PrometheusCredentials source authenticates — exactly what will be sent, so a signature computed over it verifies.
| Member | Signature | Doc |
|---|---|---|
method | method: PrometheusHttpMethod | The HTTP method: GET, or POST for a form-encoded call. |
url | url: string | The absolute URL, including the query string: the base URL's own path and parameters, the endpoint path, and — on a GET — the call's parameters, percent-encoded as sent. |
headers | headers: PrometheusHeaders | The headers set so far, with lower-case names: the transport's own (accept, and content-type on a POST) plus whatever the sources configured before this one added. A source may only add headers — naming one already present fails the call — so a signer configured last signs every header that is sent. |
body | body: Uint8Array | The exact body bytes — the application/x-www-form-urlencoded form on a POST, empty on a GET. A copy: changing it changes nothing that is sent. |
interface PrometheusPoint One float sample at a point in time: a [<unix_time>, "<value>"] pair.
| Member | Signature | Doc |
|---|---|---|
timestamp | timestamp: number | The sample's time, in Unix seconds (fractional). |
value | value: number | The sample value; NaN, Infinity and -Infinity are kept as such. |
type PrometheusQueryData = PrometheusVector | PrometheusMatrix | PrometheusScalar | PrometheusStringResult The data of an expression query, discriminated on resultType exactly as the API sends it.
class PrometheusQueryRangeSettings extends PrometheusExpressionSettings Settings for a range query (/api/v1/query_range).
| Member | Signature | Doc |
|---|---|---|
start | start(time: PrometheusTime): this | The inclusive start (start): a Date, Unix seconds, or RFC 3339 text. |
end | end(time: PrometheusTime): this | The inclusive end (end): a Date, Unix seconds, or RFC 3339 text. |
step | step(duration: PrometheusDuration): this | The resolution step (step): "15s", or a number of seconds. |
start_? | start_?: string | The range's start (set by start). |
end_? | end_?: string | The range's end (set by end). |
step_? | step_?: string | The resolution step (set by step). |
class PrometheusQuerySettings extends PrometheusExpressionSettings Settings for an instant query (/api/v1/query).
| Member | Signature | Doc |
|---|---|---|
time | time(time: PrometheusTime): this | The evaluation time (time): a Date, Unix seconds, or RFC 3339 text. |
time_? | time_?: string | The evaluation time (set by time); the server's now when unset. |
interface PrometheusRecordingRule A recording rule.
| Member | Signature | Doc |
|---|---|---|
type | type: recording | The rule kind. |
class PrometheusRequestError extends Error A Prometheus call produced no usable answer: the request could not be sent or timed out, a credential source failed, or the answer was too large, not JSON, or not shaped as the API reference describes.
| Member | Signature | Doc |
|---|---|---|
name | name: string | The error name. |
method | method: string | The HTTP method of the failing call. |
path | path: string | The endpoint path, such as /api/v1/query (never the base URL). |
status | status: number | undefined | The HTTP status, when an answer arrived; undefined when none did. |
interface PrometheusResponse A successful API answer: the endpoint's typed data, plus the warnings and infos annotations Prometheus attaches to a result it still returned.
Both arrays are always present — empty when the server sent none — so a gate can fail on warnings.length > 0 without first checking for the key.
| Member | Signature | Doc |
|---|---|---|
data | data: T | The endpoint's data, parsed into its typed shape. |
warnings | warnings: unknown | Problems that did not stop the request (warnings in the envelope). |
infos | infos: unknown | Info-level annotations about possible query issues (infos). |
type PrometheusRule = PrometheusAlertingRule | PrometheusRecordingRule A rule, discriminated on type.
interface PrometheusRuleFields Fields every rule carries.
| Member | Signature | Doc |
|---|---|---|
name | name: string | The rule's name: the alert name or the recorded series. |
query | query: string | The PromQL expression. |
labels | labels: PrometheusLabels | The rule's configured labels. |
health | health: string | ok, err or unknown. |
lastError? | lastError?: string | The last evaluation's error, when it failed. |
evaluationTime? | evaluationTime?: number | How long the last evaluation took, in seconds. |
lastEvaluation? | lastEvaluation?: string | When the rule last evaluated (RFC 3339). |
interface PrometheusRuleGroup A rule group.
| Member | Signature | Doc |
|---|---|---|
name | name: string | The group's name. |
file | file: string | The file it was loaded from. |
interval | interval: number | The evaluation interval, in seconds. |
rules | rules: unknown | The group's rules. |
limit? | limit?: number | The group's alert/series limit, when the server reports it. |
evaluationTime? | evaluationTime?: number | How long the group's last evaluation took, in seconds. |
lastEvaluation? | lastEvaluation?: string | When the group last evaluated (RFC 3339). |
interface PrometheusRules The loaded rules.
| Member | Signature | Doc |
|---|---|---|
groups | groups: unknown | The rule groups. |
groupNextToken? | groupNextToken?: string | The token for the next page, when groupLimit cut the list short. |
class PrometheusRulesSettings extends PrometheusConnectionSettings Settings for the loaded rules (/api/v1/rules).
| Member | Signature | Doc |
|---|---|---|
type | type(type: PrometheusRuleType): this | Only alerting ("alert") or only recording ("record") rules (type). |
ruleName | ruleName(...names: string[]): this | Only rules with these names (rule_name[]). |
ruleGroup | ruleGroup(...groups: string[]): this | Only rules in these groups (rule_group[]). |
file | file(...paths: string[]): this | Only rules from these files (file[]). |
match | match(...selectors: string[]): this | Only rules whose configured labels match these selectors (match[]). |
excludeAlerts | excludeAlerts(on?: boolean): this | Leave out each rule's active alerts (exclude_alerts=true). |
groupLimit | groupLimit(groups: number): this | At most this many rule groups per page (group_limit). |
groupNextToken | groupNextToken(token: string): this | Continue from a previous page's groupNextToken (group_next_token). |
type_? | type_?: PrometheusRuleType | The type filter (set by type). |
ruleName_ | ruleName_: string[] | Rule names to keep (set by ruleName), as rule_name[]. |
ruleGroup_ | ruleGroup_: string[] | Rule groups to keep (set by ruleGroup), as rule_group[]. |
file_ | file_: string[] | Rule files to keep (set by file), as file[]. |
match_ | match_: string[] | Label selectors rules must match (set by match), as match[]. |
excludeAlerts_ | excludeAlerts_: boolean | Whether to leave out active alerts (set by excludeAlerts). |
groupLimit_? | groupLimit_?: string | The group page size (set by groupLimit). |
groupNextToken_? | groupNextToken_?: string | The pagination token (set by groupNextToken). |
type PrometheusRuleType = alert | record The rule kinds /api/v1/rules filters on: the API's type parameter.
interface PrometheusScalar A scalar: resultType: "scalar".
| Member | Signature | Doc |
|---|---|---|
resultType | resultType: scalar | The result type. |
result | result: PrometheusPoint | The scalar and the time it was evaluated at. |
class PrometheusSelectionSettings extends PrometheusConnectionSettings What the series, label-name and label-value endpoints share.
| Member | Signature | Doc |
|---|---|---|
match | match(...selectors: string[]): this | Add series selectors (match[]), such as up or {job="api"}. |
start | start(time: PrometheusTime): this | The start time (start): a Date, Unix seconds, or RFC 3339 text. |
end | end(time: PrometheusTime): this | The end time (end): a Date, Unix seconds, or RFC 3339 text. |
limit | limit(count: number): this | The most results to return (limit); 0 means no limit. |
match_ | match_: string[] | The series selectors (set by match), sent as repeated match[]. |
start_? | start_?: string | The start time (set by start). |
end_? | end_?: string | The end time (set by end). |
limit_? | limit_?: string | The result limit (set by limit). |
interface PrometheusSeries One series of a range vector. The API gives a series values, histograms, or both; whichever is absent is an empty array here.
| Member | Signature | Doc |
|---|---|---|
metric | metric: PrometheusLabels | The series' labels. |
values | values: unknown | The float samples, in time order. |
histograms | histograms: unknown | The native-histogram samples, in time order. |
class PrometheusSeriesSettings extends PrometheusSelectionSettings Settings for finding series by matchers (/api/v1/series).
| Member | Signature | Doc |
|---|---|---|
httpMethod | httpMethod(method: PrometheusHttpMethod): this | Send the parameters as a POST form (the default) or in a GET URL. |
httpMethod_ | httpMethod_: PrometheusHttpMethod | The HTTP method (set by httpMethod); POST by default. |
interface PrometheusStringResult A string: resultType: "string".
| Member | Signature | Doc |
|---|---|---|
resultType | resultType: string | The result type. |
result | result: unknown | The string and the time it was evaluated at. |
interface PrometheusTargets The target overview: active and dropped targets.
| Member | Signature | Doc |
|---|---|---|
activeTargets | activeTargets: unknown | The targets being scraped. |
droppedTargets | droppedTargets: unknown | The targets relabelling dropped (subject to keep_dropped_targets). |
class PrometheusTargetsSettings extends PrometheusConnectionSettings Settings for the target overview (/api/v1/targets).
| Member | Signature | Doc |
|---|---|---|
state | state(state: PrometheusTargetState): this | Only active or only dropped targets (state); both by default. |
state_? | state_?: PrometheusTargetState | The state filter (set by state). |
type PrometheusTargetState = active | dropped | any Which targets /api/v1/targets returns: the API's state parameter.
const PrometheusTasks: PrometheusTasksApi The Prometheus HTTP API as tasks (<https://prometheus.io/docs/prometheus/latest/querying/api/>).
interface PrometheusTasksApi The operations PrometheusTasks exposes.
| Member | Signature | Doc |
|---|---|---|
query | query(configure: Configure<PrometheusQuerySettings>): Promise<PrometheusResponse<PrometheusQueryData>> | Evaluate an instant query (/api/v1/query). ``ts const result = await PrometheusTasks.query((s) => s.url("https://prometheus.internal").bearerToken(token) .query('sum(rate(http_requests_total{code=~"5.."}[5m]))') ); `` |
queryRange | queryRange(configure: Configure<PrometheusQueryRangeSettings>): Promise<PrometheusResponse<PrometheusMatrix>> | Evaluate a range query (/api/v1/query_range); the answer is a matrix. |
series | series(configure: Configure<PrometheusSeriesSettings>): Promise<PrometheusResponse<PrometheusLabels[]>> | Find the series matching selectors (/api/v1/series). |
labels | labels(configure: Configure<PrometheusLabelsSettings>): Promise<PrometheusResponse<string[]>> | List label names (/api/v1/labels). |
labelValues | labelValues(configure: Configure<PrometheusLabelValuesSettings>): Promise<PrometheusResponse<string[]>> | List one label's values (/api/v1/label/<label_name>/values). |
metadata | metadata(configure: Configure<PrometheusMetadataSettings>): Promise<PrometheusResponse<Readonly<Record<string, unknown>>>> | Read metric metadata (/api/v1/metadata), keyed by metric name. |
targets | targets(configure: Configure<PrometheusTargetsSettings>): Promise<PrometheusResponse<PrometheusTargets>> | Read target discovery state (/api/v1/targets). |
rules | rules(configure: Configure<PrometheusRulesSettings>): Promise<PrometheusResponse<PrometheusRules>> | Read the loaded alerting and recording rules (/api/v1/rules). |
alerts | alerts(configure: Configure<PrometheusConnectionSettings>): Promise<PrometheusResponse<PrometheusAlerts>> | Read the active alerts (/api/v1/alerts). |
buildInfo | buildInfo(configure: Configure<PrometheusConnectionSettings>): Promise<PrometheusResponse<PrometheusBuildInfo>> | Read the server's build information (/api/v1/status/buildinfo). |
healthy | healthy(configure: Configure<PrometheusConnectionSettings>): Promise<boolean> | Probe /-/healthy: true on 2xx, false on 503, and a PrometheusApiError on any other status — a 401 is a credential problem, not an unhealthy server. |
ready | ready(configure: Configure<PrometheusConnectionSettings>): Promise<boolean> | Probe /-/ready: true once the server serves queries, false while it answers 503, and a PrometheusApiError on any other status. |
value | value(response: PrometheusResponse<PrometheusQueryData>): number | The single number an instant query returned — a scalar, or a vector of exactly one float sample — failing clearly on an empty or multi-sample vector, a matrix, a string or a native histogram. NaN is returned as NaN, which compares false both ways — gate with !(v <= max). ``ts const ratio = PrometheusTasks.value(await PrometheusTasks.query((s) => …)); `` |
samples | samples(response: PrometheusResponse<PrometheusQueryData>): PrometheusFloatSample[] | Every float sample of an instant query, with its labels: a vector's elements, or a scalar as one unlabelled sample. An empty vector is an empty list; a matrix, string or native histogram fails. |
type PrometheusTime = Date | number | string A time an API parameter accepts: a Date, Unix seconds, or RFC 3339 text.
interface PrometheusVector An instant vector: resultType: "vector".
| Member | Signature | Doc |
|---|---|---|
resultType | resultType: vector | The result type. |
result | result: unknown | One element per series. |
type PrometheusVectorSample = PrometheusFloatSample | PrometheusHistogramSample One element of an instant vector. The API gives each element a value or a histogram, never both — narrow with "value" in sample.