@bcts/dcbor 1.0.0-alpha.12 → 1.0.0-alpha.14

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
@@ -5107,7 +5107,13 @@ var TagsStore = class {
5107
5107
  /**
5108
5108
  * Insert a tag into the registry.
5109
5109
  *
5110
- * @param tag - The tag to register
5110
+ * Matches Rust's TagsStore::insert() behavior:
5111
+ * - Throws if the tag name is undefined or empty
5112
+ * - Throws if a tag with the same value exists with a different name
5113
+ * - Allows re-registering the same tag value with the same name
5114
+ *
5115
+ * @param tag - The tag to register (must have a non-empty name)
5116
+ * @throws Error if tag has no name, empty name, or conflicts with existing registration
5111
5117
  *
5112
5118
  * @example
5113
5119
  * ```typescript
@@ -5116,9 +5122,13 @@ var TagsStore = class {
5116
5122
  * ```
5117
5123
  */
5118
5124
  insert(tag) {
5125
+ const name = tag.name;
5126
+ if (name === void 0 || name === "") throw new Error(`Tag ${tag.value} must have a non-empty name`);
5119
5127
  const key = this.#valueKey(tag.value);
5128
+ const existing = this.#tagsByValue.get(key);
5129
+ if (existing?.name !== void 0 && existing.name !== name) throw new Error(`Attempt to register tag: ${tag.value} '${existing.name}' with different name: '${name}'`);
5120
5130
  this.#tagsByValue.set(key, tag);
5121
- if (tag.name !== void 0) this.#tagsByName.set(tag.name, tag);
5131
+ this.#tagsByName.set(name, tag);
5122
5132
  }
5123
5133
  /**
5124
5134
  * Insert multiple tags into the registry.
@@ -5156,21 +5166,6 @@ var TagsStore = class {
5156
5166
  const key = this.#valueKey(tagValue$1);
5157
5167
  this.#summarizers.set(key, summarizer);
5158
5168
  }
5159
- /**
5160
- * Remove a tag from the registry.
5161
- *
5162
- * @param tagValue - The numeric tag value to remove
5163
- * @returns true if a tag was removed, false otherwise
5164
- */
5165
- remove(tagValue$1) {
5166
- const key = this.#valueKey(tagValue$1);
5167
- const tag = this.#tagsByValue.get(key);
5168
- if (tag === void 0) return false;
5169
- this.#tagsByValue.delete(key);
5170
- if (tag.name !== void 0) this.#tagsByName.delete(tag.name);
5171
- this.#summarizers.delete(key);
5172
- return true;
5173
- }
5174
5169
  assignedNameForTag(tag) {
5175
5170
  const key = this.#valueKey(tag.value);
5176
5171
  return this.#tagsByValue.get(key)?.name;
@@ -5194,30 +5189,6 @@ var TagsStore = class {
5194
5189
  return this.#summarizers.get(key);
5195
5190
  }
5196
5191
  /**
5197
- * Get all registered tags.
5198
- *
5199
- * @returns Array of all registered tags
5200
- */
5201
- getAllTags() {
5202
- return Array.from(this.#tagsByValue.values());
5203
- }
5204
- /**
5205
- * Clear all registered tags and summarizers.
5206
- */
5207
- clear() {
5208
- this.#tagsByValue.clear();
5209
- this.#tagsByName.clear();
5210
- this.#summarizers.clear();
5211
- }
5212
- /**
5213
- * Get the number of registered tags.
5214
- *
5215
- * @returns Number of tags in the registry
5216
- */
5217
- get size() {
5218
- return this.#tagsByValue.size;
5219
- }
5220
- /**
5221
5192
  * Create a string key for a numeric tag value.
5222
5193
  * Handles both number and bigint types.
5223
5194
  *
@@ -5609,11 +5580,17 @@ function formatMap(map, opts) {
5609
5580
  }
5610
5581
  /**
5611
5582
  * Format tagged value.
5583
+ *
5584
+ * Matches Rust's diag_item() for Tagged case.
5612
5585
  */
5613
5586
  function formatTagged(tag, content, opts) {
5614
5587
  if (opts.summarize === true) {
5615
5588
  const summarizer = resolveTagsStore(opts.tags)?.summarizer(tag);
5616
- if (summarizer !== void 0) return summarizer(content, opts.flat ?? false);
5589
+ if (summarizer !== void 0) {
5590
+ const result$1 = summarizer(content, opts.flat ?? false);
5591
+ if (result$1.ok) return result$1.value;
5592
+ else return `<error: ${result$1.error.type === "Custom" ? result$1.error.message : result$1.error.type === "WrongTag" ? `expected CBOR tag ${result$1.error.expected.value}, but got ${result$1.error.actual.value}` : result$1.error.type}>`;
5593
+ }
5617
5594
  }
5618
5595
  let comment;
5619
5596
  if (opts.annotate === true) {
@@ -6898,21 +6875,20 @@ const asKeyValue = (element) => {
6898
6875
  * @param cbor - The CBOR value to traverse
6899
6876
  * @param initialState - Initial state value
6900
6877
  * @param visitor - Function to call for each element
6901
- * @returns Final state after traversal
6902
6878
  *
6903
6879
  * @example
6904
6880
  * ```typescript
6905
- * // Count all text strings in a structure
6906
- * interface CountState { count: number }
6881
+ * // Count all text strings in a structure using RefCell-like pattern
6882
+ * const count = { value: 0 };
6907
6883
  *
6908
6884
  * const structure = cbor({ name: 'Alice', tags: ['urgent', 'draft'] });
6909
- * const result = walk(structure, { count: 0 }, (element, level, edge, state) => {
6885
+ * walk(structure, null, (element, level, edge, state) => {
6910
6886
  * if (element.type === 'single' && element.cbor.type === MajorType.Text) {
6911
- * return [{ count: state.count + 1 }, false];
6887
+ * count.value++;
6912
6888
  * }
6913
6889
  * return [state, false];
6914
6890
  * });
6915
- * console.log(result.count); // 3 (name, urgent, draft)
6891
+ * console.log(count.value); // 3 (name, urgent, draft)
6916
6892
  * ```
6917
6893
  *
6918
6894
  * @example
@@ -6921,7 +6897,7 @@ const asKeyValue = (element) => {
6921
6897
  * const structure = cbor([1, 2, 3, 'found', 5, 6]);
6922
6898
  * let found = false;
6923
6899
  *
6924
- * walk(structure, null, (element, level, edge) => {
6900
+ * walk(structure, null, (element, level, edge, state) => {
6925
6901
  * if (element.type === 'single' &&
6926
6902
  * element.cbor.type === MajorType.Text &&
6927
6903
  * element.cbor.value === 'found') {
@@ -6933,7 +6909,7 @@ const asKeyValue = (element) => {
6933
6909
  * ```
6934
6910
  */
6935
6911
  const walk = (cbor$1, initialState, visitor) => {
6936
- return walkInternal(cbor$1, 0, { type: EdgeType.None }, initialState, visitor);
6912
+ walkInternal(cbor$1, 0, { type: EdgeType.None }, initialState, visitor);
6937
6913
  };
6938
6914
  /**
6939
6915
  * Internal recursive walk implementation.
@@ -7021,125 +6997,6 @@ function walkMap(cbor$1, level, state, visitor) {
7021
6997
  function walkTagged(cbor$1, level, state, visitor) {
7022
6998
  return walkInternal(cbor$1.value, level + 1, { type: EdgeType.TaggedContent }, state, visitor);
7023
6999
  }
7024
- /**
7025
- * Helper: Count all elements in a CBOR tree.
7026
- *
7027
- * @param cbor - The CBOR value to count
7028
- * @returns Total number of elements visited
7029
- *
7030
- * @example
7031
- * ```typescript
7032
- * const structure = cbor([1, 2, [3, 4]]);
7033
- * const count = countElements(structure);
7034
- * console.log(count); // 6 (array, 1, 2, inner array, 3, 4)
7035
- * ```
7036
- */
7037
- const countElements = (cbor$1) => {
7038
- return walk(cbor$1, { count: 0 }, (_element, _level, _edge, state) => {
7039
- return [{ count: state.count + 1 }, false];
7040
- }).count;
7041
- };
7042
- /**
7043
- * Helper: Collect all elements at a specific depth level.
7044
- *
7045
- * @param cbor - The CBOR value to traverse
7046
- * @param targetLevel - The depth level to collect (0 = root)
7047
- * @returns Array of CBOR values at the target level
7048
- *
7049
- * @example
7050
- * ```typescript
7051
- * const structure = cbor([[1, 2], [3, 4]]);
7052
- * const level1 = collectAtLevel(structure, 1);
7053
- * // Returns: [[1, 2], [3, 4]]
7054
- * const level2 = collectAtLevel(structure, 2);
7055
- * // Returns: [1, 2, 3, 4]
7056
- * ```
7057
- */
7058
- const collectAtLevel = (cbor$1, targetLevel) => {
7059
- return walk(cbor$1, { items: [] }, (element, level, _edge, state) => {
7060
- if (level === targetLevel && element.type === "single") return [{ items: [...state.items, element.cbor] }, false];
7061
- return [state, false];
7062
- }).items;
7063
- };
7064
- /**
7065
- * Helper: Find first element matching a predicate.
7066
- *
7067
- * @template T - Type of extracted value
7068
- * @param cbor - The CBOR value to search
7069
- * @param predicate - Function to test each element
7070
- * @returns First matching element, or undefined if not found
7071
- *
7072
- * @example
7073
- * ```typescript
7074
- * const structure = cbor({ users: [
7075
- * { name: 'Alice', age: 30 },
7076
- * { name: 'Bob', age: 25 }
7077
- * ]});
7078
- *
7079
- * const bob = findFirst(structure, (element) => {
7080
- * if (element.type === 'single' &&
7081
- * element.cbor.type === MajorType.Text &&
7082
- * element.cbor.value === 'Bob') {
7083
- * return true;
7084
- * }
7085
- * return false;
7086
- * });
7087
- * ```
7088
- */
7089
- const findFirst = (cbor$1, predicate) => {
7090
- return walk(cbor$1, {}, (element, _level, _edge, state) => {
7091
- if (state.found !== void 0) return [state, true];
7092
- if (predicate(element)) {
7093
- if (element.type === "single") return [{ found: element.cbor }, true];
7094
- return [state, true];
7095
- }
7096
- return [state, false];
7097
- }).found;
7098
- };
7099
- /**
7100
- * Helper: Collect all text strings in a CBOR tree.
7101
- *
7102
- * @param cbor - The CBOR value to traverse
7103
- * @returns Array of all text string values found
7104
- *
7105
- * @example
7106
- * ```typescript
7107
- * const doc = cbor({
7108
- * title: 'Document',
7109
- * tags: ['urgent', 'draft'],
7110
- * author: { name: 'Alice' }
7111
- * });
7112
- *
7113
- * const texts = collectAllText(doc);
7114
- * // Returns: ['Document', 'urgent', 'draft', 'Alice']
7115
- * ```
7116
- */
7117
- const collectAllText = (cbor$1) => {
7118
- return walk(cbor$1, { texts: [] }, (element, _level, _edge, state) => {
7119
- if (element.type === "single" && element.cbor.type === MajorType.Text) return [{ texts: [...state.texts, element.cbor.value] }, false];
7120
- return [state, false];
7121
- }).texts;
7122
- };
7123
- /**
7124
- * Helper: Get the maximum depth of a CBOR tree.
7125
- *
7126
- * @param cbor - The CBOR value to measure
7127
- * @returns Maximum depth (0 for leaf values, 1+ for containers)
7128
- *
7129
- * @example
7130
- * ```typescript
7131
- * const flat = cbor([1, 2, 3]);
7132
- * console.log(maxDepth(flat)); // 1
7133
- *
7134
- * const nested = cbor([[[1]]]);
7135
- * console.log(maxDepth(nested)); // 3
7136
- * ```
7137
- */
7138
- const maxDepth = (cbor$1) => {
7139
- return walk(cbor$1, { maxDepth: 0 }, (_element, level, _edge, state) => {
7140
- return [{ maxDepth: Math.max(state.maxDepth, level) }, false];
7141
- }).maxDepth;
7142
- };
7143
7000
 
7144
7001
  //#endregion
7145
7002
  //#region src/cbor.ts
@@ -7554,7 +7411,7 @@ const attachMethods = (obj) => {
7554
7411
  return this.value;
7555
7412
  },
7556
7413
  walk(initialState, visitor) {
7557
- return walk(this, initialState, visitor);
7414
+ walk(this, initialState, visitor);
7558
7415
  },
7559
7416
  validateTag(expectedTags) {
7560
7417
  if (this.type !== MajorType.Tagged) throw new CborError({ type: "WrongType" });
@@ -8292,9 +8149,18 @@ const registerTagsIn = (tagsStore) => {
8292
8149
  tagsStore.insertAll(tags);
8293
8150
  tagsStore.setSummarizer(TAG_DATE, (untaggedCbor, _flat) => {
8294
8151
  try {
8295
- return CborDate.fromUntaggedCbor(untaggedCbor).toString();
8296
- } catch {
8297
- return diagnostic(untaggedCbor);
8152
+ return {
8153
+ ok: true,
8154
+ value: CborDate.fromUntaggedCbor(untaggedCbor).toString()
8155
+ };
8156
+ } catch (e) {
8157
+ return {
8158
+ ok: false,
8159
+ error: {
8160
+ type: "Custom",
8161
+ message: e instanceof Error ? e.message : String(e)
8162
+ }
8163
+ };
8298
8164
  }
8299
8165
  });
8300
8166
  };
@@ -9023,5 +8889,5 @@ var ByteString = class ByteString {
9023
8889
  };
9024
8890
 
9025
8891
  //#endregion
9026
- 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, collectAllText, collectAtLevel, countElements, 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, findFirst, 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, maxDepth, registerTags, registerTagsIn, simpleName, summary, tagContent, tagValue, tagsForValues, toByteString, toByteStringFromHex, toTaggedValue, validateTag };
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 };
9027
8893
  //# sourceMappingURL=index.mjs.map