@netkitty/codec 2.1.0 → 2.3.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.
Files changed (83) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/README.md +30 -1
  3. package/README.zh-CN.md +26 -1
  4. package/dist/Codec.d.ts +25 -7
  5. package/dist/Codec.js +151 -18
  6. package/dist/PacketHeaders.d.ts +2 -0
  7. package/dist/PacketHeaders.js +8 -4
  8. package/dist/abstracts/BaseHeader.d.ts +34 -0
  9. package/dist/abstracts/BaseHeader.js +43 -0
  10. package/dist/headers/ARP.d.ts +3 -1
  11. package/dist/headers/ARP.js +8 -1
  12. package/dist/headers/BACnetIP.js +2 -1
  13. package/dist/headers/BGP.js +3 -2
  14. package/dist/headers/Babel.js +1 -1
  15. package/dist/headers/Codesys.js +3 -2
  16. package/dist/headers/DHCP.js +2 -1
  17. package/dist/headers/DNP3.d.ts +12 -7
  18. package/dist/headers/DNP3.js +98 -18
  19. package/dist/headers/DTLS.js +5 -3
  20. package/dist/headers/Diameter.js +2 -1
  21. package/dist/headers/Elasticsearch.js +3 -2
  22. package/dist/headers/EthernetII.d.ts +1 -0
  23. package/dist/headers/EthernetII.js +3 -0
  24. package/dist/headers/Goose.d.ts +31 -7
  25. package/dist/headers/Goose.js +409 -168
  26. package/dist/headers/HARTIP.js +2 -2
  27. package/dist/headers/ICMP.d.ts +1 -0
  28. package/dist/headers/ICMP.js +9 -1
  29. package/dist/headers/ICMPv6.d.ts +1 -0
  30. package/dist/headers/ICMPv6.js +1 -0
  31. package/dist/headers/IEC104_I_Frame.d.ts +28 -0
  32. package/dist/headers/IEC104_I_Frame.js +246 -160
  33. package/dist/headers/IEC104_S_Frame.js +3 -3
  34. package/dist/headers/IEC104_U_Frame.js +5 -3
  35. package/dist/headers/IEC61850SampledValues.d.ts +1 -0
  36. package/dist/headers/IEC61850SampledValues.js +16 -1
  37. package/dist/headers/IPFIX.js +2 -1
  38. package/dist/headers/IPv4.d.ts +1 -0
  39. package/dist/headers/IPv4.js +6 -0
  40. package/dist/headers/IPv6.d.ts +1 -0
  41. package/dist/headers/IPv6.js +6 -0
  42. package/dist/headers/IPv6HopByHopOptions.d.ts +2 -0
  43. package/dist/headers/IPv6HopByHopOptions.js +11 -0
  44. package/dist/headers/KNXnetIP.js +3 -2
  45. package/dist/headers/LACP.js +2 -1
  46. package/dist/headers/LDP.js +2 -2
  47. package/dist/headers/MQTT.js +3 -1
  48. package/dist/headers/MarkerProtocol.js +2 -1
  49. package/dist/headers/NHRP.js +7 -15
  50. package/dist/headers/NetFlowV5.js +2 -1
  51. package/dist/headers/OPCUA.js +4 -0
  52. package/dist/headers/OSPF.d.ts +2 -2
  53. package/dist/headers/OSPF.js +32 -20
  54. package/dist/headers/OSPFv3.d.ts +38 -0
  55. package/dist/headers/OSPFv3.js +316 -0
  56. package/dist/headers/PPTP.js +2 -2
  57. package/dist/headers/QUIC.js +8 -3
  58. package/dist/headers/RGoose.js +2 -1
  59. package/dist/headers/RIP.js +3 -2
  60. package/dist/headers/RIPng.js +3 -2
  61. package/dist/headers/RTCP.js +3 -2
  62. package/dist/headers/RTP.js +3 -2
  63. package/dist/headers/SFlow.js +4 -2
  64. package/dist/headers/SLMP.js +2 -1
  65. package/dist/headers/SLP.js +2 -1
  66. package/dist/headers/SLPv1.js +2 -1
  67. package/dist/headers/SMB1.js +3 -2
  68. package/dist/headers/SMB2.js +3 -2
  69. package/dist/headers/STUN.js +2 -1
  70. package/dist/headers/TLS_Handshake.d.ts +6 -0
  71. package/dist/headers/TLS_Handshake.js +28 -3
  72. package/dist/headers/TacacsPlus.js +3 -1
  73. package/dist/headers/Trailer.d.ts +30 -0
  74. package/dist/headers/Trailer.js +63 -0
  75. package/dist/headers/VLAN_802dot1Q.d.ts +1 -0
  76. package/dist/headers/VLAN_802dot1Q.js +3 -0
  77. package/dist/headers/WakeOnLAN.js +2 -1
  78. package/dist/headers/WireGuard.js +3 -2
  79. package/dist/headers/Zabbix.js +2 -2
  80. package/dist/lib/BERElement.d.ts +51 -0
  81. package/dist/lib/BERElement.js +125 -0
  82. package/dist/types/LayerGraph.d.ts +10 -5
  83. package/package.json +2 -2
@@ -1,11 +1,8 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ var _a;
5
3
  Object.defineProperty(exports, "__esModule", { value: true });
6
4
  exports.Goose = void 0;
7
5
  const BaseHeader_1 = require("../abstracts/BaseHeader");
8
- const node_tlv_1 = __importDefault(require("node-tlv"));
9
6
  const HexToNumber_1 = require("../helper/HexToNumber");
10
7
  const NumberToBERHex_1 = require("../helper/NumberToBERHex");
11
8
  const NumberToHex_1 = require("../helper/NumberToHex");
@@ -14,6 +11,7 @@ const NumberToBERBuffer_1 = require("../helper/NumberToBERBuffer");
14
11
  const BufferToNumber_1 = require("../helper/BufferToNumber");
15
12
  const BufferToHex_1 = require("../helper/BufferToHex");
16
13
  const NumberToBuffer_1 = require("../helper/NumberToBuffer");
14
+ const BERElement_1 = require("../lib/BERElement");
17
15
  var ItemDataType;
