@netkitty/codec 1.2.1 → 2.0.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 (176) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/README.md +58 -10
  3. package/README.zh-CN.md +52 -9
  4. package/dist/Codec.d.ts +3 -2
  5. package/dist/Codec.js +106 -10
  6. package/dist/abstracts/BaseHeader.d.ts +28 -2
  7. package/dist/abstracts/BaseHeader.js +132 -43
  8. package/dist/errors/CodecSchemaValidateError.d.ts +34 -1
  9. package/dist/errors/CodecSchemaValidateError.js +26 -3
  10. package/dist/headers/ADSAMS.js +2 -0
  11. package/dist/headers/AH.js +1 -0
  12. package/dist/headers/AMQP.js +2 -1
  13. package/dist/headers/ARP.js +16 -10
  14. package/dist/headers/BACnetIP.js +1 -0
  15. package/dist/headers/BGP.js +1 -0
  16. package/dist/headers/Babel.js +2 -1
  17. package/dist/headers/BitTorrent.d.ts +2 -0
  18. package/dist/headers/BitTorrent.js +4 -2
  19. package/dist/headers/C37118.js +1 -0
  20. package/dist/headers/CAPWAP.js +1 -0
  21. package/dist/headers/CDP.js +1 -1
  22. package/dist/headers/CMS.js +2 -2
  23. package/dist/headers/COTP.d.ts +2 -0
  24. package/dist/headers/COTP.js +6 -1
  25. package/dist/headers/CassandraCQL.js +1 -0
  26. package/dist/headers/Codesys.js +1 -0
  27. package/dist/headers/Collectd.js +1 -1
  28. package/dist/headers/DCCP.js +1 -0
  29. package/dist/headers/DHCPFailover.js +1 -0
  30. package/dist/headers/DNS.js +3 -3
  31. package/dist/headers/DTLS.js +1 -0
  32. package/dist/headers/Diameter.js +3 -2
  33. package/dist/headers/EAPOL.js +1 -1
  34. package/dist/headers/EIGRP.js +1 -1
  35. package/dist/headers/ENIP.js +1 -0
  36. package/dist/headers/Elasticsearch.js +1 -0
  37. package/dist/headers/EtherCAT.js +1 -0
  38. package/dist/headers/EthernetII.js +6 -0
  39. package/dist/headers/FTP.js +6 -6
  40. package/dist/headers/Finger.js +3 -3
  41. package/dist/headers/FoundationFieldbusHSE.js +1 -0
  42. package/dist/headers/GELF.js +7 -1
  43. package/dist/headers/GENEVE.js +1 -1
  44. package/dist/headers/GLBP.js +1 -1
  45. package/dist/headers/GTPU.js +1 -0
  46. package/dist/headers/GTPv2C.js +1 -0
  47. package/dist/headers/GitProtocol.js +2 -2
  48. package/dist/headers/Goose.js +20 -8
  49. package/dist/headers/Gopher.js +6 -6
  50. package/dist/headers/HARTIP.js +1 -0
  51. package/dist/headers/HSR.js +2 -0
  52. package/dist/headers/HTTP.js +6 -6
  53. package/dist/headers/HTTP2.js +1 -0
  54. package/dist/headers/ICMP.js +1 -0
  55. package/dist/headers/ICMPv6.js +1 -0
  56. package/dist/headers/IEC104_I_Frame.js +26 -3
  57. package/dist/headers/IEC104_S_Frame.js +7 -2
  58. package/dist/headers/IEC104_U_Frame.js +14 -3
  59. package/dist/headers/IEC61850SampledValues.js +2 -1
  60. package/dist/headers/IGMP.js +1 -0
  61. package/dist/headers/IMAP.js +5 -5
  62. package/dist/headers/IPFIX.js +2 -1
  63. package/dist/headers/IPv4.js +18 -1
  64. package/dist/headers/IPv6.js +1 -0
  65. package/dist/headers/IPv6HopByHopOptions.js +12 -11
  66. package/dist/headers/IRC.js +4 -4
  67. package/dist/headers/ISAKMP.js +2 -1
  68. package/dist/headers/ISCSI.js +2 -0
  69. package/dist/headers/ISIS.js +2 -1
  70. package/dist/headers/ISOSession.d.ts +2 -0
  71. package/dist/headers/ISOSession.js +14 -10
  72. package/dist/headers/Ident.js +8 -8
  73. package/dist/headers/KNXnetIP.js +1 -0
  74. package/dist/headers/Kafka.js +1 -0
  75. package/dist/headers/Kerberos.js +1 -0
  76. package/dist/headers/L2TP.js +2 -2
  77. package/dist/headers/LACP.js +1 -1
  78. package/dist/headers/LDAP.js +2 -3
  79. package/dist/headers/LDP.js +1 -0
  80. package/dist/headers/LLC.d.ts +2 -0
  81. package/dist/headers/LLC.js +2 -0
  82. package/dist/headers/LPD.js +3 -3
  83. package/dist/headers/MGCP.js +7 -7
  84. package/dist/headers/MMS.d.ts +2 -0
  85. package/dist/headers/MMS.js +10 -6
  86. package/dist/headers/MQTT.js +1 -0
  87. package/dist/headers/MQTTSN.js +1 -0
  88. package/dist/headers/MarkerProtocol.js +1 -1
  89. package/dist/headers/Megaco.js +3 -3
  90. package/dist/headers/Memcached.js +3 -2
  91. package/dist/headers/ModbusTCP.js +1 -0
  92. package/dist/headers/ModbusUDP.js +1 -0
  93. package/dist/headers/MongoDB.js +1 -0
  94. package/dist/headers/MySQL.js +1 -0
  95. package/dist/headers/NATS.js +2 -2
  96. package/dist/headers/NBDS.js +1 -0
  97. package/dist/headers/NBSS.js +1 -0
  98. package/dist/headers/NFS.js +1 -0
  99. package/dist/headers/NHRP.js +1 -0
  100. package/dist/headers/NNTP.js +6 -6
  101. package/dist/headers/NetFlowV5.js +1 -0
  102. package/dist/headers/OLSR.js +2 -1
  103. package/dist/headers/OPCUA.js +1 -0
  104. package/dist/headers/OpenFlow.js +1 -0
  105. package/dist/headers/OpenVPN.js +1 -0
  106. package/dist/headers/PCWorx.js +1 -0
  107. package/dist/headers/POP3.js +5 -5
  108. package/dist/headers/PPPoEDiscovery.js +2 -1
  109. package/dist/headers/PPPoESession.js +1 -0
  110. package/dist/headers/PPTP.js +1 -0
  111. package/dist/headers/PTP.js +1 -0
  112. package/dist/headers/PostgreSQL.js +2 -0
  113. package/dist/headers/QUIC.js +2 -0
  114. package/dist/headers/RADIUS.js +1 -0
  115. package/dist/headers/RDP.d.ts +2 -0
  116. package/dist/headers/RDP.js +4 -1
  117. package/dist/headers/RFB.js +4 -4
  118. package/dist/headers/RGoose.js +6 -1
  119. package/dist/headers/RSVP.js +3 -2
  120. package/dist/headers/RTCP.js +1 -0
  121. package/dist/headers/RTP.js +2 -1
  122. package/dist/headers/RTPS.d.ts +2 -0
  123. package/dist/headers/RTPS.js +4 -1
  124. package/dist/headers/RTSP.js +7 -7
  125. package/dist/headers/RawData.js +1 -1
  126. package/dist/headers/Redis.js +4 -4
  127. package/dist/headers/Rlogin.js +5 -5
  128. package/dist/headers/Rsync.js +2 -2
  129. package/dist/headers/S7comm.d.ts +2 -0
  130. package/dist/headers/S7comm.js +5 -1
  131. package/dist/headers/SCTP.js +2 -2
  132. package/dist/headers/SFlow.js +2 -1
  133. package/dist/headers/SIP.js +6 -6
  134. package/dist/headers/SLMP.js +1 -0
  135. package/dist/headers/SLP.js +2 -0
  136. package/dist/headers/SLPv1.js +1 -0
  137. package/dist/headers/SMB1.js +1 -0
  138. package/dist/headers/SMB2.js +1 -0
  139. package/dist/headers/SMPP.js +1 -0
  140. package/dist/headers/SMTP.js +6 -6
  141. package/dist/headers/SNAP.js +18 -5
  142. package/dist/headers/SNMP.js +4 -4
  143. package/dist/headers/SOCKS4.js +11 -5
  144. package/dist/headers/SSDP.js +7 -7
  145. package/dist/headers/SSH.js +5 -4
  146. package/dist/headers/STOMP.js +5 -5
  147. package/dist/headers/STUN.js +2 -0
  148. package/dist/headers/Skinny.js +1 -0
  149. package/dist/headers/StatsD.js +4 -4
  150. package/dist/headers/SunRPC.js +1 -0
  151. package/dist/headers/Syslog.js +2 -2
  152. package/dist/headers/TCP.js +18 -6
  153. package/dist/headers/TLS_Alert.js +23 -11
  154. package/dist/headers/TLS_ApplicationData.js +9 -4
  155. package/dist/headers/TLS_ChangeCipherSpec.js +10 -5
  156. package/dist/headers/TLS_Handshake.js +41 -26
  157. package/dist/headers/TLS_Heartbeat.js +10 -1
  158. package/dist/headers/TPKT.js +3 -1
  159. package/dist/headers/TacacsPlus.js +1 -0
  160. package/dist/headers/Telnet.js +2 -1
  161. package/dist/headers/Teredo.js +2 -2
  162. package/dist/headers/UDP.js +8 -0
  163. package/dist/headers/VLAN_802dot1Q.js +7 -0
  164. package/dist/headers/WCCP.js +1 -0
  165. package/dist/headers/WHOIS.js +3 -3
  166. package/dist/headers/WSDiscovery.js +2 -2
  167. package/dist/headers/XMPP.js +3 -3
  168. package/dist/headers/Zabbix.js +1 -0
  169. package/dist/index.d.ts +3 -3
  170. package/dist/lib/SchemaValidator.d.ts +31 -0
  171. package/dist/lib/SchemaValidator.js +137 -0
  172. package/dist/schema/ProtocolFieldJSONSchema.d.ts +4 -1
  173. package/dist/schema/ProtocolJSONSchema.d.ts +1 -1
  174. package/dist/types/CodecErrorInfo.d.ts +11 -0
  175. package/dist/types/LayerGraph.d.ts +14 -1
  176. package/package.json +2 -2
@@ -57,6 +57,7 @@ class WCCP extends BaseHeader_1.BaseHeader {
57
57
  version: this.fieldUInt('version', 4, 2, 'Version'),
58
58
  length: {
59
59
  type: 'integer',
60
+ autoCalculated: true,
60
61
  label: 'Length',
61
62
  minimum: 0,
62
63
  maximum: 65535,
@@ -81,10 +81,10 @@ class WHOIS extends BaseHeader_1.BaseHeader {
81
81
  //Display-only metadata parsed from the verbatim payload on decode (no encode — populated
82
82
  //by the `message` field below, never read back). `query` is the first line (the request
83
83
  //domain or a response's opening line); `isQuery` flags the single-line request shape.
84
- isQuery: { type: 'boolean', label: 'Is Query', default: false },
85
- query: { type: 'string', label: 'Query', default: '' },
84
+ isQuery: { type: 'boolean', label: 'Is Query', readOnly: true, default: false },
85
+ query: { type: 'string', label: 'Query', readOnly: true, default: '' },
86
86
  //Drives the one-line summary: the first line of the payload, else 'response'.
87
- summaryInfo: { type: 'string', label: 'Summary', hidden: true, default: '' },
87
+ summaryInfo: { type: 'string', label: 'Summary', readOnly: true, hidden: true, default: '' },
88
88
  //The whole raw payload is the single source of truth: decoded verbatim to hex and
89
89
  //re-emitted untouched (byte-perfect for any WHOIS payload). The first line is parsed into
90
90
  //the display-only metadata above, which carry no codec of their own.
@@ -96,8 +96,8 @@ class WSDiscovery extends BaseHeader_1.BaseHeader {
96
96
  //Display-only metadata parsed from the WS-Addressing Action on decode (no encode —
97
97
  //populated by the message field above, never read back). action is the full Action URI;
98
98
  //messageType is its short trailing segment (Probe / Hello / Bye / …).
99
- action: { type: 'string', label: 'Action' },
100
- messageType: { type: 'string', label: 'Message Type' }
99
+ action: { type: 'string', label: 'Action', readOnly: true },
100
+ messageType: { type: 'string', label: 'Message Type', readOnly: true }
101
101
  }
102
102
  };
103
103
  }
@@ -124,9 +124,9 @@ class XMPP extends BaseHeader_1.BaseHeader {
124
124
  //message field above, never read back). rootElement is the first element's tag name (e.g.
125
125
  //'stream:stream', 'message', 'iq', 'presence'); isStreamHeader flags the stream preamble;
126
126
  //hasXmlDeclaration flags a leading `<?xml … ?>`.
127
- rootElement: { type: 'string', label: 'Root Element' },
128
- isStreamHeader: { type: 'boolean', label: 'Is Stream Header' },
129
- hasXmlDeclaration: { type: 'boolean', label: 'Has XML Declaration' }
127
+ rootElement: { type: 'string', label: 'Root Element', readOnly: true },
128
+ isStreamHeader: { type: 'boolean', label: 'Is Stream Header', readOnly: true },
129
+ hasXmlDeclaration: { type: 'boolean', label: 'Has XML Declaration', readOnly: true }
130
130
  }
131
131
  };
132
132
  }
@@ -85,6 +85,7 @@ class Zabbix extends BaseHeader_1.BaseHeader {
85
85
  flags: this.fieldUInt('flags', 4, 1, 'Flags'),
86
86
  dataLength: {
87
87
  type: 'integer',
88
+ autoCalculated: true,
88
89
  label: 'Data Length',
89
90
  minimum: 0,
90
91
  maximum: 4294967295,
package/dist/index.d.ts CHANGED
@@ -20,8 +20,8 @@ export { type CodecSchema } from './types/CodecSchema';
20
20
  export { type HeaderTreeNode } from './types/HeaderTreeNode';
21
21
  export { type CodecModuleConstructor } from './types/CodecModuleConstructor';
22
22
  export { type CodecModule } from './types/CodecModule';
23
- export { type CodecErrorInfo } from './types/CodecErrorInfo';
24
- export { type NextLayer, type ConsistencyIssue } from './types/LayerGraph';
23
+ export { type CodecErrorInfo, type CodecErrorSeverity } from './types/CodecErrorInfo';
24
+ export { type NextLayer, type ConsistencyIssue, type HeuristicParent } from './types/LayerGraph';
25
25
  export { type DissectionField, type DissectionLayer } from './types/Dissection';
26
26
  /**
27
27
  * Schemas
@@ -53,4 +53,4 @@ export { Float32ToHex, Int16ToHex, Int32ToHex, Int64ToHex, Int8ToHex, UInt16ToHe
53
53
  /**
54
54
  * Error classes (all extend NetKittyError)
55
55
  */
56
- export { CodecSchemaValidateError } from './errors/CodecSchemaValidateError';
56
+ export { CodecSchemaValidateError, type CodecSchemaValidationIssue } from './errors/CodecSchemaValidateError';
@@ -0,0 +1,31 @@
1
+ import { ErrorObject, ValidateFunction } from 'ajv';
2
+ import { ProtocolJSONSchema } from '../schema/ProtocolJSONSchema';
3
+ import { CodecSchemaValidateError } from '../errors/CodecSchemaValidateError';
4
+ /**
5
+ * Derive the validation keywords a string field's `contentEncoding` implies, in place: an ipv4/ipv6/mac
6
+ * field gets `format: 'ipv4'|'ipv6'|'mac'`, a bigint field gets a numeric `pattern`. An explicit
7
+ * `format`/`pattern` on the field is left alone. Applied to every published schema (PROTOCOL_SCHEMA)
8
+ * and to every compiled validator, so the shape a UI sees and the shape encode enforces are the same,
9
+ * and every address field is constrained consistently without repeating the keyword per field.
10
+ */
11
+ export declare function DeriveContentConstraints<T>(node: T): T;
12
+ /**
13
+ * Compile the Ajv shape validator for a protocol schema. The schema's decode/encode closures are
14
+ * stripped first (the same JSON round-trip that produces PROTOCOL_SCHEMA), so only the declarative
15
+ * shell is compiled. One place for the Ajv options keeps every validator identical.
16
+ */
17
+ export declare function CompileSchemaValidator(schema: ProtocolJSONSchema): ValidateFunction;
18
+ /**
19
+ * The validator for a header class, compiled on first use and cached on that class. Compiling all
20
+ * ~190 schemas eagerly cost ~0.5 s at `new Codec()`; lazily, a codec only pays for the protocols it
21
+ * actually encodes.
22
+ */
23
+ export declare function SchemaValidatorOf(headerClass: object, schema: ProtocolJSONSchema): ValidateFunction;
24
+ /**
25
+ * Ajv instancePath (JSON Pointer, '/goosePdu/allData/0/dataType') → the dotted field path the codec
26
+ * uses everywhere else for errors ('goosePdu.allData[0].dataType'). A 'required' /
27
+ * 'additionalProperties' error points at the parent object, so the named property is appended.
28
+ */
29
+ export declare function AjvErrorFieldPath(error: ErrorObject): string;
30
+ /** Build the thrown error for a failed validation, carrying the layer, the field path and Ajv's errors. */
31
+ export declare function SchemaValidateErrorOf(layerId: string, ajvErrors: ErrorObject[] | null | undefined): CodecSchemaValidateError;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeriveContentConstraints = DeriveContentConstraints;
4
+ exports.CompileSchemaValidator = CompileSchemaValidator;
5
+ exports.SchemaValidatorOf = SchemaValidatorOf;
6
+ exports.AjvErrorFieldPath = AjvErrorFieldPath;
7
+ exports.SchemaValidateErrorOf = SchemaValidateErrorOf;
8
+ const ajv_1 = require("ajv");
9
+ const ip_address_1 = require("ip-address");
10
+ const CodecSchemaValidateError_1 = require("../errors/CodecSchemaValidateError");
11
+ const StringContentEncodingEnum_1 = require("./StringContentEncodingEnum");
12
+ /**
13
+ * Dotted-quad IPv4: four 0–255 decimal octets. Leading zeros ('010') are accepted because encode
14
+ * parses each octet as decimal (IPv4ToBuffer), so such input already encoded deterministically.
15
+ */
16
+ const IPV4_PATTERN = /^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/;
17
+ /** Colon-separated 6-octet MAC (what decode emits and encode parses). */
18
+ const MAC_PATTERN = /^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/;
19
+ /** A BigInt-convertible integer string: decimal (optionally negative) or 0x-hex. */
20
+ const BIGINT_PATTERN = '^(-?[0-9]+|0[xX][0-9a-fA-F]+)$';
21
+ /** Ajv `format` name each address content encoding validates against. */
22
+ const CONTENT_ENCODING_FORMATS = {
23
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.IPv4]: 'ipv4',
24
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.IPv6]: 'ipv6',
25
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.MAC]: 'mac'
26
+ };
27
+ /**
28
+ * Derive the validation keywords a string field's `contentEncoding` implies, in place: an ipv4/ipv6/mac
29
+ * field gets `format: 'ipv4'|'ipv6'|'mac'`, a bigint field gets a numeric `pattern`. An explicit
30
+ * `format`/`pattern` on the field is left alone. Applied to every published schema (PROTOCOL_SCHEMA)
31
+ * and to every compiled validator, so the shape a UI sees and the shape encode enforces are the same,
32
+ * and every address field is constrained consistently without repeating the keyword per field.
33
+ */
34
+ function DeriveContentConstraints(node) {
35
+ if (!node || typeof node !== 'object')
36
+ return node;
37
+ if (Array.isArray(node)) {
38
+ node.forEach((item) => DeriveContentConstraints(item));
39
+ return node;
40
+ }
41
+ const schemaNode = node;
42
+ const encoding = schemaNode.contentEncoding;
43
+ if (typeof encoding === 'string') {
44
+ if (CONTENT_ENCODING_FORMATS[encoding] && schemaNode.format === undefined)
45
+ schemaNode.format = CONTENT_ENCODING_FORMATS[encoding];
46
+ if (encoding === StringContentEncodingEnum_1.StringContentEncodingEnum.BIGINT && schemaNode.pattern === undefined)
47
+ schemaNode.pattern = BIGINT_PATTERN;
48
+ }
49
+ for (const key of ['properties', 'items', 'anyOf', 'oneOf', 'allOf', 'definitions', '$defs']) {
50
+ const child = schemaNode[key];
51
+ if (!child || typeof child !== 'object')
52
+ continue;
53
+ if (key === 'properties' || key === 'definitions' || key === '$defs')
54
+ Object.values(child).forEach((value) => DeriveContentConstraints(value));
55
+ else
56
+ DeriveContentConstraints(child);
57
+ }
58
+ return node;
59
+ }
60
+ //Own-property slot on each header class holding its compiled validator. Own (not inherited) so a
61
+ //custom codec extending a built-in compiles its own schema instead of reusing the base class's.
62
+ const VALIDATOR_KEY = '__validate';
63
+ /**
64
+ * Compile the Ajv shape validator for a protocol schema. The schema's decode/encode closures are
65
+ * stripped first (the same JSON round-trip that produces PROTOCOL_SCHEMA), so only the declarative
66
+ * shell is compiled. One place for the Ajv options keeps every validator identical.
67
+ */
68
+ function CompileSchemaValidator(schema) {
69
+ const ajv = new ajv_1.Ajv({
70
+ strict: false,
71
+ useDefaults: true,
72
+ coerceTypes: true
73
+ });
74
+ ajv.addFormat('ipv4', IPV4_PATTERN);
75
+ ajv.addFormat('ipv6', (value) => ip_address_1.Address6.isValid(value));
76
+ ajv.addFormat('mac', MAC_PATTERN);
77
+ return ajv.compile(DeriveContentConstraints(JSON.parse(JSON.stringify(schema))));
78
+ }
79
+ /**
80
+ * The validator for a header class, compiled on first use and cached on that class. Compiling all
81
+ * ~190 schemas eagerly cost ~0.5 s at `new Codec()`; lazily, a codec only pays for the protocols it
82
+ * actually encodes.
83
+ */
84
+ function SchemaValidatorOf(headerClass, schema) {
85
+ if (Object.hasOwn(headerClass, VALIDATOR_KEY))
86
+ return headerClass[VALIDATOR_KEY];
87
+ const validate = CompileSchemaValidator(schema);
88
+ Object.defineProperty(headerClass, VALIDATOR_KEY, { enumerable: false, configurable: false, writable: false, value: validate });
89
+ return validate;
90
+ }
91
+ /**
92
+ * Ajv instancePath (JSON Pointer, '/goosePdu/allData/0/dataType') → the dotted field path the codec
93
+ * uses everywhere else for errors ('goosePdu.allData[0].dataType'). A 'required' /
94
+ * 'additionalProperties' error points at the parent object, so the named property is appended.
95
+ */
96
+ function AjvErrorFieldPath(error) {
97
+ const segments = error.instancePath
98
+ .split('/')
99
+ .slice(1)
100
+ .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'));
101
+ const params = error.params;
102
+ if (error.keyword === 'required' && typeof params.missingProperty === 'string')
103
+ segments.push(params.missingProperty);
104
+ if (error.keyword === 'additionalProperties' && typeof params.additionalProperty === 'string')
105
+ segments.push(params.additionalProperty);
106
+ let path = '';
107
+ for (const segment of segments) {
108
+ if (/^\d+$/.test(segment))
109
+ path += `[${segment}]`;
110
+ else
111
+ path += path ? `.${segment}` : segment;
112
+ }
113
+ return path;
114
+ }
115
+ /** Build the thrown error for a failed validation, carrying the layer, the field path and Ajv's errors. */
116
+ function SchemaValidateErrorOf(layerId, ajvErrors) {
117
+ const errors = (ajvErrors ? ajvErrors : []).map((error) => ({
118
+ instancePath: error.instancePath,
119
+ schemaPath: error.schemaPath,
120
+ keyword: error.keyword,
121
+ params: error.params,
122
+ message: error.message ? error.message : '',
123
+ path: AjvErrorFieldPath(error)
124
+ }));
125
+ //Report the most specific failure. Inside an anyOf (option/item variants) Ajv lists every failed
126
+ //branch, and the first is usually just "must be equal to constant" on the variant discriminator
127
+ //of a branch that was never meant to match; the deepest instancePath is the real offending field.
128
+ //At equal depth a non-`const` failure wins over a sibling variant's discriminator mismatch. Ties
129
+ //otherwise keep Ajv's order, so a plain (non-anyOf) failure reports exactly Ajv's first error.
130
+ const score = (issue) => issue.instancePath.split('/').length * 2 + (issue.keyword === 'const' ? 0 : 1);
131
+ const primary = errors.reduce((best, issue) => (!best || score(issue) > score(best) ? issue : best), undefined);
132
+ return new CodecSchemaValidateError_1.CodecSchemaValidateError(primary && primary.message ? primary.message : 'Unknown Error', {
133
+ layerId: layerId,
134
+ path: primary ? primary.path : '',
135
+ errors: errors
136
+ });
137
+ }
@@ -5,6 +5,9 @@ export interface ProtocolFieldJSONSchema extends JSONSchema7 {
5
5
  decode?: () => void | Promise<void>;
6
6
  label?: string;
7
7
  hidden?: boolean;
8
+ readOnly?: boolean;
9
+ autoCalculated?: boolean;
10
+ byteAlignment?: number;
8
11
  $defs?: {
9
12
  [key: string]: ProtocolFieldJSONSchemaDefinition;
10
13
  } | undefined;
@@ -17,7 +20,7 @@ export interface ProtocolFieldJSONSchema extends JSONSchema7 {
17
20
  patternProperties?: {
18
21
  [key: string]: ProtocolFieldJSONSchemaDefinition;
19
22
  } | undefined;
20
- additionalProperties?: ProtocolFieldJSONSchemaDefinition | undefined;
23
+ additionalProperties?: ProtocolFieldJSONSchemaDefinition | boolean | undefined;
21
24
  dependencies?: {
22
25
  [key: string]: ProtocolFieldJSONSchemaDefinition | string[];
23
26
  } | undefined;
@@ -14,7 +14,7 @@ export interface ProtocolJSONSchema extends JSONSchema7 {
14
14
  patternProperties?: {
15
15
  [key: string]: ProtocolFieldJSONSchemaDefinition;
16
16
  } | undefined;
17
- additionalProperties?: ProtocolFieldJSONSchemaDefinition | undefined;
17
+ additionalProperties?: ProtocolFieldJSONSchemaDefinition | boolean | undefined;
18
18
  dependencies?: {
19
19
  [key: string]: ProtocolFieldJSONSchemaDefinition | string[];
20
20
  } | undefined;
@@ -1,5 +1,16 @@
1
+ /**
2
+ * How serious a recorded codec error is:
3
+ * - `error`: the field could not be decoded/encoded as given (malformed bytes on decode; an internal
4
+ * failure or an unencodable value on encode, so the emitted layer may be incomplete).
5
+ * - `warning`: encode wrote the layer but had to adjust or flag the input (value clamped to its
6
+ * range, a semantically odd value such as IPv4 version != 4, a checksum that could not be computed).
7
+ * - `info`: encode used a field's default because the input left it out ("Not Found").
8
+ */
9
+ export type CodecErrorSeverity = 'error' | 'warning' | 'info';
1
10
  export type CodecErrorInfo = {
2
11
  id: string;
3
12
  path: string;
4
13
  message: string;
14
+ /** Always set by the built-in codec; optional in the type so hand-built entries stay valid. */
15
+ severity?: CodecErrorSeverity;
5
16
  };
@@ -1,7 +1,20 @@
1
+ /**
2
+ * A parent a content-heuristic header can follow (BaseHeader.heuristicParents): the parent layer id,
3
+ * optionally with the parent field value the child needs (e.g. RDP needs COTP pduType 0xE0, a
4
+ * Connection Request) — reported by allowedNextLayers() as that child's discriminator.
5
+ */
6
+ export type HeuristicParent = string | {
7
+ parent: string;
8
+ discriminator: {
9
+ field: string;
10
+ value: string | number;
11
+ };
12
+ };
1
13
  /**
2
14
  * A layer that may follow a given parent layer in the editor's "add next layer" menu. `discriminator`
3
15
  * tells the caller which parent field to set (and to what) so decode would route to this layer;
4
- * it is null for RawData, which may always follow any layer.
16
+ * it is null when there is no parent field to set: RawData (which may follow any layer), and children
17
+ * recognized by their own content or by a value encode derives (LLC after eth, COTP after TPKT, …).
5
18
  */
6
19
  export type NextLayer = {
7
20
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netkitty/codec",
3
- "version": "1.2.1",
3
+ "version": "2.0.0",
4
4
  "description": "Schema-driven packet codec: encode/decode 180+ network and industrial (OT/ICS/SCADA) protocol headers — TCP/IP, TLS, HTTP/2, DNS, MQTT, plus Modbus, DNP3, IEC 61850 (GOOSE/SV/MMS), IEC 104, S7comm, OPC UA, PROFINET, EtherCAT, BACnet and more.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -138,5 +138,5 @@
138
138
  },
139
139
  "homepage": "https://github.com/myq1991/netkitty/tree/main/packages/codec#readme",
140
140
  "bugs": "https://github.com/myq1991/netkitty/issues",
141
- "gitHead": "519fdefcb5c76f69fade408cc36e0c2fa69ccad4"
141
+ "gitHead": "a0b16ffec11eb830dd5846bd942dd9a63ae04d5e"
142
142
  }