@bcts/dcbor 1.0.0-alpha.17 → 1.0.0-alpha.18

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/dist/index.mjs CHANGED
@@ -8044,6 +8044,268 @@ var CborDate = class CborDate {
8044
8044
  }
8045
8045
  };
8046
8046
 
8047
+ //#endregion
8048
+ //#region src/bignum.ts
8049
+ /**
8050
+ * CBOR bignum (tags 2 and 3) support.
8051
+ *
8052
+ * This module provides conversion between CBOR and JavaScript BigInt types,
8053
+ * implementing RFC 8949 §3.4.3 (Bignums) with dCBOR/CDE canonical encoding rules.
8054
+ *
8055
+ * Encoding:
8056
+ * - `biguintToCbor` always encodes as tag 2 (positive bignum) with a byte
8057
+ * string content.
8058
+ * - `bigintToCbor` encodes as tag 2 for non-negative values or tag 3
8059
+ * (negative bignum) for negative values.
8060
+ * - No numeric reduction is performed: values are always encoded as bignums,
8061
+ * even if they would fit in normal CBOR integers.
8062
+ *
8063
+ * Decoding:
8064
+ * - Accepts CBOR integers (major types 0 and 1) and converts them to bigints.
8065
+ * - Accepts tag 2 (positive bignum) and tag 3 (negative bignum) with byte
8066
+ * string content.
8067
+ * - Enforces shortest-form canonical representation for bignum magnitudes.
8068
+ * - Rejects floating-point values.
8069
+ *
8070
+ * @module bignum
8071
+ */
8072
+ const TAG_2_POSITIVE_BIGNUM = 2;
8073
+ const TAG_3_NEGATIVE_BIGNUM = 3;
8074
+ /**
8075
+ * Validates that a bignum magnitude byte string is in shortest canonical form.
8076
+ *
8077
+ * Matches Rust's `validate_bignum_magnitude()`.
8078
+ *
8079
+ * Rules:
8080
+ * - For positive bignums (tag 2): empty byte string represents zero;
8081
+ * non-empty must not have leading zero bytes.
8082
+ * - For negative bignums (tag 3): byte string must not be empty
8083
+ * (magnitude zero is encoded as `0x00`); must not have leading zero bytes
8084
+ * except when the magnitude is zero (single `0x00`).
8085
+ *
8086
+ * @param bytes - The magnitude byte string to validate
8087
+ * @param isNegative - Whether this is for a negative bignum (tag 3)
8088
+ * @throws CborError with type NonCanonicalNumeric on validation failure
8089
+ */
8090
+ function validateBignumMagnitude(bytes, isNegative) {
8091
+ if (isNegative) {
8092
+ if (bytes.length === 0) throw new CborError({ type: "NonCanonicalNumeric" });
8093
+ if (bytes.length > 1 && bytes[0] === 0) throw new CborError({ type: "NonCanonicalNumeric" });
8094
+ } else if (bytes.length > 0 && bytes[0] === 0) throw new CborError({ type: "NonCanonicalNumeric" });
8095
+ }
8096
+ /**
8097
+ * Strips leading zero bytes from a byte array, returning the minimal
8098
+ * representation.
8099
+ *
8100
+ * Matches Rust's `strip_leading_zeros()`.
8101
+ *
8102
+ * @param bytes - The byte array to strip
8103
+ * @returns A subarray with leading zeros removed
8104
+ */
8105
+ function stripLeadingZeros(bytes) {
8106
+ let start = 0;
8107
+ while (start < bytes.length && bytes[start] === 0) start++;
8108
+ return bytes.subarray(start);
8109
+ }
8110
+ /**
8111
+ * Convert a non-negative bigint to a big-endian byte array.
8112
+ *
8113
+ * Zero returns an empty Uint8Array.
8114
+ *
8115
+ * @param value - A non-negative bigint value
8116
+ * @returns Big-endian byte representation
8117
+ */
8118
+ function bigintToBytes(value) {
8119
+ if (value === 0n) return new Uint8Array(0);
8120
+ const hex = value.toString(16);
8121
+ const padded = hex.length % 2 !== 0 ? `0${hex}` : hex;
8122
+ const bytes = new Uint8Array(padded.length / 2);
8123
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(padded.substring(i * 2, i * 2 + 2), 16);
8124
+ return bytes;
8125
+ }
8126
+ /**
8127
+ * Convert a big-endian byte array to a bigint.
8128
+ *
8129
+ * Empty array returns 0n.
8130
+ *
8131
+ * @param bytes - Big-endian byte representation
8132
+ * @returns The bigint value
8133
+ */
8134
+ function bytesToBigint(bytes) {
8135
+ if (bytes.length === 0) return 0n;
8136
+ let result = 0n;
8137
+ for (const byte of bytes) result = result << 8n | BigInt(byte);
8138
+ return result;
8139
+ }
8140
+ /**
8141
+ * Encode a non-negative bigint as a CBOR tag 2 (positive bignum).
8142
+ *
8143
+ * Matches Rust's `From<BigUint> for CBOR`.
8144
+ *
8145
+ * The value is always encoded as a bignum regardless of size.
8146
+ * Zero is encoded as tag 2 with an empty byte string.
8147
+ *
8148
+ * @param value - A non-negative bigint (must be >= 0n)
8149
+ * @returns CBOR tagged value
8150
+ * @throws CborError with type OutOfRange if value is negative
8151
+ */
8152
+ function biguintToCbor(value) {
8153
+ if (value < 0n) throw new CborError({ type: "OutOfRange" });
8154
+ return toTaggedValue(TAG_2_POSITIVE_BIGNUM, stripLeadingZeros(bigintToBytes(value)));
8155
+ }
8156
+ /**
8157
+ * Encode a bigint as a CBOR tag 2 or tag 3 bignum.
8158
+ *
8159
+ * Matches Rust's `From<BigInt> for CBOR`.
8160
+ *
8161
+ * - Non-negative values use tag 2 (positive bignum).
8162
+ * - Negative values use tag 3 (negative bignum), where the encoded
8163
+ * magnitude is `|value| - 1` per RFC 8949.
8164
+ *
8165
+ * @param value - Any bigint value
8166
+ * @returns CBOR tagged value
8167
+ */
8168
+ function bigintToCbor(value) {
8169
+ if (value >= 0n) return biguintToCbor(value);
8170
+ const stripped = stripLeadingZeros(bigintToBytes(-value - 1n));
8171
+ return toTaggedValue(TAG_3_NEGATIVE_BIGNUM, stripped.length === 0 ? new Uint8Array([0]) : stripped);
8172
+ }
8173
+ /**
8174
+ * Decode a BigUint from an untagged CBOR byte string.
8175
+ *
8176
+ * Matches Rust's `biguint_from_untagged_cbor()`.
8177
+ *
8178
+ * This function is intended for use in tag summarizers where the tag has
8179
+ * already been stripped. It expects a CBOR byte string representing the
8180
+ * big-endian magnitude of a positive bignum (tag 2 content).
8181
+ *
8182
+ * Enforces canonical encoding: no leading zero bytes (except empty for zero).
8183
+ *
8184
+ * @param cbor - A CBOR value that should be a byte string
8185
+ * @returns Non-negative bigint
8186
+ * @throws CborError with type WrongType if not a byte string
8187
+ * @throws CborError with type NonCanonicalNumeric if encoding is non-canonical
8188
+ */
8189
+ function biguintFromUntaggedCbor(cbor) {
8190
+ if (cbor.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8191
+ const bytes = cbor.value;
8192
+ validateBignumMagnitude(bytes, false);
8193
+ return bytesToBigint(bytes);
8194
+ }
8195
+ /**
8196
+ * Decode a BigInt from an untagged CBOR byte string for a negative bignum.
8197
+ *
8198
+ * Matches Rust's `bigint_from_negative_untagged_cbor()`.
8199
+ *
8200
+ * This function is intended for use in tag summarizers where the tag has
8201
+ * already been stripped. It expects a CBOR byte string representing `n` where
8202
+ * the actual value is `-1 - n` (tag 3 content per RFC 8949).
8203
+ *
8204
+ * Enforces canonical encoding: no leading zero bytes (except single `0x00`
8205
+ * for -1).
8206
+ *
8207
+ * @param cbor - A CBOR value that should be a byte string
8208
+ * @returns Negative bigint
8209
+ * @throws CborError with type WrongType if not a byte string
8210
+ * @throws CborError with type NonCanonicalNumeric if encoding is non-canonical
8211
+ */
8212
+ function bigintFromNegativeUntaggedCbor(cbor) {
8213
+ if (cbor.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8214
+ const bytes = cbor.value;
8215
+ validateBignumMagnitude(bytes, true);
8216
+ return -(bytesToBigint(bytes) + 1n);
8217
+ }
8218
+ /**
8219
+ * Convert CBOR to a non-negative bigint.
8220
+ *
8221
+ * Matches Rust's `TryFrom<CBOR> for BigUint`.
8222
+ *
8223
+ * Accepts:
8224
+ * - Major type 0 (unsigned integer)
8225
+ * - Tag 2 (positive bignum) with canonical byte string
8226
+ *
8227
+ * Rejects:
8228
+ * - Major type 1 (negative integer) -> OutOfRange
8229
+ * - Tag 3 (negative bignum) -> OutOfRange
8230
+ * - Floating-point values -> WrongType
8231
+ * - Non-canonical bignum encodings -> NonCanonicalNumeric
8232
+ *
8233
+ * @param cbor - The CBOR value to convert
8234
+ * @returns Non-negative bigint
8235
+ * @throws CborError
8236
+ */
8237
+ function cborToBiguint(cbor) {
8238
+ switch (cbor.type) {
8239
+ case MajorType.Unsigned: return BigInt(cbor.value);
8240
+ case MajorType.Negative: throw new CborError({ type: "OutOfRange" });
8241
+ case MajorType.Tagged: {
8242
+ const tagValue = Number(cbor.tag);
8243
+ if (tagValue === TAG_2_POSITIVE_BIGNUM) {
8244
+ const inner = cbor.value;
8245
+ if (inner.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8246
+ const bytes = inner.value;
8247
+ validateBignumMagnitude(bytes, false);
8248
+ return bytesToBigint(bytes);
8249
+ } else if (tagValue === TAG_3_NEGATIVE_BIGNUM) throw new CborError({ type: "OutOfRange" });
8250
+ throw new CborError({ type: "WrongType" });
8251
+ }
8252
+ case MajorType.ByteString:
8253
+ case MajorType.Text:
8254
+ case MajorType.Array:
8255
+ case MajorType.Map:
8256
+ case MajorType.Simple: throw new CborError({ type: "WrongType" });
8257
+ }
8258
+ }
8259
+ /**
8260
+ * Convert CBOR to a bigint (any sign).
8261
+ *
8262
+ * Matches Rust's `TryFrom<CBOR> for BigInt`.
8263
+ *
8264
+ * Accepts:
8265
+ * - Major type 0 (unsigned integer)
8266
+ * - Major type 1 (negative integer)
8267
+ * - Tag 2 (positive bignum) with canonical byte string
8268
+ * - Tag 3 (negative bignum) with canonical byte string
8269
+ *
8270
+ * Rejects:
8271
+ * - Floating-point values -> WrongType
8272
+ * - Non-canonical bignum encodings -> NonCanonicalNumeric
8273
+ *
8274
+ * @param cbor - The CBOR value to convert
8275
+ * @returns A bigint value
8276
+ * @throws CborError
8277
+ */
8278
+ function cborToBigint(cbor) {
8279
+ switch (cbor.type) {
8280
+ case MajorType.Unsigned: return BigInt(cbor.value);
8281
+ case MajorType.Negative: return -(BigInt(cbor.value) + 1n);
8282
+ case MajorType.Tagged: {
8283
+ const tagValue = Number(cbor.tag);
8284
+ if (tagValue === TAG_2_POSITIVE_BIGNUM) {
8285
+ const inner = cbor.value;
8286
+ if (inner.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8287
+ const bytes = inner.value;
8288
+ validateBignumMagnitude(bytes, false);
8289
+ const mag = bytesToBigint(bytes);
8290
+ if (mag === 0n) return 0n;
8291
+ return mag;
8292
+ } else if (tagValue === TAG_3_NEGATIVE_BIGNUM) {
8293
+ const inner = cbor.value;
8294
+ if (inner.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8295
+ const bytes = inner.value;
8296
+ validateBignumMagnitude(bytes, true);
8297
+ return -(bytesToBigint(bytes) + 1n);
8298
+ }
8299
+ throw new CborError({ type: "WrongType" });
8300
+ }
8301
+ case MajorType.ByteString:
8302
+ case MajorType.Text:
8303
+ case MajorType.Array:
8304
+ case MajorType.Map:
8305
+ case MajorType.Simple: throw new CborError({ type: "WrongType" });
8306
+ }
8307
+ }
8308
+
8047
8309
  //#endregion
8048
8310
  //#region src/tags.ts
8049
8311
  /**
@@ -8073,6 +8335,16 @@ const TAG_POSITIVE_BIGNUM = 2;
8073
8335
  */
8074
8336
  const TAG_NEGATIVE_BIGNUM = 3;
8075
8337
  /**
8338
+ * Name for tag 2 (positive bignum).
8339
+ * Matches Rust's `TAG_NAME_POSITIVE_BIGNUM`.
8340
+ */
8341
+ const TAG_NAME_POSITIVE_BIGNUM = "positive-bignum";
8342
+ /**
8343
+ * Name for tag 3 (negative bignum).
8344
+ * Matches Rust's `TAG_NAME_NEGATIVE_BIGNUM`.
8345
+ */
8346
+ const TAG_NAME_NEGATIVE_BIGNUM = "negative-bignum";
8347
+ /**
8076
8348
  * Tag 4: Decimal fraction [exponent, mantissa]
8077
8349
  */
8078
8350
  const TAG_DECIMAL_FRACTION = 4;
@@ -8163,6 +8435,41 @@ const registerTagsIn = (tagsStore) => {
8163
8435
  };
8164
8436
  }
8165
8437
  });
8438
+ const biguintTag = createTag(TAG_POSITIVE_BIGNUM, TAG_NAME_POSITIVE_BIGNUM);
8439
+ const bigintTag = createTag(TAG_NEGATIVE_BIGNUM, TAG_NAME_NEGATIVE_BIGNUM);
8440
+ tagsStore.insertAll([biguintTag, bigintTag]);
8441
+ tagsStore.setSummarizer(TAG_POSITIVE_BIGNUM, (untaggedCbor, _flat) => {
8442
+ try {
8443
+ return {
8444
+ ok: true,
8445
+ value: `bignum(${biguintFromUntaggedCbor(untaggedCbor)})`
8446
+ };
8447
+ } catch (e) {
8448
+ return {
8449
+ ok: false,
8450
+ error: {
8451
+ type: "Custom",
8452
+ message: e instanceof Error ? e.message : String(e)
8453
+ }
8454
+ };
8455
+ }
8456
+ });
8457
+ tagsStore.setSummarizer(TAG_NEGATIVE_BIGNUM, (untaggedCbor, _flat) => {
8458
+ try {
8459
+ return {
8460
+ ok: true,
8461
+ value: `bignum(${bigintFromNegativeUntaggedCbor(untaggedCbor)})`
8462
+ };
8463
+ } catch (e) {
8464
+ return {
8465
+ ok: false,
8466
+ error: {
8467
+ type: "Custom",
8468
+ message: e instanceof Error ? e.message : String(e)
8469
+ }
8470
+ };
8471
+ }
8472
+ });
8166
8473
  };
8167
8474
  /**
8168
8475
  * Register standard tags in the global tags store.
@@ -8889,5 +9196,5 @@ var ByteString = class ByteString {
8889
9196
  };
8890
9197
 
8891
9198
  //#endregion
8892
- export { ByteString, Cbor, CborDate, CborError, CborMap, CborSet, Err, MajorType, Ok, TAG_BASE16, TAG_BASE64, TAG_BASE64URL, TAG_BASE64URL_TEXT, TAG_BASE64_TEXT, TAG_BIGFLOAT, TAG_BINARY_UUID, TAG_DATE, TAG_DATE_TIME_STRING, TAG_DECIMAL_FRACTION, TAG_ENCODED_CBOR, TAG_EPOCH_DATE, TAG_EPOCH_DATE_TIME, TAG_MIME_MESSAGE, TAG_NAME_DATE, TAG_NEGATIVE_BIGNUM, TAG_POSITIVE_BIGNUM, TAG_REGEXP, TAG_SELF_DESCRIBE_CBOR, TAG_SET, TAG_STRING_REF_NAMESPACE, TAG_URI, TAG_UUID, TagsStore, arrayIsEmpty, arrayItem, arrayLength, asArray, asBoolean, asByteString, asBytes, asCborArray, asCborMap, asFloat, asInteger, asKeyValue, asMap, asNegative, asNumber, asSingle, asTaggedValue, asText, asUnsigned, bytesToHex, cbor, cborData, createTag, createTaggedCbor, decodeCbor, decodeVarInt, decodeVarIntData, diagnosticOpt, edgeLabel, encodeVarInt, errorMsg, errorToString, expectArray, expectBoolean, expectBoolean as tryIntoBool, expectBytes, expectBytes as tryIntoByteString, expectFloat, expectInteger, expectMap, expectNegative, expectNumber, expectTaggedContent, expectTaggedContent as tryExpectedTaggedValue, expectText, expectText as tryIntoText, expectUnsigned, extractCbor, extractTaggedContent, getGlobalTagsStore, getTaggedContent, hasFractionalPart, hasTag, hexOpt, hexToBytes, isArray, isBoolean, isBytes, isFloat, isInteger, isMap, isNaN$1 as isNaN, isNegative, isNull, isNumber, isSimple, isTagged, isText, isUnsigned, mapHas, mapIsEmpty, mapKeys, mapSize, mapValue, mapValues, registerTags, registerTagsIn, simpleName, summary, tagContent, tagValue, tagsForValues, toByteString, toByteStringFromHex, toTaggedValue, validateTag, walk };
9199
+ export { ByteString, Cbor, CborDate, CborError, CborMap, CborSet, Err, MajorType, Ok, TAG_BASE16, TAG_BASE64, TAG_BASE64URL, TAG_BASE64URL_TEXT, TAG_BASE64_TEXT, TAG_BIGFLOAT, TAG_BINARY_UUID, TAG_DATE, TAG_DATE_TIME_STRING, TAG_DECIMAL_FRACTION, TAG_ENCODED_CBOR, TAG_EPOCH_DATE, TAG_EPOCH_DATE_TIME, TAG_MIME_MESSAGE, TAG_NAME_DATE, TAG_NAME_NEGATIVE_BIGNUM, TAG_NAME_POSITIVE_BIGNUM, TAG_NEGATIVE_BIGNUM, TAG_POSITIVE_BIGNUM, TAG_REGEXP, TAG_SELF_DESCRIBE_CBOR, TAG_SET, TAG_STRING_REF_NAMESPACE, TAG_URI, TAG_UUID, TagsStore, arrayIsEmpty, arrayItem, arrayLength, asArray, asBoolean, asByteString, asBytes, asCborArray, asCborMap, asFloat, asInteger, asKeyValue, asMap, asNegative, asNumber, asSingle, asTaggedValue, asText, asUnsigned, bigintFromNegativeUntaggedCbor, bigintToCbor, biguintFromUntaggedCbor, biguintToCbor, bytesToHex, cbor, cborData, cborToBigint, cborToBiguint, createTag, createTaggedCbor, decodeCbor, decodeVarInt, decodeVarIntData, diagnosticOpt, edgeLabel, encodeVarInt, errorMsg, errorToString, expectArray, expectBoolean, expectBoolean as tryIntoBool, expectBytes, expectBytes as tryIntoByteString, expectFloat, expectInteger, expectMap, expectNegative, expectNumber, expectTaggedContent, expectTaggedContent as tryExpectedTaggedValue, expectText, expectText as tryIntoText, expectUnsigned, extractCbor, extractTaggedContent, getGlobalTagsStore, getTaggedContent, hasFractionalPart, hasTag, hexOpt, hexToBytes, isArray, isBoolean, isBytes, isFloat, isInteger, isMap, isNaN$1 as isNaN, isNegative, isNull, isNumber, isSimple, isTagged, isText, isUnsigned, mapHas, mapIsEmpty, mapKeys, mapSize, mapValue, mapValues, registerTags, registerTagsIn, simpleName, summary, tagContent, tagValue, tagsForValues, toByteString, toByteStringFromHex, toTaggedValue, validateTag, walk };
8893
9200
  //# sourceMappingURL=index.mjs.map