18
16
  (function (ItemDataType) {
19
17
  ItemDataType["Boolean"] = "Boolean";
@@ -35,7 +33,14 @@ var ItemDataType;
35
33
  class Goose extends BaseHeader_1.BaseHeader {
36
34
  constructor() {
37
35
  super(...arguments);
38
- this.TLVChild = [];
36
+ //Decode: the goosePdu's child elements. Read with ReadBERElement, not node-tlv: node-tlv rebuilt
37
+ //every length field in minimal form, so the span of a long-form length (61 82 00b2) came out short
38
+ //and the PDU lost its last octets.
39
+ this.#elements = [];
40
+ //Decode: the encoding hints of the goosePdu fields, set as goosePdu.encoding once they are all read
41
+ this.#decodedEncoding = {};
42
+ //Encode: the goosePdu's child elements as encoded bytes, in field order
43
+ this.#encodedElements = [];
39
44
  this.SCHEMA = {
40
45
  type: 'object',
41
46
  properties: {
@@ -129,38 +134,36 @@ class Goose extends BaseHeader_1.BaseHeader {
129
134
  type: 'object',
130
135
  label: 'GOOSE PDU',
131
136
  decode: () => {
132
- let readTLVBufferLength = this.packet.length - this.startPos - 8;
133
- while (!this.TLVInstance) {
134
- try {
135
- const buffer = this.readBytes(8, readTLVBufferLength, true);
136
- this.TLVInstance = node_tlv_1.default.parse(buffer);
137
- //Consume exactly the outer TLV's own span (tag + length + value). Anything after
138
- //it (Ethernet padding, trailing bytes) is not part of the goosePdu and must be
139
- //left for the next layer (raw) so it survives re-encode.
140
- const TLVBufferLength = this.TLVInstance.bTag.length + this.TLVInstance.bLength.length + this.TLVInstance.bValue.length;
141
- this.TLVInstance = node_tlv_1.default.parse(this.readBytes(8, TLVBufferLength, false));
142
- }
143
- catch (e) {
144
- readTLVBufferLength -= 1;
145
- if (!readTLVBufferLength)
146
- break;
147
- }
148
- }
149
- this.TLVChild = this.TLVInstance ? this.TLVInstance.getChild() : [];
150
- //Capture the exact goosePdu region so it can be surfaced/reproduced if the PDU
151
- //turns out to be unparseable. Use the parsed outer TLV's byte span when we have
152
- //it, else the remaining buffer.
153
- const goosePduByteLength = this.TLVInstance
154
- ? this.TLVInstance.bTag.length + this.TLVInstance.bLength.length + this.TLVInstance.bValue.length
155
- : this.packet.length - this.startPos - 8;
156
- const goosePduRawHex = (0, BufferToHex_1.BufferToHex)(this.readBytes(8, goosePduByteLength, true));
157
- //Runs after every child field decode: if none produced structured content, the
158
- //PDU is effectively unparsed - expose the raw bytes as a visible field so the
159
- //analyst sees the malformed region instead of a deceptively-empty PDU.
137
+ //Length bounds the goosePdu when the frame holds that many octets (see payloadEnd); a
138
+ //goosePdu claiming more ends there. Otherwise it may run to the end of the bytes.
139
+ const length = this.instance.length.getValue(0);
140
+ const available = length >= 8 && this.startPos + length <= this.packet.length ? length - 8 : Math.max(this.packet.length - this.startPos - 8, 0);
141
+ const region = this.readBytes(8, available, true);
142
+ const pdu = (0, BERElement_1.ReadBERElement)(region, 0);
143
+ //The fields can only re-encode the goosePdu when its BER is well-formed (no element
144
+ //runs past its parent, none is unreadable) and its elements are goosePdu fields in
145
+ //order, each once. Otherwise the whole region up to Length stays raw (its own end is
146
+ //as unreliable as the rest) and re-emits as captured.
147
+ const malformed = pdu && pdu.constructed ? (0, BERElement_1.MalformedBER)(region.subarray(0, pdu.end)) ?? _a.#unexpectedField((0, BERElement_1.ReadBERElements)(pdu.value)) : undefined;
148
+ if (malformed)
149
+ this.recordError(this.instance.goosePdu.getPath(), `Malformed goosePdu, kept as raw: ${malformed}`);
150
+ this.#elements = pdu && pdu.constructed && !malformed ? (0, BERElement_1.ReadBERElements)(pdu.value) : [];
151
+ //Otherwise consume exactly the goosePdu element's own span (tag + length + value).
152
+ //Anything after it (Ethernet padding, trailing bytes) is not part of the goosePdu and
153
+ //must be left for the next layer so it survives re-encode. Without a readable element
154
+ //the remaining bytes are the goosePdu region surfaced as raw below.
155
+ const goosePduRawHex = (0, BufferToHex_1.BufferToHex)(this.readBytes(8, pdu && !malformed ? pdu.end : available));
156
+ //Runs after every child field decode: if none produced structured content, the PDU is
157
+ //effectively unparsed - expose the raw bytes as a visible field so the analyst sees the
158
+ //malformed region instead of a deceptively-empty PDU. Otherwise record how the
159
+ //elements were laid out where encode would not write them that way by default.
160
160
  this.addPostSelfDecodeHandler(() => {
161
- if (this.goosePduHasStructuredContent())
162
- return;
163
- this.instance.goosePdu.raw.setValue(goosePduRawHex);
161
+ if (!this.goosePduHasStructuredContent())
162
+ return this.instance.goosePdu.raw.setValue(goosePduRawHex);
163
+ const pduEncoding = pdu ? _a.#elementEncoding(pdu) : undefined;
164
+ const encoding = pduEncoding && pduEncoding.lengthOctets ? { lengthOctets: pduEncoding.lengthOctets, ...this.#decodedEncoding } : this.#decodedEncoding;
165
+ if (Object.keys(encoding).length)
166
+ this.instance.goosePdu.encoding.setValue(encoding);
164
167
  });
165
168
  },
166
169
  encode: () => {
@@ -174,10 +177,7 @@ class Goose extends BaseHeader_1.BaseHeader {
174
177
  this.instance.length.setValue(8 + rawBuffer.length);
175
178
  return;
176
179
  }
177
- let buffers = Buffer.from([]);
178
- this.TLVChild.forEach((item) => buffers = Buffer.concat([buffers, item.bTag, item.bLength, item.bValue]));
179
- const goosePduTLV = new node_tlv_1.default(0x61, buffers);
180
- const goosePduBuffer = Buffer.concat([goosePduTLV.bTag, goosePduTLV.bLength, goosePduTLV.bValue]);
180
+ const goosePduBuffer = (0, BERElement_1.EncodeBERElement)(0x61, Buffer.concat(this.#encodedElements), this.instance.goosePdu.encoding.lengthOctets.getValue());
181
181
  this.writeBytes(8, goosePduBuffer);
182
182
  /**
183
183
  * Update the length only if it is not set
@@ -194,10 +194,11 @@ class Goose extends BaseHeader_1.BaseHeader {
194
194
  label: 'GoCBReference',
195
195
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.ASCII,
196
196
  decode: () => {
197
- const gocbRefTLV = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x80);
198
- if (!gocbRefTLV)
197
+ const gocbRefElement = this.#findElement(0x80);
198
+ if (!gocbRefElement)
199
199
  return this.recordError(this.instance.goosePdu.gocbRef.getPath(), 'Not Found');
200
- this.instance.goosePdu.gocbRef.setValue(gocbRefTLV.getValue('buffer').toString('ascii'));
200
+ this.instance.goosePdu.gocbRef.setValue(gocbRefElement.value.toString('ascii'));
201
+ this.#recordFieldEncoding('gocbRef', gocbRefElement);
201
202
  },
202
203
  encode: () => {
203
204
  const gocbRefValue = this.instance.goosePdu.gocbRef.getValue('', (nodePath) => this.recordError(nodePath, 'Not Found'));
@@ -208,7 +209,7 @@ class Goose extends BaseHeader_1.BaseHeader {
208
209
  this.recordError(this.instance.goosePdu.gocbRef.getPath(), 'This VisibleString shall have a maximum size of 129 octets');
209
210
  gocbRefBuffer = gocbRefBuffer.subarray(0, 129);
210
211
  }
211
- this.TLVChild.push(new node_tlv_1.default(0x80, gocbRefBuffer));
212
+ this.#encodeField('gocbRef', 0x80, gocbRefBuffer);
212
213
  }
213
214
  },
214
215
  timeAllowedtoLive: {
@@ -217,10 +218,7 @@ class Goose extends BaseHeader_1.BaseHeader {
217
218
  maximum: 4294967295,
218
219
  label: 'TimeAllowedtoLive',
219
220
  decode: () => {
220
- const timeAllowedtoLiveString = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x81)?.getValue('hex');
221
- if (!timeAllowedtoLiveString)
222
- return this.recordError(this.instance.goosePdu.timeAllowedtoLive.getPath(), 'Not Found');
223
- this.instance.goosePdu.timeAllowedtoLive.setValue((0, HexToNumber_1.HexToUInt32)(timeAllowedtoLiveString));
221
+ this.#decodeUnsignedField('timeAllowedtoLive', 0x81);
224
222
  },
225
223
  encode: () => {
226
224
  let timeAllowedtoLiveValue = this.instance.goosePdu.timeAllowedtoLive.getValue(-1, (nodePath) => this.recordError(nodePath, 'Not Found'));
@@ -230,8 +228,7 @@ class Goose extends BaseHeader_1.BaseHeader {
230
228
  this.recordError(this.instance.goosePdu.timeAllowedtoLive.getPath(), 'This INTEGER value shall have a range of 1 to 4294967295');
231
229
  timeAllowedtoLiveValue = 4294967295;
232
230
  }
233
- const timeAllowedtoLiveTLV = new node_tlv_1.default(0x81, (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(timeAllowedtoLiveValue));
234
- this.TLVChild.push(timeAllowedtoLiveTLV);
231
+ this.#encodeUnsignedField('timeAllowedtoLive', 0x81, timeAllowedtoLiveValue);
235
232
  }
236
233
  },
237
234
  datSet: {
@@ -240,10 +237,11 @@ class Goose extends BaseHeader_1.BaseHeader {
240
237
  label: 'DatSet',
241
238
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.ASCII,
242
239
  decode: () => {
243
- const datSetTLV = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x82);
244
- if (!datSetTLV)
240
+ const datSetElement = this.#findElement(0x82);
241
+ if (!datSetElement)
245
242
  return this.recordError(this.instance.goosePdu.datSet.getPath(), 'Not Found');
246
- this.instance.goosePdu.datSet.setValue(datSetTLV.getValue('buffer').toString('ascii'));
243
+ this.instance.goosePdu.datSet.setValue(datSetElement.value.toString('ascii'));
244
+ this.#recordFieldEncoding('datSet', datSetElement);
247
245
  },
248
246
  encode: () => {
249
247
  const datSetValue = this.instance.goosePdu.datSet.getValue('', (nodePath) => this.recordError(nodePath, 'Not Found'));
@@ -254,7 +252,7 @@ class Goose extends BaseHeader_1.BaseHeader {
254
252
  this.recordError(this.instance.goosePdu.datSet.getPath(), 'This VisibleString shall have a maximum size of 129 octets');
255
253
  datSetBuffer = datSetBuffer.subarray(0, 129);
256
254
  }
257
- this.TLVChild.push(new node_tlv_1.default(0x82, datSetBuffer));
255
+ this.#encodeField('datSet', 0x82, datSetBuffer);
258
256
  }
259
257
  },
260
258
  goID: {
@@ -263,10 +261,11 @@ class Goose extends BaseHeader_1.BaseHeader {
263
261
  label: 'GoID',
264
262
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.ASCII,
265
263
  decode: () => {
266
- const goIDTLV = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x83);
267
- if (!goIDTLV)
264
+ const goIDElement = this.#findElement(0x83);
265
+ if (!goIDElement)
268
266
  return this.recordError(this.instance.goosePdu.goID.getPath(), 'Not Found');
269
- this.instance.goosePdu.goID.setValue(goIDTLV.getValue('buffer').toString('ascii'));
267
+ this.instance.goosePdu.goID.setValue(goIDElement.value.toString('ascii'));
268
+ this.#recordFieldEncoding('goID', goIDElement);
270
269
  },
271
270
  encode: () => {
272
271
  const goIDValue = this.instance.goosePdu.goID.getValue('', (nodePath) => this.recordError(nodePath, 'Not Found'));
@@ -277,7 +276,7 @@ class Goose extends BaseHeader_1.BaseHeader {
277
276
  this.recordError(this.instance.goosePdu.goID.getPath(), 'This VisibleString shall have a maximum size of 65 octets');
278
277
  goIDBuffer = goIDBuffer.subarray(0, 65);
279
278
  }
280
- this.TLVChild.push(new node_tlv_1.default(0x83, goIDBuffer));
279
+ this.#encodeField('goID', 0x83, goIDBuffer);
281
280
  }
282
281
  },
283
282
  t: {
@@ -285,18 +284,18 @@ class Goose extends BaseHeader_1.BaseHeader {
285
284
  label: 'TimeStamp',
286
285
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.BIGINT,
287
286
  decode: () => {
288
- const tStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x84)?.getValue('hex');
289
- if (!tStr)
287
+ const tElement = this.#findElement(0x84);
288
+ if (!tElement || !tElement.value.length)
290
289
  return this.recordError(this.instance.goosePdu.t.getPath(), 'Not Found');
291
- this.instance.goosePdu.t.setValue(BigInt(`0x${tStr}`).toString());
290
+ this.instance.goosePdu.t.setValue(BigInt(`0x${tElement.value.toString('hex')}`).toString());
291
+ this.#recordFieldEncoding('t', tElement);
292
292
  },
293
293
  encode: () => {
294
294
  const tStr = this.instance.goosePdu.t.getValue('', (nodePath) => this.recordError(nodePath, 'Not Found'));
295
295
  if (!tStr)
296
296
  return;
297
297
  const tBigIntValue = BigInt(tStr);
298
- const tTLV = new node_tlv_1.default(0x84, Buffer.from(tBigIntValue.toString(16).padStart(8 * 2, '0'), 'hex'));
299
- this.TLVChild.push(tTLV);
298
+ this.#encodeField('t', 0x84, Buffer.from(tBigIntValue.toString(16).padStart(8 * 2, '0'), 'hex'));
300
299
  }
301
300
  },
302
301
  stNum: {
@@ -305,11 +304,10 @@ class Goose extends BaseHeader_1.BaseHeader {
305
304
  maximum: 4294967295,
306
305
  label: 'StNum',
307
306
  decode: () => {
308
- const stNumStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x85)?.getValue('hex');
309
- if (!stNumStr)
310
- return this.recordError(this.instance.goosePdu.stNum.getPath(), 'Not Found');
311
- this.instance.goosePdu.stNum.setValue((0, HexToNumber_1.HexToUInt32)(stNumStr));
312
- if (this.instance.goosePdu.stNum.getValue() < 1 || this.instance.goosePdu.stNum.getValue() > 4294967295)
307
+ const stNumValue = this.#decodeUnsignedField('stNum', 0x85);
308
+ if (stNumValue === undefined)
309
+ return;
310
+ if (stNumValue < 1 || stNumValue > 4294967295)
313
311
  this.recordError(this.instance.goosePdu.stNum.getPath(), 'This INTEGER value shall have a range of 1 to 4294967295');
314
312
  },
315
313
  encode: () => {
@@ -322,8 +320,7 @@ class Goose extends BaseHeader_1.BaseHeader {
322
320
  }
323
321
  if (stNumValue === undefined)
324
322
  return this.recordError(this.instance.goosePdu.stNum.getPath(), 'Not Found');
325
- const stNumTLV = new node_tlv_1.default(0x85, (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(stNumValue));
326
- this.TLVChild.push(stNumTLV);
323
+ this.#encodeUnsignedField('stNum', 0x85, stNumValue);
327
324
  }
328
325
  },
329
326
  sqNum: {
@@ -332,10 +329,7 @@ class Goose extends BaseHeader_1.BaseHeader {
332
329
  maximum: 4294967295,
333
330
  label: 'SqNum',
334
331
  decode: () => {
335
- const sqNumStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x86)?.getValue('hex');
336
- if (!sqNumStr)
337
- return this.recordError(this.instance.goosePdu.sqNum.getPath(), 'Not Found');
338
- this.instance.goosePdu.sqNum.setValue((0, HexToNumber_1.HexToUInt32)(sqNumStr));
332
+ this.#decodeUnsignedField('sqNum', 0x86);
339
333
  },
340
334
  encode: () => {
341
335
  let sqNumValue = this.instance.goosePdu.sqNum.getValue(-1, (nodePath) => this.recordError(nodePath, 'Not Found'));
@@ -347,39 +341,34 @@ class Goose extends BaseHeader_1.BaseHeader {
347
341
  }
348
342
  if (sqNumValue === undefined)
349
343
  return this.recordError(this.instance.goosePdu.sqNum.getPath(), 'Not Found');
350
- const sqNumTLV = new node_tlv_1.default(0x86, (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(sqNumValue));
351
- this.TLVChild.push(sqNumTLV);
344
+ this.#encodeUnsignedField('sqNum', 0x86, sqNumValue);
352
345
  }
353
346
  },
354
347
  simulation: {
355
348
  type: 'boolean',
356
349
  label: 'Simulation',
357
350
  decode: () => {
358
- const simulationStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x87)?.getValue('hex');
359
- if (!simulationStr)
351
+ const simulationElement = this.#findElement(0x87);
352
+ if (!simulationElement || !simulationElement.value.length)
360
353
  return this.recordError(this.instance.goosePdu.simulation.getPath(), 'Not Found');
361
- const simulationNum = parseInt(simulationStr, 16);
354
+ const simulationNum = parseInt(simulationElement.value.toString('hex'), 16);
362
355
  if (simulationNum > 1)
363
356
  this.recordError(this.instance.goosePdu.simulation.getPath(), 'This Boolean shall have a range of TRUE, FALSE');
364
357
  this.instance.goosePdu.simulation.setValue(!!simulationNum);
358
+ this.#recordFieldEncoding('simulation', simulationElement);
365
359
  },
366
360
  encode: () => {
367
361
  const simulationValue = this.instance.goosePdu.simulation.getValue(undefined, (nodePath) => this.recordError(nodePath, 'Not Found'));
368
362
  if (simulationValue === undefined)
369
363
  return;
370
- const simulationNum = simulationValue ? 1 : 0;
371
- const simulationTLV = new node_tlv_1.default(0x87, Buffer.from(simulationNum.toString(16).padStart(2, '0'), 'hex'));
372
- this.TLVChild.push(simulationTLV);
364
+ this.#encodeField('simulation', 0x87, Buffer.from([simulationValue ? 1 : 0]));
373
365
  }
374
366
  },
375
367
  confRev: {
376
368
  type: 'integer',
377
369
  label: 'ConfRev',
378
370
  decode: () => {
379
- const confRevStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x88)?.getValue('hex');
380
- if (!confRevStr)
381
- return this.recordError(this.instance.goosePdu.confRev.getPath(), 'Not Found');
382
- this.instance.goosePdu.confRev.setValue((0, HexToNumber_1.HexToUInt32)(confRevStr));
371
+ this.#decodeUnsignedField('confRev', 0x88);
383
372
  },
384
373
  encode: () => {
385
374
  let confRevValue = this.instance.goosePdu.confRev.getValue(-1, (nodePath) => this.recordError(nodePath, 'Not Found'));
@@ -389,46 +378,40 @@ class Goose extends BaseHeader_1.BaseHeader {
389
378
  }
390
379
  if (confRevValue === -1)
391
380
  return;
392
- const confRevTLV = new node_tlv_1.default(0x88, (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(confRevValue));
393
- this.TLVChild.push(confRevTLV);
381
+ this.#encodeUnsignedField('confRev', 0x88, confRevValue);
394
382
  }
395
383
  },
396
384
  ndsCom: {
397
385
  type: 'boolean',
398
386
  label: 'NdsCom',
399
387
  decode: () => {
400
- const ndsComStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x89)?.getValue('hex');
401
- if (!ndsComStr)
388
+ const ndsComElement = this.#findElement(0x89);
389
+ if (!ndsComElement || !ndsComElement.value.length)
402
390
  return this.recordError(this.instance.goosePdu.ndsCom.getPath(), 'Not Found');
403
- const ndsComNum = parseInt(ndsComStr, 16);
391
+ const ndsComNum = parseInt(ndsComElement.value.toString('hex'), 16);
404
392
  if (ndsComNum > 1)
405
393
  this.recordError(this.instance.goosePdu.ndsCom.getPath(), 'This Boolean shall have a range of TRUE, FALSE');
406
394
  this.instance.goosePdu.ndsCom.setValue(!!ndsComNum);
395
+ this.#recordFieldEncoding('ndsCom', ndsComElement);
407
396
  },
408
397
  encode: () => {
409
398
  const ndsComValue = this.instance.goosePdu.ndsCom.getValue(undefined, (nodePath) => this.recordError(nodePath, 'Not Found'));
410
399
  if (ndsComValue === undefined)
411
400
  return;
412
- const ndsComNum = ndsComValue ? 1 : 0;
413
- const ndsComTLV = new node_tlv_1.default(0x89, Buffer.from(ndsComNum.toString(16).padStart(2, '0'), 'hex'));
414
- this.TLVChild.push(ndsComTLV);
401
+ this.#encodeField('ndsCom', 0x89, Buffer.from([ndsComValue ? 1 : 0]));
415
402
  }
416
403
  },
417
404
  numDatSetEntries: {
418
405
  type: 'integer',
419
406
  label: 'NumDatSetEntries',
420
407
  decode: () => {
421
- const numDatSetEntriesStr = this.TLVChild.find((tlv) => tlv.getTag('number') === 0x8A)?.getValue('hex');
422
- if (!numDatSetEntriesStr)
423
- return this.recordError(this.instance.goosePdu.numDatSetEntries.getPath(), 'Not Found');
424
- this.instance.goosePdu.numDatSetEntries.setValue(parseInt(numDatSetEntriesStr, 16));
408
+ this.#decodeUnsignedField('numDatSetEntries', 0x8A, (hex) => parseInt(hex, 16));
425
409
  },
426
410
  encode: () => {
427
411
  const numDatSetEntriesValue = this.instance.goosePdu.numDatSetEntries.getValue(undefined, (nodePath) => this.recordError(nodePath, 'Not Found'));
428
412
  if (numDatSetEntriesValue === undefined)
429
413
  return;
430
- const numDatSetEntriesTLV = new node_tlv_1.default(0x8A, (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(numDatSetEntriesValue));
431
- this.TLVChild.push(numDatSetEntriesTLV);
414
+ this.#encodeUnsignedField('numDatSetEntries', 0x8A, numDatSetEntriesValue);
432
415
  }
433
416
  },
434
417
  allData: {
@@ -450,7 +433,8 @@ class Goose extends BaseHeader_1.BaseHeader {
450
433
  value: {
451
434
  type: 'boolean',
452
435
  label: 'Value'
453
- }
436
+ },
437
+ encoding: _a.#encodingSchema()
454
438
  }
455
439
  },
456
440
  {
@@ -467,7 +451,8 @@ class Goose extends BaseHeader_1.BaseHeader {
467
451
  value: {
468
452
  type: 'integer',
469
453
  label: 'Value'
470
- }
454
+ },
455
+ encoding: _a.#encodingSchema(true)
471
456
  }
472
457
  },
473
458
  {
@@ -484,7 +469,8 @@ class Goose extends BaseHeader_1.BaseHeader {
484
469
  value: {
485
470
  type: 'integer',
486
471
  label: 'Value'
487
- }
472
+ },
473
+ encoding: _a.#encodingSchema(true)
488
474
  }
489
475
  },
490
476
  {
@@ -501,7 +487,8 @@ class Goose extends BaseHeader_1.BaseHeader {
501
487
  value: {
502
488
  type: 'integer',
503
489
  label: 'Value'
504
- }
490
+ },
491
+ encoding: _a.#encodingSchema(true)
505
492
  }
506
493
  },
507
494
  {
@@ -519,7 +506,8 @@ class Goose extends BaseHeader_1.BaseHeader {
519
506
  type: 'string',
520
507
  label: 'Value',
521
508
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.BIGINT
522
- }
509
+ },
510
+ encoding: _a.#encodingSchema(true)
523
511
  }
524
512
  },
525
513
  {
@@ -536,7 +524,8 @@ class Goose extends BaseHeader_1.BaseHeader {
536
524
  value: {
537
525
  type: 'integer',
538
526
  label: 'Value'
539
- }
527
+ },
528
+ encoding: _a.#encodingSchema(true)
540
529
  }
541
530
  },
542
531
  {
@@ -553,7 +542,8 @@ class Goose extends BaseHeader_1.BaseHeader {
553
542
  value: {
554
543
  type: 'integer',
555
544
  label: 'Value'
556
- }
545
+ },
546
+ encoding: _a.#encodingSchema(true)
557
547
  }
558
548
  },
559
549
  {
@@ -570,7 +560,8 @@ class Goose extends BaseHeader_1.BaseHeader {
570
560
  value: {
571
561
  type: 'integer',
572
562
  label: 'Value'
573
- }
563
+ },
564
+ encoding: _a.#encodingSchema(true)
574
565
  }
575
566
  },
576
567
  {
@@ -587,7 +578,8 @@ class Goose extends BaseHeader_1.BaseHeader {
587
578
  value: {
588
579
  type: 'number',
589
580
  label: 'Value'
590
- }
581
+ },
582
+ encoding: _a.#encodingSchema(false, true)
591
583
  }
592
584
  },
593
585
  {
@@ -604,7 +596,8 @@ class Goose extends BaseHeader_1.BaseHeader {
604
596
  value: {
605
597
  type: 'integer',
606
598
  label: 'Value'
607
- }
599
+ },
600
+ encoding: _a.#encodingSchema()
608
601
  }
609
602
  },
610
603
  {
@@ -622,7 +615,8 @@ class Goose extends BaseHeader_1.BaseHeader {
622
615
  type: 'string',
623
616
  label: 'Value',
624
617
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX
625
- }
618
+ },
619
+ encoding: _a.#encodingSchema()
626
620
  }
627
621
  },
628
622
  {
@@ -640,7 +634,8 @@ class Goose extends BaseHeader_1.BaseHeader {
640
634
  type: 'string',
641
635
  label: 'Value',
642
636
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.ASCII
643
- }
637
+ },
638
+ encoding: _a.#encodingSchema()
644
639
  }
645
640
  },
646
641
  {
@@ -657,7 +652,8 @@ class Goose extends BaseHeader_1.BaseHeader {
657
652
  value: {
658
653
  type: 'string',
659
654
  label: 'Value'
660
- }
655
+ },
656
+ encoding: _a.#encodingSchema()
661
657
  }
662
658
  },
663
659
  {
@@ -675,7 +671,8 @@ class Goose extends BaseHeader_1.BaseHeader {
675
671
  type: 'string',
676
672
  label: 'Value',
677
673
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.BINARY
678
- }
674
+ },
675
+ encoding: _a.#encodingSchema()
679
676
  }
680
677
  },
681
678
  {
@@ -692,7 +689,8 @@ class Goose extends BaseHeader_1.BaseHeader {
692
689
  value: {
693
690
  $ref: '#/properties/goosePdu/properties/allData',
694
691
  label: 'Value'
695
- }
692
+ },
693
+ encoding: _a.#encodingSchema()
696
694
  }
697
695
  }
698
696
  ]
@@ -710,7 +708,7 @@ class Goose extends BaseHeader_1.BaseHeader {
710
708
  * | INT16U | 0x86 | 3 | 16 Bit Big Endian; unsigned |
711
709
  * | INT24U | - | - | Not used |
712
710
  * | INT32U | 0x86 | 5 | 32 Bit Big Endian; unsigned |
713
- * | FLOAT32 | 0x87 | 4 | 32 Bit IEEE Floating Point (IEEE 754) |
711
+ * | FLOAT32 | 0x87 | 5 | Exponent width octet (8), then 32 Bit IEEE Floating Point (IEEE 754) |
714
712
  * | CODED-ENUM | 0x84 | 2 | Bit-string; depending on CODED ENUM definition – most of the time, can be encoded with 2 bytes (1st Byte = number of unused bit, 2nd Byte = Value) |
715
713
  * | OCTET-STRING | 0x89 | 20 | 20 Bytes ASCII Text, Null terminated |
716
714
  * | VISIBLE-STRING | 0x8a | 35 | 35 Bytes ASCII Text, Null terminated |
@@ -719,25 +717,48 @@ class Goose extends BaseHeader_1.BaseHeader {
719
717
  * +-----------------------------------+-------------------+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
720
718
  */
721
719
  decode: () => {
722
- const allDataTLV = this.TLVChild.find((tlv) => tlv.getTag('number') === 0xAB);
723
- const dataTLVs = allDataTLV ? allDataTLV.getChild() : [];
724
- const allData = this.decodeDataTLVItem(dataTLVs, this.instance.goosePdu.allData.getPath());
725
- if (allData.length)
726
- this.instance.goosePdu.allData.setValue(allData);
720
+ const allDataElement = this.#findElement(0xAB);
721
+ if (!allDataElement)
722
+ return;
723
+ const allData = this.decodeDataTLVItem((0, BERElement_1.ReadBERElements)(allDataElement.value), this.instance.goosePdu.allData.getPath());
724
+ if (!allData.length)
725
+ return;
726
+ this.instance.goosePdu.allData.setValue(allData);
727
+ this.#recordFieldEncoding('allData', allDataElement);
727
728
  },
728
729
  encode: () => {
729
730
  const allData = this.instance.goosePdu.allData.getValue([], (nodePath) => this.recordError(nodePath, 'Not Found'));
730
- const dataItemTLVs = this.encodeDataTLVItem(allData);
731
- if (dataItemTLVs.length) {
732
- const allDataTLV = new node_tlv_1.default(0xAB, Buffer.concat(dataItemTLVs.map((dataItemTLV) => Buffer.concat([dataItemTLV.bTag, dataItemTLV.bLength, dataItemTLV.bValue]))));
733
- this.TLVChild.push(allDataTLV);
734
- }
731
+ const dataItemElements = this.encodeDataTLVItem(allData);
732
+ if (dataItemElements.length)
733
+ this.#encodeField('allData', 0xAB, Buffer.concat(dataItemElements));
735
734
  }
736
735
  },
737
736
  raw: {
738
737
  type: 'string',
739
738
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX,
740
739
  label: 'Unparsed Raw'
740
+ },
741
+ //How the capture laid out the goosePdu where encode would not by default: its own
742
+ //length octets (lengthOctets) and, per field, the field's ElementEncoding.
743
+ encoding: {
744
+ type: 'object',
745
+ label: 'Encoding',
746
+ hidden: true,
747
+ properties: {
748
+ lengthOctets: { type: 'integer', minimum: 1, maximum: 5, label: 'Length Octets', hidden: true },
749
+ gocbRef: _a.#encodingSchema(),
750
+ timeAllowedtoLive: _a.#encodingSchema(true),
751
+ datSet: _a.#encodingSchema(),
752
+ goID: _a.#encodingSchema(),
753
+ t: _a.#encodingSchema(),
754
+ stNum: _a.#encodingSchema(true),
755
+ sqNum: _a.#encodingSchema(true),
756
+ simulation: _a.#encodingSchema(),
757
+ confRev: _a.#encodingSchema(true),
758
+ ndsCom: _a.#encodingSchema(),
759
+ numDatSetEntries: _a.#encodingSchema(true),
760
+ allData: _a.#encodingSchema()
761
+ }
741
762
  }
742
763
  }
743
764
  }
@@ -748,6 +769,14 @@ class Goose extends BaseHeader_1.BaseHeader {
748
769
  this.name = 'IEC61850 GOOSE';
749
770
  this.nickname = 'GOOSE';
750
771
  }
772
+ //Decode: the goosePdu's child elements. Read with ReadBERElement, not node-tlv: node-tlv rebuilt
773
+ //every length field in minimal form, so the span of a long-form length (61 82 00b2) came out short
774
+ //and the PDU lost its last octets.
775
+ #elements;
776
+ //Decode: the encoding hints of the goosePdu fields, set as goosePdu.encoding once they are all read
777
+ #decodedEncoding;
778
+ //Encode: the goosePdu's child elements as encoded bytes, in field order
779
+ #encodedElements;
751
780
  /**
752
781
  * True when at least one structured goosePdu field decoded/was supplied. Used to
753
782
  * decide whether the raw-passthrough fallback applies.
@@ -768,84 +797,264 @@ class Goose extends BaseHeader_1.BaseHeader {
768
797
  return false;
769
798
  return !this.goosePduHasStructuredContent();
770
799
  }
800
+ /**
801
+ * Schema of an `encoding` hint (ElementEncoding). Hidden: it records how a capture laid out an
802
+ * element so the element re-encodes as captured, and is not meant for a form. Deleting it encodes
803
+ * the minimal form.
804
+ * @param width true for an INTEGER element
805
+ * @param content true for a FLOATING-POINT element
806
+ */
807
+ static #encodingSchema(width = false, content = false) {
808
+ const properties = {
809
+ lengthOctets: { type: 'integer', minimum: 1, maximum: 5, label: 'Length Octets', hidden: true }
810
+ };
811
+ if (width)
812
+ properties.width = { type: 'integer', minimum: 1, maximum: 9, label: 'Content Octets', hidden: true };
813
+ if (content)
814
+ properties.content = { type: 'string', contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX, label: 'Content', hidden: true };
815
+ return { type: 'object', label: 'Encoding', hidden: true, properties: properties };
816
+ }
817
+ //Tags of the goosePdu fields in SEQUENCE order (IEC 61850-8-1 IECGoosePdu, [0] gocbRef to [11] allData)
818
+ static #FIELD_TAGS = [0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0xAB];
819
+ /**
820
+ * Why the goosePdu child elements are not its fields in order, each at most once (an unknown tag,
821
+ * a repeated or out-of-order field), or undefined when they are
822
+ * @param elements
823
+ */
824
+ static #unexpectedField(elements) {
825
+ let previous = -1;
826
+ for (const element of elements) {
827
+ const index = _a.#FIELD_TAGS.indexOf(element.tag);
828
+ if (index <= previous)
829
+ return `element ${element.tag.toString(16).padStart(2, '0')} is not a goosePdu field, or is repeated or out of order`;
830
+ previous = index;
831
+ }
832
+ return undefined;
833
+ }
834
+ /**
835
+ * `value` in exactly `width` content octets (two's complement when signed, plain big-endian
836
+ * otherwise), or undefined when no width is given or the value does not fit in it
837
+ * @param value
838
+ * @param width
839
+ * @param signed
840
+ */
841
+ static #fixedWidthContent(value, width, signed) {
842
+ if (width === undefined || !Number.isInteger(width) || width < 1 || width > 9)
843
+ return undefined;
844
+ const bits = BigInt(width * 8);
845
+ const minimum = signed ? -(1n << (bits - 1n)) : 0n;
846
+ const maximum = signed ? (1n << (bits - 1n)) - 1n : (1n << bits) - 1n;
847
+ if (value < minimum || value > maximum)
848
+ return undefined;
849
+ return Buffer.from(BigInt.asUintN(width * 8, value).toString(16).padStart(width * 2, '0'), 'hex');
850
+ }
851
+ /**
852
+ * The content width to record for a decoded INTEGER: undefined when the minimal form encode writes
853
+ * already reproduces `content`, or when no width does
854
+ * @param value the decoded value
855
+ * @param minimal the content encode writes without a width
856
+ * @param content the content as captured
857
+ * @param signed
858
+ */
859
+ static #integerWidth(value, minimal, content, signed) {
860
+ if (minimal.equals(content))
861
+ return undefined;
862
+ const fixed = _a.#fixedWidthContent(value, content.length, signed);
863
+ return fixed && fixed.equals(content) ? content.length : undefined;
864
+ }
865
+ /**
866
+ * The encoding hint of a decoded element: `encoding` plus its length octets when they are not the
867
+ * minimal form. Undefined when there is nothing to record.
868
+ * @param element
869
+ * @param encoding
870
+ */
871
+ static #elementEncoding(element, encoding = {}) {
872
+ const hint = {};
873
+ if (!element.truncated && element.lengthOctets !== (0, BERElement_1.MinimalBERLengthOctets)(element.value.length))
874
+ hint.lengthOctets = element.lengthOctets;
875
+ if (encoding.width !== undefined)
876
+ hint.width = encoding.width;
877
+ if (encoding.content !== undefined)
878
+ hint.content = encoding.content;
879
+ return Object.keys(hint).length ? hint : undefined;
880
+ }
881
+ /**
882
+ * The value of a FLOATING-POINT content (MMS FloatingPoint: an exponent-width octet, then the IEEE
883
+ * 754 bits). IEC 61850-8-1 maps FLOAT32 to exponent width 8 with 4 octets, FLOAT64 to exponent
884
+ * width 11 with 8 octets; any other form has no value here and reads as 0.
885
+ * @param content
886
+ */
887
+ static #floatingPointValue(content) {
888
+ if (content.length === 5 && content[0] === 8)
889
+ return (0, HexToNumber_1.HexToFloat32)(content.subarray(1).toString('hex'));
890
+ if (content.length === 9 && content[0] === 11)
891
+ return content.readDoubleBE(1);
892
+ return 0;
893
+ }
894
+ /**
895
+ * Encode an INTEGER data item: in its recorded width while the value fits, else minimal
896
+ * @param tag
897
+ * @param value
898
+ * @param minimalHex the minimal content
899
+ * @param encoding
900
+ * @param signed
901
+ */
902
+ static #encodeIntegerItem(tag, value, minimalHex, encoding, signed) {
903
+ const content = _a.#fixedWidthContent(value, encoding.width, signed) ?? Buffer.from(minimalHex, 'hex');
904
+ return (0, BERElement_1.EncodeBERElement)(tag, content, encoding.lengthOctets);
905
+ }
906
+ /**
907
+ * The first goosePdu child element with `tag`
908
+ * @param tag
909
+ */
910
+ #findElement(tag) {
911
+ return this.#elements.find((element) => element.tag === tag);
912
+ }
913
+ /**
914
+ * Keep the encoding hint of a decoded goosePdu field, if it has one, for goosePdu.encoding
915
+ * @param field
916
+ * @param element
917
+ * @param width
918
+ */
919
+ #recordFieldEncoding(field, element, width) {
920
+ const encoding = _a.#elementEncoding(element, { width: width });
921
+ if (encoding)
922
+ this.#decodedEncoding[field] = encoding;
923
+ }
924
+ /**
925
+ * Decode an unsigned INTEGER goosePdu field, recording its width when it is not the minimal form
926
+ * @param field
927
+ * @param tag
928
+ * @param read the value of the content hex
929
+ */
930
+ #decodeUnsignedField(field, tag, read = HexToNumber_1.HexToUInt32) {
931
+ const element = this.#findElement(tag);
932
+ if (!element || !element.value.length) {
933
+ this.recordError(this.instance.goosePdu[field].getPath(), 'Not Found');
934
+ return undefined;
935
+ }
936
+ const value = read(element.value.toString('hex'));
937
+ this.instance.goosePdu[field].setValue(value);
938
+ this.#recordFieldEncoding(field, element, _a.#integerWidth(BigInt(value), (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(value), element.value, false));
939
+ return value;
940
+ }
941
+ /**
942
+ * The encoding hint given for a goosePdu field (empty when there is none)
943
+ * @param field
944
+ */
945
+ #fieldEncoding(field) {
946
+ const encoding = this.instance.goosePdu.encoding[field].getValue();
947
+ return encoding && typeof encoding === 'object' ? encoding : {};
948
+ }
949
+ /**
950
+ * Encode a goosePdu field element from its content, with the length octets its hint gives
951
+ * @param field
952
+ * @param tag
953
+ * @param content
954
+ */
955
+ #encodeField(field, tag, content) {
956
+ this.#encodedElements.push((0, BERElement_1.EncodeBERElement)(tag, content, this.#fieldEncoding(field).lengthOctets));
957
+ }
958
+ /**
959
+ * Encode an unsigned INTEGER goosePdu field: in its recorded width while the value fits, else minimal
960
+ * @param field
961
+ * @param tag
962
+ * @param value
963
+ */
964
+ #encodeUnsignedField(field, tag, value) {
965
+ const content = _a.#fixedWidthContent(BigInt(value), this.#fieldEncoding(field).width, false) ?? (0, NumberToBERBuffer_1.UInt32ToBERBuffer)(value);
966
+ this.#encodeField(field, tag, content);
967
+ }
771
968
  /**
772
969
  * Decode data TLV items
773
- * @param dataTLVs
970
+ * @param dataElements
971
+ * @param path
774
972
  * @protected
775
973
  */
