wpilog-parser 4.3.0 → 4.4.1

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
@@ -28,6 +28,30 @@ Use `readRecords()` and `decodeRecords()` separately when you need access to raw
28
28
  Struct schemas are compiled lazily into reusable decoders, and struct payloads are returned as plain objects, including nested structs and arrays of structs.
29
29
  In environments where Content Security Policy blocks runtime code generation, decoding falls back to a CSP-safe implementation.
30
30
 
31
+ Protobuf entries, such as a `proto:wpi.proto.ProtobufPose2d` entry, are decoded with the `/.schema/proto:*` schemas WPILib logs for them, into `protobuf` records with a plain object payload. See [wpilib-protobuf](https://github.com/jonahsnider/wpilog-parser/tree/main/packages/wpilib-protobuf#readme) for how fields are decoded.
32
+ Struct and protobuf values logged before their schemas are yielded once the schemas arrive, with their original timestamps.
33
+
34
+ A value that can't be decoded for its entry's type, such as a struct or protobuf value that doesn't match its schema or an invalid schema, throws by default.
35
+ Apps that should show what they can of a damaged log can pass `{ invalidValues: 'raw' }` to get these as `raw` records holding their bytes instead, and keep reading.
36
+
37
+ ### Streaming
38
+
39
+ `DataLogStreamParser` decodes a log as its bytes arrive, such as a download, without holding the whole file in memory. It produces the same records as `parseDataLog()`.
40
+
41
+ ```ts
42
+ import { DataLogStreamParser } from 'wpilog-parser';
43
+
44
+ const parser = new DataLogStreamParser();
45
+ for await (const chunk of response.body) {
46
+ for (const record of parser.push(chunk)) {
47
+ console.log(record);
48
+ }
49
+ }
50
+ parser.end();
51
+ ```
52
+
53
+ `push()` keeps only the bytes of a record split between chunks. `bytesRead` and `truncated` report progress and a cut-off last record, like they do on `parseDataLog()`'s generator.
54
+
31
55
  ### Writing logs
32
56
 
33
57
  ```ts
@@ -1,4 +1,5 @@
1
1
  import { defineDiagnostics } from "nostics";
2
+ import { ProtobufRegistry } from "wpilib-protobuf";
2
3
  import { StructDependencyGraph, StructError, StructRegistry } from "wpilib-struct";
3
4
  // src/byte-offset.ts
4
5
  var ByteOffset = class {
@@ -89,6 +90,14 @@ const diagnostics = defineDiagnostics({ codes: {
89
90
  why: (p) => `Unknown struct definition: ${p.name}`,
90
91
  fix: "Register the struct definition before decoding its records."
91
92
  },
93
+ WPILOG_R0015: {
94
+ why: (p) => `Invalid protobuf schema in ${p.name}`,
95
+ fix: "Check that the entry holds a serialized google.protobuf.FileDescriptorProto."
96
+ },
97
+ WPILOG_R0016: {
98
+ why: (p) => `Invalid ${p.messageName} protobuf message in ${p.name}`,
99
+ fix: "Check that the entry was written with the schema logged for its type."
100
+ },
92
101
  WPILOG_W0001: {
93
102
  why: (p) => `Entry ID ${p.entryId} is not started`,
94
103
  fix: "Use an ID returned by start() for an entry that has not been finished."
@@ -128,6 +137,7 @@ const RecordType = {
128
137
  StringArray: "string[]",
129
138
  Struct: "struct",
130
139
  StructArray: "struct[]",
140
+ Protobuf: "protobuf",
131
141
  Raw: "raw"
132
142
  };
133
143
  /** Type guard that narrows a {@link DecodedRecord} to a {@link DataRecord}. */
@@ -186,16 +196,16 @@ function toUint8Array(input) {
186
196
  if (input instanceof Uint8Array) return input;
187
197
  return new Uint8Array(input);
188
198
  }
189
- function openDataLog(input) {
190
- const bytes = toUint8Array(input);
191
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
192
- if (bytes.byteLength < 12) throw diagnostics.WPILOG_R0002();
199
+ /**
200
+ * Read the file header at the start of `bytes`, or `undefined` if `bytes` ends before the header does.
201
+ * Throws if it isn't a WPILOG file.
202
+ */
203
+ function readHeader(bytes, view) {
204
+ if (bytes.byteLength < 12) return;
193
205
  for (let i = 0; i < MAGIC.byteLength; i++) if (bytes[i] !== MAGIC[i]) throw diagnostics.WPILOG_R0003();
194
206
  const recordsOffset = 12 + view.getUint32(8, true);
195
- if (recordsOffset > bytes.byteLength) throw diagnostics.WPILOG_R0004();
207
+ if (recordsOffset > bytes.byteLength) return;
196
208
  return {
197
- bytes,
198
- view,
199
209
  header: {
200
210
  version: {
201
211
  major: view.getUint8(7),
@@ -206,6 +216,21 @@ function openDataLog(input) {
206
216
  recordsOffset
207
217
  };
208
218
  }
219
+ /** The error for a file that ends before its header does, see {@link readHeader} */
220
+ function truncatedHeaderError(byteLength) {
221
+ return byteLength < 12 ? diagnostics.WPILOG_R0002() : diagnostics.WPILOG_R0004();
222
+ }
223
+ function openDataLog(input) {
224
+ const bytes = toUint8Array(input);
225
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
226
+ const opened = readHeader(bytes, view);
227
+ if (!opened) throw truncatedHeaderError(bytes.byteLength);
228
+ return {
229
+ bytes,
230
+ view,
231
+ ...opened
232
+ };
233
+ }
209
234
  function readVarInt(view, offset, length) {
210
235
  switch (length) {
211
236
  case 1: return view.getUint8(offset);
@@ -228,11 +253,10 @@ function readTimestamp(view, offset, length) {
228
253
  default: throw new RangeError(`Invalid timestamp length ${length}`);
229
254
  }
230
255
  }
231
- /** Mutable record cursor used by the fused decoder to avoid intermediate record allocations. */
232
- var RecordCursor = class {
256
+ /** Mutable record cursor used by the fused and streaming decoders to avoid intermediate record allocations. */
257
+ var RecordCursor = class RecordCursor {
233
258
  bytes;
234
259
  view;
235
- header;
236
260
  entryId = 0;
237
261
  timestamp = 0;
238
262
  payloadOffset = 0;
@@ -241,12 +265,16 @@ var RecordCursor = class {
241
265
  offset;
242
266
  /** Whether the input ended partway through a record. */
243
267
  truncated = false;
244
- constructor(input) {
245
- const source = openDataLog(input);
246
- this.bytes = source.bytes;
247
- this.view = source.view;
248
- this.header = source.header;
249
- this.offset = source.recordsOffset;
268
+ /** Read the records of a WPILOG file */
269
+ static open(input) {
270
+ const { bytes, view, recordsOffset } = openDataLog(input);
271
+ return new RecordCursor(bytes, view, recordsOffset);
272
+ }
273
+ /** Read the records in `bytes` starting at `offset` */
274
+ constructor(bytes, view, offset) {
275
+ this.bytes = bytes;
276
+ this.view = view;
277
+ this.offset = offset;
250
278
  }
251
279
  next() {
252
280
  const total = this.bytes.byteLength;
@@ -432,6 +460,8 @@ const TEXT_DECODER = new TextDecoder();
432
460
  const STRUCT_PREFIX = "struct:";
433
461
  const STRUCT_ARRAY_SUFFIX = "[]";
434
462
  const STRUCT_SCHEMA_NAME_PREFIX = "/.schema/struct:";
463
+ const PROTOBUF_PREFIX = "proto:";
464
+ const PROTOBUF_SCHEMA_TYPE = "proto:FileDescriptorProto";
435
465
  /**
436
466
  * Build a non-struct data record as one flat object literal.
437
467
  * Struct records are built inline with the same field order plus `structName`.
@@ -461,6 +491,8 @@ var RecordDecoder = class {
461
491
  recordEntries = /* @__PURE__ */ new WeakMap();
462
492
  structDecodeQueue;
463
493
  structRegistry;
494
+ protobufRegistry = new ProtobufRegistry();
495
+ queuedProtobufs = /* @__PURE__ */ new Map();
464
496
  options;
465
497
  constructor(options) {
466
498
  this.options = options;
@@ -468,25 +500,30 @@ var RecordDecoder = class {
468
500
  for (const raw of queuedRecords) {
469
501
  const entry = this.recordEntries.get(raw);
470
502
  if (!entry) continue;
471
- const structName = entry.type.slice(7);
472
- if (entry.type.endsWith(STRUCT_ARRAY_SUFFIX)) {
473
- const payload = this.structRegistry.decodeArray(structName, raw.payload);
474
- if (typeof payload !== "string") this.delayedRecords.push({
475
- entry,
476
- timestamp: raw.timestamp,
477
- type: RecordType.StructArray,
478
- structName,
479
- payload
480
- });
481
- } else {
482
- const payload = this.structRegistry.decode(structName, raw.payload);
483
- if (typeof payload !== "string") this.delayedRecords.push({
484
- entry,
485
- timestamp: raw.timestamp,
486
- type: RecordType.Struct,
487
- structName,
488
- payload
489
- });
503
+ try {
504
+ const structName = entry.type.slice(7);
505
+ if (entry.type.endsWith(STRUCT_ARRAY_SUFFIX)) {
506
+ const payload = this.structRegistry.decodeArray(structName, raw.payload);
507
+ if (typeof payload !== "string") this.delayedRecords.push({
508
+ entry,
509
+ timestamp: raw.timestamp,
510
+ type: RecordType.StructArray,
511
+ structName,
512
+ payload
513
+ });
514
+ } else {
515
+ const payload = this.structRegistry.decode(structName, raw.payload);
516
+ if (typeof payload !== "string") this.delayedRecords.push({
517
+ entry,
518
+ timestamp: raw.timestamp,
519
+ type: RecordType.Struct,
520
+ structName,
521
+ payload
522
+ });
523
+ }
524
+ } catch (error) {
525
+ if (this.options.invalidValues !== "raw") throw error;
526
+ this.delayedRecords.push(dataRecord(entry, raw.timestamp, RecordType.Raw, new Uint8Array(raw.payload)));
490
527
  }
491
528
  }
492
529
  });
@@ -527,6 +564,14 @@ var RecordDecoder = class {
527
564
  if (this.options.strict) throw diagnostics.WPILOG_R0006({ entryId });
528
565
  return;
529
566
  }
567
+ if (this.options.invalidValues !== "raw") return this.decodeValue(entry, timestamp, bytes, view, payloadOffset, payloadSize);
568
+ try {
569
+ return this.decodeValue(entry, timestamp, bytes, view, payloadOffset, payloadSize);
570
+ } catch {
571
+ return dataRecord(entry, timestamp, RecordType.Raw, bytes.slice(payloadOffset, payloadOffset + payloadSize));
572
+ }
573
+ }
574
+ decodeValue(entry, timestamp, bytes, view, payloadOffset, payloadSize) {
530
575
  switch (entry.type) {
531
576
  case "boolean": return dataRecord(entry, timestamp, RecordType.Boolean, byteToBoolean(view.getUint8(payloadOffset)));
532
577
  case "int64": return dataRecord(entry, timestamp, RecordType.Int64, view.getBigInt64(payloadOffset, true));
@@ -534,8 +579,9 @@ var RecordDecoder = class {
534
579
  case "double": return dataRecord(entry, timestamp, RecordType.Double, view.getFloat64(payloadOffset, true));
535
580
  }
536
581
  const payload = payloadOffset === 0 && payloadSize === bytes.byteLength ? bytes : bytes.subarray(payloadOffset, payloadOffset + payloadSize);
582
+ if (entry.type.startsWith(PROTOBUF_PREFIX)) return this.decodeProtobuf(entry, timestamp, payload);
537
583
  const raw = {
538
- entryId,
584
+ entryId: entry.entryId,
539
585
  timestamp,
540
586
  payload
541
587
  };
@@ -543,6 +589,59 @@ var RecordDecoder = class {
543
589
  if (!decoded) this.recordEntries.set(raw, entry);
544
590
  return decoded;
545
591
  }
592
+ /** Register a `/.schema/proto:*` file descriptor, or decode a protobuf message, queuing it until its schema arrives */
593
+ decodeProtobuf(entry, timestamp, payload) {
594
+ if (entry.type === PROTOBUF_SCHEMA_TYPE) {
595
+ try {
596
+ this.protobufRegistry.register(payload);
597
+ } catch (cause) {
598
+ throw diagnostics.WPILOG_R0015({
599
+ name: entry.name,
600
+ cause
601
+ });
602
+ }
603
+ for (const [messageName, queued] of this.queuedProtobufs) {
604
+ if (!this.protobufRegistry.has(messageName)) continue;
605
+ this.queuedProtobufs.delete(messageName);
606
+ for (const record of queued) try {
607
+ this.delayedRecords.push(this.decodeProtobuf(record.entry, record.timestamp, record.payload));
608
+ } catch (error) {
609
+ if (this.options.invalidValues !== "raw") throw error;
610
+ this.delayedRecords.push(dataRecord(record.entry, record.timestamp, RecordType.Raw, new Uint8Array(record.payload)));
611
+ }
612
+ }
613
+ return dataRecord(entry, timestamp, RecordType.Raw, new Uint8Array(payload));
614
+ }
615
+ const messageName = entry.type.slice(6);
616
+ let decoded;
617
+ try {
618
+ decoded = this.protobufRegistry.decode(messageName, payload);
619
+ } catch (cause) {
620
+ throw diagnostics.WPILOG_R0016({
621
+ name: entry.name,
622
+ messageName,
623
+ cause
624
+ });
625
+ }
626
+ if (typeof decoded === "string") {
627
+ const queued = this.queuedProtobufs.get(messageName);
628
+ const record = {
629
+ entry,
630
+ timestamp,
631
+ payload
632
+ };
633
+ if (queued) queued.push(record);
634
+ else this.queuedProtobufs.set(messageName, [record]);
635
+ return;
636
+ }
637
+ return {
638
+ entry,
639
+ timestamp,
640
+ type: RecordType.Protobuf,
641
+ messageName,
642
+ payload: decoded
643
+ };
644
+ }
546
645
  };
547
646
  /**
548
647
  * Decode raw WPILOG records into typed values.
@@ -583,7 +682,7 @@ function parseDataLog(input, options = { strict: false }) {
583
682
  return withProgress(decodeCursorRecords(input, options, state), () => state.cursor?.offset ?? 0, () => state.cursor?.truncated ?? false);
584
683
  }
585
684
  function* decodeCursorRecords(input, options, state) {
586
- const cursor = new RecordCursor(input);
685
+ const cursor = RecordCursor.open(input);
587
686
  state.cursor = cursor;
588
687
  const decoder = new RecordDecoder(options);
589
688
  while (cursor.next()) {
@@ -709,4 +808,4 @@ function* catalogEntries(records) {
709
808
  }
710
809
  }
711
810
  }
712
- export { readRecords as a, isDataRecord as c, withStructDiagnostics as i, diagnostics as l, decodeRecords as n, ControlRecordType as o, parseDataLog as r, RecordType as s, catalogEntries as t };
811
+ export { withStructDiagnostics as a, readHeader as c, ControlRecordType as d, RecordType as f, parseDataLog as i, readRecords as l, diagnostics as m, RecordDecoder as n, RecordCursor as o, isDataRecord as p, decodeRecords as r, readControlRecordPayload as s, catalogEntries as t, truncatedHeaderError as u };
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as readRecords, l as diagnostics, t as catalogEntries } from "./catalog-DHvmiSNX.mjs";
2
+ import { l as readRecords, m as diagnostics, t as catalogEntries } from "./catalog-DZyefKH5.mjs";
3
3
  import { Diagnostic, formatDiagnostic } from "nostics";
4
4
  import { RootCommand, script } from "@bomb.sh/tab";
5
5
  import { boolean, command, commandsInfo, positional, run } from "@drizzle-team/brocli";
@@ -7,7 +7,7 @@ import oscStatus from "osc-status";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import { encode } from "@toon-format/toon";
9
9
  // package.json
10
- var version = "4.3.0";
10
+ var version = "4.4.1";
11
11
  var description = "Read WPILib wpilog data log files in TypeScript & JavaScript";
12
12
  // src/cli/catalog.ts
13
13
  async function catalogFile(filePath) {
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ProtobufPayload, ProtobufPayload as ProtobufPayload$1, ProtobufValue } from "wpilib-protobuf";
1
2
  import { EnumSpecification, KnownStructTypeName, StructDeclaration, StructPayload, StructPayload as StructPayload$1, StructSpecification, StructTypeName } from "wpilib-struct";
2
3
  /** The parsed WPILOG file header. */
3
4
  type DataLogHeader = {
@@ -67,6 +68,7 @@ export declare const RecordType: {
67
68
  readonly StringArray: 'string[]';
68
69
  readonly Struct: 'struct';
69
70
  readonly StructArray: 'struct[]';
71
+ readonly Protobuf: 'protobuf';
70
72
  readonly Raw: 'raw';
71
73
  };
72
74
  export type RecordType = (typeof RecordType)[keyof typeof RecordType];
@@ -138,6 +140,11 @@ type DecodedRecord = {
138
140
  type: typeof RecordType.StructArray;
139
141
  structName: string;
140
142
  payload: StructPayload$1[];
143
+ } | {
144
+ type: typeof RecordType.Protobuf;
145
+ /** The message's type, ex. `wpi.proto.ProtobufPose2d` for a `proto:wpi.proto.ProtobufPose2d` entry */
146
+ messageName: string;
147
+ payload: ProtobufPayload$1;
141
148
  })));
142
149
  /** A raw record or control record yielded by {@link readRecords}. */
143
150
  type ReadRecord = {
@@ -183,6 +190,14 @@ type DecodeRecordsOptions = {
183
190
  * such orphan records are silently skipped.
184
191
  */
185
192
  strict?: boolean;
193
+ /**
194
+ * What to do with a data record whose value can't be decoded for its entry's type, such as a struct value that
195
+ * doesn't match its schema, an invalid struct schema, or a boolean that isn't 0 or 1.
196
+ * `'throw'` (default) throws. `'raw'` yields it as a `raw` record holding its bytes and keeps reading, which suits
197
+ * apps that should show what they can of a log with a few bad values.
198
+ * Values whose struct schema is invalid wait for a valid one, like values whose schema hasn't been logged.
199
+ */
200
+ invalidValues?: 'throw' | 'raw';
186
201
  };
187
202
  /**
188
203
  * Decode raw WPILOG records into typed values.
@@ -202,6 +217,55 @@ export declare function decodeRecords(records: Iterable<ReadRecord>, options?: D
202
217
  * {@link decodeRecords} while preserving the same output and strict-mode behavior.
203
218
  */
204
219
  export declare function parseDataLog(input: DataLogInput, options?: DecodeRecordsOptions): DataLogGenerator<DecodedRecord>;
220
+ /**
221
+ * Read and decode a WPILOG file from chunks of its bytes as they arrive, such as a download, keeping only the bytes of
222
+ * a record split between chunks. Produces the same records as `parseDataLog`.
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * const parser = new DataLogStreamParser();
227
+ * for await (const chunk of response.body) {
228
+ * for (const record of parser.push(chunk)) {
229
+ * console.log(record);
230
+ * }
231
+ * }
232
+ * parser.end();
233
+ * ```
234
+ */
235
+ export declare class DataLogStreamParser {
236
+ private readonly decoder;
237
+ private buffer;
238
+ private view;
239
+ private cursor;
240
+ private discarded;
241
+ private fileHeader;
242
+ private readonly pending;
243
+ private pendingIndex;
244
+ private ended;
245
+ /** Accepts the same options as `parseDataLog` */
246
+ constructor(options?: DecodeRecordsOptions);
247
+ /** The file header, `undefined` until enough of the file has been pushed to read it */
248
+ get header(): DataLogHeader | undefined;
249
+ /** Bytes of the input read into the file header and decoded records, the rest is part of a record that isn't complete yet */
250
+ get bytesRead(): number;
251
+ /**
252
+ * Whether the input ended partway through a record, such as a log cut off by a power loss.
253
+ * The incomplete record is not yielded. This is `false` until {@link DataLogStreamParser.end} is called and every record has been read.
254
+ */
255
+ get truncated(): boolean;
256
+ /**
257
+ * Add the next chunk of the file and decode the records it completes.
258
+ * The chunk is copied, so it can be reused once this returns.
259
+ *
260
+ * Records left unread when iteration stops early are yielded by the next push.
261
+ * Throws while iterating if the file is damaged, the records before the damage have already been yielded.
262
+ */
263
+ push(chunk: Uint8Array): Generator<DecodedRecord>;
264
+ /** Signal the end of the file. Throws if it ended before the file header did. */
265
+ end(): void;
266
+ private records;
267
+ private drainPending;
268
+ }
205
269
  /**
206
270
  * A value for {@link DataLogWriter.append}. The entry's type decides which values are accepted:
207
271
  * `boolean`, `int64` (a `bigint` or safe integer `number`), `float`, `double`, `string`, their arrays,
@@ -280,4 +344,4 @@ export declare class DataLogWriter {
280
344
  export declare function catalogEntries(records: Iterable<ReadRecord>): Generator<CatalogEntry>;
281
345
  /** Parse a WPILib struct specification string into declarations. */
282
346
  export declare function parseStructSpecification(declaration: string): import("wpilib-struct").StructDeclaration[];
283
- export { type CatalogEntry, type ControlRecord, type ControlRecordPayload, type DataLogGenerator, type DataLogHeader, type DataLogInput, type DataLogValue, type DataLogWriterOptions, type DataRecord, type DecodeRecordsOptions, type DecodedRecord, type EnumSpecification, type FinishControlRecord, KnownStructTypeName, type RawRecord, type ReadRecord, type SetMetadataControlRecord, type StartControlRecord, type StructDeclaration, type StructPayload, type StructSpecification, type StructTypeName };
347
+ export { type CatalogEntry, type ControlRecord, type ControlRecordPayload, type DataLogGenerator, type DataLogHeader, type DataLogInput, type DataLogValue, type DataLogWriterOptions, type DataRecord, type DecodeRecordsOptions, type DecodedRecord, type EnumSpecification, type FinishControlRecord, KnownStructTypeName, type ProtobufPayload, type ProtobufValue, type RawRecord, type ReadRecord, type SetMetadataControlRecord, type StartControlRecord, type StructDeclaration, type StructPayload, type StructSpecification, type StructTypeName };
package/dist/index.mjs CHANGED
@@ -1,5 +1,118 @@
1
- import { a as readRecords, c as isDataRecord, i as withStructDiagnostics, l as diagnostics, n as decodeRecords, o as ControlRecordType, r as parseDataLog, s as RecordType, t as catalogEntries } from "./catalog-DHvmiSNX.mjs";
1
+ import { a as withStructDiagnostics, c as readHeader, d as ControlRecordType, f as RecordType, i as parseDataLog, l as readRecords, m as diagnostics, n as RecordDecoder, o as RecordCursor, p as isDataRecord, r as decodeRecords, s as readControlRecordPayload, t as catalogEntries, u as truncatedHeaderError } from "./catalog-DZyefKH5.mjs";
2
2
  import { KnownStructTypeName, StructRegistry, parseStructSpecification as parseStructSpecification$1 } from "wpilib-struct";
3
+ // src/data-log-stream-parser.ts
4
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
5
+ const MIN_BUFFER_SIZE = 65536;
6
+ /**
7
+ * Read and decode a WPILOG file from chunks of its bytes as they arrive, such as a download, keeping only the bytes of
8
+ * a record split between chunks. Produces the same records as `parseDataLog`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const parser = new DataLogStreamParser();
13
+ * for await (const chunk of response.body) {
14
+ * for (const record of parser.push(chunk)) {
15
+ * console.log(record);
16
+ * }
17
+ * }
18
+ * parser.end();
19
+ * ```
20
+ */
21
+ var DataLogStreamParser = class {
22
+ decoder;
23
+ buffer = EMPTY;
24
+ view = new DataView(EMPTY.buffer);
25
+ cursor = new RecordCursor(EMPTY, this.view, 0);
26
+ discarded = 0;
27
+ fileHeader;
28
+ pending = [];
29
+ pendingIndex = 0;
30
+ ended = false;
31
+ /** Accepts the same options as `parseDataLog` */
32
+ constructor(options = { strict: false }) {
33
+ this.decoder = new RecordDecoder(options);
34
+ }
35
+ /** The file header, `undefined` until enough of the file has been pushed to read it */
36
+ get header() {
37
+ return this.fileHeader;
38
+ }
39
+ /** Bytes of the input read into the file header and decoded records, the rest is part of a record that isn't complete yet */
40
+ get bytesRead() {
41
+ return this.discarded + this.cursor.offset;
42
+ }
43
+ /**
44
+ * Whether the input ended partway through a record, such as a log cut off by a power loss.
45
+ * The incomplete record is not yielded. This is `false` until {@link DataLogStreamParser.end} is called and every record has been read.
46
+ */
47
+ get truncated() {
48
+ return this.ended && this.cursor.offset < this.cursor.bytes.byteLength;
49
+ }
50
+ /**
51
+ * Add the next chunk of the file and decode the records it completes.
52
+ * The chunk is copied, so it can be reused once this returns.
53
+ *
54
+ * Records left unread when iteration stops early are yielded by the next push.
55
+ * Throws while iterating if the file is damaged, the records before the damage have already been yielded.
56
+ */
57
+ push(chunk) {
58
+ let { offset } = this.cursor;
59
+ let end = this.cursor.bytes.byteLength;
60
+ if (end + chunk.byteLength > this.buffer.byteLength) {
61
+ const rest = end - offset;
62
+ const buffer = new Uint8Array(Math.max(MIN_BUFFER_SIZE, 2 * rest + chunk.byteLength));
63
+ buffer.set(this.buffer.subarray(offset, end));
64
+ this.discarded += offset;
65
+ this.buffer = buffer;
66
+ this.view = new DataView(buffer.buffer);
67
+ offset = 0;
68
+ end = rest;
69
+ }
70
+ this.buffer.set(chunk, end);
71
+ this.cursor = new RecordCursor(this.buffer.subarray(0, end + chunk.byteLength), this.view, offset);
72
+ return this.records();
73
+ }
74
+ /** Signal the end of the file. Throws if it ended before the file header did. */
75
+ end() {
76
+ this.ended = true;
77
+ if (!this.fileHeader) throw truncatedHeaderError(this.cursor.bytes.byteLength);
78
+ }
79
+ *records() {
80
+ yield* this.drainPending();
81
+ const { cursor, decoder } = this;
82
+ if (!this.fileHeader) {
83
+ const opened = readHeader(cursor.bytes, cursor.view);
84
+ if (!opened) return;
85
+ this.fileHeader = opened.header;
86
+ cursor.offset = opened.recordsOffset;
87
+ }
88
+ while (true) {
89
+ const start = cursor.offset;
90
+ if (!cursor.next()) {
91
+ cursor.offset = start;
92
+ cursor.truncated = false;
93
+ return;
94
+ }
95
+ let decoded;
96
+ try {
97
+ decoded = cursor.entryId === 0 ? decoder.decodeControl(0, cursor.timestamp, readControlRecordPayload(cursor.getPayload())) : decoder.decodeData(cursor.entryId, cursor.timestamp, cursor.bytes, cursor.view, cursor.payloadOffset, cursor.payloadSize);
98
+ } catch (error) {
99
+ cursor.offset = start;
100
+ throw error;
101
+ }
102
+ if (decoder.delayedRecords.length > 0) {
103
+ this.pending.push(...decoder.delayedRecords);
104
+ decoder.delayedRecords.length = 0;
105
+ }
106
+ if (decoded) yield decoded;
107
+ if (this.pending.length > 0) yield* this.drainPending();
108
+ }
109
+ }
110
+ *drainPending() {
111
+ while (this.pendingIndex < this.pending.length) yield this.pending[this.pendingIndex++];
112
+ this.pending.length = 0;
113
+ this.pendingIndex = 0;
114
+ }
115
+ };
3
116
  // src/data-log-writer.ts
4
117
  const TEXT_ENCODER = new TextEncoder();
5
118
  const MAGIC = TEXT_ENCODER.encode("WPILOG");
@@ -330,4 +443,4 @@ var DataLogWriter = class {
330
443
  function parseStructSpecification(declaration) {
331
444
  return withStructDiagnostics(() => parseStructSpecification$1(declaration));
332
445
  }
333
- export { ControlRecordType, DataLogWriter, KnownStructTypeName, RecordType, catalogEntries, decodeRecords, isDataRecord, parseDataLog, parseStructSpecification, readRecords };
446
+ export { ControlRecordType, DataLogStreamParser, DataLogWriter, KnownStructTypeName, RecordType, catalogEntries, decodeRecords, isDataRecord, parseDataLog, parseStructSpecification, readRecords };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wpilog-parser",
3
- "version": "4.3.0",
3
+ "version": "4.4.1",
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",
@@ -35,12 +35,13 @@
35
35
  "@toon-format/toon": "^4.1.1",
36
36
  "nostics": "^1.3.0",
37
37
  "osc-status": "^1.0.0",
38
- "wpilib-struct": "^1.1.0"
38
+ "wpilib-protobuf": "^1.0.1",
39
+ "wpilib-struct": "^1.1.1"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@microsoft/api-extractor": "7.60.1",
42
- "vite-plus": "1.7.0",
43
- "vitest": "5.1.0"
43
+ "vite-plus": "1.8.0",
44
+ "vitest": "5.1.1"
44
45
  },
45
46
  "tsdocMetadata": "./dist/tsdoc-metadata.json",
46
47
  "scripts": {
@@ -55,6 +55,9 @@ for (const record of parseDataLog(bytes)) {
55
55
  }
56
56
  ```
57
57
 
58
+ Protobuf entries (types like `proto:wpi.proto.ProtobufPose2d`) are decoded the same way, as `RecordType.Protobuf` records with a `messageName` and the same field names as WPILib's structs.
59
+ Unset message fields are left out of protobuf payloads, so check for them before reading nested fields.
60
+
58
61
  ### Strict mode
59
62
 
60
63
  ```ts
@@ -63,6 +66,16 @@ for (const record of parseDataLog(bytes, { strict: true })) {
63
66
  }
64
67
  ```
65
68
 
69
+ ### Invalid values
70
+
71
+ Parsing throws on a value that can't be decoded, such as a struct or protobuf value that doesn't match its schema. To read the rest of the log anyway, yield those values as `raw` records:
72
+
73
+ ```ts
74
+ for (const record of parseDataLog(bytes, { invalidValues: 'raw' })) {
75
+ // record.type is 'raw' for values that couldn't be decoded
76
+ }
77
+ ```
78
+
66
79
  ## Robot state cheatsheet
67
80
 
68
81
  When DriverStation logging is on, every WPILOG has these `boolean` entries: