UNPKG

@stordata/grammars

Version:

A collection of ANTLR grammars used at Stordata. This project exists so that we can package the grammars (and various utilities) as a CommonJS module. The `antlr4` Javascript runtime is only available as an ES module at the time of writing.

70 lines (53 loc) 1.31 kB
import PrometheusMetricsVisitor from '../../generated/src/grammars/PrometheusMetricsVisitor.js'; export default class PrometheusMetricsParserVisitor extends PrometheusMetricsVisitor { visitLine(ctx) { const metric = ctx.metric(); return new Metric(metric.name, ctx.value, ctx.timestamp, metric.label()); } } class Metric { name = ''; labels = {}; value = null; timestamp = null; constructor(name, value, timestamp, labels) { this.name = getText(name); this.value = parseNumber(getText(value)); this.timestamp = parseNumber(getText(timestamp)); this.labels = labels.reduce(toKeyedLabelsReducer, {}); } } function getText(ctx) { const text = ctx?.text; if (!text) { return null; } if (!text.startsWith('"')) { return text; } return text .slice(1, text.length - 1) .replaceAll('\\\\', '\\') .replaceAll('\\"', '"') .replaceAll('\\r', '\r') .replaceAll('\\n', '\n'); } function parseNumber(text) { if (!text) { return null; } switch (text) { case 'NaN': return NaN; case '+Inf': return Infinity; case '-Inf': return -Infinity; default: return parseFloat(text); } } function toKeyedLabelsReducer(acc, ctx) { acc[getText(ctx.name)] = getText(ctx.value); return acc; }