wpilog-parser 4.2.1 → 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
@@ -1,6 +1,6 @@
1
1
  # wpilog-parser
2
2
 
3
- Read [WPILib data log (`.wpilog`)](https://docs.wpilib.org/en/stable/docs/software/telemetry/datalog.html) files in TypeScript & JavaScript.
3
+ Read and write [WPILib data log (`.wpilog`)](https://docs.wpilib.org/en/stable/docs/software/telemetry/datalog.html) files in TypeScript & JavaScript.
4
4
 
5
5
  ## Install
6
6
 
@@ -28,6 +28,65 @@ 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
+
55
+ ### Writing logs
56
+
57
+ ```ts
58
+ import { createWriteStream } from 'node:fs';
59
+ import { Writable } from 'node:stream';
60
+ import { DataLogWriter } from 'wpilog-parser';
61
+
62
+ const writer = new DataLogWriter();
63
+ const done = writer.readable.pipeTo(Writable.toWeb(createWriteStream('./example.wpilog')));
64
+
65
+ const speed = writer.start('/drive/speed', 'double');
66
+ writer.addStructSchema('Translation2d', 'double x;double y');
67
+ writer.addStructSchema('Rotation2d', 'double value');
68
+ writer.addStructSchema('Pose2d', 'Translation2d translation;Rotation2d rotation');
69
+ const pose = writer.start('/drive/pose', 'struct:Pose2d');
70
+
71
+ writer.append(speed, 1.5, 20_000);
72
+ writer.append(pose, { translation: { x: 1, y: 2 }, rotation: { value: 0.5 } }, 20_000);
73
+
74
+ writer.close();
75
+ await done;
76
+ ```
77
+
78
+ `append()` encodes a value for the entry's type. It accepts the same payloads that `parseDataLog()` returns, and `int64` values can also be safe integer numbers. Other types, such as `raw`, take a `Uint8Array`.
79
+ Add every struct schema an entry uses, including nested ones, with `addStructSchema()` before appending to the entry.
80
+
81
+ Timestamps are integer microseconds. When a timestamp is omitted, the writer uses a monotonic clock counting from the JavaScript time origin.
82
+
83
+ `writer.readable` is a `ReadableStream` of the log's bytes, so it can be piped to any `WritableStream`, such as a file from the browser's File System API, or through a `CompressionStream`. Records are buffered in memory until the stream reads them, and the stream ends after `close()`. To build a log in memory, close the writer and read the whole stream:
84
+
85
+ ```ts
86
+ writer.close();
87
+ const bytes = new Uint8Array(await new Response(writer.readable).arrayBuffer());
88
+ ```
89
+
31
90
  A summary of the full API is available in [wpilog-parser.api.md](https://github.com/jonahsnider/wpilog-parser/blob/main/packages/wpilog-parser/etc/wpilog-parser.api.md).
32
91
 
33
92
  ## CLI
@@ -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 {
@@ -88,6 +89,30 @@ const diagnostics = defineDiagnostics({ codes: {
88
89
  WPILOG_R0013: {
89
90
  why: (p) => `Unknown struct definition: ${p.name}`,
90
91
  fix: "Register the struct definition before decoding its records."
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
+ },
101
+ WPILOG_W0001: {
102
+ why: (p) => `Entry ID ${p.entryId} is not started`,
103
+ fix: "Use an ID returned by start() for an entry that has not been finished."
104
+ },
105
+ WPILOG_W0002: {
106
+ why: (p) => `Entry ${p.name} is already started`,
107
+ fix: "Reuse the existing entry ID, or finish the entry before starting it again."
108
+ },
109
+ WPILOG_W0003: {
110
+ why: (p) => `Missing struct schema ${p.name} for entry ${p.entry}`,
111
+ fix: (p) => `Add the ${p.name} schema with addStructSchema() before appending values.`
112
+ },
113
+ WPILOG_W0004: {
114
+ why: "The writer is closed",
115
+ fix: "Write every record before calling close() or cancelling the readable stream."
91
116
  }
92
117
  } });
93
118
  // src/types.ts
@@ -112,6 +137,7 @@ const RecordType = {
112
137
  StringArray: "string[]",
113
138
  Struct: "struct",
114
139
  StructArray: "struct[]",
140
+ Protobuf: "protobuf",
115
141
  Raw: "raw"
116
142
  };
117
143
  /** Type guard that narrows a {@link DecodedRecord} to a {@link DataRecord}. */
@@ -170,16 +196,16 @@ function toUint8Array(input) {
170
196
  if (input instanceof Uint8Array) return input;
171
197
  return new Uint8Array(input);
172
198
  }
173
- function openDataLog(input) {
174
- const bytes = toUint8Array(input);
175
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
176
- 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;
177
205
  for (let i = 0; i < MAGIC.byteLength; i++) if (bytes[i] !== MAGIC[i]) throw diagnostics.WPILOG_R0003();
178
206
  const recordsOffset = 12 + view.getUint32(8, true);
179
- if (recordsOffset > bytes.byteLength) throw diagnostics.WPILOG_R0004();
207
+ if (recordsOffset > bytes.byteLength) return;
180
208
  return {
181
- bytes,
182
- view,
183
209
  header: {
184
210
  version: {
185
211
  major: view.getUint8(7),
@@ -190,6 +216,21 @@ function openDataLog(input) {
190
216
  recordsOffset
191
217
  };
192
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
+ }
193
234
  function readVarInt(view, offset, length) {
194
235
  switch (length) {
195
236
  case 1: return view.getUint8(offset);
@@ -212,11 +253,10 @@ function readTimestamp(view, offset, length) {
212
253
  default: throw new RangeError(`Invalid timestamp length ${length}`);
213
254
  }
214
255
  }
215
- /** Mutable record cursor used by the fused decoder to avoid intermediate record allocations. */
216
- var RecordCursor = class {
256
+ /** Mutable record cursor used by the fused and streaming decoders to avoid intermediate record allocations. */
257
+ var RecordCursor = class RecordCursor {
217
258
  bytes;
218
259
  view;
219
- header;
220
260
  entryId = 0;
221
261
  timestamp = 0;
222
262
  payloadOffset = 0;
@@ -225,12 +265,16 @@ var RecordCursor = class {
225
265
  offset;
226
266
  /** Whether the input ended partway through a record. */
227
267
  truncated = false;
228
- constructor(input) {
229
- const source = openDataLog(input);
230
- this.bytes = source.bytes;
231
- this.view = source.view;
232
- this.header = source.header;
233
- 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;
234
278
  }
235
279
  next() {
236
280
  const total = this.bytes.byteLength;
@@ -416,6 +460,8 @@ const TEXT_DECODER = new TextDecoder();
416
460
  const STRUCT_PREFIX = "struct:";
417
461
  const STRUCT_ARRAY_SUFFIX = "[]";
418
462
  const STRUCT_SCHEMA_NAME_PREFIX = "/.schema/struct:";
463
+ const PROTOBUF_PREFIX = "proto:";
464
+ const PROTOBUF_SCHEMA_TYPE = "proto:FileDescriptorProto";
419
465
  /**
420
466
  * Build a non-struct data record as one flat object literal.
421
467
  * Struct records are built inline with the same field order plus `structName`.
@@ -445,6 +491,8 @@ var RecordDecoder = class {
445
491
  recordEntries = /* @__PURE__ */ new WeakMap();
446
492
  structDecodeQueue;
447
493
  structRegistry;
494
+ protobufRegistry = new ProtobufRegistry();
495
+ queuedProtobufs = /* @__PURE__ */ new Map();
448
496
  options;
449
497
  constructor(options) {
450
498
  this.options = options;
@@ -452,25 +500,30 @@ var RecordDecoder = class {
452
500
  for (const raw of queuedRecords) {
453
501
  const entry = this.recordEntries.get(raw);
454
502
  if (!entry) continue;
455
- const structName = entry.type.slice(7);
456
- if (entry.type.endsWith(STRUCT_ARRAY_SUFFIX)) {
457
- const payload = this.structRegistry.decodeArray(structName, raw.payload);
458
- if (typeof payload !== "string") this.delayedRecords.push({
459
- entry,
460
- timestamp: raw.timestamp,
461
- type: RecordType.StructArray,
462
- structName,
463
- payload
464
- });
465
- } else {
466
- const payload = this.structRegistry.decode(structName, raw.payload);
467
- if (typeof payload !== "string") this.delayedRecords.push({
468
- entry,
469
- timestamp: raw.timestamp,
470
- type: RecordType.Struct,
471
- structName,
472
- payload
473
- });
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)));
474
527
  }
475
528
  }
476
529
  });
@@ -511,6 +564,14 @@ var RecordDecoder = class {
511
564
  if (this.options.strict) throw diagnostics.WPILOG_R0006({ entryId });
512
565
  return;
513
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) {
514
575
  switch (entry.type) {
515
576
  case "boolean": return dataRecord(entry, timestamp, RecordType.Boolean, byteToBoolean(view.getUint8(payloadOffset)));
516
577
  case "int64": return dataRecord(entry, timestamp, RecordType.Int64, view.getBigInt64(payloadOffset, true));
@@ -518,8 +579,9 @@ var RecordDecoder = class {
518
579
  case "double": return dataRecord(entry, timestamp, RecordType.Double, view.getFloat64(payloadOffset, true));
519
580
  }
520
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);
521
583
  const raw = {
522
- entryId,
584
+ entryId: entry.entryId,
523
585
  timestamp,
524
586
  payload
525
587
  };
@@ -527,6 +589,59 @@ var RecordDecoder = class {
527
589
  if (!decoded) this.recordEntries.set(raw, entry);
528
590
  return decoded;
529
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
+ }
530
645
  };
531
646
  /**
532
647
  * Decode raw WPILOG records into typed values.
@@ -567,7 +682,7 @@ function parseDataLog(input, options = { strict: false }) {
567
682
  return withProgress(decodeCursorRecords(input, options, state), () => state.cursor?.offset ?? 0, () => state.cursor?.truncated ?? false);
568
683
  }
569
684
  function* decodeCursorRecords(input, options, state) {
570
- const cursor = new RecordCursor(input);
685
+ const cursor = RecordCursor.open(input);
571
686
  state.cursor = cursor;
572
687
  const decoder = new RecordDecoder(options);
573
688
  while (cursor.next()) {
@@ -693,4 +808,4 @@ function* catalogEntries(records) {
693
808
  }
694
809
  }
695
810
  }
696
- 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-BP1qf30c.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.2.1";
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,123 @@ 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
+ }
269
+ /**
270
+ * A value for {@link DataLogWriter.append}. The entry's type decides which values are accepted:
271
+ * `boolean`, `int64` (a `bigint` or safe integer `number`), `float`, `double`, `string`, their arrays,
272
+ * `struct:Name` (a {@link StructPayload}), `struct:Name[]`, and `Uint8Array` for any other type, such as `raw`.
273
+ */
274
+ type DataLogValue = boolean | number | bigint | string | readonly boolean[] | readonly (number | bigint)[] | readonly string[] | StructPayload | readonly StructPayload[] | Uint8Array;
275
+ /** Options for {@link DataLogWriter}. */
276
+ type DataLogWriterOptions = {
277
+ /** Arbitrary text stored in the file header. Defaults to an empty string. */
278
+ extraHeader?: string;
279
+ };
280
+ /**
281
+ * Write a WPILOG file incrementally.
282
+ *
283
+ * Records are buffered in memory until {@link DataLogWriter.readable} is read, so a log can be streamed to a file
284
+ * while it is written, or built in memory and read once. Timestamps are integer microseconds. When omitted, they
285
+ * come from a monotonic clock that counts from the JavaScript time origin.
286
+ *
287
+ * Every method writes a complete record or, if it throws, nothing.
288
+ */
289
+ export declare class DataLogWriter {
290
+ /**
291
+ * The log's bytes, starting with the file header. Each read returns every record written since the previous read,
292
+ * waiting for the next record if there are none. The stream ends after {@link DataLogWriter.close}.
293
+ * Cancelling it closes the writer and discards unread records.
294
+ */
295
+ readonly readable: ReadableStream<Uint8Array>;
296
+ private bytes;
297
+ private view;
298
+ private length;
299
+ private closed;
300
+ /** Resolves a read that is waiting for the next record. */
301
+ private wake?;
302
+ private nextEntryId;
303
+ private readonly entries;
304
+ private readonly entryIds;
305
+ private readonly structs;
306
+ private readonly schemas;
307
+ constructor(options?: DataLogWriterOptions);
308
+ /** Stop writing. {@link DataLogWriter.readable} ends once its remaining records are read. */
309
+ close(): void;
310
+ /**
311
+ * Start an entry and return its ID. Entry IDs are never reused, even after an entry is finished.
312
+ * Data for `struct:` entries can only be appended once {@link DataLogWriter.addStructSchema} has added its schemas.
313
+ */
314
+ start(name: string, type: string, metadata?: string, timestamp?: number): number;
315
+ /** Finish an entry. Its ID cannot be used afterward, and its name can be started again. */
316
+ finish(entryId: number, timestamp?: number): void;
317
+ /** Replace an entry's metadata. */
318
+ setMetadata(entryId: number, metadata: string, timestamp?: number): void;
319
+ /**
320
+ * Add a struct schema, such as `addStructSchema('Translation2d', 'double x;double y')`, in a
321
+ * `/.schema/struct:Name` entry. Add the schemas of nested structs too. Adding the same schema again does nothing.
322
+ */
323
+ addStructSchema(name: string, schema: string, timestamp?: number): void;
324
+ /** Append a value to an entry, encoded according to the entry's type. See {@link DataLogValue}. */
325
+ append(entryId: number, value: DataLogValue, timestamp?: number): void;
326
+ private appendStruct;
327
+ private appendBytes;
328
+ private getEntry;
329
+ /**
330
+ * Write a record header after the committed bytes and return the payload's offset. The record is committed by
331
+ * setting `length` to the payload's end, so a record that throws while its payload is written is discarded.
332
+ */
333
+ private beginRecord;
334
+ private writeString;
335
+ private ensureCapacity;
336
+ }
205
337
  /**
206
338
  * Collect all entry definitions from a WPILOG record stream.
207
339
  *
@@ -212,4 +344,4 @@ export declare function parseDataLog(input: DataLogInput, options?: DecodeRecord
212
344
  export declare function catalogEntries(records: Iterable<ReadRecord>): Generator<CatalogEntry>;
213
345
  /** Parse a WPILib struct specification string into declarations. */
214
346
  export declare function parseStructSpecification(declaration: string): import("wpilib-struct").StructDeclaration[];
215
- export { type CatalogEntry, type ControlRecord, type ControlRecordPayload, type DataLogGenerator, type DataLogHeader, type DataLogInput, 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,8 +1,446 @@
1
- import { a as readRecords, c as isDataRecord, i as withStructDiagnostics, n as decodeRecords, o as ControlRecordType, r as parseDataLog, s as RecordType, t as catalogEntries } from "./catalog-BP1qf30c.mjs";
2
- import { KnownStructTypeName, parseStructSpecification as parseStructSpecification$1 } from "wpilib-struct";
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
+ 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
+ };
116
+ // src/data-log-writer.ts
117
+ const TEXT_ENCODER = new TextEncoder();
118
+ const MAGIC = TEXT_ENCODER.encode("WPILOG");
119
+ const STRUCT_PREFIX = "struct:";
120
+ const STRUCT_ARRAY_SUFFIX = "[]";
121
+ const STRUCT_SCHEMA_NAME_PREFIX = "/.schema/struct:";
122
+ const MAX_UINT32 = 4294967295;
123
+ const MIN_INT64 = -(2n ** 63n);
124
+ const MAX_INT64 = 2n ** 63n - 1n;
125
+ /** Microseconds since the JavaScript time origin, from a monotonic clock. */
126
+ function now() {
127
+ return Math.trunc(performance.now() * 1e3);
128
+ }
129
+ function uintByteLength(value) {
130
+ let length = 1;
131
+ while (value >= 2 ** (8 * length)) length++;
132
+ return length;
133
+ }
134
+ function writeUint(bytes, at, value, length) {
135
+ for (let i = 0; i < length; i++) {
136
+ bytes[at + i] = value % 256;
137
+ value = Math.floor(value / 256);
138
+ }
139
+ return at + length;
140
+ }
141
+ function describe(entry) {
142
+ return `${entry.name} (${entry.type})`;
143
+ }
144
+ function toArray(value, entry) {
145
+ if (!Array.isArray(value)) throw new TypeError(`Expected an array for ${describe(entry)}`);
146
+ return value;
147
+ }
148
+ function toBoolean(value, entry) {
149
+ if (typeof value !== "boolean") throw new TypeError(`Expected a boolean for ${describe(entry)}`);
150
+ return value;
151
+ }
152
+ function toNumber(value, entry) {
153
+ if (typeof value !== "number") throw new TypeError(`Expected a number for ${describe(entry)}`);
154
+ return value;
155
+ }
156
+ function toString(value, entry) {
157
+ if (typeof value !== "string") throw new TypeError(`Expected a string for ${describe(entry)}`);
158
+ return value;
159
+ }
160
+ function toInt64(value, entry) {
161
+ if (typeof value === "number") {
162
+ if (!Number.isSafeInteger(value)) throw new TypeError(`Expected a safe integer or bigint for ${describe(entry)}`);
163
+ return BigInt(value);
164
+ }
165
+ if (typeof value !== "bigint") throw new TypeError(`Expected an integer for ${describe(entry)}`);
166
+ if (value < MIN_INT64 || value > MAX_INT64) throw new RangeError(`${describe(entry)} must fit in an int64`);
167
+ return value;
168
+ }
169
+ /**
170
+ * Write a WPILOG file incrementally.
171
+ *
172
+ * Records are buffered in memory until {@link DataLogWriter.readable} is read, so a log can be streamed to a file
173
+ * while it is written, or built in memory and read once. Timestamps are integer microseconds. When omitted, they
174
+ * come from a monotonic clock that counts from the JavaScript time origin.
175
+ *
176
+ * Every method writes a complete record or, if it throws, nothing.
177
+ */
178
+ var DataLogWriter = class {
179
+ /**
180
+ * The log's bytes, starting with the file header. Each read returns every record written since the previous read,
181
+ * waiting for the next record if there are none. The stream ends after {@link DataLogWriter.close}.
182
+ * Cancelling it closes the writer and discards unread records.
183
+ */
184
+ readable;
185
+ bytes = /* @__PURE__ */ new Uint8Array(4096);
186
+ view = new DataView(this.bytes.buffer);
187
+ length = 0;
188
+ closed = false;
189
+ /** Resolves a read that is waiting for the next record. */
190
+ wake;
191
+ nextEntryId = 1;
192
+ entries = /* @__PURE__ */ new Map();
193
+ entryIds = /* @__PURE__ */ new Map();
194
+ structs = new StructRegistry();
195
+ schemas = /* @__PURE__ */ new Map();
196
+ constructor(options = {}) {
197
+ const extraHeader = TEXT_ENCODER.encode(options.extraHeader ?? "");
198
+ this.ensureCapacity(12 + extraHeader.byteLength);
199
+ this.bytes.set(MAGIC);
200
+ this.view.setUint16(6, 256, true);
201
+ this.view.setUint32(8, extraHeader.byteLength, true);
202
+ this.bytes.set(extraHeader, 12);
203
+ this.length = 12 + extraHeader.byteLength;
204
+ this.readable = new ReadableStream({
205
+ pull: async (controller) => {
206
+ while (this.length === 0 && !this.closed) await new Promise((resolve) => this.wake = resolve);
207
+ if (this.length > 0) {
208
+ controller.enqueue(this.bytes.slice(0, this.length));
209
+ this.length = 0;
210
+ }
211
+ if (this.closed) controller.close();
212
+ },
213
+ cancel: () => {
214
+ this.closed = true;
215
+ this.length = 0;
216
+ }
217
+ }, { highWaterMark: 0 });
218
+ }
219
+ /** Stop writing. {@link DataLogWriter.readable} ends once its remaining records are read. */
220
+ close() {
221
+ if (this.closed) return;
222
+ this.closed = true;
223
+ this.wake?.();
224
+ }
225
+ /**
226
+ * Start an entry and return its ID. Entry IDs are never reused, even after an entry is finished.
227
+ * Data for `struct:` entries can only be appended once {@link DataLogWriter.addStructSchema} has added its schemas.
228
+ */
229
+ start(name, type, metadata = "", timestamp = now()) {
230
+ if (this.entryIds.has(name)) throw diagnostics.WPILOG_W0002({ name });
231
+ const entryId = this.nextEntryId;
232
+ if (entryId > MAX_UINT32) throw new RangeError("A log cannot have more than 4,294,967,295 entries");
233
+ let structName;
234
+ if (type === "structschema") {
235
+ const prefixIndex = name.indexOf(STRUCT_SCHEMA_NAME_PREFIX);
236
+ if (prefixIndex === -1) throw new TypeError(`structschema entry names must contain ${STRUCT_SCHEMA_NAME_PREFIX}<name>`);
237
+ structName = name.slice(prefixIndex + 16);
238
+ } else if (type.startsWith(STRUCT_PREFIX)) {
239
+ structName = type.slice(7);
240
+ if (structName.endsWith(STRUCT_ARRAY_SUFFIX)) structName = structName.slice(0, -2);
241
+ }
242
+ const encodedName = TEXT_ENCODER.encode(name);
243
+ const encodedType = TEXT_ENCODER.encode(type);
244
+ const encodedMetadata = TEXT_ENCODER.encode(metadata);
245
+ let at = this.beginRecord(0, timestamp, 17 + encodedName.byteLength + encodedType.byteLength + encodedMetadata.byteLength);
246
+ this.bytes[at++] = ControlRecordType.Start;
247
+ this.view.setUint32(at, entryId, true);
248
+ at = this.writeString(at + 4, encodedName);
249
+ at = this.writeString(at, encodedType);
250
+ this.length = this.writeString(at, encodedMetadata);
251
+ this.nextEntryId++;
252
+ this.entries.set(entryId, {
253
+ name,
254
+ type,
255
+ structName
256
+ });
257
+ this.entryIds.set(name, entryId);
258
+ return entryId;
259
+ }
260
+ /** Finish an entry. Its ID cannot be used afterward, and its name can be started again. */
261
+ finish(entryId, timestamp = now()) {
262
+ const entry = this.getEntry(entryId);
263
+ const at = this.beginRecord(0, timestamp, 5);
264
+ this.bytes[at] = ControlRecordType.Finish;
265
+ this.view.setUint32(at + 1, entryId, true);
266
+ this.length = at + 5;
267
+ this.entries.delete(entryId);
268
+ this.entryIds.delete(entry.name);
269
+ }
270
+ /** Replace an entry's metadata. */
271
+ setMetadata(entryId, metadata, timestamp = now()) {
272
+ this.getEntry(entryId);
273
+ const encoded = TEXT_ENCODER.encode(metadata);
274
+ const at = this.beginRecord(0, timestamp, 9 + encoded.byteLength);
275
+ this.bytes[at] = ControlRecordType.SetMetadata;
276
+ this.view.setUint32(at + 1, entryId, true);
277
+ this.length = this.writeString(at + 5, encoded);
278
+ }
279
+ /**
280
+ * Add a struct schema, such as `addStructSchema('Translation2d', 'double x;double y')`, in a
281
+ * `/.schema/struct:Name` entry. Add the schemas of nested structs too. Adding the same schema again does nothing.
282
+ */
283
+ addStructSchema(name, schema, timestamp = now()) {
284
+ if (this.schemas.get(name) === schema) return;
285
+ const entryName = STRUCT_SCHEMA_NAME_PREFIX + name;
286
+ const entryId = this.entryIds.get(entryName) ?? this.start(entryName, "structschema", "", timestamp);
287
+ this.append(entryId, schema, timestamp);
288
+ }
289
+ /** Append a value to an entry, encoded according to the entry's type. See {@link DataLogValue}. */
290
+ append(entryId, value, timestamp = now()) {
291
+ const entry = this.getEntry(entryId);
292
+ switch (entry.type) {
293
+ case "boolean": {
294
+ const at = this.beginRecord(entryId, timestamp, 1);
295
+ this.bytes[at] = toBoolean(value, entry) ? 1 : 0;
296
+ this.length = at + 1;
297
+ return;
298
+ }
299
+ case "int64": {
300
+ const at = this.beginRecord(entryId, timestamp, 8);
301
+ this.view.setBigInt64(at, toInt64(value, entry), true);
302
+ this.length = at + 8;
303
+ return;
304
+ }
305
+ case "float": {
306
+ const at = this.beginRecord(entryId, timestamp, 4);
307
+ this.view.setFloat32(at, toNumber(value, entry), true);
308
+ this.length = at + 4;
309
+ return;
310
+ }
311
+ case "double": {
312
+ const at = this.beginRecord(entryId, timestamp, 8);
313
+ this.view.setFloat64(at, toNumber(value, entry), true);
314
+ this.length = at + 8;
315
+ return;
316
+ }
317
+ case "string":
318
+ this.appendBytes(entryId, timestamp, TEXT_ENCODER.encode(toString(value, entry)));
319
+ return;
320
+ case "structschema": {
321
+ const schema = toString(value, entry);
322
+ const encoded = TEXT_ENCODER.encode(schema);
323
+ const at = this.beginRecord(entryId, timestamp, encoded.byteLength);
324
+ withStructDiagnostics(() => this.structs.register(entry.structName, schema));
325
+ this.schemas.set(entry.structName, schema);
326
+ this.bytes.set(encoded, at);
327
+ this.length = at + encoded.byteLength;
328
+ return;
329
+ }
330
+ case "boolean[]": {
331
+ const values = toArray(value, entry);
332
+ const at = this.beginRecord(entryId, timestamp, values.length);
333
+ for (let i = 0; i < values.length; i++) this.bytes[at + i] = toBoolean(values[i], entry) ? 1 : 0;
334
+ this.length = at + values.length;
335
+ return;
336
+ }
337
+ case "int64[]": {
338
+ const values = toArray(value, entry);
339
+ const at = this.beginRecord(entryId, timestamp, values.length * 8);
340
+ for (let i = 0; i < values.length; i++) this.view.setBigInt64(at + i * 8, toInt64(values[i], entry), true);
341
+ this.length = at + values.length * 8;
342
+ return;
343
+ }
344
+ case "float[]": {
345
+ const values = toArray(value, entry);
346
+ const at = this.beginRecord(entryId, timestamp, values.length * 4);
347
+ for (let i = 0; i < values.length; i++) this.view.setFloat32(at + i * 4, toNumber(values[i], entry), true);
348
+ this.length = at + values.length * 4;
349
+ return;
350
+ }
351
+ case "double[]": {
352
+ const values = toArray(value, entry);
353
+ const at = this.beginRecord(entryId, timestamp, values.length * 8);
354
+ for (let i = 0; i < values.length; i++) this.view.setFloat64(at + i * 8, toNumber(values[i], entry), true);
355
+ this.length = at + values.length * 8;
356
+ return;
357
+ }
358
+ case "string[]": {
359
+ const strings = toArray(value, entry).map((string) => TEXT_ENCODER.encode(toString(string, entry)));
360
+ let at = this.beginRecord(entryId, timestamp, strings.reduce((size, string) => size + 4 + string.byteLength, 4));
361
+ this.view.setUint32(at, strings.length, true);
362
+ at += 4;
363
+ for (const string of strings) at = this.writeString(at, string);
364
+ this.length = at;
365
+ return;
366
+ }
367
+ }
368
+ if (entry.structName !== void 0) {
369
+ this.appendStruct(entryId, entry, value, timestamp);
370
+ return;
371
+ }
372
+ if (!(value instanceof Uint8Array)) throw new TypeError(`Expected a Uint8Array for ${describe(entry)}`);
373
+ this.appendBytes(entryId, timestamp, value);
374
+ }
375
+ appendStruct(entryId, entry, value, timestamp) {
376
+ const structName = entry.structName;
377
+ const byteLength = this.structs.getByteLength(structName);
378
+ if (typeof byteLength === "string") throw diagnostics.WPILOG_W0003({
379
+ name: byteLength,
380
+ entry: entry.name
381
+ });
382
+ if (!entry.type.endsWith(STRUCT_ARRAY_SUFFIX)) {
383
+ const at = this.beginRecord(entryId, timestamp, byteLength);
384
+ this.structs.encodeInto(structName, value, this.bytes, at);
385
+ this.length = at + byteLength;
386
+ return;
387
+ }
388
+ const values = toArray(value, entry);
389
+ if (byteLength === 0 && values.length > 0) throw new RangeError("Cannot encode an array of zero-length structs");
390
+ const at = this.beginRecord(entryId, timestamp, values.length * byteLength);
391
+ for (let i = 0; i < values.length; i++) this.structs.encodeInto(structName, values[i], this.bytes, at + i * byteLength);
392
+ this.length = at + values.length * byteLength;
393
+ }
394
+ appendBytes(entryId, timestamp, payload) {
395
+ const at = this.beginRecord(entryId, timestamp, payload.byteLength);
396
+ this.bytes.set(payload, at);
397
+ this.length = at + payload.byteLength;
398
+ }
399
+ getEntry(entryId) {
400
+ const entry = this.entries.get(entryId);
401
+ if (!entry) throw diagnostics.WPILOG_W0001({ entryId });
402
+ return entry;
403
+ }
404
+ /**
405
+ * Write a record header after the committed bytes and return the payload's offset. The record is committed by
406
+ * setting `length` to the payload's end, so a record that throws while its payload is written is discarded.
407
+ */
408
+ beginRecord(entryId, timestamp, payloadSize) {
409
+ if (this.closed) throw diagnostics.WPILOG_W0004();
410
+ this.wake?.();
411
+ if (!Number.isSafeInteger(timestamp)) throw new TypeError("Timestamps must be safe integers in microseconds");
412
+ if (payloadSize > MAX_UINT32) throw new RangeError("Record payloads must be smaller than 4 GiB");
413
+ const entryIdLength = uintByteLength(entryId);
414
+ const payloadSizeLength = uintByteLength(payloadSize);
415
+ const timestampLength = timestamp < 0 ? 8 : uintByteLength(timestamp);
416
+ let at = this.length;
417
+ this.ensureCapacity(at + 1 + entryIdLength + payloadSizeLength + timestampLength + payloadSize);
418
+ const bytes = this.bytes;
419
+ bytes[at++] = entryIdLength - 1 | payloadSizeLength - 1 << 2 | timestampLength - 1 << 4;
420
+ at = writeUint(bytes, at, entryId, entryIdLength);
421
+ at = writeUint(bytes, at, payloadSize, payloadSizeLength);
422
+ if (timestamp < 0) {
423
+ this.view.setBigInt64(at, BigInt(timestamp), true);
424
+ return at + 8;
425
+ }
426
+ return writeUint(bytes, at, timestamp, timestampLength);
427
+ }
428
+ writeString(at, encoded) {
429
+ this.view.setUint32(at, encoded.byteLength, true);
430
+ this.bytes.set(encoded, at + 4);
431
+ return at + 4 + encoded.byteLength;
432
+ }
433
+ ensureCapacity(byteLength) {
434
+ if (byteLength <= this.bytes.byteLength) return;
435
+ const bytes = new Uint8Array(Math.max(byteLength, this.bytes.byteLength * 2));
436
+ bytes.set(this.bytes.subarray(0, this.length));
437
+ this.bytes = bytes;
438
+ this.view = new DataView(bytes.buffer);
439
+ }
440
+ };
3
441
  // src/struct/parse-struct.ts
4
442
  /** Parse a WPILib struct specification string into declarations. */
5
443
  function parseStructSpecification(declaration) {
6
444
  return withStructDiagnostics(() => parseStructSpecification$1(declaration));
7
445
  }
8
- export { ControlRecordType, 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.2.1",
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.0.2"
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: