Toolkit
LabBuild

Aggregation-grain data contract

A runnable contract for exact, censored, and lower-bound values across detailed and coarse grains.

node:test · data contract · aggregation
Use this

Read and copy the source

Read it before copying. Replace example paths, workflow names, product dimensions, and authority boundaries with those in your own system.

Aggregation-grain contractdashboard-data-contract.mjs · javascript
export function parsePublishedCount(raw) {
  const token = String(raw ?? '').trim()

  if (/^<\d+$/.test(token)) {
    const upperExclusive = Number(token.slice(1))
    return {
      kind: 'censored',
      exact: null,
      lower: 0,
      upper: upperExclusive - 1,
      source: token,
    }
  }

  const exact = Number(token.replaceAll(',', ''))
  if (!Number.isSafeInteger(exact) || exact < 0) {
    throw new Error(`Invalid published count: ${JSON.stringify(token)}`)
  }

  return { kind: 'exact', exact, lower: exact, upper: exact, source: token }
}

export function assertCoarseTotalCoversDetail(coarse, detailedFloor) {
  if (coarse.kind === 'exact' && coarse.exact < detailedFloor) {
    throw new Error(
      `Coarse exact total ${coarse.exact} is below detailed exact-only floor ${detailedFloor}`
    )
  }
}

export function displayCount(count) {
  return count.kind === 'exact' ? count.exact.toLocaleString('en-AU') : count.source
}
Contract testsdashboard-data-contract.test.mjs · javascript
import assert from 'node:assert/strict'
import test from 'node:test'

import {
  assertCoarseTotalCoversDetail,
  displayCount,
  parsePublishedCount,
} from './dashboard-data-contract.mjs'

test('keeps a censored value as an interval', () => {
  assert.deepEqual(parsePublishedCount('<20'), {
    kind: 'censored',
    exact: null,
    lower: 0,
    upper: 19,
    source: '<20',
  })
})

test('rejects a coarse total below the detailed floor', () => {
  assert.throws(
    () => assertCoarseTotalCoversDetail(parsePublishedCount('99'), 100),
    /below detailed exact-only floor/
  )
})

test('renders the published semantics', () => {
  assert.equal(displayCount(parsePublishedCount('1,095')), '1,095')
  assert.equal(displayCount(parsePublishedCount('<20')), '<20')
})