Skip to content

vizspec

Since v8.0.75

The vizspec module is the JSH API for building, validating, parsing, and converting ADVN documents. ADVN, short for Analysis Data Visualization Notation, is the renderer-neutral document format for analysis visualization.

Use ADVN when you want to keep analytical meaning separate from renderer-specific output.

ADVN And vizspec

  • ADVN is the semantic layer.
  • ADVN is the document format. It describes what the analysis result means.
  • The vizspec module is the JSH API that creates and transforms ADVN documents.
  • viz is the command-line tool that validates, previews, and exports ADVN documents.

Basic Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const vizspec = require('vizspec');

const spec = new vizspec.Builder()
    .setDomain({
        kind: 'time',
        timeformat: vizspec.Timeformat.ns,
    })
    .setXAxis({ id: 'time', type: 'time', label: 'Time' })
    .addYAxis({ id: 'value', type: 'linear', label: 'Value' })
    .addTimeBucketValueSeries({
        id: 'series-1',
        axis: 'value',
        data: [
            ['1712102400000000000', 10],
            ['1712102460000000000', 12],
        ],
    })
    .build();

Constants

The module exports the following constant groups.

  • RepresentationKind
  • AnnotationKind
  • Timeformat

Use these constants when you want explicit and typo-safe ADVN values in application code.

RepresentationKind

MemberValueDescription
RepresentationKind.rawPointraw-pointRaw point samples such as [x, y].
RepresentationKind.timeBucketValuetime-bucket-valueAggregated time bucket with a single numeric value.
RepresentationKind.timeBucketBandtime-bucket-bandAggregated time bucket with min/max/avg band values.
RepresentationKind.distributionHistogramdistribution-histogramHistogram distribution buckets.
RepresentationKind.distributionBoxplotdistribution-boxplotBoxplot distribution groups.
RepresentationKind.eventPointevent-pointInstant events at one time/value point.
RepresentationKind.eventRangeevent-rangeDuration events with from/to time range.

AnnotationKind

MemberValueDescription
AnnotationKind.pointpointA point annotation at one position.
AnnotationKind.linelineA threshold or reference line annotation.
AnnotationKind.rangerangeA highlighted range annotation.

Timeformat

MemberValueDescription
Timeformat.rfc3339rfc3339RFC3339 string time representation.
Timeformat.ssEpoch seconds.
Timeformat.msmsEpoch milliseconds.
Timeformat.ususEpoch microseconds.
Timeformat.nsnsEpoch nanoseconds.

parse()

Parses an ADVN JSON string and returns a normalized spec object.

Syntax
parse(text)
Parameters
NameTypeDescription
textstringADVN JSON text to parse.
Usage example
1
2
3
const vizspec = require('vizspec');
const spec = vizspec.parse('{"version":1,"series":[]}');
console.println(spec.version);

stringify()

Serializes a spec object into ADVN JSON text.

Syntax
stringify(spec)
Parameters
NameTypeDescription
specobjectADVN spec object to serialize.
Usage example
1
2
3
const vizspec = require('vizspec');
const text = vizspec.stringify(vizspec.createSpec({ version: 1 }));
console.println(typeof text);

validate()

Validates a spec object. Throws on invalid structure or field combinations.

Syntax
validate(spec)
Parameters
NameTypeDescription
specobjectADVN spec object to validate.
Usage example
1
2
3
const vizspec = require('vizspec');
const ok = vizspec.validate(vizspec.createSpec({ version: 1 }));
console.println(ok);

normalize()

Normalizes a partially specified spec object and fills default structural fields.

Syntax
normalize(spec)
Parameters
NameTypeDescription
specobjectPartial ADVN spec object to normalize.
Usage example
1
2
3
const vizspec = require('vizspec');
const spec = vizspec.normalize({});
console.println(spec.version);

createSpec()

Creates, normalizes, and validates a spec object from an initializer.

Syntax
createSpec(init)
Parameters
NameTypeDescription
initobjectInitial fields for the ADVN spec.
Usage example
1
2
3
4
5
6
const vizspec = require('vizspec');
const spec = vizspec.createSpec({
    domain: { kind: 'time', timeformat: vizspec.Timeformat.ns },
    series: [],
});
console.println(spec.domain.kind);

listSeries()

Returns a normalized summary list for spec.series.

Syntax
listSeries(spec)
Parameters
NameTypeDescription
specobjectADVN spec object to inspect.
Return fields
FieldTypeDescription
indexintegerZero-based series index in spec.series.
idstringSeries id.
namestringSeries name when present.
titlestringDisplay title. Uses name first, then id.
kindstringRepresentation kind.
tuiLinesCompatiblebooleanWhether toTUILines() can render the series.
Usage example
1
2
3
const listed = vizspec.listSeries(spec);
console.println(listed[0].id);
console.println(listed[0].tuiLinesCompatible);

