/* The merge rule is the whole point of vitals.js: an automation that runs every five minutes must not turn a day of steps into three days of steps. These tests are all about that, plus the shapes HAE actually sends (day-grouped totals, raw samples, Min/Avg/Max heart rate, aggregated and segmented sleep, blood pressure, a metric that is selected but empty). Every merge is given an explicit `now`, because the dedupe ledger is pruned against the wall clock: a test that let the real clock in would delete its own fixtures the moment they were a few days old, and start passing for the wrong reason. */ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { parsePayload, mergeVitals, vitalsSeries, emptyVitals, parseHaeDate, normalizeDoc, RETENTION_DAYS, LEDGER_MS } from '../vitals.js'; const NOW = Date.parse('2026-05-01T23:30:00Z'); const merge = (doc, payload, now = NOW) => mergeVitals(doc, payload, now); const at = (day, time = '00:00:00', off = '+0000') => `${day} ${time} ${off}`; /** One metric, one payload. */ const metric = (name, units, data) => ({ data: { metrics: [{ name, units, data }] } }); /* ---------- parsing ---------- */ test('parses both HAE date spellings, including the 12-hour one with a narrow no-break space', () => { const a = parseHaeDate('2026-05-01 13:04:05 +0200'); assert.equal(a.day, '2026-05-01'); assert.equal(a.time, '13:04:05'); assert.equal(a.ms, Date.parse('2026-05-01T13:04:05+02:00')); // U+202F between the time and the meridiem — what HAE writes on a 12-hour phone. const b = parseHaeDate('2026-05-01 1:04:05\u202fPM -0700'); assert.equal(b.time, '13:04:05'); assert.equal(b.ms, Date.parse('2026-05-01T13:04:05-07:00')); // The two hours a naive modulo gets wrong. assert.equal(parseHaeDate('2026-05-01 12:00:00\u202fAM +0000').time, '00:00:00'); assert.equal(parseHaeDate('2026-05-01 12:30:00\u202fPM +0000').time, '12:30:00'); // No offset at all means UTC, not "whatever the server is". assert.equal(parseHaeDate('2026-05-01 08:00:00').ms, Date.parse('2026-05-01T08:00:00Z')); assert.equal(parseHaeDate('not a date'), null); assert.equal(parseHaeDate('2026-13-45 08:00:00 +0000'), null); assert.equal(parseHaeDate(undefined), null); }); test('parsePayload accepts v2 (wrapped in data), the older flat shape, and drops empty metrics', () => { const v2 = parsePayload({ data: { metrics: [ { name: 'step_count', units: 'count', data: [{ qty: 100, date: at('2026-05-01', '09:00:00') }] }, { name: 'basal_body_temperature', units: 'degC', data: null } ], workouts: [] } }); assert.equal(v2.metrics.length, 2); assert.equal(v2.metrics[1].points.length, 0, 'a selected-but-empty metric parses to no points'); const flat = parsePayload({ metrics: [{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80, date: at('2026-05-01', '07:00:00') }] }] }); assert.equal(flat.metrics[0].points[0].fields.qty, 80); assert.throws(() => parsePayload({ hello: 'world' }), e => e.code === 'shape'); assert.throws(() => parsePayload(null), e => e.code === 'shape'); assert.throws(() => parsePayload({ data: { metrics: [], workouts: [] } }), e => e.code === 'empty'); // A datapoint with no readable date, or with no numbers at all, is not a datapoint. const junk = parsePayload(metric('foo', 'x', [{ qty: 1, date: 'nonsense' }, { date: at('2026-05-01') }])); assert.equal(junk.metrics[0].points.length, 0); }); /* ---------- the merge rule ---------- */ test('raw samples: disjoint windows accumulate, overlapping ones do not double count', () => { const p = (t, qty) => ({ qty, date: at('2026-05-01', t) }); // "Since Last Sync": each run carries only what happened since the last one. let doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [p('09:00:00', 300), p('09:05:00', 700)]))).doc; assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000); const inc = merge(doc, parsePayload(metric('step_count', 'count', [p('09:10:00', 200), p('09:15:00', 800)]))); doc = inc.doc; assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 2000, 'new samples add on'); assert.equal(inc.stats.points, 2); // "Today": every run re-sends the whole day, with the two samples since the last run added. const today = metric('step_count', 'count', [ p('09:00:00', 300), p('09:05:00', 700), p('09:10:00', 200), p('09:15:00', 800), p('09:20:00', 1000), p('09:25:00', 500) ]); const first = merge(doc, parsePayload(today)); assert.equal(first.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 'only the two new samples count'); assert.equal(first.stats.points, 2); assert.equal(first.stats.duplicates, 4); const again = merge(first.doc, parsePayload(today)); assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 're-sending changes nothing'); assert.equal(again.stats.points, 0); assert.equal(again.stats.duplicates, 6); }); test('day-grouped payloads replace the day: a growing total never adds up', () => { const grouped = sum => metric('step_count', 'count', [{ qty: sum, date: at('2026-05-01') }]); let doc = merge(emptyVitals(), parsePayload(grouped(1200))).doc; assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1200); // Ten more syncs through the day, each carrying the day's total so far — "Time Grouping: Days". for (const total of [1400, 2600, 4100, 9800]) doc = merge(doc, parsePayload(grouped(total))).doc; assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800, 'replaced, not accumulated'); const same = merge(doc, parsePayload(grouped(9800))); assert.equal(same.stats.duplicates, 1); assert.equal(same.stats.points, 0, 'the same total again is a no-op'); assert.equal(same.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800); // A day-grouped payload covering several days corrects each of them independently. const multi = merge(same.doc, parsePayload(metric('step_count', 'count', [ { qty: 9800, date: at('2026-05-01') }, { qty: 3000, date: at('2026-04-30') } ]))); assert.equal(multi.doc.metrics.step_count.days['2026-04-30'].f.qty.sum, 3000); assert.equal(multi.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800); }); test('a day total and raw samples for the same day are kept apart by their own payload shape', () => { // Two metrics in one payload, one grouped by day and one raw: each takes its own branch. const body = { data: { metrics: [ { name: 'step_count', units: 'count', data: [{ qty: 5000, date: at('2026-05-01') }] }, { name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 52, date: at('2026-05-01', '06:30:00') }] } ] } }; const { doc } = merge(emptyVitals(), parsePayload(body)); assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 5000); assert.equal(doc.metrics.resting_heart_rate.days['2026-05-01'].f.qty.sum, 52); }); test('the day key is the phone\'s own date, not the server\'s', () => { // 23:30 in Manila is the previous day in UTC. The sample belongs to the phone's day. const { doc } = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [ { qty: 500, date: at('2026-05-01', '23:30:00', '+0800') } ]))); assert.deepEqual(Object.keys(doc.metrics.step_count.days), ['2026-05-01']); }); /* ---------- the shapes HAE actually sends ---------- */ test('heart rate keeps Min/Avg/Max per day instead of pretending they are one number', () => { const body = metric('heart_rate', 'bpm', [ { date: at('2026-05-01', '09:00:00'), Min: 58, Avg: 72, Max: 96, source: 'Apple Watch' }, { date: at('2026-05-01', '10:00:00'), Min: 55, Avg: 68, Max: 88, source: 'Apple Watch' } ]); const { doc } = merge(emptyVitals(), parsePayload(body)); const day = doc.metrics.heart_rate.days['2026-05-01']; assert.equal(day.f.Avg.n, 2); assert.equal(Math.round(day.f.Avg.sum), 140); assert.equal(day.f.Min.min, 55); assert.equal(day.f.Max.max, 96); assert.deepEqual(doc.metrics.heart_rate.sources, ['Apple Watch']); }); test('sleep: both the aggregated night and the segmented one land as hours per day', () => { const aggregated = metric('sleep_analysis', 'hr', [{ date: at('2026-05-01', '07:00:00'), sleepStart: at('2026-04-30', '23:10:00'), sleepEnd: at('2026-05-01', '06:55:00'), inBed: 8.2, asleep: 7.4, core: 4.1, deep: 1.2, rem: 2.1, awake: 0.8, source: 'Apple Watch' }]); const { doc } = merge(emptyVitals(), parsePayload(aggregated)); // Keyed by the day the metric's own `date` names — the morning you woke up. assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.asleep.last, 7.4); assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.deep.last, 1.2); const segments = [ { startDate: at('2026-05-01', '22:10:00'), endDate: at('2026-05-01', '22:50:00'), qty: 0.67, value: 'asleepCore' }, { startDate: at('2026-05-01', '23:10:00'), endDate: at('2026-05-01', '23:25:00'), qty: 1.33, value: 'asleepDeep' } ]; const seg = merge(emptyVitals(), parsePayload(metric('sleep_analysis', 'hr', segments))).doc; // Segments carry no `date`, only startDate/endDate, so the day comes from the segment start. assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2); assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.n, 2); const repeat = merge(seg, parsePayload(metric('sleep_analysis', 'hr', segments))); assert.equal(repeat.stats.duplicates, 2, 'the same segments again are the same segments'); assert.equal(repeat.doc.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2, 'and do not add up twice'); }); test('blood pressure keeps both numbers, and an unknown metric is stored rather than dropped', () => { const body = { data: { metrics: [ { name: 'blood_pressure_systolic', units: 'mmHg', data: [{ date: at('2026-05-01', '08:00:00'), systolic: 128, diastolic: 82 }] }, { name: 'walking_steadiness', units: '%', data: [{ date: at('2026-05-01', '08:00:00'), qty: 91 }] } ] } }; const { doc } = merge(emptyVitals(), parsePayload(body)); assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.systolic.last, 128); assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.diastolic.last, 82); assert.equal(doc.metrics.walking_steadiness.days['2026-05-01'].f.qty.last, 91); }); /* ---------- workouts ---------- */ test('workouts dedupe on name+start+end, newest first, and a re-send adds nothing', () => { const w = (name, start, end, energy) => ({ name, start, end, activeEnergy: { qty: energy, units: 'kcal' }, distance: { qty: 3.2, units: 'km' }, heartRateData: [{ date: at('2026-05-01', '18:00:00'), Avg: 128 }, { date: at('2026-05-01', '18:05:00'), Avg: 136, Max: 172 }] }); const body = { data: { workouts: [ w('Walking', at('2026-05-01', '17:00:00'), at('2026-05-01', '18:00:00'), 210), w('Functional Strength Training', at('2026-05-01', '07:00:00'), at('2026-05-01', '07:45:00'), 320) ] } }; const first = merge(emptyVitals(), parsePayload(body)); assert.equal(first.stats.workouts, 2); assert.equal(first.doc.workouts[0].name, 'Walking', 'newest first (17:00 after 07:00)'); assert.equal(first.doc.workouts[0].durMin, 60); assert.equal(first.doc.workouts[0].fields.activeEnergy.qty, 210); assert.equal(first.doc.workouts[0].avgHr, 132, 'average of the heart-rate samples'); assert.equal(first.doc.workouts[0].maxHr, 172); assert.equal(first.doc.workouts[1].name, 'Functional Strength Training'); assert.equal(first.doc.workouts[1].fields.activeEnergy.qty, 320); const again = merge(first.doc, parsePayload(body)); assert.equal(again.stats.workouts, 0); assert.equal(again.stats.duplicates, 2); assert.equal(again.doc.workouts.length, 2); }); /* ---------- housekeeping ---------- */ test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => { const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }])), NOW); const seen = first.doc.metrics.step_count.seen; assert.equal(Object.keys(seen).length, 1); assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:00:00Z')); // A sync a week later: last week's sample can no longer be a repeat, so its ledger row goes // while the day it belongs to stays. const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:00:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc; assert.equal(Object.keys(later.metrics.step_count.seen).length, 1, 'the stale ledger row is gone'); assert.deepEqual(Object.keys(later.metrics.step_count.days), ['2026-05-01', '2026-05-08']); // Days past retention are dropped. const old = new Date(NOW - (RETENTION_DAYS + 30) * 86400000).toISOString().slice(0, 10); const withOld = normalizeDoc({ metrics: { step_count: { days: { [old]: { n: 1, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } } } }); const pruned = merge(withOld, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }]))).doc; assert.equal(pruned.metrics.step_count.days[old], undefined); assert.ok(LEDGER_MS === 72 * 3600 * 1000 && RETENTION_DAYS > 365); }); test('normalizeDoc survives a hand-edited or half-written file', () => { const d = normalizeDoc({ metrics: { step_count: null, heart_rate: { days: 'nope', units: 7, sources: 'x' } }, workouts: 'nope' }); assert.deepEqual(d.workouts, []); assert.deepEqual(Object.keys(d.metrics), ['heart_rate']); assert.deepEqual(d.metrics.heart_rate.days, {}); assert.deepEqual(d.metrics.heart_rate.sources, []); assert.equal(d.metrics.heart_rate.units, ''); assert.deepEqual(normalizeDoc(null).metrics, {}); }); /* ---------- reading it back ---------- */ test('vitalsSeries gives per-field totals, averages and a window, oldest day first', () => { const body = { data: { metrics: [ { name: 'step_count', units: 'count', data: [{ qty: 4000, date: at('2026-04-30') }, { qty: 6000, date: at('2026-05-01') }] }, { name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Min: 55, Avg: 70, Max: 90 }] } ], workouts: [{ name: 'Walking', start: at('2026-05-01', '09:00:00'), end: at('2026-05-01', '09:30:00'), activeEnergy: { qty: 100, units: 'kcal' } }] } }; const { doc } = merge(emptyVitals(), parsePayload(body)); const s = vitalsSeries(doc, { days: 90, now: NOW }); assert.deepEqual(s.metrics.step_count.days.map(d => d.day), ['2026-04-30', '2026-05-01']); assert.deepEqual(s.metrics.step_count.days.map(d => d.f.qty.sum), [4000, 6000]); assert.equal(s.metrics.heart_rate.days[0].f.Avg.avg, 70); assert.equal(s.metrics.step_count.units, 'count'); assert.equal(s.workouts.length, 1); // A one-day window keeps only the day inside it. const narrow = vitalsSeries(doc, { days: 1, now: NOW }); assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), ['2026-05-01']); });