@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.
@@ -8047,6 +8047,268 @@ var import_byte_data = /* @__PURE__ */ __toESM(require_byte_data(), 1);
8047
8047
  }
8048
8048
  };
8049
8049
 
8050
+ //#endregion
8051
+ //#region src/bignum.ts
8052
+ /**
8053
+ * CBOR bignum (tags 2 and 3) support.
8054
+ *
8055
+ * This module provides conversion between CBOR and JavaScript BigInt types,
8056
+ * implementing RFC 8949 §3.4.3 (Bignums) with dCBOR/CDE canonical encoding rules.
8057
+ *
8058
+ * Encoding:
8059
+ * - `biguintToCbor` always encodes as tag 2 (positive bignum) with a byte
8060
+ * string content.
8061
+ * - `bigintToCbor` encodes as tag 2 for non-negative values or tag 3
8062
+ * (negative bignum) for negative values.
8063
+ * - No numeric reduction is performed: values are always encoded as bignums,
8064
+ * even if they would fit in normal CBOR integers.
8065
+ *
8066
+ * Decoding:
8067
+ * - Accepts CBOR integers (major types 0 and 1) and converts them to bigints.
8068
+ * - Accepts tag 2 (positive bignum) and tag 3 (negative bignum) with byte
8069
+ * string content.
8070
+ * - Enforces shortest-form canonical representation for bignum magnitudes.
8071
+ * - Rejects floating-point values.
8072
+ *
8073
+ * @module bignum
8074
+ */
8075
+ const TAG_2_POSITIVE_BIGNUM = 2;
8076
+ const TAG_3_NEGATIVE_BIGNUM = 3;
8077
+ /**
8078
+ * Validates that a bignum magnitude byte string is in shortest canonical form.
8079
+ *
8080
+ * Matches Rust's `validate_bignum_magnitude()`.
8081
+ *
8082
+ * Rules:
8083
+ * - For positive bignums (tag 2): empty byte string represents zero;
8084
+ * non-empty must not have leading zero bytes.
8085
+ * - For negative bignums (tag 3): byte string must not be empty
8086
+ * (magnitude zero is encoded as `0x00`); must not have leading zero bytes
8087
+ * except when the magnitude is zero (single `0x00`).
8088
+ *
8089
+ * @param bytes - The magnitude byte string to validate
8090
+ * @param isNegative - Whether this is for a negative bignum (tag 3)
8091
+ * @throws CborError with type NonCanonicalNumeric on validation failure
8092
+ */
8093
+ function validateBignumMagnitude(bytes, isNegative) {
8094
+ if (isNegative) {
8095
+ if (bytes.length === 0) throw new CborError({ type: "NonCanonicalNumeric" });
8096
+ if (bytes.length > 1 && bytes[0] === 0) throw new CborError({ type: "NonCanonicalNumeric" });
8097
+ } else if (bytes.length > 0 && bytes[0] === 0) throw new CborError({ type: "NonCanonicalNumeric" });
8098
+ }
8099
+ /**
8100
+ * Strips leading zero bytes from a byte array, returning the minimal
8101
+ * representation.
8102
+ *
8103
+ * Matches Rust's `strip_leading_zeros()`.
8104
+ *
8105
+ * @param bytes - The byte array to strip
8106
+ * @returns A subarray with leading zeros removed
8107
+ */
8108
+ function stripLeadingZeros(bytes) {
8109
+ let start = 0;
8110
+ while (start < bytes.length && bytes[start] === 0) start++;
8111
+ return bytes.subarray(start);
8112
+ }
8113
+ /**
8114
+ * Convert a non-negative bigint to a big-endian byte array.
8115
+ *
8116
+ * Zero returns an empty Uint8Array.
8117
+ *
8118
+ * @param value - A non-negative bigint value
8119
+ * @returns Big-endian byte representation
8120
+ */
8121
+ function bigintToBytes(value) {
8122
+ if (value === 0n) return new Uint8Array(0);
8123
+ const hex = value.toString(16);
8124
+ const padded = hex.length % 2 !== 0 ? `0${hex}` : hex;
8125
+ const bytes = new Uint8Array(padded.length / 2);
8126
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(padded.substring(i * 2, i * 2 + 2), 16);
8127
+ return bytes;
8128
+ }
8129
+ /**
8130
+ * Convert a big-endian byte array to a bigint.
8131
+ *
8132
+ * Empty array returns 0n.
8133
+ *
8134
+ * @param bytes - Big-endian byte representation
8135
+ * @returns The bigint value
8136
+ */
8137
+ function bytesToBigint(bytes) {
8138
+ if (bytes.length === 0) return 0n;
8139
+ let result = 0n;
8140
+ for (const byte of bytes) result = result << 8n | BigInt(byte);
8141
+ return result;
8142
+ }
8143
+ /**
8144
+ * Encode a non-negative bigint as a CBOR tag 2 (positive bignum).
8145
+ *
8146
+ * Matches Rust's `From<BigUint> for CBOR`.
8147
+ *
8148
+ * The value is always encoded as a bignum regardless of size.
8149
+ * Zero is encoded as tag 2 with an empty byte string.
8150
+ *
8151
+ * @param value - A non-negative bigint (must be >= 0n)
8152
+ * @returns CBOR tagged value
8153
+ * @throws CborError with type OutOfRange if value is negative
8154
+ */
8155
+ function biguintToCbor(value) {
8156
+ if (value < 0n) throw new CborError({ type: "OutOfRange" });
8157
+ return toTaggedValue(TAG_2_POSITIVE_BIGNUM, stripLeadingZeros(bigintToBytes(value)));
8158
+ }
8159
+ /**
8160
+ * Encode a bigint as a CBOR tag 2 or tag 3 bignum.
8161
+ *
8162
+ * Matches Rust's `From<BigInt> for CBOR`.
8163
+ *
8164
+ * - Non-negative values use tag 2 (positive bignum).
8165
+ * - Negative values use tag 3 (negative bignum), where the encoded
8166
+ * magnitude is `|value| - 1` per RFC 8949.
8167
+ *
8168
+ * @param value - Any bigint value
8169
+ * @returns CBOR tagged value
8170
+ */
8171
+ function bigintToCbor(value) {
8172
+ if (value >= 0n) return biguintToCbor(value);
8173
+ const stripped = stripLeadingZeros(bigintToBytes(-value - 1n));
8174
+ return toTaggedValue(TAG_3_NEGATIVE_BIGNUM, stripped.length === 0 ? new Uint8Array([0]) : stripped);
8175
+ }
8176
+ /**
8177
+ * Decode a BigUint from an untagged CBOR byte string.
8178
+ *
8179
+ * Matches Rust's `biguint_from_untagged_cbor()`.
8180
+ *
8181
+ * This function is intended for use in tag summarizers where the tag has
8182
+ * already been stripped. It expects a CBOR byte string representing the
8183
+ * big-endian magnitude of a positive bignum (tag 2 content).
8184
+ *
8185
+ * Enforces canonical encoding: no leading zero bytes (except empty for zero).
8186
+ *
8187
+ * @param cbor - A CBOR value that should be a byte string
8188
+ * @returns Non-negative bigint
8189
+ * @throws CborError with type WrongType if not a byte string
8190
+ * @throws CborError with type NonCanonicalNumeric if encoding is non-canonical
8191
+ */
8192
+ function biguintFromUntaggedCbor(cbor) {
8193
+ if (cbor.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8194
+ const bytes = cbor.value;
8195
+ validateBignumMagnitude(bytes, false);
8196
+ return bytesToBigint(bytes);
8197
+ }
8198
+ /**
8199
+ * Decode a BigInt from an untagged CBOR byte string for a negative bignum.
8200
+ *
8201
+ * Matches Rust's `bigint_from_negative_untagged_cbor()`.
8202
+ *
8203
+ * This function is intended for use in tag summarizers where the tag has
8204
+ * already been stripped. It expects a CBOR byte string representing `n` where
8205
+ * the actual value is `-1 - n` (tag 3 content per RFC 8949).
8206
+ *
8207
+ * Enforces canonical encoding: no leading zero bytes (except single `0x00`
8208
+ * for -1).
8209
+ *
8210
+ * @param cbor - A CBOR value that should be a byte string
8211
+ * @returns Negative bigint
8212
+ * @throws CborError with type WrongType if not a byte string
8213
+ * @throws CborError with type NonCanonicalNumeric if encoding is non-canonical
8214
+ */
8215
+ function bigintFromNegativeUntaggedCbor(cbor) {
8216
+ if (cbor.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8217
+ const bytes = cbor.value;
8218
+ validateBignumMagnitude(bytes, true);
8219
+ return -(bytesToBigint(bytes) + 1n);
8220
+ }
8221
+ /**
8222
+ * Convert CBOR to a non-negative bigint.
8223
+ *
8224
+ * Matches Rust's `TryFrom<CBOR> for BigUint`.
8225
+ *
8226
+ * Accepts:
8227
+ * - Major type 0 (unsigned integer)
8228
+ * - Tag 2 (positive bignum) with canonical byte string
8229
+ *
8230
+ * Rejects:
8231
+ * - Major type 1 (negative integer) -> OutOfRange
8232
+ * - Tag 3 (negative bignum) -> OutOfRange
8233
+ * - Floating-point values -> WrongType
8234
+ * - Non-canonical bignum encodings -> NonCanonicalNumeric
8235
+ *
8236
+ * @param cbor - The CBOR value to convert
8237
+ * @returns Non-negative bigint
8238
+ * @throws CborError
8239
+ */
8240
+ function cborToBiguint(cbor) {
8241
+ switch (cbor.type) {
8242
+ case MajorType.Unsigned: return BigInt(cbor.value);
8243
+ case MajorType.Negative: throw new CborError({ type: "OutOfRange" });
8244
+ case MajorType.Tagged: {
8245
+ const tagValue = Number(cbor.tag);
8246
+ if (tagValue === TAG_2_POSITIVE_BIGNUM) {
8247
+ const inner = cbor.value;
8248
+ if (inner.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8249
+ const bytes = inner.value;
8250
+ validateBignumMagnitude(bytes, false);
8251
+ return bytesToBigint(bytes);
8252
+ } else if (tagValue === TAG_3_NEGATIVE_BIGNUM) throw new CborError({ type: "OutOfRange" });
8253
+ throw new CborError({ type: "WrongType" });
8254
+ }
8255
+ case MajorType.ByteString:
8256
+ case MajorType.Text:
8257
+ case MajorType.Array:
8258
+ case MajorType.Map:
8259
+ case MajorType.Simple: throw new CborError({ type: "WrongType" });
8260
+ }
8261
+ }
8262
+ /**
8263
+ * Convert CBOR to a bigint (any sign).
8264
+ *
8265
+ * Matches Rust's `TryFrom<CBOR> for BigInt`.
8266
+ *
8267
+ * Accepts:
8268
+ * - Major type 0 (unsigned integer)
8269
+ * - Major type 1 (negative integer)
8270
+ * - Tag 2 (positive bignum) with canonical byte string
8271
+ * - Tag 3 (negative bignum) with canonical byte string
8272
+ *
8273
+ * Rejects:
8274
+ * - Floating-point values -> WrongType
8275
+ * - Non-canonical bignum encodings -> NonCanonicalNumeric
8276
+ *
8277
+ * @param cbor - The CBOR value to convert
8278
+ * @returns A bigint value
8279
+ * @throws CborError
8280
+ */
8281
+ function cborToBigint(cbor) {
8282
+ switch (cbor.type) {
8283
+ case MajorType.Unsigned: return BigInt(cbor.value);
8284
+ case MajorType.Negative: return -(BigInt(cbor.value) + 1n);
8285
+ case MajorType.Tagged: {
8286
+ const tagValue = Number(cbor.tag);
8287
+ if (tagValue === TAG_2_POSITIVE_BIGNUM) {
8288
+ const inner = cbor.value;
8289
+ if (inner.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8290
+ const bytes = inner.value;
8291
+ validateBignumMagnitude(bytes, false);
8292
+ const mag = bytesToBigint(bytes);
8293
+ if (mag === 0n) return 0n;
8294
+ return mag;
8295
+ } else if (tagValue === TAG_3_NEGATIVE_BIGNUM) {
8296
+ const inner = cbor.value;
8297
+ if (inner.type !== MajorType.ByteString) throw new CborError({ type: "WrongType" });
8298
+ const bytes = inner.value;
8299
+ validateBignumMagnitude(bytes, true);
8300
+ return -(bytesToBigint(bytes) + 1n);
8301
+ }
8302
+ throw new CborError({ type: "WrongType" });
8303
+ }
8304
+ case MajorType.ByteString:
8305
+ case MajorType.Text:
8306
+ case MajorType.Array:
8307
+ case MajorType.Map:
8308
+ case MajorType.Simple: throw new CborError({ type: "WrongType" });
8309
+ }
8310
+ }
8311
+
8050
8312
  //#endregion
8051
8313
  //#region src/tags.ts
8052
8314
  /**
@@ -8076,6 +8338,16 @@ var import_byte_data = /* @__PURE__ */ __toESM(require_byte_data(), 1);
8076
8338
  */
8077
8339
  const TAG_NEGATIVE_BIGNUM = 3;
8078
8340
  /**
8341
+ * Name for tag 2 (positive bignum).
8342
+ * Matches Rust's `TAG_NAME_POSITIVE_BIGNUM`.
8343
+ */
8344
+ const TAG_NAME_POSITIVE_BIGNUM = "positive-bignum";
8345
+ /**
8346
+ * Name for tag 3 (negative bignum).
8347
+ * Matches Rust's `TAG_NAME_NEGATIVE_BIGNUM`.
8348
+ */
8349
+ const TAG_NAME_NEGATIVE_BIGNUM = "negative-bignum";
8350
+ /**
8079
8351
  * Tag 4: Decimal fraction [exponent, mantissa]
8080
8352
  */
8081
8353
  const TAG_DECIMAL_FRACTION = 4;
@@ -8166,6 +8438,41 @@ var import_byte_data = /* @__PURE__ */ __toESM(require_byte_data(), 1);
8166
8438
  };
8167
8439
  }
8168
8440
  });
