tcxkit 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +14 -0
- data/LICENSE +21 -0
- data/README.md +100 -0
- data/SPECIFICATION.md +323 -0
- data/lib/tcxkit/activity.rb +311 -0
- data/lib/tcxkit/error.rb +40 -0
- data/lib/tcxkit/field.rb +51 -0
- data/lib/tcxkit/limits.rb +63 -0
- data/lib/tcxkit/message.rb +63 -0
- data/lib/tcxkit/message_builder.rb +253 -0
- data/lib/tcxkit/reader.rb +108 -0
- data/lib/tcxkit/schema.rb +162 -0
- data/lib/tcxkit/types.rb +270 -0
- data/lib/tcxkit/version.rb +5 -0
- data/lib/tcxkit/xml/clock.rb +41 -0
- data/lib/tcxkit/xml/element.rb +60 -0
- data/lib/tcxkit/xml/parser.rb +193 -0
- data/lib/tcxkit/xml/source.rb +265 -0
- data/lib/tcxkit.rb +26 -0
- metadata +110 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 2420d5b8de6921491b7c72407da1f3b76ff02c41b046b2ff1c83385e2cb127f7
|
|
4
|
+
data.tar.gz: 3ef6208abb71d60e63b428f197374df601a522fbc821a0149cbc3619f428febf
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 6a0188926505f2ab82752ecad4052d60f8f169918a95c742f827684e4109f7bc16fa7d3d02b1b0c91adc431cf6f8340b577a9350230b6b3383fb4c162d8a7880
|
|
7
|
+
data.tar.gz: 84c57d48f57c232f5055dcba40fce2481b35431eb743e5478c50444b252d35466d4ef52c04999b3be6a39fe3da39cbbbdfcc93613dfe2becd51e4254bcb6130a
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release: a read-only, streaming reader for Garmin Training Center Database v2 files, with typed messages and fields, enforced limits, refusal of DTDs, and an `Activity` view in the shape of `FitKit::Activity`. Requires Ruby 3.1 and Nokogiri 1.17.
|
|
6
|
+
|
|
7
|
+
Development, by milestone:
|
|
8
|
+
|
|
9
|
+
- M4: hardening. Reading 24-hour files is about 25% faster (the time limit's clock now pauses once per message, and paths, names and types are cached per place in a message). Seeded fuzz tests of bytes, markup and values run with the suite. Exporter quirks are reproduced in tests; undeclared namespace prefixes no longer stop reading (decision 6), a DTD in a UTF-16 document is refused before parsing, and numbers beyond a Float are decoded without Ruby warnings.
|
|
10
|
+
- M3: `Activity` view in the shape of `FitKit::Activity`: sessions (one per `<Activity>`), laps, transitions and records, with the session totals of decision 2. Checked against FIT exports of the same activities; `cadence` reports running cadence from the Activity Extension when `Cadence` is absent (decision 4), and the Activity's records leave out exact repeats of lap boundary trackpoints (decision 5).
|
|
11
|
+
- Fields typed with the schema's length, pattern and enumeration restrictions that M2 left out: `RestrictedToken_t` (course and plan names, 1 to 15 characters), `CoursePointName_t` (1 to 10), `CoursePointType_t` (an enumeration), `LangID_t` (2 characters) and `PartNumber_t` (a pattern). New invalid reasons `:too_short`, `:too_long` and `:no_pattern_match`. Accepting `+` and `-0` on unsigned integers (the XSD 1.1 rule) is now documented.
|
|
12
|
+
- M2: messages and fields. The Reader yields a `Message` per trackpoint, track, lap, transition, creator, activity, multisport session, author, course and course point (plus generic `:element` messages and a final `:document`), each with its `context`. Every leaf element and attribute is a `Field` with the text as written, a value typed from the TCX v2 and Activity Extension v2 schemas, and `valid?`/`invalid_reason`. Unknown elements and extensions are kept as untyped fields.
|
|
13
|
+
- M1: safe streaming reader. `Reader` (paths, Pathnames and IO, `close_io:`, re-reading seekable IO), `Limits` (`max_bytes`, `max_elements`, `max_depth`, `max_text_bytes`, `max_seconds`), refusal of DTD internal subsets and DTD entities, `TruncatedFileError` for files cut off, `UnsupportedFormatError` for anything but TCX v2, and skipping whitespace before the XML declaration. Yields no messages yet. Requires Nokogiri 1.17.
|
|
14
|
+
- M0: specification, gem skeleton and CI.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The tcxkit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# TcxKit
|
|
2
|
+
|
|
3
|
+
A read-only, streaming Ruby parser for Garmin Training Center Database v2 (`.tcx`) files.
|
|
4
|
+
|
|
5
|
+
**Status: 0.1.0, the first release.** All four milestones of [`SPECIFICATION.md`](SPECIFICATION.md) are done. The API may still change before 1.0.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```ruby
|
|
10
|
+
# Gemfile
|
|
11
|
+
gem "tcxkit"
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Requires Ruby 3.1 or newer and Nokogiri 1.17 or newer (the only runtime dependency).
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ruby
|
|
19
|
+
require "tcxkit"
|
|
20
|
+
|
|
21
|
+
activity = TcxKit::Activity.read("activity.tcx", limits: { max_seconds: 30 })
|
|
22
|
+
puts "#{activity.sport}: #{activity.total_distance} m in #{activity.total_timer_time} s"
|
|
23
|
+
|
|
24
|
+
activity.laps.each do |lap|
|
|
25
|
+
puts "lap: #{lap.total_timer_time} s, #{lap.total_distance} m, avg #{lap.avg_heart_rate} bpm"
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
activity.records.each do |record|
|
|
29
|
+
puts [record.timestamp, record.latitude, record.longitude, record.heart_rate, record.cadence, record.power].inspect
|
|
30
|
+
end
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The low-level reader yields one message per element:
|
|
34
|
+
|
|
35
|
+
```ruby
|
|
36
|
+
require "tcxkit"
|
|
37
|
+
|
|
38
|
+
TcxKit::Reader.new("activity.tcx", limits: { max_seconds: 30 }).each_message do |message|
|
|
39
|
+
case message.name
|
|
40
|
+
when :trackpoint
|
|
41
|
+
puts [message.timestamp, message[:latitude_degrees], message[:longitude_degrees], message[:heart_rate_bpm]].inspect
|
|
42
|
+
when :lap
|
|
43
|
+
puts "lap #{message.context[:lap]}: #{message[:total_time_seconds]} s, #{message[:distance_meters]} m"
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Every value is a `Field` with the text as written, a typed value, and a reason when the value does not fit the schema:
|
|
49
|
+
|
|
50
|
+
```ruby
|
|
51
|
+
field = message.field(:heart_rate_bpm)
|
|
52
|
+
field.text # "0"
|
|
53
|
+
field.value # nil
|
|
54
|
+
field.invalid_reason # :out_of_range (heart rates are 1 to 255)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Errors carry the line and column:
|
|
58
|
+
|
|
59
|
+
```ruby
|
|
60
|
+
rescue TcxKit::TruncatedFileError, TcxKit::InvalidFileError, TcxKit::UnsupportedFormatError,
|
|
61
|
+
TcxKit::UnsafeContentError, TcxKit::LimitExceededError => error
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
TcxKit is a sister project of [fitkit](https://github.com/scarhand/fitkit) (FIT) and [gpxkit](https://github.com/scarhand/gpxkit) (GPX), and shares their API shape: the same reader contract and limits, matching error classes, and an `Activity` view with fitkit's method names.
|
|
65
|
+
|
|
66
|
+
## Principles
|
|
67
|
+
|
|
68
|
+
- Read-only: never writes or repairs files.
|
|
69
|
+
- Untrusted input: no network access, no DTD entities, enforced limits on size, depth and time.
|
|
70
|
+
- Values exactly as written next to typed values; unknown elements and extensions kept.
|
|
71
|
+
- Nothing filled in, estimated or smoothed.
|
|
72
|
+
|
|
73
|
+
## Development
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
bundle install
|
|
77
|
+
bundle exec rake test
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Requires Ruby 3.1 or newer. The only runtime dependency is Nokogiri.
|
|
81
|
+
|
|
82
|
+
The suite includes seeded fuzz tests. Longer or different rounds:
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
FUZZ_ITERATIONS=50000 FUZZ_SEED=7 bundle exec ruby -Ilib -Itest test/tcxkit/fuzz_test.rb
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Test fixtures must be synthetic. Never commit real activity files: they contain locations, times and health data.
|
|
89
|
+
|
|
90
|
+
## Performance
|
|
91
|
+
|
|
92
|
+
Reading streams, so memory stays flat however long the file is (the `Activity` view keeps every message, by design). A one-hour activity reads in well under a second. A synthetic 24-hour file with a trackpoint every second takes about 11 s of CPU time on a laptop; set `limits: { max_seconds: ... }` for untrusted files.
|
|
93
|
+
|
|
94
|
+
## Releasing
|
|
95
|
+
|
|
96
|
+
Releases are published by the maintainer: bump `lib/tcxkit/version.rb`, move the changelog's notes under the new version, then `bundle exec rake release`, which builds the gem, tags the commit and pushes the gem to RubyGems.
|
|
97
|
+
|
|
98
|
+
## Licence
|
|
99
|
+
|
|
100
|
+
MIT, see [`LICENSE`](LICENSE). Garmin's TCX schemas are not part of this repository.
|
data/SPECIFICATION.md
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# TcxKit — Project Specification
|
|
2
|
+
|
|
3
|
+
**Status:** Approved by the maintainer on 2026-11-20; all milestones done for 0.1.0 (2026-11-23)
|
|
4
|
+
**Project type:** Read-only Ruby library for Garmin Training Center XML (TCX) files
|
|
5
|
+
**Gem name:** `tcxkit` (free on RubyGems on 2026-11-20)
|
|
6
|
+
**Ruby namespace / require path:** `TcxKit` / `require "tcxkit"`
|
|
7
|
+
**Ruby support:** 3.1 and newer
|
|
8
|
+
**Licence:** MIT
|
|
9
|
+
|
|
10
|
+
Sister projects: [`fitkit`](https://github.com/scarhand/fitkit) (FIT) and [`gpxkit`](https://github.com/scarhand/gpxkit) (GPX). The three gems expose the same shape of API (section 6.4) so an application can handle all three formats the same way.
|
|
11
|
+
|
|
12
|
+
## 1. Purpose
|
|
13
|
+
|
|
14
|
+
Build a reliable, read-only parser for Training Center Database v2 files (`.tcx`), the XML format Garmin introduced with Training Center and that many platforms still export.
|
|
15
|
+
|
|
16
|
+
The library exposes:
|
|
17
|
+
|
|
18
|
+
1. A low-level streaming `Reader` that yields one `Message` per meaningful TCX element (trackpoint, lap, activity, ...), keeping every value exactly as written in the file, including elements and extensions the library does not recognise.
|
|
19
|
+
2. An optional `Activity` view with sessions, laps and records, in the same shape as `FitKit::Activity`.
|
|
20
|
+
|
|
21
|
+
The library must not create, modify, rewrite or repair TCX files.
|
|
22
|
+
|
|
23
|
+
## 2. Goals
|
|
24
|
+
|
|
25
|
+
- Parse TCX v2 documents according to Garmin's published schema and its Activity Extension v2.
|
|
26
|
+
- Stream: memory use must not grow with the number of trackpoints unless the caller keeps them.
|
|
27
|
+
- Treat every file as untrusted input: no network access, no external entities, no DTD-defined entities, and enforced limits on size, depth, element count and time.
|
|
28
|
+
- Keep the text exactly as it appears in the file next to every typed value.
|
|
29
|
+
- Preserve unknown elements, attributes and extensions instead of dropping them.
|
|
30
|
+
- Never fill in, estimate, smooth or derive measurements the file does not contain.
|
|
31
|
+
- Raise useful, explicit exceptions with line and column numbers.
|
|
32
|
+
- One runtime dependency: Nokogiri 1.17 or later, used through its SAX interface.
|
|
33
|
+
|
|
34
|
+
## 3. Non-goals
|
|
35
|
+
|
|
36
|
+
- Writing, editing or repairing TCX files.
|
|
37
|
+
- XSD validation at runtime. Values are checked against the schema's types, but the document is not rejected for schema violations it can still be read through (section 7).
|
|
38
|
+
- Reading `Courses`, `Workouts`, `Folders` or `Author` in depth in the first release. They are recognised and their elements are passed through as generic messages (section 6.2), but they get no convenience API.
|
|
39
|
+
- TCX v1 (`TrainingCenterDatabase/v1`).
|
|
40
|
+
- Mapping, charting, analysis, unit preferences.
|
|
41
|
+
|
|
42
|
+
## 4. Reference material
|
|
43
|
+
|
|
44
|
+
- Training Center Database v2 schema: `http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2`, published at https://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd
|
|
45
|
+
- Activity Extension v2 schema: `http://www.garmin.com/xmlschemas/ActivityExtension/v2`, published at https://www8.garmin.com/xmlschemas/ActivityExtensionv2.xsd
|
|
46
|
+
|
|
47
|
+
Garmin publishes these schemas without stating a licence. **Do not copy them, or parts of them, into this repository.** Implement from reading them, cite the type names in comments and tests, and if XSD validation is ever wanted in tests, fetch the files at test time from Garmin, never at runtime.
|
|
48
|
+
|
|
49
|
+
Every element, type and range this gem relies on must be checked against the published schema, not taken from memory or inferred from sample files.
|
|
50
|
+
|
|
51
|
+
## 5. Architecture
|
|
52
|
+
|
|
53
|
+
Three layers, each usable on its own.
|
|
54
|
+
|
|
55
|
+
### 5.1 XML layer
|
|
56
|
+
|
|
57
|
+
- Nokogiri `XML::SAX::Parser#parse_io` over the source IO, wrapped so bytes read are counted (for `max_bytes`) as they are read.
|
|
58
|
+
- Keeps an element stack (namespace URI, local name, attributes, line, column) and collects text.
|
|
59
|
+
- Rejects unsafe or malformed input (section 7, section 8).
|
|
60
|
+
- Knows nothing about laps or trackpoints.
|
|
61
|
+
|
|
62
|
+
### 5.2 TCX layer
|
|
63
|
+
|
|
64
|
+
- Recognises the root `TrainingCenterDatabase` in the v2 namespace; anything else raises `UnsupportedFormatError`.
|
|
65
|
+
- Decides which elements become messages (section 6.2) and which are fields of the enclosing message.
|
|
66
|
+
- Types each field from the schema (section 6.3) and from known extension namespaces.
|
|
67
|
+
- Assigns each message its context: which activity, lap and track it belongs to.
|
|
68
|
+
|
|
69
|
+
### 5.3 Activity layer
|
|
70
|
+
|
|
71
|
+
- Collects messages into sessions, laps and records (section 6.4).
|
|
72
|
+
- Keeps every underlying `Message` reachable (`raw_message`, `messages`).
|
|
73
|
+
|
|
74
|
+
## 6. Public API
|
|
75
|
+
|
|
76
|
+
### 6.1 Reader
|
|
77
|
+
|
|
78
|
+
```ruby
|
|
79
|
+
reader = TcxKit::Reader.new("activity.tcx")
|
|
80
|
+
|
|
81
|
+
reader.each_message do |message|
|
|
82
|
+
case message.name
|
|
83
|
+
when :trackpoint then puts message[:heart_rate_bpm]
|
|
84
|
+
when :lap then puts message[:total_time_seconds]
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Same contract as `FitKit::Reader`:
|
|
90
|
+
|
|
91
|
+
- `Reader.new(source, close_io: false, source_label: nil, limits: Limits::DEFAULT)`. `source` is a path, a `Pathname` or an IO-like object that responds to `read`. A `Pathname` is read as a path even though it responds to `read`.
|
|
92
|
+
- `each_message` streams, and returns an Enumerator without a block.
|
|
93
|
+
- Seekable sources can be iterated again; a non-seekable IO can be read once, and a second iteration raises `Error`.
|
|
94
|
+
- Caller-owned IO is closed only with `close_io: true`.
|
|
95
|
+
- Time spent in the caller's block does not count towards `max_seconds`.
|
|
96
|
+
|
|
97
|
+
### 6.2 Messages
|
|
98
|
+
|
|
99
|
+
A message is emitted when its element closes, so it carries everything inside it. As in FIT, a lap's trackpoints therefore arrive before the lap, and an activity's laps arrive before the activity. Elements in the TCX v2 namespace become messages only where the schema puts them:
|
|
100
|
+
|
|
101
|
+
| Message name | Element (where) | Fields include |
|
|
102
|
+
|---|---|---|
|
|
103
|
+
| `:trackpoint` | `Trackpoint` (in a `Track`) | `time`, `latitude_degrees`, `longitude_degrees`, `altitude_meters`, `distance_meters`, `heart_rate_bpm`, `cadence`, `sensor_state`, and from `TPX`: `speed`, `run_cadence`, `watts`, `cadence_sensor` |
|
|
104
|
+
| `:track` | `Track` (in a lap, transition or course) | none of its own; marks the end of a track |
|
|
105
|
+
| `:lap` | `Lap` (in an activity: `ActivityLap_t`; in a course: `CourseLap_t`) | `start_time`, `total_time_seconds`, `distance_meters`, `maximum_speed`, `calories`, `average_heart_rate_bpm`, `maximum_heart_rate_bpm`, `intensity`, `cadence`, `trigger_method`, `notes`, and from `LX`: `avg_speed`, `max_bike_cadence`, `avg_run_cadence`, `max_run_cadence`, `steps`, `avg_watts`, `max_watts` |
|
|
106
|
+
| `:transition` | `Transition` (in a multisport `NextSport`) | as `:lap` |
|
|
107
|
+
| `:creator` | `Creator` (in an activity or course) | `type` (`xsi:type`), `name`, `unit_id`, `product_id`, `version_major`, `version_minor`, `build_major`, `build_minor` |
|
|
108
|
+
| `:activity` | `Activity` (in `Activities`, `FirstSport` or `NextSport`) | `sport`, `id`, `notes`, and from `Training`: `virtual_partner`, `type`, `interval_workout`, `name` |
|
|
109
|
+
| `:multi_sport_session` | `MultiSportSession` | `id`, `notes` |
|
|
110
|
+
| `:author` | `Author` | `type`, `name`, `version_major` (in `Build`), `lang_id`, `part_number`, ... |
|
|
111
|
+
| `:course` | `Course` | `name`, `notes` |
|
|
112
|
+
| `:course_point` | `CoursePoint` | `name`, `time`, `latitude_degrees`, `longitude_degrees`, `altitude_meters`, `point_type`, `notes` |
|
|
113
|
+
| `:element` | anything else at message level: `Folders`, `Workouts`, the root's `Extensions`, unknown elements | every leaf inside, untyped |
|
|
114
|
+
| `:document` | `TrainingCenterDatabase` | the root's attributes (such as `xsi:schemaLocation`); always the last message |
|
|
115
|
+
|
|
116
|
+
Every leaf element and every attribute inside a message, outside the messages nested in it, is one of its fields. `Activities`, `Courses`, `FirstSport` and `NextSport` only group messages. An element with only attributes (`<TPX CadenceSensor="Bike"/>`) gives only its attribute fields, and an empty `Extensions` element is not a field.
|
|
117
|
+
|
|
118
|
+
Field names are the local name in snake_case. A `Value` element takes its parent's name (`HeartRateBpm/Value` becomes `heart_rate_bpm`). The path keeps every element: `Position/LatitudeDegrees`, `Extensions/TPX/Speed`, `@StartTime`. Paths use local names only, since prefixes are chosen by each file. When names repeat (`Build/Version/VersionMajor` and `Version/VersionMajor`, or the begin and end positions of a course lap), look fields up by path.
|
|
119
|
+
|
|
120
|
+
`context` places a message: its own index and its ancestors'. `activity`, `multi_sport_session`, `course`, `author` and `element` count across the document; the others count within their parent (`lap` within its activity, `track` within its lap, `trackpoint` within its track).
|
|
121
|
+
|
|
122
|
+
```ruby
|
|
123
|
+
message.name # :trackpoint
|
|
124
|
+
message.element_name # "Trackpoint"
|
|
125
|
+
message.context # { activity: 0, lap: 2, track: 0, trackpoint: 41 }
|
|
126
|
+
message.line, message.column # where the element starts
|
|
127
|
+
message.fields # Array of Field, in document order (names can repeat)
|
|
128
|
+
message[:heart_rate_bpm] # typed value of the first field with that name
|
|
129
|
+
message["HeartRateBpm/Value"] # lookup by path
|
|
130
|
+
message.field(:heart_rate_bpm)
|
|
131
|
+
message.fields_named(:notes) # every field with that name
|
|
132
|
+
message.attributes # fields for the message element's own attributes
|
|
133
|
+
message.timestamp # the time field, for trackpoints and course points
|
|
134
|
+
message.to_h # name => value (first of each name)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 6.3 Fields
|
|
138
|
+
|
|
139
|
+
```ruby
|
|
140
|
+
field.name # :heart_rate_bpm
|
|
141
|
+
field.path # "HeartRateBpm/Value"
|
|
142
|
+
field.namespace # namespace URI of the element or attribute (nil for an unqualified attribute)
|
|
143
|
+
field.text # " 142 ", exactly as written
|
|
144
|
+
field.raw_value # "142": the text after the type's whitespace rule
|
|
145
|
+
field.value # 142, typed; nil when invalid
|
|
146
|
+
field.type # :positive_byte, :double, :date_time, :sport, :token, :string, :unknown, ...
|
|
147
|
+
field.known? # false where the schema does not put this element or attribute
|
|
148
|
+
field.valid?
|
|
149
|
+
field.invalid_reason # nil, :empty, :not_a_number, :not_finite, :not_an_integer, :out_of_range,
|
|
150
|
+
# :not_a_date_time, :no_utc_offset, :not_in_enumeration, :not_a_boolean,
|
|
151
|
+
# :too_short, :too_long, :no_pattern_match
|
|
152
|
+
field.line
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Types come from tables written from the schemas, keyed by path and namespace: `Extensions/TPX/Speed` is typed only when `TPX` and `Speed` are in the Activity Extension v2 namespace, whatever their prefix.
|
|
156
|
+
|
|
157
|
+
- Whitespace: `xsd:string` (such as `Notes`) keeps the text as written; every other type collapses it (XSD `collapse`), so `raw_value` is the collapsed text.
|
|
158
|
+
- `xsd:double` → `Float`. `INF` and `NaN` are not finite (`:not_finite`). Callers that need exact decimals use `BigDecimal(field.raw_value)`.
|
|
159
|
+
- Integer types → `Integer`, range-checked: `unsignedShort`, `unsignedInt`, `positiveByte` (1 to 255, heart rates) and `CadenceValue_t` (0 to 254). A decimal such as `142.0` is `:not_an_integer`. Signs follow the XSD 1.1 rule: an optional `+`, and `-` only before zero (`+007` is 7, `-0` is 0, `-1` is `:not_an_integer`). XSD 1.0 allows digits only for the unsigned types; the value is the same either way, so the more lenient rule is kept.
|
|
160
|
+
- `xsd:dateTime` → `Time` in UTC when the text has `Z` or an offset. Without an offset the value is `nil` and `invalid_reason` is `:no_utc_offset` (decision 1, section 13). Fractional seconds are kept. Impossible dates and times (February 30, hour 24, second 60, offsets beyond 14 hours) are `:not_a_date_time`.
|
|
161
|
+
- `xsd:boolean` → `true` or `false`.
|
|
162
|
+
- Enumerations (`Sport_t`, `Intensity_t`, `TriggerMethod_t`, `SensorState_t`, `CadenceSensorType_t`, `BuildType_t`, `TrainingType_t`, `CoursePointType_t`) → `Symbol` in snake_case, spaces included (`First Aid` is `:first_aid`, `4th Category` is `:"4th_category"`). Matching is exact after collapsing whitespace (`Absent`, not `absent`); anything else is `:not_in_enumeration`.
|
|
163
|
+
- `Token_t` → the collapsed `String`. Restrictions on its length (in characters) and pattern are validity: `RestrictedToken_t` (`Course/Name`, `Training/Plan/Name`) 1 to 15 characters, `CoursePointName_t` 1 to 10, `LangID_t` exactly 2, `PartNumber_t` the pattern `[\p{Lu}\d]{3}-[\p{Lu}\d]{5}-[\p{Lu}\d]{2}`. Text outside them keeps its `raw_value` with `:too_short`, `:too_long` or `:no_pattern_match`.
|
|
164
|
+
- Ranges are validity, not errors: `DegreesLatitude_t` (-90 to 90), `DegreesLongitude_t` (-180 up to, not including, 180).
|
|
165
|
+
- Unknown elements and attributes: `known?` false, `type` `:unknown`, `value` is the text as written.
|
|
166
|
+
|
|
167
|
+
### 6.4 Activity view
|
|
168
|
+
|
|
169
|
+
The shared shape across fitkit, tcxkit and gpxkit:
|
|
170
|
+
|
|
171
|
+
```ruby
|
|
172
|
+
activity = TcxKit::Activity.read("activity.tcx", limits: { max_seconds: 30 })
|
|
173
|
+
# also Activity.from_file(path) and Activity.from_io(io); options go to Reader.new
|
|
174
|
+
|
|
175
|
+
activity.sessions # one per <Activity> element, multisport ones included
|
|
176
|
+
activity.laps # every activity lap, in file order
|
|
177
|
+
activity.transitions # multisport transitions, as laps
|
|
178
|
+
activity.records # every activity trackpoint, in file order (see below)
|
|
179
|
+
activity.multi_sport_sessions # :multi_sport_session messages
|
|
180
|
+
activity.author # the :author message, or nil
|
|
181
|
+
activity.messages # every Message
|
|
182
|
+
activity.session # the first session
|
|
183
|
+
activity.creator # the first session's :creator message, or nil
|
|
184
|
+
|
|
185
|
+
# Summary methods read the first session, as in fitkit:
|
|
186
|
+
activity.sport # :running, :biking or :other
|
|
187
|
+
activity.start_time # the first lap's StartTime
|
|
188
|
+
activity.end_time # the last valid trackpoint time of the last session
|
|
189
|
+
activity.total_timer_time # sums of stated lap values (decision 2)
|
|
190
|
+
activity.total_distance
|
|
191
|
+
activity.total_calories
|
|
192
|
+
activity.max_heart_rate # the largest stated lap value (decision 2)
|
|
193
|
+
activity.max_speed
|
|
194
|
+
activity.num_laps
|
|
195
|
+
|
|
196
|
+
session = activity.session
|
|
197
|
+
session.id, session.notes, session.laps, session.records, session.creator
|
|
198
|
+
session.multi_sport_session # index of its multisport session, or nil
|
|
199
|
+
|
|
200
|
+
lap = activity.laps.first
|
|
201
|
+
lap.start_time
|
|
202
|
+
lap.total_timer_time # TotalTimeSeconds
|
|
203
|
+
lap.total_distance # DistanceMeters
|
|
204
|
+
lap.max_speed
|
|
205
|
+
lap.total_calories
|
|
206
|
+
lap.avg_heart_rate
|
|
207
|
+
lap.max_heart_rate
|
|
208
|
+
lap.avg_cadence # Cadence, else LX AvgRunCadence
|
|
209
|
+
lap.max_cadence # LX MaxBikeCadence, else LX MaxRunCadence
|
|
210
|
+
lap.avg_run_cadence, lap.max_run_cadence, lap.steps
|
|
211
|
+
lap.avg_speed # LX AvgSpeed
|
|
212
|
+
lap.avg_power, lap.max_power # LX AvgWatts, MaxWatts
|
|
213
|
+
lap.intensity, lap.trigger_method, lap.notes
|
|
214
|
+
lap.transition?
|
|
215
|
+
lap.records # this lap's trackpoints, every one
|
|
216
|
+
|
|
217
|
+
record = activity.records.first
|
|
218
|
+
record.timestamp # Time (UTC)
|
|
219
|
+
record.latitude, record.longitude # degrees
|
|
220
|
+
record.altitude # m
|
|
221
|
+
record.distance # m, as stated
|
|
222
|
+
record.heart_rate # bpm
|
|
223
|
+
record.cadence # Cadence, else TPX RunCadence
|
|
224
|
+
record.run_cadence # TPX RunCadence
|
|
225
|
+
record.speed # m/s, TPX Speed
|
|
226
|
+
record.power # W, TPX Watts
|
|
227
|
+
record.sensor_state, record.cadence_sensor
|
|
228
|
+
record.raw_message
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Method names match `FitKit::Activity` wherever the meaning matches; methods for what TCX never states return `nil`: a session's averages, ascent and descent, elapsed time (a TCX lap has a single `TotalTimeSeconds`), `sub_sport`, and a record's `grade` and `temperature`. Every value is reported in SI units and as the file states it; nothing is computed from positions or timestamps. Values are read by schema path, so an unknown element at the same path is never used, and an invalid value is `nil`.
|
|
232
|
+
|
|
233
|
+
Courses are not activities: their laps and trackpoints are not in `laps` or `records` (they stay in `messages`).
|
|
234
|
+
|
|
235
|
+
`activity.sport` is the TCX `Sport_t` value. Mapping it to an application's sports is the caller's job.
|
|
236
|
+
|
|
237
|
+
**Cadence** (decision 4). Garmin writes cycling cadence in `Cadence` and running cadence in the Activity Extension (`TPX RunCadence`, `LX AvgRunCadence`). `cadence`, `avg_cadence` and `max_cadence` report whichever is stated, as fitkit's `cadence` does for both sports; the running-specific methods stay available.
|
|
238
|
+
|
|
239
|
+
**Repeated lap boundary points** (decision 5). Garmin repeats the trackpoint at a lap boundary as the last point of one lap and the first of the next. `activity.records` and `session.records` leave out a trackpoint that exactly repeats the one before it (the same time and the same fields, as written); `lap.records` and the messages keep every one. A trackpoint at the same time with any different value is kept.
|
|
240
|
+
|
|
241
|
+
## 7. Leniency and strictness
|
|
242
|
+
|
|
243
|
+
Strict (raise):
|
|
244
|
+
|
|
245
|
+
- Not well-formed XML, a wrong root element, or the TCX v1 namespace.
|
|
246
|
+
- A DTD internal subset, or any entity reference other than the five predefined XML entities and character references (section 8).
|
|
247
|
+
- Input cut off before the root element closes (`TruncatedFileError`). libxml2 reports only a message and a position, so a file counts as cut off when the error is on the last line with at most part of one token (no `<` or `>`) after it, and the input starts with `<`. Anything else that is not well-formed is `InvalidFileError`.
|
|
248
|
+
- Any limit crossed.
|
|
249
|
+
|
|
250
|
+
Lenient (keep reading, record it on the field or message):
|
|
251
|
+
|
|
252
|
+
- Values that do not fit their type or range (`valid?` false).
|
|
253
|
+
- Unknown elements, unknown attributes, unknown extension namespaces.
|
|
254
|
+
- Elements in an order the schema does not allow, or missing required elements (for example a `Lap` without `TotalTimeSeconds`): the field is simply absent.
|
|
255
|
+
|
|
256
|
+
Known real-world quirks, each reproduced in `test/tcxkit/exporter_quirks_test.rb`:
|
|
257
|
+
|
|
258
|
+
- Whitespace before the XML declaration, which is not well-formed XML: skipped (decision 3). A UTF-8 byte order mark is accepted as XML allows.
|
|
259
|
+
- A namespace prefix used without being declared (`<ns3:TPX>` with no `xmlns:ns3`), or bound to an empty namespace: libxml2 reports these and reads on, and so does the reader. The element has no namespace, so its values are kept as untyped fields; the gem does not guess which namespace was meant (decision 6). Any other error still makes the file invalid.
|
|
260
|
+
- UTF-16 documents (with or without a byte order mark) and single-byte encodings named in the XML declaration (`ISO-8859-1`, `windows-1252`) are read; values come out as UTF-8. The DTD check decodes the start of a UTF-16 document, so a DTD is refused there too.
|
|
261
|
+
- Bytes that do not match the declared encoding (Latin-1 bytes in a UTF-8 document) make the file invalid.
|
|
262
|
+
- Carriage returns: XML turns `\r\n` into `\n` in text, as libxml2 does.
|
|
263
|
+
- Near-miss values stay invalid, with their text kept: `+0000` or a lowercase `z` in a time, a heart rate written as `142.0`.
|
|
264
|
+
|
|
265
|
+
## 8. Security
|
|
266
|
+
|
|
267
|
+
Files come from users and third parties. The reader must:
|
|
268
|
+
|
|
269
|
+
- Never access the network or the filesystem beyond the source (Nokogiri's SAX parser does not load external DTDs or entities by default; the reader must not turn that on).
|
|
270
|
+
- Raise `UnsafeContentError` on a DTD internal subset (`<!DOCTYPE x [ ... ]>`), which is where entities are declared, before the XML parser sees it. A document type declaration without one is allowed, and its external DTD is never loaded.
|
|
271
|
+
- Raise `UnsafeContentError` on any reference to a DTD-declared entity, as a second line of defence. Nokogiri reports these through the SAX `reference` callback (Nokogiri 1.17 and later).
|
|
272
|
+
- Enforce `Limits` while reading:
|
|
273
|
+
- `max_bytes` (default 64 MB): bytes read from the source.
|
|
274
|
+
- `max_elements` (default 5,000,000): elements opened.
|
|
275
|
+
- `max_depth` (default 64): element nesting.
|
|
276
|
+
- `max_text_bytes` (default 1 MB): text of one element without child elements, one attribute value, or the prolog before the root element. Text between child elements is not kept and not counted.
|
|
277
|
+
- `max_seconds` (default none): parse time on a monotonic clock, excluding the caller's block.
|
|
278
|
+
- `nil` switches a limit off; `Limits.none` switches all off.
|
|
279
|
+
- Never log or include file content in exception messages beyond element names and positions.
|
|
280
|
+
|
|
281
|
+
## 9. Errors
|
|
282
|
+
|
|
283
|
+
```
|
|
284
|
+
TcxKit::Error base; source, line, column
|
|
285
|
+
├── InvalidFileError not well-formed XML
|
|
286
|
+
├── UnsupportedFormatError not a TCX v2 document
|
|
287
|
+
├── TruncatedFileError ended before the root element closed
|
|
288
|
+
├── UnsafeContentError DTD-declared entity
|
|
289
|
+
└── LimitExceededError `limit` names the bound crossed
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Names match fitkit's where the meaning matches, so an application can map all three gems' errors to the same failure codes.
|
|
293
|
+
|
|
294
|
+
## 10. Testing
|
|
295
|
+
|
|
296
|
+
- Minitest, no other development dependencies beyond rake.
|
|
297
|
+
- Fixtures are synthetic: built in `test/support` or written by hand, with made-up positions and values. Never commit real activities. Document every fixture in `test/fixtures/README.md`.
|
|
298
|
+
- Cover each message, field, type, range and enumeration; unknown elements and extensions; every error and limit; hostile inputs (entity expansion, deep nesting, huge text, truncated files, binary garbage, a FIT file passed by mistake); and IO ownership and re-iteration.
|
|
299
|
+
- Assert decoded values, not merely that parsing succeeds.
|
|
300
|
+
- Each bug fix gets a regression test.
|
|
301
|
+
|
|
302
|
+
## 11. Compatibility and packaging
|
|
303
|
+
|
|
304
|
+
- Ruby 3.1+, CI on 3.1, 3.2, 3.3, 3.4 and 4.0.
|
|
305
|
+
- Runtime dependency: `nokogiri ~> 1.17` (1.17 added the SAX `reference` callback).
|
|
306
|
+
- Semantic versioning. Publish to RubyGems only after the maintainer approves a release.
|
|
307
|
+
|
|
308
|
+
## 12. Milestones
|
|
309
|
+
|
|
310
|
+
- **M0 — Foundation** (done): specification, gem skeleton, CI.
|
|
311
|
+
- **M1 — Safe streaming reader** (done): XML layer, `Limits`, errors, root detection, the leniency rules in section 7, security tests.
|
|
312
|
+
- **M2 — Messages and fields** (done): the message table in 6.2, schema typing and ranges in 6.3, Activity Extension v2, unknown preservation.
|
|
313
|
+
- **M3 — Activity view** (done): section 6.4.
|
|
314
|
+
- **M4 — Hardening and release** (done; release on approval): quirks from real exporters (reproduced synthetically), a benchmark on a 24-hour file, README examples verified, first release on approval. Also seeded fuzz tests of bytes, markup and values, and reading without Ruby warnings.
|
|
315
|
+
|
|
316
|
+
## 13. Decisions (approved 2026-11-20)
|
|
317
|
+
|
|
318
|
+
1. **Times without a UTC offset.** The schema's `xsd:dateTime` allows them; their time zone is unknown. Decided: `value` nil, `invalid_reason` `:no_utc_offset`, raw text kept, so the gem never guesses a zone.
|
|
319
|
+
2. **Session totals.** TCX has no activity-level totals. Decided: `Session#total_timer_time`, `total_distance` and `total_calories` are the sum of the laps' stated values when every lap states it, otherwise nil; `max_heart_rate` and `max_speed` the largest lap value, under the same rule that every lap states one (refined 2026-11-23: otherwise the largest of the others could understate the session's); averages nil. Documented as sums of stated values.
|
|
320
|
+
3. **Whitespace before the XML declaration.** Decided: skip it, as described in section 7.
|
|
321
|
+
4. **Cadence in the Activity view** (2026-11-23). Checked against FIT exports of the same activities: Garmin's TCX states running cadence only in the Activity Extension, with the same values as FIT's `cadence`. Decided: `cadence`, `avg_cadence` and `max_cadence` report the `Cadence` element, else the running cadence. Accepted by the maintainer on 2026-11-23.
|
|
322
|
+
5. **Repeated lap boundary points** (2026-11-23). Garmin's TCX writes the lap boundary trackpoint in both laps, identically; FIT has it once. Decided: the Activity's and sessions' `records` leave out exact repeats; laps and messages keep them. Accepted by the maintainer on 2026-11-23.
|
|
323
|
+
6. **Namespace errors** (2026-11-23). A file whose exporter used an undeclared namespace prefix was rejected outright, although libxml2 reads on. Decided: such namespace errors do not stop reading; the elements involved have no namespace, so their values are untyped fields. Accepted by the maintainer on 2026-11-23.
|