How HealthDock Processes Apple Health Data — Methodology & Data Dictionary
This page documents the exact parsing, de-duplication, aggregation, and export rules implemented in HealthDock’s browser-local Apple Health converter. Every rule below matches the code running on this site.
assets/health-worker.js
⚡ 4 MB streaming chunks
🔒 100% browser-local execution
1. Input Handling (ZIP & XML Streaming)
The parser accepts either Apple Health’s compressed export.zip (detected when the filename ends in .zip or the MIME type is application/zip) or an unzipped export.xml. It never builds an XML DOM in memory.
- Locating
export.xmlinside ZIP: Reads up to the last 65,557 bytes of the archive to locate the ZIP End of Central Directory (including ZIP64 EOCD locator and ZIP64 extra fields for archives over 4 GB). It then scans the Central Directory, ignores any entry starting with__macosx/, and picks the first entry whose lowercased path isexport.xmlor ends with/export.xml(for example,apple_health_export/export.xml). - Streaming chunk size: Plain
.xmlfiles and uncompressed stored ZIP entries (method0) are sliced and decoded as UTF-8 in 4 MB chunks (CHUNK_BYTES = 4 * 1024 * 1024bytes). DEFLATE-compressed ZIP entries (method8) are streamed through the browser’s nativeDecompressionStream('deflate-raw')and decoded incrementally as chunks arrive. Other ZIP compression methods are rejected with an instruction to unzip first. - Tag scanning across chunk boundaries: Each decoded text chunk is scanned linearly for
<Record,<Workout, nested<WorkoutStatistics(while inside a non-self-closing<Workout>), and</Workout>. Any partial tag split across two chunks is buffered instate.tailuntil the closing>arrives.
Code references: CHUNK_BYTES, findExportXmlInZip, parseFile, feedTextChunk, extractAttr.
2. Record Types Read vs. Not Exported
HealthDock reads 13 HealthKit <Record> types plus <Workout> and selected nested <WorkoutStatistics> elements. Unit conversions happen during ingestion.
| Apple Health Identifier | Output Metric Key | Aggregation & Unit Normalization |
|---|---|---|
HKQuantityTypeIdentifierRestingHeartRate | resting_hr_avg | Daily arithmetic mean (bpm) |
HKQuantityTypeIdentifierHeartRateVariabilitySDNN | hrv_sdnn_ms | Daily arithmetic mean; s converted to ms (×1000) |
HKQuantityTypeIdentifierWalkingHeartRateAverage | walking_hr_avg | Daily arithmetic mean (bpm) |
HKQuantityTypeIdentifierStepCount | steps | Per-source daily sum, then chooseCumulativeSum |
HKQuantityTypeIdentifierActiveEnergyBurned | active_kcal | Per-source daily sum, then chooseCumulativeSum; kJ ÷ 4.184 |
HKQuantityTypeIdentifierAppleExerciseTime | exercise_min | Per-source daily sum, then chooseCumulativeSum; s ÷ 60 |
HKQuantityTypeIdentifierOxygenSaturation | spo2_pct | Daily arithmetic mean; values ≤ 1.5 multiplied by 100 |
HKQuantityTypeIdentifierRespiratoryRate | resp_rate | Daily arithmetic mean (/min) |
HKQuantityTypeIdentifierVO2Max | vo2max | Daily arithmetic mean (ml/kg·min) |
HKQuantityTypeIdentifierBloodPressureSystolic | bp_sys | Daily arithmetic mean (mmHg) |
HKQuantityTypeIdentifierBloodPressureDiastolic | bp_dia | Daily arithmetic mean (mmHg) |
HKQuantityTypeIdentifierBodyMass | weight_kg | Daily arithmetic mean; lb × 0.45359237, g ÷ 1000 |
HKCategoryTypeIdentifierSleepAnalysis | sleep_min, deep_min, rem_min | Night-window interval union (asleep stages only) |
Workouts: Reads <Workout> attributes (workoutActivityType, startDate, endDate, duration/durationUnit, totalEnergyBurned, totalDistance, sourceName) and nested <WorkoutStatistics> for HKQuantityTypeIdentifierActiveEnergyBurned (sum), HKQuantityTypeIdentifierHeartRate (average), and DistanceWalkingRunning / DistanceCycling / DistanceSwimming (sum, converting mi × 1.609344 and m ÷ 1000).
Not exported (ignored by the browser parser): All other XML elements and record types are skipped, including per-sample HKQuantityTypeIdentifierHeartRate records outside <WorkoutStatistics>, InBed and Awake sleep records, BasalEnergyBurned, AppleStandTime, distance <Record> entries, body fat / height / body temperature / blood glucose / mindfulness records, <Electrocardiogram> and electrocardiograms/ CSVs, <WorkoutRoute> and workout-routes/ GPX files, <ClinicalRecord>, <ActivitySummary>, <Correlation>, <MetadataEntry>, and <Me>.
Code references: RECORD_TYPE_MAP, WORKOUT_NAMES, processRecordTag, processWorkoutStart, processWorkoutStatsTag.
3. Steps, Active Energy & Exercise De-duplication
When you wear an Apple Watch and carry an iPhone, both devices write overlapping cumulative records for the same walk. HealthDock applies per-source daily selection to the three cumulative metrics (PARTIAL_KEYS: steps, active_kcal, exercise_min):
- During parsing, each cumulative record is summed into a bucket keyed by
(date, metricKey, sourceName). - At finalization, if only one source recorded values on that date, its sum is used.
- If multiple sources recorded values on that date,
chooseCumulativeSumchecks whether anysourceNamematches the case-insensitive regular expression/watch/i.- If one or more sources match
/watch/i, the parser returns the highest single Watch source total and discards all non-Watch sources for that day. - If no source matches
/watch/i, the parser returns the highest single source total across all sources for that day.
- If one or more sources match
/watch/i in sourceName, an Apple Watch renamed without the word “watch” falls back to the highest single source total.
Code references: PARTIAL_KEYS, processRecordTag, chooseCumulativeSum, finalizeDataset.
4. Sleep Night Window & Interval Merging
- Included values: Only the five asleep values in
ASLEEP_VALUESare counted:Asleep,AsleepUnspecified,AsleepCore,AsleepDeep, andAsleepREM.InBedandAwakeintervals are ignored. - Anomalous record filtering: Any sleep record with invalid timestamps,
endMs <= startMs,startMs < 0(before 1970-01-01 UTC), orstartMs > now + 24 hoursis ignored and counted per source inignoredSleep(printed at the bottom ofcontext.mdwhen non-zero). - Night window (18:00 → 12:00): Each night is assigned to its morning calendar date (
nightDay) and covers18:00:00of the previous day through12:00:00noon ofnightDay, anchored using the timezone offset found instartDate. Daytime naps starting and ending between12:00and18:00fall outside all night windows and are excluded. - Overlapping sources & stages: All asleep segments from all sources in a night window are pooled into
asleep(producingsleep_min), whileAsleepDeepintervals are pooled intodeep(deep_min) andAsleepREMintervals intorem(rem_min).AsleepCorecontributes tosleep_minand has no separate column. For each pool,mergeIntervalsMinutessorts segments, clamps them to[winStart, winEnd], unions overlapping or contiguous intervals (s <= curE), and rounds total milliseconds to the nearest integer minute (Math.round(total / 60000)). Overlapping records from multiple apps or devices are therefore unioned rather than double-counted. If a night has no deep or REM stage segments,deep_min/rem_minremain empty (null).
Code references: ASLEEP_VALUES, mergeIntervalsMinutes, applySleepNights.
5. HRV, Resting Heart Rate & Other Daily Metrics
All nine non-cumulative quantity metrics—resting_hr_avg, hrv_sdnn_ms, walking_hr_avg, spo2_pct, resp_rate, vo2max, bp_sys, bp_dia, and weight_kg—are aggregated as the simple arithmetic mean (sum / count) of every valid record sharing the same calendar date across all sources. The parser does not take the last reading, median, or per-source priority for these metrics.
Code references: processRecordTag, finalizeDataset.
6. Time Zones, Dates, Travel & DST
- Non-sleep records and workouts: Grouped by the first 10 characters of
startDate(YYYY-MM-DD) exactly as written in Apple Health’s XML, without shifting into the browser’s time zone. Records before1970-01-01or afterhorizonDay(browser local date + 24 hours) are dropped. - Sleep timestamps:
parseAppleDateMsconverts Apple Health timestamps (e.g.2026-01-15 07:32:30 +0800) to ISO-8601 with their explicit offset (defaulting toZif absent) and parses them to UTC epoch milliseconds viaDate.parse.applySleepNightsdetermines candidate nights from the recorded local date and hour instartStr/endStrand anchors the night’s18:00–12:00window to the offset of the first segment assigned to that night. - Browser local time zone:
formatLocalDate,parseYMD,addDaysYMD, andformatClockoperate in the browser’s local time zone. That local clock controlshorizonDay, theGenerated attimestamp, the staleness count (up to datevs.last synced N days ago), and the exclusion of “today’s” partial steps/active energy/exercise incontext.md. - Travel & DST notes: Stepping day-by-day via
Date.setDatestays aligned to local calendar dates across DST transitions, andstaleDaysrounds elapsed milliseconds divided by 86,400,000 to absorb ±1-hour DST shifts. If a single night’s sleep spans two different timezone offsets during travel, the night window uses the offset of whichever segment is encountered first. If your browser is set to a different time zone than the export’s latest date, partial-day exclusion for “today” incontext.mdcompares against your browser’s local date.
Code references: parseAppleDateMs, formatLocalDate, parseYMD, addDaysYMD, formatClock.
7. Missing Data: Blank vs. Zero
- Daily Summary CSV: Missing metric values are written as empty cells (
""), never0. The only zero defaults areworkout_count(0) andworkout_min(0) on days without workouts. Calendar dates with no metric values and no workouts are omitted from the CSV. - Workouts CSV: Missing
active_kcal,avg_hr_bpm, ordistance_kmare written as empty cells (""). - Daily Summary JSON: Missing metrics are omitted from each day’s
valuesobject. Days with no workouts omit theworkoutskey; missing workout fields are omitted. context.md: Missing averages or zero-denominator percentage deltas display as—. Metrics with zero days in the selected window are omitted from the Recent vs. Baseline table.
Code references: buildExportPayload, formatNumber, deltaText.
8. Baselines & Unusual Days in context.md
- Today’s partial data: In
renderContextMarkdownonly, if the latest date in the export equals the browser’s local today (todayStr),steps,active_kcal, andexercise_minare dropped from that last day so an unfinished day does not drag down averages. CSV and JSON exports keep today’s partial totals intact. - Recent vs. Baseline windows: Anchored backward from the latest date in the export (
endText) using the selectedwindowDays(default90; UI also offers60and30):Last 7d: 7 calendar days ending onendText(skip = 0).Last 30d: 30 calendar days ending onendText(skip = 0).Last <windowDays>d:windowDayscalendar days ending onendText(skip = 0).7d vs. Baseline: percentage difference betweenLast 7dmean and the baseline window ofwindowDaysexcluding the most recent 7 days (skip = 7), rounded to the nearest integer percent. Minimum sample size for this table: 1 day in the full window to display a row, and 1 day in both 7d and baseline (with non-zero baseline) to compute a delta.
- Unusual Days (≥2 SD rule): Evaluates each of the last 14 calendar days (
skip = 0) against a baseline coveringwindowDaysexcluding the most recent 14 days (skip = 14—up to 76 prior days for a 90-day window, 46 for 60 days, or 16 for 30 days).- Minimum sample size: Requires at least 14 days with values in that baseline (
bNums.length >= 14) andsd > 0. - Formula: Population standard deviation (dividing squared deviations by
N, notN − 1); a day is flagged when|value − mean| / sd >= 2. - Checked metrics (10): Resting HR, HRV, Walking HR, Sleep, Deep Sleep, REM Sleep, Blood Oxygen, Respiratory Rate, Systolic BP, and Diastolic BP. Activity volume and body metrics (
steps,active_kcal,exercise_min,vo2max,weight_kg) haveflagged: falseand are never flagged.
- Minimum sample size: Requires at least 14 days with values in that baseline (
- Long-Term Trends & Workouts: Long-Term Trends shows yearly arithmetic means for up to the newest 10 years across 6 metrics (
resting_hr_avg,hrv_sdnn_ms,sleep_min,steps,vo2max,weight_kg). Workouts summarizes the last 30 calendar days by activity type, followed by 8 Monday-anchored weeks of training volume whenever at least one workout occurred in the last 30 days.
Code references: METRICS, windowRows, metricMean, renderContextMarkdown.
9. CSV & JSON Column Dictionary
Daily Summary CSV (daily-csv) & JSON (daily-json)
In Daily Summary CSV, every row is one calendar date in ascending order. In Daily Summary JSON, the same metric keys live inside days[].values (with sleep_min in integer minutes, unlike context.md which divides sleep_min by 60 to display hours).
| Column | Unit | Format | Meaning |
|---|---|---|---|
date | — | YYYY-MM-DD | Calendar date from Apple Health startDate (or sleep morning date). |
resting_hr_avg | bpm | integer | Daily mean resting heart rate. |
hrv_sdnn_ms | ms | integer | Daily mean heart rate variability (SDNN). |
walking_hr_avg | bpm | integer | Daily mean walking heart rate average. |
sleep_min | min | integer | Merged total asleep minutes in the 18:00–12:00 night window (all asleep stages). |
deep_min | min | integer | Merged deep sleep minutes in the night window (blank if no deep segments). |
rem_min | min | integer | Merged REM sleep minutes in the night window (blank if no REM segments). |
steps | count | integer | Daily cumulative steps from the source selected by chooseCumulativeSum. |
active_kcal | kcal | integer | Daily cumulative active energy burned from the selected source. |
exercise_min | min | integer | Daily cumulative Apple Exercise minutes from the selected source. |
spo2_pct | % | 1 decimal | Daily mean blood oxygen saturation in percent. |
resp_rate | /min | 1 decimal | Daily mean respiratory rate in breaths per minute. |
vo2max | ml/kg·min | 1 decimal | Daily mean cardio fitness (VO₂max). |
bp_sys | mmHg | integer | Daily mean systolic blood pressure. |
bp_dia | mmHg | integer | Daily mean diastolic blood pressure. |
weight_kg | kg | 1 decimal | Daily mean body mass in kilograms. |
workout_count | count | integer | Number of <Workout> entries on this date (0 if none; CSV only). |
workout_min | min | 1 decimal or 0 | Sum of workout durations on this date (0 if none; CSV only). |
Workouts CSV (workouts-csv)
Sorted newest-first by workout start timestamp.
| Column | Unit | Format | Meaning |
|---|---|---|---|
date | — | YYYY-MM-DD | Workout start calendar date. |
start | — | YYYY-MM-DD HH:MM:SS | First 19 characters of the workout’s recorded startDate. |
activity_type | — | text | Human-readable activity name mapped from workoutActivityType. |
duration_min | min | 1 decimal | Workout duration (falls back to endDate − startDate if duration is missing). |
active_kcal | kcal | integer | Workout active energy from totalEnergyBurned or nested <WorkoutStatistics>; blank if absent. |
avg_hr_bpm | bpm | integer | Average workout heart rate from nested <WorkoutStatistics>; blank if absent. |
distance_km | km | 2 decimals | Workout distance in kilometers from totalDistance or nested <WorkoutStatistics>; blank if absent. |
source | — | text | sourceName attribute of the <Workout> element (or Unknown). |
Code references: METRICS, buildExportPayload, csvCell.
10. Privacy Boundary, Offline Verification & Parser Source
All file reading, ZIP decompression, aggregation, and CSV/JSON/Markdown generation run strictly inside your browser tab via a local Web Worker. HealthDock sends zero health bytes to any server and loads no third-party analytics or tracking scripts.
Privacy boundary: Once you copy context.md or upload a generated CSV/JSON file into a cloud AI service (such as ChatGPT, Claude, Gemini, Grok, or Perplexity), that AI provider receives the text you share under its own privacy policy.
How to verify offline: Load any converter page (for example XML → CSV or Apple Health to ChatGPT), disconnect your computer from the internet (or check Offline in browser DevTools → Network), and then drop your export.zip or export.xml file. Conversion completes normally with zero network activity.
Parser source: The parser is a single file, assets/health-worker.js, served with this site. You can also inspect real synthetic input and output files in Sample input and output (samples/README.txt).
Methodology FAQ
How does HealthDock deduplicate steps, active energy, and exercise minutes between Apple Watch and iPhone?
For steps, active_kcal, and exercise_min, HealthDock sums records separately by sourceName per day. When multiple sources exist on the same day, chooseCumulativeSum checks whether any source matches /watch/i; if so, it keeps the largest single Watch source total, otherwise the largest single source total. That prevents 2× double-counting, with the trade-off that iPhone-only activity while the Watch was off is dropped on any day that also has Watch data.
How are overlapping sleep segments and sleep stages calculated?
Only asleep values (Asleep, AsleepUnspecified, AsleepCore, AsleepDeep, and AsleepREM) are included; InBed and Awake are ignored. Segments are grouped into 18:00–12:00 night windows anchored to the offset in startDate and unioned via mergeIntervalsMinutes so overlapping sources are not double-counted.
How are HRV, resting heart rate, and other daily metrics aggregated when there are multiple readings per day?
All nine non-cumulative quantity metrics (resting_hr_avg, hrv_sdnn_ms, walking_hr_avg, spo2_pct, resp_rate, vo2max, bp_sys, bp_dia, and weight_kg) are aggregated as the simple arithmetic mean across all records on that calendar date.
How are unusual days (≥2 SD) calculated in context.md?
Each of the last 14 calendar days is compared against the baseline window (windowDays excluding the most recent 14 days). A metric is evaluated only if it is one of the 10 flagged physiological metrics and has at least 14 days in that baseline with a non-zero population standard deviation. Days with |value − mean| / SD >= 2 are flagged.
How can I verify that HealthDock processes my export.zip completely offline?
Open any converter page on gethealthdock.com, disconnect from Wi-Fi (or toggle Offline in DevTools), and drop your export.zip or export.xml. Everything runs locally in assets/health-worker.js with zero network calls.