8441
+ const biguintTag = createTag(TAG_POSITIVE_BIGNUM, TAG_NAME_POSITIVE_BIGNUM);
8442
+ const bigintTag = createTag(TAG_NEGATIVE_BIGNUM, TAG_NAME_NEGATIVE_BIGNUM);
8443
+ tagsStore.insertAll([biguintTag, bigintTag]);
8444
+ tagsStore.setSummarizer(TAG_POSITIVE_BIGNUM, (untaggedCbor, _flat) => {
8445
+ try {
8446
+ return {
8447
+ ok: true,
8448
+ value: `bignum(${biguintFromUntaggedCbor(untaggedCbor)})`
8449
+ };
8450
+ } catch (e) {
8451
+ return {
8452
+ ok: false,
8453
+ error: {
8454
+ type: "Custom",
8455
+ message: e instanceof Error ? e.message : String(e)
8456
+ }
8457
+ };
8458
+ }
8459
+ });
8460
+ tagsStore.setSummarizer(TAG_NEGATIVE_BIGNUM, (untaggedCbor, _flat) => {
8461
+ try {
8462
+ return {
8463
+ ok: true,
8464
+ value: `bignum(${bigintFromNegativeUntaggedCbor(untaggedCbor)})`
8465
+ };
8466
+ } catch (e) {
8467
+ return {
8468
+ ok: false,
8469
+ error: {
8470
+ type: "Custom",
8471
+ message: e instanceof Error ? e.message : String(e)
8472
+ }
8473
+ };
8474
+ }
8475
+ });
8169
8476
  };