776
- decodeDataTLVItem(dataTLVs, path) {
974
+ decodeDataTLVItem(dataElements, path) {
777
975
  const dataItems = [];
778
- dataTLVs.forEach((dataTLV, index) => {
976
+ dataElements.forEach((dataElement, index) => {
779
977
  const itemPath = `${path}[${index}]`;
780
- const length = dataTLV.getLength('number');
781
- const value = dataTLV.getValue('buffer');
782
- switch (dataTLV.getTag('number')) {
978
+ const value = dataElement.value;
979
+ const encoding = {};
980
+ let dataItem;
981
+ switch (dataElement.tag) {
783
982
  case 0x83:
784
983
  {
785
- dataItems.push({
984
+ dataItem = {
786
985
  dataType: ItemDataType.Boolean,
787
986
  value: !!parseInt(value.toString('hex'), 16)
788
- });
987
+ };
789
988
  }
790
989
  break;
791
990
  case 0x84:
792
991
  {
793
- dataItems.push(this.decodeBitStringItem(value, itemPath));
992
+ dataItem = this.decodeBitStringItem(value, itemPath);
794
993
  }
795
994
  break;
796
995
  case 0x85:
797
996
  {
798
- dataItems.push(this.decodeSignedIntegerItem(value, itemPath));
997
+ dataItem = this.decodeSignedIntegerItem(value, itemPath);
998
+ const intValue = BigInt(dataItem.value);
999
+ encoding.width = _a.#integerWidth(intValue, Buffer.from((0, NumberToBERHex_1.Int64ToBERHex)(intValue), 'hex'), value, true);
799
1000
  }
800
1001
  break;
801
1002
  case 0x86:
802
1003
  {
803
- dataItems.push(this.decodeUnsignedIntegerItem(value, itemPath));
1004
+ dataItem = this.decodeUnsignedIntegerItem(value, itemPath);
1005
+ const uintValue = BigInt(dataItem.value);
1006
+ encoding.width = _a.#integerWidth(uintValue, Buffer.from((0, NumberToBERHex_1.UInt64ToBERHex)(uintValue), 'hex'), value, false);
804
1007
  }
805
1008
  break;
806
1009
  case 0x87:
807
1010
  {
808
- dataItems.push({
809
- dataType: ItemDataType.FLOAT32,
810
- value: (0, HexToNumber_1.HexToFloat32)(value.toString('hex'))
811
- });
1011
+ dataItem = this.decodeFloatingPointItem(value, itemPath);
1012
+ //A form encode does not write (another exponent width) is kept as captured, and so is a
1013
+ //NaN, which encode would otherwise write as 0
1014
+ if (Number.isNaN(dataItem.value) || !Buffer.from((0, NumberToBERHex_1.Float32ToBERHex)(dataItem.value), 'hex').equals(value))
1015
+ encoding.content = value.toString('hex');
812
1016
  }
813
1017
  break;
814
1018
  case 0x89:
815
1019
  {
816
- dataItems.push({
1020
+ dataItem = {
817
1021
  dataType: ItemDataType.OCTETSTRING,
818
1022
  value: value.toString('hex')
819
- });
1023
+ };
820
1024
  }
821
1025
  break;
822
1026
  case 0x8a:
823
1027
  {
824
- dataItems.push({
1028
+ dataItem = {
825
1029
  dataType: ItemDataType.VISIBLESTRING,
826
1030
  value: value.toString('ascii')
827
- });
1031
+ };
828
1032
  }
829
1033
  break;
830
1034
  case 0x91:
831
1035
  {
832
- dataItems.push({
1036
+ dataItem = {
833
1037
  dataType: ItemDataType.TimeStamp,
834
1038
  //BigInt to preserve full 64-bit precision (parseInt would round above 2^53).
835
1039
  value: value.length ? BigInt(`0x${value.toString('hex')}`).toString() : '0'
836
- });
1040
+ };
837
1041
  }
838
1042
  break;
839
1043
  case 0xa2:
840
1044
  {
841
- const subDataTLVs = node_tlv_1.default.parseList(value);
842
- dataItems.push({
1045
+ dataItem = {
843
1046
  dataType: ItemDataType.Structure,
844
- value: this.decodeDataTLVItem(subDataTLVs, `${itemPath}.value`)
845
- });
1047
+ value: this.decodeDataTLVItem((0, BERElement_1.ReadBERElements)(value), `${itemPath}.value`)
1048
+ };
846
1049
  }
847
1050
  break;
1051
+ default:
1052
+ return;
848
1053
  }
1054
+ const itemEncoding = _a.#elementEncoding(dataElement, encoding);
1055
+ if (itemEncoding)
1056
+ dataItem.encoding = itemEncoding;
1057
+ dataItems.push(dataItem);
849
1058
  });
850
1059
  return dataItems;
851
1060
  }
@@ -922,6 +1131,25 @@ class Goose extends BaseHeader_1.BaseHeader {
922
1131
  this.recordError(path, 'Unsigned INTEGER exceeds 32 bits');
923
1132
  return { dataType: ItemDataType.INT32U, value: uintValue };
924
1133
  }
1134
+ /**
1135
+ * Decode a FLOATING-POINT (tag 0x87) data item
1136
+ * The first content octet is the exponent width, not part of the number: IEC 61850-8-1 encodes a
1137
+ * FLOAT32 as 08 followed by the 4 octets of an IEEE 754 single. A FLOAT64 (exponent width 11, 8
1138
+ * octets) keeps its value; other forms read as 0. Either way the item re-encodes as captured until
1139
+ * its value changes.
1140
+ * @param value
1141
+ * @param path
1142
+ * @protected
1143
+ */
1144
+ decodeFloatingPointItem(value, path) {
1145
+ if (value.length === 9 && value[0] === 11) {
1146
+ this.recordError(path, 'FLOAT64 (exponent width 11) decoded as FLOAT32', 'warning');
1147
+ }
1148
+ else if (value.length !== 5 || value[0] !== 8) {
1149
+ this.recordError(path, 'FLOATING-POINT is not a FLOAT32 (exponent width 8, 4 value octets), decoded as 0');
1150
+ }
1151
+ return { dataType: ItemDataType.FLOAT32, value: _a.#floatingPointValue(value) };
1152
+ }
925
1153
  /**
926
1154
  * Encode data TLV items
927
1155
  * @param dataItems
@@ -931,10 +1159,10 @@ class Goose extends BaseHeader_1.BaseHeader {
931
1159
  return dataItems
932
1160
  .map((dataItem, index) => {
933
1161
  const errorNodePath = this.instance.goosePdu.allData.getPath(index);
1162
+ const encoding = dataItem.encoding && typeof dataItem.encoding === 'object' ? dataItem.encoding : {};
934
1163
  switch (dataItem.dataType) {
935
1164
  case ItemDataType.Boolean: {
936
- const booleanIntValue = dataItem.value ? 1 : 0;
937
- return new node_tlv_1.default(0x83, Buffer.from(booleanIntValue.toString(16).padStart(2, '0'), 'hex'));
1165
+ return (0, BERElement_1.EncodeBERElement)(0x83, Buffer.from([dataItem.value ? 1 : 0]), encoding.lengthOctets);
938
1166
  }
939
1167
  case ItemDataType.INT8: {
940
1168
  let intValue = dataItem.value;
@@ -943,7 +1171,7 @@ class Goose extends BaseHeader_1.BaseHeader {
943
1171
  intValue = intValue ? intValue : 0;
944
1172
  if (intValue < -128 || intValue > 127)
945
1173
  this.recordError(errorNodePath, 'Invalid INT8 value');
946
- return new node_tlv_1.default(0x85, Buffer.from((0, NumberToBERHex_1.Int8ToBERHex)(intValue), 'hex'));
1174
+ return _a.#encodeIntegerItem(0x85, BigInt(intValue), (0, NumberToBERHex_1.Int8ToBERHex)(intValue), encoding, true);
947
1175
  }
948
1176
  case ItemDataType.INT16: {
949
1177
  let intValue = dataItem.value;
@@ -952,7 +1180,7 @@ class Goose extends BaseHeader_1.BaseHeader {
952
1180
  intValue = intValue ? intValue : 0;
953
1181
  if (intValue < -32768 || intValue > 32767)
954
1182
  this.recordError(errorNodePath, 'Invalid INT16 value');
955
- return new node_tlv_1.default(0x85, Buffer.from((0, NumberToBERHex_1.Int16ToBERHex)(intValue), 'hex'));
1183
+ return _a.#encodeIntegerItem(0x85, BigInt(intValue), (0, NumberToBERHex_1.Int16ToBERHex)(intValue), encoding, true);
956
1184
  }
957
1185
  case ItemDataType.INT32: {
958
1186
  let intValue = dataItem.value;
@@ -961,7 +1189,7 @@ class Goose extends BaseHeader_1.BaseHeader {
961
1189
  intValue = intValue ? intValue : 0;
962
1190
  if (intValue < -2147483648 || intValue > 2147483647)
963
1191
  this.recordError(errorNodePath, 'Invalid INT32 value');
964
- return new node_tlv_1.default(0x85, Buffer.from((0, NumberToBERHex_1.Int32ToBERHex)(intValue), 'hex'));
1192
+ return _a.#encodeIntegerItem(0x85, BigInt(intValue), (0, NumberToBERHex_1.Int32ToBERHex)(intValue), encoding, true);
965
1193
  }
966
1194
  case ItemDataType.INT64: {
967
1195
  let intValue = 0n;
@@ -973,7 +1201,7 @@ class Goose extends BaseHeader_1.BaseHeader {
973
1201
  }
974
1202
  if (intValue < BigInt('-9223372036854775808') || intValue > BigInt('9223372036854775807'))
975
1203
  this.recordError(errorNodePath, 'Invalid INT64 value');
976
- return new node_tlv_1.default(0x85, Buffer.from((0, NumberToBERHex_1.Int64ToBERHex)(intValue), 'hex'));
1204
+ return _a.#encodeIntegerItem(0x85, intValue, (0, NumberToBERHex_1.Int64ToBERHex)(intValue), encoding, true);
977
1205
  }
978
1206
  case ItemDataType.INT8U: {
979
1207
  let uintValue = dataItem.value;
@@ -982,7 +1210,7 @@ class Goose extends BaseHeader_1.BaseHeader {
982
1210
  uintValue = uintValue ? uintValue : 0;
983
1211
  if (uintValue < 0 || uintValue > 255)
984
1212
  this.recordError(errorNodePath, 'Invalid INT8U value');
985
- return new node_tlv_1.default(0x86, Buffer.from((0, NumberToBERHex_1.UInt8ToBERHex)(uintValue), 'hex'));
1213
+ return _a.#encodeIntegerItem(0x86, BigInt(uintValue), (0, NumberToBERHex_1.UInt8ToBERHex)(uintValue), encoding, false);
986
1214
  }
987
1215
  case ItemDataType.INT16U: {
988
1216
  let uintValue = dataItem.value;
@@ -991,7 +1219,7 @@ class Goose extends BaseHeader_1.BaseHeader {
991
1219
  uintValue = uintValue ? uintValue : 0;
992
1220
  if (uintValue < 0 || uintValue > 65535)
993
1221
  this.recordError(errorNodePath, 'Invalid INT16U value');
994
- return new node_tlv_1.default(0x86, Buffer.from((0, NumberToBERHex_1.UInt16ToBERHex)(uintValue), 'hex'));
1222
+ return _a.#encodeIntegerItem(0x86, BigInt(uintValue), (0, NumberToBERHex_1.UInt16ToBERHex)(uintValue), encoding, false);
995
1223
  }
996
1224
  case ItemDataType.INT32U: {
997
1225
  let uintValue = dataItem.value;
@@ -1000,14 +1228,19 @@ class Goose extends BaseHeader_1.BaseHeader {
1000
1228
  uintValue = uintValue ? uintValue : 0;
1001
1229
  if (uintValue < 0 || uintValue > 4294967295)
1002
1230
  this.recordError(errorNodePath, 'Invalid INT32U value');
1003
- return new node_tlv_1.default(0x86, Buffer.from((0, NumberToBERHex_1.UInt32ToBERHex)(uintValue), 'hex'));
1231
+ return _a.#encodeIntegerItem(0x86, BigInt(uintValue), (0, NumberToBERHex_1.UInt32ToBERHex)(uintValue), encoding, false);
1004
1232
  }
1005
1233
  case ItemDataType.FLOAT32: {
1234
+ //A form encode does not write itself goes out as captured while it still holds the value
1235
+ const captured = encoding.content ? Buffer.from(encoding.content, 'hex') : undefined;
1236
+ if (captured && Object.is(_a.#floatingPointValue(captured), dataItem.value))
1237
+ return (0, BERElement_1.EncodeBERElement)(0x87, captured, encoding.lengthOctets);
1006
1238
  let float32Value = dataItem.value;
1007
1239
  if (isNaN(float32Value))
1008
1240
  this.recordError(errorNodePath, 'Invalid FLOAT32 value');
1009
- float32Value = float32Value ? float32Value : 0;
1010
- return new node_tlv_1.default(0x87, Buffer.from((0, NumberToBERHex_1.Float32ToBERHex)(float32Value), 'hex'));
1241
+ //Keeps -0 (80000000), which a truthiness check turned into +0
1242
+ float32Value = typeof float32Value === 'number' && !isNaN(float32Value) ? float32Value : 0;
1243
+ return (0, BERElement_1.EncodeBERElement)(0x87, Buffer.from((0, NumberToBERHex_1.Float32ToBERHex)(float32Value), 'hex'), encoding.lengthOctets);
1011
1244
  }
1012
1245
  case ItemDataType.CODEDENUM: {
1013
1246
  let codedEnumValue = dataItem.value;
@@ -1020,7 +1253,7 @@ class Goose extends BaseHeader_1.BaseHeader {
1020
1253
  }
1021
1254
  //A BIT STRING, not an INTEGER: always 2 octets and never sign-padded, so it
1022
1255
  //re-decodes as CODED-ENUM (a 1-octet or 00-padded 3-octet form did not).
1023
- return new node_tlv_1.default(0x84, Buffer.from((0, NumberToHex_1.UInt16ToHex)(codedEnumValue), 'hex'));
1256
+ return (0, BERElement_1.EncodeBERElement)(0x84, Buffer.from((0, NumberToHex_1.UInt16ToHex)(codedEnumValue), 'hex'), encoding.lengthOctets);
1024
1257
  }
1025
1258
  case ItemDataType.OCTETSTRING: {
1026
1259
  const hexText = dataItem.value;
@@ -1030,7 +1263,7 @@ class Goose extends BaseHeader_1.BaseHeader {
1030
1263
  }
1031
1264
  if (hexText.length > 40)
1032
1265
  this.recordError(errorNodePath, 'OCTET-STRING too long');
1033
- return new node_tlv_1.default(0x89, Buffer.from(hexText, 'hex').subarray(0, 20));
1266
+ return (0, BERElement_1.EncodeBERElement)(0x89, Buffer.from(hexText, 'hex').subarray(0, 20), encoding.lengthOctets);
1034
1267
  }
1035
1268
  case ItemDataType.VISIBLESTRING: {
1036
1269
  const asciiText = dataItem.value;
@@ -1044,7 +1277,7 @@ class Goose extends BaseHeader_1.BaseHeader {
1044
1277
  //bytes directly. The previous padStart(35*2) used a space fill, so
1045
1278
  //Buffer.from(<space-prefixed hex>,'hex') stopped at the first space and
1046
1279
  //produced an empty buffer for any string shorter than 35 chars.
1047
- return new node_tlv_1.default(0x8a, Buffer.from(asciiText, 'ascii').subarray(0, 35));
1280
+ return (0, BERElement_1.EncodeBERElement)(0x8a, Buffer.from(asciiText, 'ascii').subarray(0, 35), encoding.lengthOctets);
1048
1281
  }
1049
1282
  case ItemDataType.TimeStamp: {
1050
1283
  //Use BigInt + padStart(16,'0') like the top-level goosePdu.t field: a
@@ -1057,7 +1290,7 @@ class Goose extends BaseHeader_1.BaseHeader {
1057
1290
  catch (e) {
1058
1291
  this.recordError(errorNodePath, 'Invalid TimeStamp value');
1059
1292
  }
1060
- return new node_tlv_1.default(0x91, Buffer.from(timestamp.toString(16).padStart(8 * 2, '0'), 'hex'));
1293
+ return (0, BERElement_1.EncodeBERElement)(0x91, Buffer.from(timestamp.toString(16).padStart(8 * 2, '0'), 'hex'), encoding.lengthOctets);
1061
1294
  }
1062
1295
  case ItemDataType.Quality: {
1063
1296
  let bitString = `${dataItem.value}`;
@@ -1068,14 +1301,14 @@ class Goose extends BaseHeader_1.BaseHeader {
1068
1301
  //At least 3 octets; a wider bit string keeps its full width. BigInt + padStart
1069
1302
  //avoids the odd-length hex that Buffer.from(...,'hex') silently truncated.
1070
1303
  const octets = Math.max(3, Math.ceil(bitString.length / 8));
1071
- return new node_tlv_1.default(0x84, Buffer.from(BigInt(`0b${bitString}`).toString(16).padStart(octets * 2, '0'), 'hex'));
1304
+ return (0, BERElement_1.EncodeBERElement)(0x84, Buffer.from(BigInt(`0b${bitString}`).toString(16).padStart(octets * 2, '0'), 'hex'), encoding.lengthOctets);
1072
1305
  }
1073
1306
  case ItemDataType.Structure: {
1074
1307
  //A Structure without members (value omitted) is an empty SEQUENCE, not an error.
1075
1308
  const members = Array.isArray(dataItem.value) ? dataItem.value : [];
1076
1309
  if (dataItem.value !== undefined && !Array.isArray(dataItem.value))
1077
1310
  this.recordError(errorNodePath, 'Invalid Structure value, encoded as empty');
1078
- return new node_tlv_1.default(0xa2, Buffer.concat(this.encodeDataTLVItem(members).map((tlv) => Buffer.concat([tlv.bTag, tlv.bLength, tlv.bValue]))));
1311
+ return (0, BERElement_1.EncodeBERElement)(0xa2, Buffer.concat(this.encodeDataTLVItem(members)), encoding.lengthOctets);
1079
1312
  }
1080
1313
  default: {
1081
1314
  this.recordError(errorNodePath, 'Invalid dataType, ignored');
@@ -1090,5 +1323,13 @@ class Goose extends BaseHeader_1.BaseHeader {
1090
1323
  return false;
1091
1324
  return this.prevCodecModule.instance.etherType.getValue() === (0, NumberToHex_1.UInt16ToHex)(0x88b8);
1092
1325
  }
1326
+ payloadEnd() {
1327
+ //Length counts the octets from APPID on: the 8-octet header plus the goosePdu (IEC 61850-8-1).
1328
+ //Bytes past it (Ethernet padding, a trailer) are not GOOSE. A Length shorter than the header
1329
+ //sets no bound.
1330
+ const length = this.instance.length.getValue(0);
1331
+ return length >= 8 ? this.startPos + length : undefined;
1332
+ }
1093
1333
  }
1094
1334
  exports.Goose = Goose;
1335
+ _a = Goose;