Series Helpers

Series helper functions create series objects with the correct representation kind and default field layout.

Available helpers:

  • rawPointSeries(init)
  • timeBucketValueSeries(init)
  • timeBucketBandSeries(init)
  • distributionHistogramSeries(init)
  • distributionBoxplotSeries(init)
  • eventPointSeries(init)
  • eventRangeSeries(init)
Syntax
timeBucketValueSeries(init)
eventRangeSeries(init)
Common initializer fields
NameTypeDescription
idstringSeries identifier.
namestringDisplay name used by adapters.
axisstringY-axis id for numeric renderers.
representationobjectOptional overrides for fields or representation metadata.
dataarraySeries payload rows.
styleobjectRenderer-hint style values such as color or opacity.
qualityobjectQuality metadata such as coverage or row count.
sourceobjectProvenance metadata for the series.
extraobjectExtra representation-specific data such as boxplot outliers.
Usage example
1
2
3
4
5
6
7
const vizspec = require('vizspec');
const series = vizspec.timeBucketValueSeries({
    id: 'cpu',
    axis: 'value',
    data: [['1712102400000000000', 10]],
});
console.println(series.representation.kind);

Annotation Helpers

Annotation helper functions create top-level annotation objects with the correct annotation kind.

Available helpers:

  • pointAnnotation(init)
  • lineAnnotation(init)
  • rangeAnnotation(init)
Syntax
lineAnnotation(init)
rangeAnnotation(init)
Common initializer fields
NameTypeDescription
axisstringTarget axis id.
labelstringHuman-readable annotation label.
valueanyValue used by line or point annotations.
atanyPosition used by point annotations.
fromanyRange start value.
toanyRange end value.
styleobjectOptional renderer-hint style values.
Usage example
1
2
3
const vizspec = require('vizspec');
const annotation = vizspec.lineAnnotation({ axis: 'value', value: 80, label: 'warning' });
console.println(annotation.kind);

Builder

Use the builder when you want fluent ADVN document construction.

Syntax
new Builder([init])
Common methods
MethodDescription
setDomain(definition)Sets spec.domain.
setXAxis(definition)Sets spec.axes.x.
addYAxis(definition)Appends one y-axis definition.
addRawPointSeries(definition)Adds a raw-point series.
addTimeBucketValueSeries(definition)Adds a time-bucket-value series.
addTimeBucketBandSeries(definition)Adds a time-bucket-band series.
addDistributionHistogramSeries(definition)Adds a histogram series.
addDistributionBoxplotSeries(definition)Adds a boxplot series.
addEventPointSeries(definition)Adds an event-point series.
addEventRangeSeries(definition)Adds an event-range series.
addAnnotation(definition)Adds an annotation object.
addLineAnnotation(definition)Adds a line annotation.
addRangeAnnotation(definition)Adds a range annotation.
setView(definition)Sets spec.view.
setMeta(definition)Sets spec.meta.
build()Returns a normalized spec.
stringify()Serializes the built spec.
listSeries()Returns the normalized series summary list.
toEChartsOption(options)Builds and converts to ECharts options.
toTUILines(options)Builds and converts to terminal-ready TUI chart lines.
toTUIBlocks(options)Builds and converts to TUI blocks.
toSVG(options)Builds and converts to SVG text.
toPNG([svgOptions[, pngOptions]])Builds and converts to PNG binary data.
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const vizspec = require('vizspec');

const spec = new vizspec.Builder()
    .setDomain({ kind: 'time', timeformat: vizspec.Timeformat.ns })
    .setXAxis({ id: 'time', type: 'time', label: 'Time' })
    .addYAxis({ id: 'value', type: 'linear', label: 'Temperature' })
    .addTimeBucketBandSeries({
        id: 'sensor-1',
        axis: 'value',
        data: [
            ['1712102400000000000', 18, 24, 21],
            ['1712102460000000000', 17, 23, 20],
        ],
    })
    .build();

Output Adapters

toEChartsOption()

Converts a spec into an ECharts option object.

Syntax
toEChartsOption(spec[, options])
Parameters
NameTypeDescription
specobjectADVN spec object to render.
optionsobjectOptional output-side time settings.
Option fields
OptionTypeDefaultDescription
timeformatstringrfc3339Output time representation used when encoding time values for ECharts.
tzstringlocal timezoneOutput timezone used when rendering RFC3339 time values.
Usage example
1
2
3
4
5
const option = vizspec.toEChartsOption(spec, {
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});
console.println(JSON.stringify(option));

toTUILines()

Converts the first sparkline-compatible series into terminal-friendly sparkline lines.

Syntax
toTUILines(spec[, options])
Parameters
NameTypeDescription
specobjectADVN spec object to render.
optionsobjectOptional sparkline rendering settings.
Option fields
OptionTypeDefaultDescription
heightinteger3Chart height used for raw-point and time-bucket-value line output.
widthinteger40Width used to sample values and render the sparkline body.
seriesIdstringfirst compatible seriesSelects the series to render by series[].id.
timeformatstringrfc3339Output time format used for sparkline x-axis labels.
tzstringlocal timezoneOutput timezone used for sparkline x-axis labels.

Notes:

  • toTUILines() returns the first sparkline-compatible series when seriesId is not provided.
  • When seriesId is provided, toTUILines() renders the matching series[].id.
  • Use listSeries() when you need to discover selectable series ids ahead of time.
  • If seriesId does not exist or points to a non-sparkline series, the adapter throws an error.
  • The return value is an array of terminal-ready lines for a multi-line TUI chart.
  • Unlike toTUIBlocks(), this adapter keeps the expanded multi-line chart form with axis labels.
  • height applies to raw-point and time-bucket-value output. time-bucket-band keeps its max/avg/min line form.
  • toTUILines() currently ignores rows and compact even if they are provided.
Usage example
1
2
const lines = vizspec.toTUILines(spec, { width: 32, height: 5, seriesId: 'series-1' });
console.println(lines.join('\n'));

CLI example:

viz lines --height 5 --series series-1 sample.json
Full source code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const vizspec = require('vizspec');
const { Client } = require('machcli');

const dbConf = {
    host: '127.0.0.1', port: 5656,
    user: 'sys', password: 'manager',
};

var db, conn, rows;
var data = [];
try {
    db = new Client(dbConf);
    conn = db.connect();
    rows = conn.query(`SELECT TIME, VALUE FROM EXAMPLE
        WHERE NAME = ? AND TIME > now - 2h`, 'machbase:ps:cpu_percent');
    for (const row of rows) {
        data.push([row.TIME, row.VALUE]);
    }
} catch( e ) {
    console.println("ERROR", e.message);
} finally {
    rows && rows.close();
    conn && conn.close();
    db && db.close();
}

const spec = new vizspec.Builder()
    .setDomain({ kind: 'time', timeformat: vizspec.Timeformat.rfc3339 })
    .setXAxis({ id: 'time', type: 'time', label: 'Time' })
    .addYAxis({ id: 'value', type: 'linear', label: 'Value' })
    .addTimeBucketValueSeries({ id: 'series-1', axis: 'value', data: data })
    .build();

console.println(vizspec.toTUILines(spec, { width: 80 }).join('\n'));

Example output:

toTUIBlocks()

Converts a spec into TUI block objects for terminal inspection.

Syntax
toTUIBlocks(spec[, options])
Parameters
NameTypeDescription
specobjectADVN spec object to render.
optionsobjectOptional TUI rendering settings.
Option fields
OptionTypeDefaultDescription
widthinteger40Width used for sparkline, histogram, and timeline rendering.
rowsinteger8Maximum detail rows shown in table, histogram, and event blocks.
compactbooleanfalseHides series summary and raw data table blocks.
timeformatstringrfc3339Output time format: rfc3339, s, ms, us, ns.
tzstringlocal timezoneOutput timezone used with rendered time values.
Return value

The return value is an array of block objects. Each block may contain the following fields.

FieldTypeDescription
typestringBlock kind such as summary, series-summary, sparkline, bandline, bars, box-summary, event-list, timeline, table, annotations.
titlestringBlock title.
statsarrayArray of { label, value } objects used by summary-style blocks.
linesarrayArray of rendered text lines used by sparkline, timeline, histogram, and similar line-oriented blocks. A sparkline block currently returns one compact sparkline line.
columnsarrayColumn names used by table blocks.
rowsarrayTable row array used by table blocks. Each row is an array of values ordered by columns.
metaobjectBlock-specific metadata such as representation, axis, totalRows, or truncated.

The populated fields vary by type. For example, a sparkline block mainly uses lines, while a table block uses columns, rows, and meta.

Notes:

  • sparkline blocks in toTUIBlocks() return the original compact sparkline representation.
  • If you want the expanded sparkline with axis labels and multiple chart rows, use toTUILines() instead.
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const blocks = vizspec.toTUIBlocks(spec, {
    width: 80,
    rows: 5,
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});
console.println(blocks[0].type);           // summary
console.println(blocks[0].stats[0].label); // series
console.println(blocks[2].type);           // sparkline
console.println(blocks[2].lines[0]);       // ▁▃▅▇█▆▄▂

toSVG()

Converts a spec into an SVG string.

Syntax
toSVG(spec[, options])
Parameters
NameTypeDescription
specobjectADVN spec object to render.
optionsobjectOptional SVG rendering settings.
Option fields
OptionTypeDefaultDescription
widthinteger960SVG canvas width in pixels.
heightinteger420SVG canvas height in pixels.
paddinginteger48Outer chart padding in pixels.
backgroundstringwhiteSVG background color.
fontFamilystringsans-serifBase font family.
fontSizeinteger12Base font size in pixels.
showLegendbooleantrueControls whether legend rendering is enabled.
titlestringemptyOptional chart title.
timeformatstringrfc3339Output time format used for axis labels and rendered time values.
tzstringlocal timezoneOutput timezone used with RFC3339 time rendering.
Usage example
1
2
3
4
5
6
7
const svg = vizspec.toSVG(spec, {
    title: 'Sensor Overview',
    width: 960,
    height: 420,
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});

toPNG()

Converts a spec into PNG binary data. The return value is an ArrayBuffer, which you can read with new Uint8Array(png) when needed.

Syntax
toPNG(spec[, options])
Parameters
NameTypeDescription
specobjectADVN spec object to render.
optionsobjectOptional combined chart layout, text, output-time, and rasterization settings.
Option fields

Layout and text fields:

OptionTypeDefaultDescription
widthinteger960Output width in pixels before raster scaling.
heightinteger420Output height in pixels before raster scaling.
paddinginteger48Outer chart padding in pixels.
backgroundstringwhiteBackground color applied to both the SVG layout and PNG raster output.
fontFamilystringsans-serifBase font family.
fontSizeinteger12Base font size in pixels.
showLegendbooleantrueControls whether legend rendering is enabled.
titlestringemptyOptional chart title.
timeformatstringrfc3339Output time format used for axis labels and rendered time values.
tzstringlocal timezoneOutput timezone used with RFC3339 time rendering.

Rasterization fields:

OptionTypeDefaultDescription
scalenumber1Scales the SVG-based layout before rasterization.
dpiintegerunsetTarget DPI used when scale is not provided. Internally this is applied as dpi / 96.
themestringmrtgPNG theme name. Currently only mrtg is supported.

Notes:

  • When both scale and dpi are provided, scale takes precedence.
  • The current PNG renderer produces MRTG-style output.
  • The JavaScript API accepts a single options object and internally splits layout and raster fields.
  • The older toPNG(spec, svgOptions, pngOptions) call shape is still accepted for compatibility.
Usage example
1
2
3
4
5
6
7
8
9
const png = vizspec.toPNG(spec, {
    title: 'Sensor Overview',
    width: 640,
    height: 240,
    scale: 2,
    theme: 'mrtg'
});
const bytes = new Uint8Array(png);
console.println(bytes[0].toString(16));

Time Handling

When you use epoch timestamps in s, ms, us, or ns, the value already represents an absolute UTC-based instant, so the input data does not need an explicit timezone. Treat timezone as an output-side rendering option, not as part of the epoch value itself.

This matters especially for ns. Nanosecond epoch values can exceed JavaScript’s safe integer range, so using number may lose precision. Values such as 1712102400000000000 should be passed as strings.

For Machbase Neo timestamp data, prefer:

  • timeformat: vizspec.Timeformat.ns
  • string timestamps instead of JavaScript numbers

Example:

const spec = vizspec.createSpec({
    domain: {
        kind: 'time',
        timeformat: vizspec.Timeformat.ns,
    },
    series: [vizspec.eventRangeSeries({
        id: 'maintenance',
        data: [['1712102400000000000', '1712102460000000000', 'maintenance']],
    })],
});

Time Rendering

Source-side time encoding and output-side time representation are separate concerns.

  • domain.timeformat describes how timestamps in the ADVN document are encoded.
  • adapter timeformat and tz options describe how those timestamps should be rendered.

When adapter options are omitted, vizspec adapters default to rfc3339 and the local timezone.

Example:

const svg = vizspec.toSVG(spec, {
    title: 'CPU Usage',
    width: 960,
    height: 420,
    timeformat: vizspec.Timeformat.rfc3339,
    tz: 'Asia/Seoul',
});

The same rule applies to toTUIBlocks() and toEChartsOption().

Using viz command

Validate the generated spec:

/work > viz validate cpu-usage.json
VALID version=1 series=1 annotations=1

Preview the spec in the terminal:

/work > viz view cpu-usage.json

Export the spec to SVG:

/work > viz export --title "CPU Usage" --output cpu-usage.svg cpu-usage.json

Render terminal output with explicit output-side time settings:

/work > viz view --timeformat rfc3339 --tz Asia/Seoul cpu-usage.json
Last updated on