8170
8477
  /**
8171
8478
  * Register standard tags in the global tags store.
@@ -8916,6 +9223,8 @@ exports.TAG_EPOCH_DATE = TAG_EPOCH_DATE;
8916
9223
  exports.TAG_EPOCH_DATE_TIME = TAG_EPOCH_DATE_TIME;
8917
9224
  exports.TAG_MIME_MESSAGE = TAG_MIME_MESSAGE;
8918
9225
  exports.TAG_NAME_DATE = TAG_NAME_DATE;
9226
+ exports.TAG_NAME_NEGATIVE_BIGNUM = TAG_NAME_NEGATIVE_BIGNUM;
9227
+ exports.TAG_NAME_POSITIVE_BIGNUM = TAG_NAME_POSITIVE_BIGNUM;
8919
9228
  exports.TAG_NEGATIVE_BIGNUM = TAG_NEGATIVE_BIGNUM;
8920
9229
  exports.TAG_POSITIVE_BIGNUM = TAG_POSITIVE_BIGNUM;
8921
9230
  exports.TAG_REGEXP = TAG_REGEXP;
@@ -8944,9 +9253,15 @@ exports.asSingle = asSingle;
8944
9253
  exports.asTaggedValue = asTaggedValue;
8945
9254
  exports.asText = asText;
8946
9255
  exports.asUnsigned = asUnsigned;
9256
+ exports.bigintFromNegativeUntaggedCbor = bigintFromNegativeUntaggedCbor;
9257
+ exports.bigintToCbor = bigintToCbor;
9258
+ exports.biguintFromUntaggedCbor = biguintFromUntaggedCbor;
9259
+ exports.biguintToCbor = biguintToCbor;
8947
9260
  exports.bytesToHex = bytesToHex;
8948
9261
  exports.cbor = cbor;
8949
9262
  exports.cborData = cborData;
9263
+ exports.cborToBigint = cborToBigint;
9264
+ exports.cborToBiguint = cborToBiguint;
8950
9265
  exports.createTag = createTag;
8951
9266
  exports.createTaggedCbor = createTaggedCbor;
8952
9267
  exports.decodeCbor = decodeCbor;