wpilog-parser 1.0.1 → 2.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.
package/README.md CHANGED
@@ -11,17 +11,30 @@ npm install wpilog-parser
11
11
  ## Usage
12
12
 
13
13
  ```ts
14
- import { createReadStream } from 'node:fs';
15
- import { Readable } from 'node:stream';
14
+ import { readFile } from 'node:fs/promises';
16
15
  import { readRecords, decodeRecords } from 'wpilog-parser';
17
16
 
18
- const stream = Readable.toWeb(createReadStream('./example.wpilog'));
17
+ const bytes = await readFile('./example.wpilog');
19
18
 
20
- for await (const record of decodeRecords(readRecords(stream))) {
19
+ for (const record of decodeRecords(readRecords(bytes))) {
21
20
  console.log(record);
22
21
  }
23
22
  ```
24
23
 
24
+ ## Agent skill
25
+
26
+ This package ships an [Agent Skill](https://agentskills.io) at `skills/wpilog-parser/SKILL.md` that teaches AI coding agents how to use the library. Install it into your project with either:
27
+
28
+ ```bash
29
+ # https://skills.sh/
30
+ npx skills add wpilog-parser
31
+ ```
32
+
33
+ ```bash
34
+ # https://github.com/antfu/skills-npm
35
+ npx skills-npm
36
+ ```
37
+
25
38
  ## Development
26
39
 
27
40
  ```bash
package/dist/index.d.mts CHANGED
@@ -137,23 +137,35 @@ type ReadRecord = {
137
137
  record: RawRecord;
138
138
  };
139
139
  /** Accepted input types for {@link readRecords}. */
140
- type DataLogInput = ReadableStream<Uint8Array> | Uint8Array | ArrayBuffer;
140
+ type DataLogInput = Uint8Array | ArrayBuffer;
141
141
  /**
142
- * Read raw WPILOG records from a byte stream.
142
+ * Read raw WPILOG records from an in-memory buffer.
143
143
  *
144
144
  * Yields a header record first, then control and data records in order.
145
145
  * Data record payloads are not decoded — use {@link decodeRecords} for that.
146
146
  */
147
- declare function readRecords(input: DataLogInput): AsyncGenerator<ReadRecord>;
147
+ declare function readRecords(input: DataLogInput): Generator<ReadRecord>;
148
148
  //#endregion
149
149
  //#region src/decode-records.d.ts
150
+ /** Options for {@link decodeRecords}. */
151
+ type DecodeRecordsOptions = {
152
+ /**
153
+ * When `true`, throw if a data record references an entry ID with no preceding
154
+ * Start control record (i.e. a corrupt or truncated log). When `false` (default),
155
+ * such orphan records are silently skipped.
156
+ */
157
+ strict?: boolean;
158
+ };
150
159
  /**
151
160
  * Decode raw WPILOG records into typed values.
152
161
  *
153
162
  * Accepts the output of {@link readRecords} and yields fully decoded records,
154
163
  * including struct decoding with dependency resolution.
164
+ *
165
+ * By default, data records that reference an entry ID with no preceding Start
166
+ * control record are silently skipped. Pass `{ strict: true }` to throw instead.
155
167
  */
156
- declare function decodeRecords(records: AsyncIterable<ReadRecord>): AsyncGenerator<DecodedRecord>;
168
+ declare function decodeRecords(records: Iterable<ReadRecord>, options?: DecodeRecordsOptions): Generator<DecodedRecord>;
157
169
  //#endregion
158
170
  //#region src/struct-payload-to-json.d.ts
159
171
  /** Convert a {@link StructPayload} Map to a plain JSON-compatible object. */
@@ -174,7 +186,7 @@ type CatalogEntry = {
174
186
  * Data record bytes are still read from the stream but not decoded,
175
187
  * making this much cheaper than full decoding via {@link decodeRecords}.
176
188
  */
177
- declare function catalogEntries(records: AsyncIterable<ReadRecord>): AsyncGenerator<CatalogEntry, void, never>;
189
+ declare function catalogEntries(records: Iterable<ReadRecord>): Generator<CatalogEntry>;
178
190
  //#endregion
179
191
  //#region src/struct/types.d.ts
180
192
  declare enum KnownStructTypeName {
@@ -210,4 +222,4 @@ type StructDeclaration = {
210
222
  /** Parse a WPILib struct specification string into declarations. */
211
223
  declare function parseStructSpecification(declaration: string): StructDeclaration[];
212
224
  //#endregion
213
- export { type CatalogEntry, type ControlRecord, type ControlRecordPayload, ControlRecordType, type DataLogHeader, type DataLogInput, type DataRecord, type DecodedRecord, type EnumSpecification, type FinishControlRecord, KnownStructTypeName, type RawRecord, type ReadRecord, RecordType, type SetMetadataControlRecord, type StartControlRecord, type StructDeclaration, type StructPayload, type StructSpecification, type StructTypeName, catalogEntries, decodeRecords, isDataRecord, parseStructSpecification, readRecords, structPayloadToJson };
225
+ export { type CatalogEntry, type ControlRecord, type ControlRecordPayload, ControlRecordType, type DataLogHeader, type DataLogInput, type DataRecord, type DecodeRecordsOptions, type DecodedRecord, type EnumSpecification, type FinishControlRecord, KnownStructTypeName, type RawRecord, type ReadRecord, RecordType, type SetMetadataControlRecord, type StartControlRecord, type StructDeclaration, type StructPayload, type StructSpecification, type StructTypeName, catalogEntries, decodeRecords, isDataRecord, parseStructSpecification, readRecords, structPayloadToJson };
package/dist/index.mjs CHANGED
@@ -25,38 +25,6 @@ var ByteOffset = class {
25
25
  }
26
26
  };
27
27
  //#endregion
28
- //#region src/input-stream.ts
29
- var StreamFinishedError = class extends Error {
30
- constructor(bytesRead) {
31
- super(`Reached end of stream after reading ${bytesRead} bytes`);
32
- }
33
- };
34
- var InputStream = class {
35
- reader;
36
- bytesRead = 0;
37
- buffer = new Uint8Array();
38
- constructor(stream) {
39
- this.reader = stream.getReader();
40
- }
41
- async readBytesAndAdvance(length) {
42
- while (this.buffer.byteLength < length) {
43
- const chunk = await this.reader.read();
44
- if (chunk.done) throw new StreamFinishedError(this.bytesRead);
45
- const newBuffer = new Uint8Array(this.buffer.byteLength + chunk.value.byteLength);
46
- newBuffer.set(this.buffer);
47
- newBuffer.set(chunk.value, this.buffer.byteLength);
48
- this.buffer = newBuffer;
49
- }
50
- return this.readAndAdvanceFromBuffer(length);
51
- }
52
- readAndAdvanceFromBuffer(length) {
53
- const result = this.buffer.slice(0, length);
54
- this.buffer = this.buffer.slice(length);
55
- this.bytesRead += length;
56
- return result;
57
- }
58
- };
59
- //#endregion
60
28
  //#region src/types.ts
61
29
  /** Control record types in the WPILOG format. */
62
30
  let ControlRecordType = /* @__PURE__ */ function(ControlRecordType) {
@@ -85,97 +53,20 @@ let RecordType = /* @__PURE__ */ function(RecordType) {
85
53
  }({});
86
54
  /** Type guard that narrows a {@link DecodedRecord} to a {@link DataRecord}. */
87
55
  function isDataRecord(record) {
88
- return record.type !== RecordType.Control;
56
+ return record.type !== "control";
89
57
  }
90
58
  //#endregion
91
59
  //#region src/read-records.ts
92
60
  const TEXT_ENCODER = new TextEncoder();
93
61
  const TEXT_DECODER$1 = new TextDecoder();
94
62
  const MAGIC = TEXT_ENCODER.encode("WPILOG");
95
- async function readHeader(buffer) {
96
- const magic = await buffer.readBytesAndAdvance(MAGIC.byteLength);
97
- for (let i = 0; i < MAGIC.byteLength; i++) if (magic[i] !== MAGIC[i]) throw new Error("Not a WPILOG file (invalid magic bytes)");
98
- const chunk = await buffer.readBytesAndAdvance(6);
99
- const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
100
- const versionMinor = view.getUint8(0);
101
- const versionMajor = view.getUint8(1);
102
- const extraHeaderLength = view.getUint32(2, true);
103
- const extraHeader = await buffer.readBytesAndAdvance(extraHeaderLength);
104
- return {
105
- version: {
106
- major: versionMajor,
107
- minor: versionMinor
108
- },
109
- extraHeader: TEXT_DECODER$1.decode(extraHeader)
110
- };
111
- }
112
- async function readRecordHeaderLength(buffer) {
113
- const chunk = await buffer.readBytesAndAdvance(1);
114
- const bitfield = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength).getUint8(0);
115
- return {
116
- entryIdLength: 1 + (bitfield & 3),
117
- payloadSizeLength: 1 + (bitfield >> 2 & 3),
118
- timestampLength: 1 + (bitfield >> 4 & 7)
119
- };
120
- }
121
- async function readVarInt(buffer, length) {
122
- const chunk = await buffer.readBytesAndAdvance(length);
123
- const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
124
- switch (length) {
125
- case 1: return view.getUint8(0);
126
- case 2: return view.getUint16(0, true);
127
- case 3: return view.getUint8(2) << 16 | view.getUint8(1) << 8 | view.getUint8(0);
128
- case 4: return view.getUint32(0, true);
129
- default: throw new RangeError(`Invalid varint length ${length}`);
130
- }
131
- }
132
- async function readTimestamp(buffer, length) {
133
- const chunk = await buffer.readBytesAndAdvance(length);
134
- const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
135
- switch (length) {
136
- case 1: return BigInt(view.getUint8(0));
137
- case 2: return BigInt(view.getUint16(0, true));
138
- case 3: {
139
- const b0 = BigInt(view.getUint8(0));
140
- const b1 = BigInt(view.getUint8(1));
141
- return BigInt(view.getUint8(2)) << 16n | b1 << 8n | b0;
142
- }
143
- case 4: return BigInt(view.getUint32(0, true));
144
- case 5: {
145
- const b0 = BigInt(view.getUint8(0));
146
- const b1 = BigInt(view.getUint8(1));
147
- const b2 = BigInt(view.getUint8(2));
148
- const b3 = BigInt(view.getUint8(3));
149
- return BigInt(view.getUint8(4)) << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
150
- }
151
- case 6: {
152
- const b0 = BigInt(view.getUint8(0));
153
- const b1 = BigInt(view.getUint8(1));
154
- const b2 = BigInt(view.getUint8(2));
155
- const b3 = BigInt(view.getUint8(3));
156
- const b4 = BigInt(view.getUint8(4));
157
- return BigInt(view.getUint8(5)) << 40n | b4 << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
158
- }
159
- case 7: {
160
- const b0 = BigInt(view.getUint8(0));
161
- const b1 = BigInt(view.getUint8(1));
162
- const b2 = BigInt(view.getUint8(2));
163
- const b3 = BigInt(view.getUint8(3));
164
- const b4 = BigInt(view.getUint8(4));
165
- const b5 = BigInt(view.getUint8(5));
166
- return BigInt(view.getUint8(6)) << 48n | b5 << 40n | b4 << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
167
- }
168
- case 8: return view.getBigUint64(0, true);
169
- default: throw new RangeError(`Invalid timestamp length ${length}`);
170
- }
171
- }
172
63
  function readControlRecordPayload(payload) {
173
64
  const offset = new ByteOffset();
174
65
  const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
175
66
  const type = view.getUint8(offset.get());
176
67
  offset.advance8();
177
68
  switch (type) {
178
- case ControlRecordType.Start: {
69
+ case 0: {
179
70
  const entryId = view.getUint32(offset.get(), true);
180
71
  offset.advance32();
181
72
  const entryNameLength = view.getUint32(offset.get(), true);
@@ -198,7 +89,7 @@ function readControlRecordPayload(payload) {
198
89
  entryMetadata
199
90
  };
200
91
  }
201
- case ControlRecordType.Finish: {
92
+ case 1: {
202
93
  const entryId = view.getUint32(offset.get(), true);
203
94
  offset.advance32();
204
95
  return {
@@ -206,7 +97,7 @@ function readControlRecordPayload(payload) {
206
97
  entryId
207
98
  };
208
99
  }
209
- case ControlRecordType.SetMetadata: {
100
+ case 2: {
210
101
  const entryId = view.getUint32(offset.get(), true);
211
102
  offset.advance32();
212
103
  const entryMetadataLength = view.getUint32(offset.get(), true);
@@ -222,34 +113,102 @@ function readControlRecordPayload(payload) {
222
113
  default: throw new RangeError(`Invalid control record type ${type}`);
223
114
  }
224
115
  }
225
- function toReadableStream(input) {
226
- if (input instanceof ReadableStream) return input;
227
- return new Blob([input]).stream();
116
+ function toUint8Array(input) {
117
+ if (input instanceof Uint8Array) return input;
118
+ return new Uint8Array(input);
119
+ }
120
+ function readVarInt(view, offset, length) {
121
+ switch (length) {
122
+ case 1: return view.getUint8(offset);
123
+ case 2: return view.getUint16(offset, true);
124
+ case 3: return view.getUint8(offset + 2) << 16 | view.getUint8(offset + 1) << 8 | view.getUint8(offset);
125
+ case 4: return view.getUint32(offset, true);
126
+ default: throw new RangeError(`Invalid varint length ${length}`);
127
+ }
128
+ }
129
+ function readTimestamp(view, offset, length) {
130
+ switch (length) {
131
+ case 1: return BigInt(view.getUint8(offset));
132
+ case 2: return BigInt(view.getUint16(offset, true));
133
+ case 3: {
134
+ const b0 = BigInt(view.getUint8(offset));
135
+ const b1 = BigInt(view.getUint8(offset + 1));
136
+ return BigInt(view.getUint8(offset + 2)) << 16n | b1 << 8n | b0;
137
+ }
138
+ case 4: return BigInt(view.getUint32(offset, true));
139
+ case 5: {
140
+ const b0 = BigInt(view.getUint8(offset));
141
+ const b1 = BigInt(view.getUint8(offset + 1));
142
+ const b2 = BigInt(view.getUint8(offset + 2));
143
+ const b3 = BigInt(view.getUint8(offset + 3));
144
+ return BigInt(view.getUint8(offset + 4)) << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
145
+ }
146
+ case 6: {
147
+ const b0 = BigInt(view.getUint8(offset));
148
+ const b1 = BigInt(view.getUint8(offset + 1));
149
+ const b2 = BigInt(view.getUint8(offset + 2));
150
+ const b3 = BigInt(view.getUint8(offset + 3));
151
+ const b4 = BigInt(view.getUint8(offset + 4));
152
+ return BigInt(view.getUint8(offset + 5)) << 40n | b4 << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
153
+ }
154
+ case 7: {
155
+ const b0 = BigInt(view.getUint8(offset));
156
+ const b1 = BigInt(view.getUint8(offset + 1));
157
+ const b2 = BigInt(view.getUint8(offset + 2));
158
+ const b3 = BigInt(view.getUint8(offset + 3));
159
+ const b4 = BigInt(view.getUint8(offset + 4));
160
+ const b5 = BigInt(view.getUint8(offset + 5));
161
+ return BigInt(view.getUint8(offset + 6)) << 48n | b5 << 40n | b4 << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
162
+ }
163
+ case 8: return view.getBigUint64(offset, true);
164
+ default: throw new RangeError(`Invalid timestamp length ${length}`);
165
+ }
228
166
  }
229
167
  /**
230
- * Read raw WPILOG records from a byte stream.
168
+ * Read raw WPILOG records from an in-memory buffer.
231
169
  *
232
170
  * Yields a header record first, then control and data records in order.
233
171
  * Data record payloads are not decoded — use {@link decodeRecords} for that.
234
172
  */
235
- async function* readRecords(input) {
236
- const inputStream = new InputStream(toReadableStream(input));
173
+ function* readRecords(input) {
174
+ const bytes = toUint8Array(input);
175
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
176
+ const total = bytes.byteLength;
177
+ if (total < 12) throw new Error("Not a WPILOG file (truncated header)");
178
+ for (let i = 0; i < MAGIC.byteLength; i++) if (bytes[i] !== MAGIC[i]) throw new Error("Not a WPILOG file (invalid magic bytes)");
179
+ const versionMinor = view.getUint8(6);
180
+ const versionMajor = view.getUint8(7);
181
+ const extraHeaderLength = view.getUint32(8, true);
182
+ let offset = 12;
183
+ if (offset + extraHeaderLength > total) throw new Error("Not a WPILOG file (truncated extra header)");
184
+ const extraHeader = TEXT_DECODER$1.decode(bytes.subarray(offset, offset + extraHeaderLength));
185
+ offset += extraHeaderLength;
237
186
  yield {
238
187
  kind: "header",
239
- header: await readHeader(inputStream)
240
- };
241
- while (true) {
242
- let headerLength;
243
- try {
244
- headerLength = await readRecordHeaderLength(inputStream);
245
- } catch (error) {
246
- if (error instanceof StreamFinishedError) return;
247
- throw error;
188
+ header: {
189
+ version: {
190
+ major: versionMajor,
191
+ minor: versionMinor
192
+ },
193
+ extraHeader
248
194
  }
249
- const entryId = await readVarInt(inputStream, headerLength.entryIdLength);
250
- const payloadSize = await readVarInt(inputStream, headerLength.payloadSizeLength);
251
- const timestamp = await readTimestamp(inputStream, headerLength.timestampLength);
252
- const payload = await inputStream.readBytesAndAdvance(payloadSize);
195
+ };
196
+ while (offset < total) {
197
+ const bitfield = view.getUint8(offset);
198
+ offset += 1;
199
+ const entryIdLength = 1 + (bitfield & 3);
200
+ const payloadSizeLength = 1 + (bitfield >> 2 & 3);
201
+ const timestampLength = 1 + (bitfield >> 4 & 7);
202
+ if (offset + entryIdLength + payloadSizeLength + timestampLength > total) return;
203
+ const entryId = readVarInt(view, offset, entryIdLength);
204
+ offset += entryIdLength;
205
+ const payloadSize = readVarInt(view, offset, payloadSizeLength);
206
+ offset += payloadSizeLength;
207
+ const timestamp = readTimestamp(view, offset, timestampLength);
208
+ offset += timestampLength;
209
+ if (offset + payloadSize > total) return;
210
+ const payload = bytes.subarray(offset, offset + payloadSize);
211
+ offset += payloadSize;
253
212
  if (entryId === 0) yield {
254
213
  kind: "control",
255
214
  entryId,
@@ -516,14 +475,14 @@ var StructAstVisitor = class extends BaseStructVisitorWithDefaults {
516
475
  }
517
476
  enumSpecification(children, dataType) {
518
477
  switch (dataType) {
519
- case KnownStructTypeName.Int8:
520
- case KnownStructTypeName.Uint8:
521
- case KnownStructTypeName.Int16:
522
- case KnownStructTypeName.Uint16:
523
- case KnownStructTypeName.Int32:
524
- case KnownStructTypeName.Uint32:
525
- case KnownStructTypeName.Int64:
526
- case KnownStructTypeName.Uint64: break;
478
+ case "int8":
479
+ case "uint8":
480
+ case "int16":
481
+ case "uint16":
482
+ case "int32":
483
+ case "uint32":
484
+ case "int64":
485
+ case "uint64": break;
527
486
  default: throw new RangeError("Enums must be integers");
528
487
  }
529
488
  const entries = children.enumMember?.map((member) => this.enumMember(member.children));
@@ -538,23 +497,23 @@ var StructAstVisitor = class extends BaseStructVisitorWithDefaults {
538
497
  const [value] = children.Integer;
539
498
  const parsed = Number(value.image);
540
499
  switch (dataType) {
541
- case KnownStructTypeName.Boolean:
500
+ case "bool":
542
501
  if (parsed !== 1) throw new RangeError("Boolean bit-field members must be 1 bit");
543
502
  break;
544
- case KnownStructTypeName.Int8:
545
- case KnownStructTypeName.Uint8:
503
+ case "int8":
504
+ case "uint8":
546
505
  if (parsed > 8) throw new RangeError("8-bit bit-field members must be less than 8 bits");
547
506
  break;
548
- case KnownStructTypeName.Int16:
549
- case KnownStructTypeName.Uint16:
507
+ case "int16":
508
+ case "uint16":
550
509
  if (parsed > 16) throw new RangeError("16-bit bit-field members must be less than 16 bits");
551
510
  break;
552
- case KnownStructTypeName.Int32:
553
- case KnownStructTypeName.Uint32:
511
+ case "int32":
512
+ case "uint32":
554
513
  if (parsed > 32) throw new RangeError("32-bit bit-field members must be less than 32 bits");
555
514
  break;
556
- case KnownStructTypeName.Int64:
557
- case KnownStructTypeName.Uint64:
515
+ case "int64":
516
+ case "uint64":
558
517
  if (parsed > 64) throw new RangeError("64-bit bit-field members must be less than 64 bits");
559
518
  break;
560
519
  default: throw new RangeError("Bit-field members must be integers or booleans");
@@ -627,7 +586,7 @@ var StructRegistry = class StructRegistry {
627
586
  for (const member of specification) {
628
587
  if (member.bitWidth) throw new Error("Bit-field members are not implemented");
629
588
  switch (member.value) {
630
- case KnownStructTypeName.Boolean:
589
+ case "bool":
631
590
  if (member.arraySize !== void 0) {
632
591
  const array = [];
633
592
  for (let i = 0; i < member.arraySize; i++) {
@@ -640,7 +599,7 @@ var StructRegistry = class StructRegistry {
640
599
  offset.advance8();
641
600
  }
642
601
  break;
643
- case KnownStructTypeName.Int8:
602
+ case "int8":
644
603
  if (member.arraySize !== void 0) {
645
604
  const array = [];
646
605
  for (let i = 0; i < member.arraySize; i++) {
@@ -653,7 +612,7 @@ var StructRegistry = class StructRegistry {
653
612
  offset.advance8();
654
613
  }
655
614
  break;
656
- case KnownStructTypeName.Int16:
615
+ case "int16":
657
616
  if (member.arraySize !== void 0) {
658
617
  const array = [];
659
618
  for (let i = 0; i < member.arraySize; i++) {
@@ -666,7 +625,7 @@ var StructRegistry = class StructRegistry {
666
625
  offset.advance16();
667
626
  }
668
627
  break;
669
- case KnownStructTypeName.Int32:
628
+ case "int32":
670
629
  if (member.arraySize !== void 0) {
671
630
  const array = [];
672
631
  for (let i = 0; i < member.arraySize; i++) {
@@ -679,7 +638,7 @@ var StructRegistry = class StructRegistry {
679
638
  offset.advance32();
680
639
  }
681
640
  break;
682
- case KnownStructTypeName.Int64:
641
+ case "int64":
683
642
  if (member.arraySize !== void 0) {
684
643
  const array = [];
685
644
  for (let i = 0; i < member.arraySize; i++) {
@@ -692,7 +651,7 @@ var StructRegistry = class StructRegistry {
692
651
  offset.advance64();
693
652
  }
694
653
  break;
695
- case KnownStructTypeName.Uint8:
654
+ case "uint8":
696
655
  if (member.arraySize !== void 0) {
697
656
  const array = [];
698
657
  for (let i = 0; i < member.arraySize; i++) {
@@ -705,7 +664,7 @@ var StructRegistry = class StructRegistry {
705
664
  offset.advance8();
706
665
  }
707
666
  break;
708
- case KnownStructTypeName.Uint16:
667
+ case "uint16":
709
668
  if (member.arraySize !== void 0) {
710
669
  const array = [];
711
670
  for (let i = 0; i < member.arraySize; i++) {
@@ -718,7 +677,7 @@ var StructRegistry = class StructRegistry {
718
677
  offset.advance16();
719
678
  }
720
679
  break;
721
- case KnownStructTypeName.Uint32:
680
+ case "uint32":
722
681
  if (member.arraySize !== void 0) {
723
682
  const array = [];
724
683
  for (let i = 0; i < member.arraySize; i++) {
@@ -731,7 +690,7 @@ var StructRegistry = class StructRegistry {
731
690
  offset.advance32();
732
691
  }
733
692
  break;
734
- case KnownStructTypeName.Uint64:
693
+ case "uint64":
735
694
  if (member.arraySize !== void 0) {
736
695
  const array = [];
737
696
  for (let i = 0; i < member.arraySize; i++) {
@@ -744,8 +703,8 @@ var StructRegistry = class StructRegistry {
744
703
  offset.advance64();
745
704
  }
746
705
  break;
747
- case KnownStructTypeName.Float32:
748
- case KnownStructTypeName.Float:
706
+ case "float32":
707
+ case "float":
749
708
  if (member.arraySize !== void 0) {
750
709
  const array = [];
751
710
  for (let i = 0; i < member.arraySize; i++) {
@@ -758,8 +717,8 @@ var StructRegistry = class StructRegistry {
758
717
  offset.advance32();
759
718
  }
760
719
  break;
761
- case KnownStructTypeName.Float64:
762
- case KnownStructTypeName.Double:
720
+ case "float64":
721
+ case "double":
763
722
  if (member.arraySize !== void 0) {
764
723
  const array = [];
765
724
  for (let i = 0; i < member.arraySize; i++) {
@@ -772,7 +731,7 @@ var StructRegistry = class StructRegistry {
772
731
  offset.advance64();
773
732
  }
774
733
  break;
775
- case KnownStructTypeName.Character:
734
+ case "char":
776
735
  if (member.arraySize !== void 0) result.set(member.name, StructRegistry.TEXT_DECODER.decode(payload.subarray(offset.get(), offset.advance(member.arraySize).get())));
777
736
  else result.set(member.name, StructRegistry.TEXT_DECODER.decode(payload.subarray(offset.get(), offset.advance8().get())));
778
737
  break;
@@ -810,30 +769,30 @@ var StructRegistry = class StructRegistry {
810
769
  if (member.bitWidth) throw new Error("Bit-field members are not implemented");
811
770
  let byteLengthForOne = 0;
812
771
  switch (member.value) {
813
- case KnownStructTypeName.Boolean:
814
- case KnownStructTypeName.Character:
815
- case KnownStructTypeName.Int8:
816
- case KnownStructTypeName.Uint8:
772
+ case "bool":
773
+ case "char":
774
+ case "int8":
775
+ case "uint8":
817
776
  byteLengthForOne = 1;
818
777
  break;
819
- case KnownStructTypeName.Int16:
820
- case KnownStructTypeName.Uint16:
778
+ case "int16":
779
+ case "uint16":
821
780
  byteLengthForOne = 2;
822
781
  break;
823
- case KnownStructTypeName.Int32:
824
- case KnownStructTypeName.Uint32:
782
+ case "int32":
783
+ case "uint32":
825
784
  byteLengthForOne = 4;
826
785
  break;
827
- case KnownStructTypeName.Int64:
828
- case KnownStructTypeName.Uint64:
786
+ case "int64":
787
+ case "uint64":
829
788
  byteLengthForOne = 8;
830
789
  break;
831
- case KnownStructTypeName.Float32:
832
- case KnownStructTypeName.Float:
790
+ case "float32":
791
+ case "float":
833
792
  byteLengthForOne = 4;
834
793
  break;
835
- case KnownStructTypeName.Float64:
836
- case KnownStructTypeName.Double:
794
+ case "float64":
795
+ case "double":
837
796
  byteLengthForOne = 8;
838
797
  break;
839
798
  default: {
@@ -868,8 +827,11 @@ function normalizeEntryName(rawName) {
868
827
  *
869
828
  * Accepts the output of {@link readRecords} and yields fully decoded records,
870
829
  * including struct decoding with dependency resolution.
830
+ *
831
+ * By default, data records that reference an entry ID with no preceding Start
832
+ * control record are silently skipped. Pass `{ strict: true }` to throw instead.
871
833
  */
872
- async function* decodeRecords(records) {
834
+ function* decodeRecords(records, options = { strict: false }) {
873
835
  const asyncDecodedStructs = [];
874
836
  const structDecodeQueue = new StructDecodeQueue((structName, queuedRecords) => {
875
837
  for (const raw of queuedRecords) {
@@ -886,7 +848,7 @@ async function* decodeRecords(records) {
886
848
  timestamp: raw.timestamp,
887
849
  name,
888
850
  metadata,
889
- type: RecordType.StructArray,
851
+ type: "struct[]",
890
852
  structName: normalizedName,
891
853
  payload: decoded
892
854
  });
@@ -898,7 +860,7 @@ async function* decodeRecords(records) {
898
860
  timestamp: raw.timestamp,
899
861
  name,
900
862
  metadata,
901
- type: RecordType.Struct,
863
+ type: "struct",
902
864
  structName: normalizedName,
903
865
  payload: decoded
904
866
  });
@@ -907,29 +869,32 @@ async function* decodeRecords(records) {
907
869
  });
908
870
  const structRegistry = new StructRegistry(structDecodeQueue);
909
871
  const context = /* @__PURE__ */ new Map();
910
- for await (const readRecord of records) {
872
+ for (const readRecord of records) {
911
873
  if (readRecord.kind === "header") continue;
912
874
  if (readRecord.kind === "control") {
913
875
  const controlPayload = readRecord.payload;
914
876
  switch (controlPayload.controlRecordType) {
915
- case ControlRecordType.Start:
877
+ case 0:
916
878
  context.set(controlPayload.entryId, controlPayload);
917
879
  break;
918
- case ControlRecordType.Finish:
880
+ case 1:
919
881
  context.delete(controlPayload.entryId);
920
882
  break;
921
883
  }
922
884
  yield {
923
885
  entryId: readRecord.entryId,
924
886
  timestamp: readRecord.timestamp,
925
- type: RecordType.Control,
887
+ type: "control",
926
888
  payload: controlPayload
927
889
  };
928
890
  continue;
929
891
  }
930
892
  const raw = readRecord.record;
931
893
  const recordContext = context.get(raw.entryId);
932
- if (recordContext === void 0) throw new RangeError(`No type registered for entry ID ${raw.entryId}`);
894
+ if (recordContext === void 0) {
895
+ if (options.strict) throw new RangeError(`No type registered for entry ID ${raw.entryId}`);
896
+ continue;
897
+ }
933
898
  const name = normalizeEntryName(recordContext.entryName);
934
899
  const metadata = recordContext.entryMetadata;
935
900
  const view = new DataView(raw.payload.buffer, raw.payload.byteOffset, raw.payload.byteLength);
@@ -949,27 +914,27 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
949
914
  switch (entryType) {
950
915
  case "boolean": return {
951
916
  ...base,
952
- type: RecordType.Boolean,
917
+ type: "boolean",
953
918
  payload: byteToBoolean(view.getUint8(0))
954
919
  };
955
920
  case "int64": return {
956
921
  ...base,
957
- type: RecordType.Int64,
922
+ type: "int64",
958
923
  payload: view.getBigInt64(0, true)
959
924
  };
960
925
  case "float": return {
961
926
  ...base,
962
- type: RecordType.Float,
927
+ type: "float",
963
928
  payload: view.getFloat32(0, true)
964
929
  };
965
930
  case "double": return {
966
931
  ...base,
967
- type: RecordType.Double,
932
+ type: "double",
968
933
  payload: view.getFloat64(0, true)
969
934
  };
970
935
  case "string": return {
971
936
  ...base,
972
- type: RecordType.String,
937
+ type: "string",
973
938
  payload: TEXT_DECODER.decode(raw.payload)
974
939
  };
975
940
  case "boolean[]": {
@@ -977,7 +942,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
977
942
  for (let i = 0; i < raw.payload.byteLength; i++) payload.push(byteToBoolean(view.getUint8(i)));
978
943
  return {
979
944
  ...base,
980
- type: RecordType.BooleanArray,
945
+ type: "boolean[]",
981
946
  payload
982
947
  };
983
948
  }
@@ -986,7 +951,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
986
951
  for (let i = 0; i < raw.payload.byteLength; i += 8) payload.push(view.getBigUint64(i, true));
987
952
  return {
988
953
  ...base,
989
- type: RecordType.Int64Array,
954
+ type: "int64[]",
990
955
  payload
991
956
  };
992
957
  }
@@ -995,7 +960,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
995
960
  for (let i = 0; i < raw.payload.byteLength; i += 4) payload.push(view.getFloat32(i, true));
996
961
  return {
997
962
  ...base,
998
- type: RecordType.FloatArray,
963
+ type: "float[]",
999
964
  payload
1000
965
  };
1001
966
  }
@@ -1004,7 +969,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
1004
969
  for (let i = 0; i < raw.payload.byteLength; i += 8) payload.push(view.getFloat64(i, true));
1005
970
  return {
1006
971
  ...base,
1007
- type: RecordType.DoubleArray,
972
+ type: "double[]",
1008
973
  payload
1009
974
  };
1010
975
  }
@@ -1022,7 +987,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
1022
987
  }
1023
988
  return {
1024
989
  ...base,
1025
- type: RecordType.StringArray,
990
+ type: "string[]",
1026
991
  payload
1027
992
  };
1028
993
  }
@@ -1032,7 +997,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
1032
997
  structRegistry.register(structName, payload);
1033
998
  return {
1034
999
  ...base,
1035
- type: RecordType.String,
1000
+ type: "string",
1036
1001
  payload
1037
1002
  };
1038
1003
  }
@@ -1047,7 +1012,7 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
1047
1012
  }
1048
1013
  return {
1049
1014
  ...base,
1050
- type: RecordType.StructArray,
1015
+ type: "struct[]",
1051
1016
  structName: normalizedStructName,
1052
1017
  payload: decoded
1053
1018
  };
@@ -1060,14 +1025,14 @@ function decodePayload(raw, entryType, name, metadata, view, structRegistry, str
1060
1025
  }
1061
1026
  return {
1062
1027
  ...base,
1063
- type: RecordType.Struct,
1028
+ type: "struct",
1064
1029
  structName: normalizedStructName,
1065
1030
  payload: decoded
1066
1031
  };
1067
1032
  }
1068
1033
  return {
1069
1034
  ...base,
1070
- type: RecordType.Raw,
1035
+ type: "raw",
1071
1036
  payload: raw.payload
1072
1037
  };
1073
1038
  }
@@ -1091,21 +1056,21 @@ function structPayloadToJson(payload) {
1091
1056
  * Data record bytes are still read from the stream but not decoded,
1092
1057
  * making this much cheaper than full decoding via {@link decodeRecords}.
1093
1058
  */
1094
- async function* catalogEntries(records) {
1059
+ function* catalogEntries(records) {
1095
1060
  const entries = /* @__PURE__ */ new Map();
1096
- for await (const record of records) {
1061
+ for (const record of records) {
1097
1062
  if (record.kind !== "control") continue;
1098
- if (record.payload.controlRecordType === ControlRecordType.Start) {
1063
+ if (record.payload.controlRecordType === 0) {
1099
1064
  const entry = {
1100
1065
  entryId: record.payload.entryId,
1101
- name: record.payload.entryName,
1066
+ name: normalizeEntryName(record.payload.entryName),
1102
1067
  type: record.payload.entryType,
1103
1068
  metadata: record.payload.entryMetadata
1104
1069
  };
1105
1070
  entries.set(record.payload.entryId, entry);
1106
1071
  yield entry;
1107
1072
  }
1108
- if (record.payload.controlRecordType === ControlRecordType.SetMetadata) {
1073
+ if (record.payload.controlRecordType === 2) {
1109
1074
  const existing = entries.get(record.payload.entryId);
1110
1075
  if (existing) existing.metadata = record.payload.entryMetadata;
1111
1076
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wpilog-parser",
3
- "version": "1.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "Read WPILib wpilog data log files in TypeScript & JavaScript",
5
5
  "homepage": "https://github.com/jonahsnider/wpilog-parser#readme",
6
6
  "license": "MIT",
@@ -14,7 +14,8 @@
14
14
  "url": "git+https://github.com/jonahsnider/wpilog-parser.git"
15
15
  },
16
16
  "files": [
17
- "dist"
17
+ "dist",
18
+ "skills"
18
19
  ],
19
20
  "type": "module",
20
21
  "exports": {
@@ -25,6 +26,7 @@
25
26
  "access": "public"
26
27
  },
27
28
  "scripts": {
29
+ "bench": "vp test bench",
28
30
  "build": "vp pack",
29
31
  "check": "vp check",
30
32
  "dev": "vp pack --watch",
@@ -37,14 +39,18 @@
37
39
  "chevrotain": "^12.0.0"
38
40
  },
39
41
  "devDependencies": {
40
- "@types/node": "24.12.0",
41
- "@typescript/native-preview": "7.0.0-dev.20260401.1",
42
- "typescript": "6.0.2",
43
- "vite-plus": "0.1.15"
42
+ "@codspeed/vitest-plugin": "^5.2.0",
43
+ "@types/node": "24.12.2",
44
+ "@typescript/native-preview": "7.0.0-dev.20260425.1",
45
+ "typescript": "6.0.3",
46
+ "vite-plus": "0.1.19"
44
47
  },
45
48
  "overrides": {
46
49
  "vite": "npm:@voidzero-dev/vite-plus-core@latest",
47
50
  "vitest": "npm:@voidzero-dev/vite-plus-test@latest"
48
51
  },
49
- "packageManager": "bun@1.3.10"
52
+ "packageManager": "bun@1.3.10",
53
+ "patchedDependencies": {
54
+ "@codspeed/vitest-plugin@5.2.0": "patches/@codspeed%2Fvitest-plugin@5.2.0.patch"
55
+ }
50
56
  }
@@ -0,0 +1,128 @@
1
+ ---
2
+ name: wpilog-parser
3
+ description: Analyze WPILOG log files from FRC robots using the wpilog-parser library with TypeScript.
4
+ ---
5
+
6
+ # wpilog-parser
7
+
8
+ WPILOG is the binary log format used by logging libraries in the FRC ecosystem. The wpilog-parser library makes it easy to read and analyze the log files using TS/JS.
9
+
10
+ ## Creating a project
11
+
12
+ 1. Init a project using `bun init` or similar
13
+ 2. Add `wpilog-parser` as a dependency
14
+ 3. Create a `.ts` file for catalogging the records in the WPILOG file
15
+
16
+ ```ts
17
+ import { readFile } from 'node:fs/promises';
18
+ import { readRecords, catalogEntries } from 'wpilog-parser';
19
+
20
+ const bytes = await readFile('./example.wpilog');
21
+
22
+ for (const catalogEntry of catalogEntries(readRecords(bytes))) {
23
+ console.log(catalogEntry);
24
+ // {
25
+ // entryId: 3,
26
+ // name: "/Robot/DogLog/Options",
27
+ // type: "string",
28
+ // metadata: "{\"source\":\"DogLog\"}",
29
+ // }
30
+ }
31
+ ```
32
+
33
+ ## Analyzing logs
34
+
35
+ Use `decodeRecords` to parse record contents. Filter by `name` and narrow on `type`:
36
+
37
+ ```ts
38
+ import { readFile } from 'node:fs/promises';
39
+ import { readRecords, decodeRecords, isDataRecord, RecordType } from 'wpilog-parser';
40
+
41
+ const bytes = await readFile('./example.wpilog');
42
+
43
+ for (const record of decodeRecords(readRecords(bytes))) {
44
+ if (!isDataRecord(record)) continue;
45
+
46
+ if (record.name === '/Robot/Intake/Voltage' && record.type === RecordType.Double) {
47
+ console.log(record.timestamp, record.payload);
48
+ }
49
+ }
50
+ ```
51
+
52
+ ### Decoding structs
53
+
54
+ ```ts
55
+ import { structPayloadToJson, RecordType } from 'wpilog-parser';
56
+
57
+ for (const record of decodeRecords(readRecords(bytes))) {
58
+ if (record.type === RecordType.Struct && record.name === '/Robot/Localization/EstimatedPose') {
59
+ console.log(record.timestamp, structPayloadToJson(record.payload));
60
+ // 18688018n {
61
+ // translation: { x: 10.289, y: 0.47 },
62
+ // rotation: { value: 1.5707961072652017 },
63
+ // }
64
+ }
65
+ }
66
+ ```
67
+
68
+ ### Strict mode
69
+
70
+ ```ts
71
+ for (const record of decodeRecords(readRecords(bytes), { strict: true })) {
72
+ // throws on orphan data records instead of skipping
73
+ }
74
+ ```
75
+
76
+ ## Robot state cheatsheet
77
+
78
+ When DriverStation logging is on, every WPILOG has these `boolean` entries:
79
+
80
+ | Entry | Meaning |
81
+ | ---------------- | ------------------------------------------------------------------- |
82
+ | `/DS:enabled` | `true` while the robot is enabled (any mode). |
83
+ | `/DS:autonomous` | `true` during autonomous. `false` means teleop (unless `/DS:test`). |
84
+ | `/DS:test` | `true` during test mode. |
85
+ | `/DS:estop` | `true` if e-stopped. |
86
+
87
+ The mode flags (`autonomous`, `test`) reflect what the DS _would_ run if enabled, so check `/DS:enabled` together with them. Timestamps are microseconds (`bigint`).
88
+
89
+ ### Tracking enable/mode durations
90
+
91
+ ```ts
92
+ import { readRecords, decodeRecords, isDataRecord, RecordType } from 'wpilog-parser';
93
+
94
+ type Mode = 'auto' | 'teleop' | 'test';
95
+ function modeOf(auto: boolean, test: boolean): Mode {
96
+ if (test) return 'test';
97
+ if (auto) return 'auto';
98
+ return 'teleop';
99
+ }
100
+
101
+ let enabled = false;
102
+ let auto = false;
103
+ let test = false;
104
+ let enabledSince: bigint | null = null;
105
+ const totals = { auto: 0n, teleop: 0n, test: 0n };
106
+
107
+ for (const r of decodeRecords(readRecords(bytes))) {
108
+ if (!isDataRecord(r) || r.type !== RecordType.Boolean) continue;
109
+
110
+ const wasEnabled = enabled;
111
+ const prevMode = modeOf(auto, test);
112
+
113
+ if (r.name === '/DS:enabled') enabled = r.payload;
114
+ else if (r.name === '/DS:autonomous') auto = r.payload;
115
+ else if (r.name === '/DS:test') test = r.payload;
116
+ else continue;
117
+
118
+ if (wasEnabled && (!enabled || modeOf(auto, test) !== prevMode)) {
119
+ totals[prevMode] += r.timestamp - (enabledSince ?? r.timestamp);
120
+ enabledSince = enabled ? r.timestamp : null;
121
+ } else if (!wasEnabled && enabled) {
122
+ enabledSince = r.timestamp;
123
+ }
124
+ }
125
+
126
+ // Durations in microseconds; divide by 1_000_000n for seconds.
127
+ console.log(totals);
128
+ ```