@twin.org/core 0.0.1-next.9 → 0.0.1

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 (77) hide show
  1. package/dist/cjs/index.cjs +1564 -834
  2. package/dist/esm/index.mjs +1561 -835
  3. package/dist/types/errors/baseError.d.ts +2 -1
  4. package/dist/types/factories/factory.d.ts +20 -1
  5. package/dist/types/helpers/arrayHelper.d.ts +13 -0
  6. package/dist/types/helpers/envHelper.d.ts +16 -0
  7. package/dist/types/helpers/errorHelper.d.ts +2 -1
  8. package/dist/types/helpers/jsonHelper.d.ts +30 -0
  9. package/dist/types/helpers/objectHelper.d.ts +25 -0
  10. package/dist/types/helpers/uint8ArrayHelper.d.ts +11 -0
  11. package/dist/types/index.d.ts +6 -0
  12. package/dist/types/models/IComponent.d.ts +12 -3
  13. package/dist/types/models/II18nShared.d.ts +29 -0
  14. package/dist/types/models/coerceType.d.ts +49 -0
  15. package/dist/types/models/compressionType.d.ts +1 -1
  16. package/dist/types/models/objectOrArray.d.ts +4 -0
  17. package/dist/types/utils/asyncCache.d.ts +10 -1
  18. package/dist/types/utils/coerce.d.ts +22 -0
  19. package/dist/types/utils/guards.d.ts +35 -0
  20. package/dist/types/utils/is.d.ts +12 -0
  21. package/dist/types/utils/sharedStore.d.ts +23 -0
  22. package/dist/types/utils/validation.d.ts +2 -0
  23. package/docs/changelog.md +230 -1
  24. package/docs/reference/classes/AlreadyExistsError.md +77 -27
  25. package/docs/reference/classes/ArrayHelper.md +79 -5
  26. package/docs/reference/classes/AsyncCache.md +75 -13
  27. package/docs/reference/classes/Base32.md +9 -5
  28. package/docs/reference/classes/Base58.md +9 -5
  29. package/docs/reference/classes/Base64.md +12 -6
  30. package/docs/reference/classes/Base64Url.md +9 -5
  31. package/docs/reference/classes/BaseError.md +79 -29
  32. package/docs/reference/classes/BitString.md +23 -11
  33. package/docs/reference/classes/Coerce.md +110 -12
  34. package/docs/reference/classes/Compression.md +19 -11
  35. package/docs/reference/classes/ConflictError.md +80 -28
  36. package/docs/reference/classes/Converter.md +72 -28
  37. package/docs/reference/classes/EnvHelper.md +45 -0
  38. package/docs/reference/classes/ErrorHelper.md +19 -7
  39. package/docs/reference/classes/Factory.md +95 -17
  40. package/docs/reference/classes/FilenameHelper.md +6 -4
  41. package/docs/reference/classes/GeneralError.md +75 -27
  42. package/docs/reference/classes/GuardError.md +80 -28
  43. package/docs/reference/classes/Guards.md +398 -80
  44. package/docs/reference/classes/HexHelper.md +18 -8
  45. package/docs/reference/classes/I18n.md +46 -20
  46. package/docs/reference/classes/Is.md +179 -51
  47. package/docs/reference/classes/JsonHelper.md +146 -10
  48. package/docs/reference/classes/NotFoundError.md +77 -27
  49. package/docs/reference/classes/NotImplementedError.md +71 -25
  50. package/docs/reference/classes/NotSupportedError.md +74 -26
  51. package/docs/reference/classes/ObjectHelper.md +197 -39
  52. package/docs/reference/classes/RandomHelper.md +6 -4
  53. package/docs/reference/classes/SharedStore.md +94 -0
  54. package/docs/reference/classes/StringHelper.md +54 -20
  55. package/docs/reference/classes/Uint8ArrayHelper.md +35 -0
  56. package/docs/reference/classes/UnauthorizedError.md +74 -26
  57. package/docs/reference/classes/UnprocessableError.md +75 -27
  58. package/docs/reference/classes/Url.md +37 -17
  59. package/docs/reference/classes/Urn.md +63 -27
  60. package/docs/reference/classes/Validation.md +349 -135
  61. package/docs/reference/classes/ValidationError.md +74 -26
  62. package/docs/reference/index.md +7 -0
  63. package/docs/reference/interfaces/IComponent.md +30 -8
  64. package/docs/reference/interfaces/IError.md +2 -2
  65. package/docs/reference/interfaces/II18nShared.md +47 -0
  66. package/docs/reference/interfaces/IKeyValue.md +3 -1
  67. package/docs/reference/interfaces/ILabelledValue.md +3 -1
  68. package/docs/reference/interfaces/ILocaleDictionary.md +1 -1
  69. package/docs/reference/interfaces/IPatchOperation.md +1 -1
  70. package/docs/reference/interfaces/IValidationFailure.md +1 -1
  71. package/docs/reference/type-aliases/CoerceType.md +5 -0
  72. package/docs/reference/type-aliases/CompressionType.md +1 -1
  73. package/docs/reference/type-aliases/ObjectOrArray.md +11 -0
  74. package/docs/reference/variables/CoerceType.md +67 -0
  75. package/docs/reference/variables/CompressionType.md +1 -1
  76. package/locales/en.json +14 -1
  77. package/package.json +7 -7
@@ -1,5 +1,5 @@
1
- import { IntlMessageFormat } from 'intl-messageformat';
2
1
  import { createPatch, applyPatch } from 'rfc6902';
2
+ import { IntlMessageFormat } from 'intl-messageformat';
3
3
 
4
4
  // Copyright 2024 IOTA Stiftung.
5
5
  // SPDX-License-Identifier: Apache-2.0.
@@ -111,7 +111,12 @@ class Is {
111
111
  }
112
112
  try {
113
113
  const json = JSON.parse(value);
114
- return typeof json === "object";
114
+ return (Is.object(json) ||
115
+ Is.array(json) ||
116
+ Is.string(json) ||
117
+ Is.number(json) ||
118
+ Is.boolean(json) ||
119
+ Is.null(json));
115
120
  }
116
121
  catch {
117
122
  return false;
@@ -135,7 +140,17 @@ class Is {
135
140
  static stringBase64Url(value) {
136
141
  return (Is.stringValue(value) &&
137
142
  // eslint-disable-next-line unicorn/better-regex
138
- /^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=)?$/.test(value));
143
+ /^([A-Za-z0-9-_])*$/.test(value));
144
+ }
145
+ /**
146
+ * Is the value a base58 string.
147
+ * @param value The value to test.
148
+ * @returns True if the value is a base58 string.
149
+ */
150
+ static stringBase58(value) {
151
+ return (Is.stringValue(value) &&
152
+ // eslint-disable-next-line unicorn/better-regex
153
+ /^[A-HJ-NP-Za-km-z1-9]*$/.test(value));
139
154
  }
140
155
  /**
141
156
  * Is the value a hex string.
@@ -349,6 +364,14 @@ class Is {
349
364
  static promise(value) {
350
365
  return value instanceof Promise;
351
366
  }
367
+ /**
368
+ * Is the value a regexp.
369
+ * @param value The value to test.
370
+ * @returns True if the value is a regexp.
371
+ */
372
+ static regexp(value) {
373
+ return value instanceof RegExp;
374
+ }
352
375
  }
353
376
 
354
377
  // Copyright 2024 IOTA Stiftung.
@@ -644,7 +667,10 @@ class BaseError extends Error {
644
667
  let properties;
645
668
  let inner;
646
669
  let stack;
647
- if (Is.object(err)) {
670
+ if (Is.object(err) && Is.stringValue(err.error)) {
671
+ message = err.error;
672
+ }
673
+ else if (Is.object(err)) {
648
674
  if (Is.stringValue(err.name)) {
649
675
  name = err.name;
650
676
  }
@@ -664,9 +690,6 @@ class BaseError extends Error {
664
690
  stack = err.stack;
665
691
  }
666
692
  }
667
- else if (Is.object(err) && Is.stringValue(err.error)) {
668
- message = err.error;
669
- }
670
693
  else if (Is.stringValue(err)) {
671
694
  message = err;
672
695
  }
@@ -684,7 +707,7 @@ class BaseError extends Error {
684
707
  */
685
708
  static flatten(err) {
686
709
  const flattened = [];
687
- let e = BaseError.fromError(err).toJsonObject();
710
+ let e = BaseError.fromError(err).toJsonObject(true);
688
711
  while (e) {
689
712
  const inner = e.inner;
690
713
  e.inner = undefined;
@@ -780,9 +803,10 @@ class BaseError extends Error {
780
803
  }
781
804
  /**
782
805
  * Serialize the error to the error model.
806
+ * @param includeStackTrace Whether to include the error stack in the model, defaults to false.
783
807
  * @returns The error model.
784
808
  */
785
- toJsonObject() {
809
+ toJsonObject(includeStackTrace) {
786
810
  const err = {};
787
811
  if (Is.stringValue(this.name)) {
788
812
  err.name = this.name;
@@ -796,11 +820,11 @@ class BaseError extends Error {
796
820
  if (Is.object(this.properties)) {
797
821
  err.properties = this.properties;
798
822
  }
799
- if (Is.stringValue(this.stack)) {
823
+ if ((includeStackTrace ?? false) && Is.stringValue(this.stack)) {
800
824
  err.stack = this.stack;
801
825
  }
802
826
  if (Is.notEmpty(this.inner)) {
803
- err.inner = BaseError.fromError(this.inner).toJsonObject();
827
+ err.inner = BaseError.fromError(this.inner).toJsonObject(includeStackTrace);
804
828
  }
805
829
  return err;
806
830
  }
@@ -1173,7 +1197,7 @@ class Base64 {
1173
1197
  const maxChunkLength = 16383; // must be multiple of 3
1174
1198
  // go through the array every three bytes, we'll deal with trailing stuff later
1175
1199
  for (let i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1176
- parts.push(Base64.encodeChunk(bytes, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
1200
+ parts.push(Base64.encodeChunk(bytes, i, Math.min(i + maxChunkLength, len2)));
1177
1201
  }
1178
1202
  // pad the end with zeros, but make sure to not forget the extra bytes
1179
1203
  if (extraBytes === 1) {
@@ -1469,6 +1493,49 @@ class ValidationError extends BaseError {
1469
1493
  }
1470
1494
  }
1471
1495
 
1496
+ /**
1497
+ * Class to help with arrays.
1498
+ */
1499
+ class ArrayHelper {
1500
+ /**
1501
+ * Do the two arrays match.
1502
+ * @param arr1 The first array.
1503
+ * @param arr2 The second array.
1504
+ * @returns True if both arrays are empty of have the same values.
1505
+ */
1506
+ static matches(arr1, arr2) {
1507
+ if (Is.empty(arr1) && Is.empty(arr2)) {
1508
+ return true;
1509
+ }
1510
+ if (!((Is.array(arr1) && Is.array(arr2)) || (Is.typedArray(arr1) && Is.typedArray(arr2)))) {
1511
+ return false;
1512
+ }
1513
+ if (arr1.length !== arr2.length) {
1514
+ return false;
1515
+ }
1516
+ for (let i = 0; i < arr1.length; i++) {
1517
+ if (arr1[i] !== arr2[i]) {
1518
+ return false;
1519
+ }
1520
+ }
1521
+ return true;
1522
+ }
1523
+ /**
1524
+ * Convert an object or array to an array.
1525
+ * @param value The object or array to convert.
1526
+ * @returns The array.
1527
+ */
1528
+ static fromObjectOrArray(value) {
1529
+ if (Is.empty(value)) {
1530
+ return undefined;
1531
+ }
1532
+ if (Is.array(value)) {
1533
+ return value;
1534
+ }
1535
+ return [value];
1536
+ }
1537
+ }
1538
+
1472
1539
  // Copyright 2024 IOTA Stiftung.
1473
1540
  // SPDX-License-Identifier: Apache-2.0.
1474
1541
  /**
@@ -1514,6 +1581,18 @@ class Guards {
1514
1581
  throw new GuardError(source, "guard.stringEmpty", property, value);
1515
1582
  }
1516
1583
  }
1584
+ /**
1585
+ * Is the property a JSON value.
1586
+ * @param source The source of the error.
1587
+ * @param property The name of the property.
1588
+ * @param value The value to test.
1589
+ * @throws GuardError If the value does not match the assertion.
1590
+ */
1591
+ static json(source, property, value) {
1592
+ if (!Is.json(value)) {
1593
+ throw new GuardError(source, "guard.stringJson", property, value);
1594
+ }
1595
+ }
1517
1596
  /**
1518
1597
  * Is the property a base64 string.
1519
1598
  * @param source The source of the error.
@@ -1538,6 +1617,18 @@ class Guards {
1538
1617
  throw new GuardError(source, "guard.base64Url", property, value);
1539
1618
  }
1540
1619
  }
1620
+ /**
1621
+ * Is the property a base58 string.
1622
+ * @param source The source of the error.
1623
+ * @param property The name of the property.
1624
+ * @param value The value to test.
1625
+ * @throws GuardError If the value does not match the assertion.
1626
+ */
1627
+ static stringBase58(source, property, value) {
1628
+ if (!Is.stringBase58(value)) {
1629
+ throw new GuardError(source, "guard.base58", property, value);
1630
+ }
1631
+ }
1541
1632
  /**
1542
1633
  * Is the property a string with a hex value.
1543
1634
  * @param source The source of the error.
@@ -1727,6 +1818,50 @@ class Guards {
1727
1818
  throw new GuardError(source, "guard.arrayOneOf", property, value, options.join(", "));
1728
1819
  }
1729
1820
  }
1821
+ /**
1822
+ * Does the array start with the specified data.
1823
+ * @param source The source of the error.
1824
+ * @param property The name of the property.
1825
+ * @param value The value to test.
1826
+ * @param startValues The values that must start the array.
1827
+ * @throws GuardError If the value does not match the assertion.
1828
+ */
1829
+ static arrayStartsWith(source, property, value, startValues) {
1830
+ if (!Is.arrayValue(value)) {
1831
+ throw new GuardError(source, "guard.array", property, value);
1832
+ }
1833
+ const startValuesArray = ArrayHelper.fromObjectOrArray(startValues);
1834
+ if (!Is.arrayValue(startValuesArray)) {
1835
+ throw new GuardError(source, "guard.array", property, startValuesArray);
1836
+ }
1837
+ for (let i = 0; i < startValuesArray.length; i++) {
1838
+ if (value[i] !== startValuesArray[i]) {
1839
+ throw new GuardError(source, "guard.arrayStartsWith", property, value, startValuesArray.join(", "));
1840
+ }
1841
+ }
1842
+ }
1843
+ /**
1844
+ * Does the array end with the specified data.
1845
+ * @param source The source of the error.
1846
+ * @param property The name of the property.
1847
+ * @param value The value to test.
1848
+ * @param endValues The values that must end the array.
1849
+ * @throws GuardError If the value does not match the assertion.
1850
+ */
1851
+ static arrayEndsWith(source, property, value, endValues) {
1852
+ if (!Is.arrayValue(value)) {
1853
+ throw new GuardError(source, "guard.array", property, value);
1854
+ }
1855
+ const endValuesArray = ArrayHelper.fromObjectOrArray(endValues);
1856
+ if (!Is.arrayValue(endValuesArray)) {
1857
+ throw new GuardError(source, "guard.array", property, endValuesArray);
1858
+ }
1859
+ for (let i = 0; i < endValuesArray.length; i++) {
1860
+ if (value[value.length - i - 1] !== endValuesArray[endValuesArray.length - i - 1]) {
1861
+ throw new GuardError(source, "guard.arrayEndsWith", property, value, endValuesArray.join(", "));
1862
+ }
1863
+ }
1864
+ }
1730
1865
  /**
1731
1866
  * Is the property a Uint8Array.
1732
1867
  * @param source The source of the error.
@@ -1767,6 +1902,53 @@ class Guards {
1767
1902
  }
1768
1903
  }
1769
1904
 
1905
+ // Copyright 2024 IOTA Stiftung.
1906
+ // SPDX-License-Identifier: Apache-2.0.
1907
+ /**
1908
+ * Provide a store for shared objects which can be accesses through multiple
1909
+ * instance loads of a packages.
1910
+ */
1911
+ class SharedStore {
1912
+ /**
1913
+ * Get a property from the shared store.
1914
+ * @param prop The name of the property to get.
1915
+ * @returns The property if it exists.
1916
+ */
1917
+ static get(prop) {
1918
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1919
+ const shared = globalThis.__TWIN_SHARED__;
1920
+ if (Is.undefined(shared)) {
1921
+ return;
1922
+ }
1923
+ return shared[prop];
1924
+ }
1925
+ /**
1926
+ * Set the property in the shared store.
1927
+ * @param prop The name of the property to set.
1928
+ * @param value The value to set.
1929
+ */
1930
+ static set(prop, value) {
1931
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1932
+ if (Is.undefined(globalThis.__TWIN_SHARED__)) {
1933
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1934
+ globalThis.__TWIN_SHARED__ = {};
1935
+ }
1936
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1937
+ globalThis.__TWIN_SHARED__[prop] = value;
1938
+ }
1939
+ /**
1940
+ * Remove a property from the shared store.
1941
+ * @param prop The name of the property to remove.
1942
+ */
1943
+ static remove(prop) {
1944
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1945
+ const shared = globalThis.__TWIN_SHARED__;
1946
+ if (!Is.undefined(shared)) {
1947
+ delete shared[prop];
1948
+ }
1949
+ }
1950
+ }
1951
+
1770
1952
  /**
1771
1953
  * Factory for creating implementation of generic types.
1772
1954
  */
@@ -1776,11 +1958,6 @@ class Factory {
1776
1958
  * @internal
1777
1959
  */
1778
1960
  static _CLASS_NAME = "Factory";
1779
- /**
1780
- * Store all the created factories.
1781
- * @internal
1782
- */
1783
- static _factories = {};
1784
1961
  /**
1785
1962
  * Type name for the instances.
1786
1963
  * @internal
@@ -1834,10 +2011,41 @@ class Factory {
1834
2011
  * @returns The factory instance.
1835
2012
  */
1836
2013
  static createFactory(typeName, autoInstance = false, matcher) {
1837
- if (Is.undefined(Factory._factories[typeName])) {
1838
- Factory._factories[typeName] = new Factory(typeName, autoInstance, matcher);
2014
+ const factories = Factory.getFactories();
2015
+ if (Is.undefined(factories[typeName])) {
2016
+ factories[typeName] = new Factory(typeName, autoInstance, matcher);
2017
+ }
2018
+ return factories[typeName];
2019
+ }
2020
+ /**
2021
+ * Get all the factories.
2022
+ * @returns All the factories.
2023
+ */
2024
+ static getFactories() {
2025
+ let factories = SharedStore.get("factories");
2026
+ if (Is.undefined(factories)) {
2027
+ factories = {};
2028
+ SharedStore.set("factories", factories);
2029
+ }
2030
+ return factories;
2031
+ }
2032
+ /**
2033
+ * Reset all the factories, which removes any created instances, but not the registrations.
2034
+ */
2035
+ static resetFactories() {
2036
+ const factories = Factory.getFactories();
2037
+ for (const typeName in factories) {
2038
+ factories[typeName].reset();
2039
+ }
2040
+ }
2041
+ /**
2042
+ * Clear all the factories, which removes anything registered with the factories.
2043
+ */
2044
+ static clearFactories() {
2045
+ const factories = Factory.getFactories();
2046
+ for (const typeName in factories) {
2047
+ factories[typeName].clear();
1839
2048
  }
1840
- return Factory._factories[typeName];
1841
2049
  }
1842
2050
  /**
1843
2051
  * Register a new generator.
@@ -1910,7 +2118,7 @@ class Factory {
1910
2118
  }
1911
2119
  }
1912
2120
  /**
1913
- * Reset all the instances.
2121
+ * Remove all the instances and leave the generators intact.
1914
2122
  */
1915
2123
  reset() {
1916
2124
  for (const name in this._generators) {
@@ -1918,6 +2126,14 @@ class Factory {
1918
2126
  }
1919
2127
  this._instances = {};
1920
2128
  }
2129
+ /**
2130
+ * Remove all the instances and the generators.
2131
+ */
2132
+ clear() {
2133
+ this._instances = {};
2134
+ this._generators = {};
2135
+ this._orderCounter = 0;
2136
+ }
1921
2137
  /**
1922
2138
  * Get all the instances as a map.
1923
2139
  * @returns The instances as a map.
@@ -1992,518 +2208,265 @@ const ComponentFactory = Factory.createFactory("component");
1992
2208
 
1993
2209
  // Copyright 2024 IOTA Stiftung.
1994
2210
  // SPDX-License-Identifier: Apache-2.0.
2211
+ /* eslint-disable no-bitwise */
1995
2212
  /**
1996
- * Class to help with arrays.
1997
- */
1998
- class ArrayHelper {
1999
- /**
2000
- * Do the two arrays match.
2001
- * @param arr1 The first array.
2002
- * @param arr2 The second array.
2003
- * @returns True if both arrays are empty of have the same values.
2004
- */
2005
- static matches(arr1, arr2) {
2006
- if (Is.empty(arr1) && Is.empty(arr2)) {
2007
- return true;
2008
- }
2009
- if (!((Is.array(arr1) && Is.array(arr2)) || (Is.typedArray(arr1) && Is.typedArray(arr2)))) {
2010
- return false;
2011
- }
2012
- if (arr1.length !== arr2.length) {
2013
- return false;
2014
- }
2015
- for (let i = 0; i < arr1.length; i++) {
2016
- if (arr1[i] !== arr2[i]) {
2017
- return false;
2018
- }
2019
- }
2020
- return true;
2021
- }
2022
- }
2023
-
2024
- // Copyright 2024 IOTA Stiftung.
2025
- // SPDX-License-Identifier: Apache-2.0.
2026
- /**
2027
- * Class to perform internationalization.
2213
+ * Convert arrays to and from different formats.
2028
2214
  */
2029
- class I18n {
2030
- /**
2031
- * The default translation.
2032
- */
2033
- static DEFAULT_LOCALE = "en";
2034
- /**
2035
- * Dictionaries for lookups.
2036
- * @internal
2037
- */
2038
- static _localeDictionaries = {};
2039
- /**
2040
- * The current locale.
2041
- * @internal
2042
- */
2043
- static _currentLocale = I18n.DEFAULT_LOCALE;
2215
+ class Converter {
2044
2216
  /**
2045
- * Change handler for the locale being updated.
2217
+ * Lookup table for encoding.
2046
2218
  * @internal
2047
2219
  */
2048
- static _localeChangedHandlers = {};
2220
+ static _ENCODE_LOOKUP;
2049
2221
  /**
2050
- * Change handler for the dictionaries being updated.
2222
+ * Lookup table for decoding.
2051
2223
  * @internal
2052
2224
  */
2053
- static _dictionaryChangedHandlers = {};
2225
+ static _DECODE_LOOKUP;
2054
2226
  /**
2055
- * Set the locale.
2056
- * @param locale The new locale.
2227
+ * Encode a raw array to UTF8 string.
2228
+ * @param array The bytes to encode.
2229
+ * @param startIndex The index to start in the bytes.
2230
+ * @param length The length of bytes to read.
2231
+ * @returns The array formatted as UTF8.
2057
2232
  */
2058
- static setLocale(locale) {
2059
- I18n._currentLocale = locale;
2060
- for (const callback in I18n._localeChangedHandlers) {
2061
- I18n._localeChangedHandlers[callback](I18n._currentLocale);
2233
+ static bytesToUtf8(array, startIndex, length) {
2234
+ const start = startIndex ?? 0;
2235
+ const len = length ?? array.length;
2236
+ let str = "";
2237
+ for (let i = start; i < start + len; i++) {
2238
+ const value = array[i];
2239
+ if (value < 0x80) {
2240
+ str += String.fromCharCode(value);
2241
+ }
2242
+ else if (value > 0xbf && value < 0xe0) {
2243
+ str += String.fromCharCode(((value & 0x1f) << 6) | (array[i + 1] & 0x3f));
2244
+ i += 1;
2245
+ }
2246
+ else if (value > 0xdf && value < 0xf0) {
2247
+ str += String.fromCharCode(((value & 0x0f) << 12) | ((array[i + 1] & 0x3f) << 6) | (array[i + 2] & 0x3f));
2248
+ i += 2;
2249
+ }
2250
+ else {
2251
+ // surrogate pair
2252
+ const charCode = (((value & 0x07) << 18) |
2253
+ ((array[i + 1] & 0x3f) << 12) |
2254
+ ((array[i + 2] & 0x3f) << 6) |
2255
+ (array[i + 3] & 0x3f)) -
2256
+ 0x010000;
2257
+ str += String.fromCharCode((charCode >> 10) | 0xd800, (charCode & 0x03ff) | 0xdc00);
2258
+ i += 3;
2259
+ }
2062
2260
  }
2261
+ return str;
2063
2262
  }
2064
2263
  /**
2065
- * Get the locale.
2066
- * @returns The current locale.
2264
+ * Convert a UTF8 string to raw array.
2265
+ * @param utf8 The text to decode.
2266
+ * @returns The array.
2067
2267
  */
2068
- static getLocale() {
2069
- return I18n._currentLocale;
2268
+ static utf8ToBytes(utf8) {
2269
+ const bytes = [];
2270
+ for (let i = 0; i < utf8.length; i++) {
2271
+ let charCode = utf8.charCodeAt(i);
2272
+ if (charCode < 0x80) {
2273
+ bytes.push(charCode);
2274
+ }
2275
+ else if (charCode < 0x800) {
2276
+ bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
2277
+ }
2278
+ else if (charCode < 0xd800 || charCode >= 0xe000) {
2279
+ bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
2280
+ }
2281
+ else {
2282
+ // surrogate pair
2283
+ i++;
2284
+ // UTF-16 encodes 0x10000-0x10FFFF by
2285
+ // subtracting 0x10000 and splitting the
2286
+ // 20 bits of 0x0-0xFFFFF into two halves
2287
+ charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (utf8.charCodeAt(i) & 0x3ff));
2288
+ bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
2289
+ }
2290
+ }
2291
+ return Uint8Array.from(bytes);
2070
2292
  }
2071
2293
  /**
2072
- * Add a locale dictionary.
2073
- * @param locale The locale.
2074
- * @param dictionary The dictionary to add.
2075
- */
2076
- static addDictionary(locale, dictionary) {
2077
- const mergedKeys = {};
2078
- I18n.flattenTranslationKeys(dictionary, "", mergedKeys);
2079
- I18n._localeDictionaries[locale] = mergedKeys;
2080
- for (const callback in I18n._dictionaryChangedHandlers) {
2081
- I18n._dictionaryChangedHandlers[callback](I18n._currentLocale);
2294
+ * Encode a raw array to hex string.
2295
+ * @param array The bytes to encode.
2296
+ * @param includePrefix Include the 0x prefix on the returned hex.
2297
+ * @param startIndex The index to start in the bytes.
2298
+ * @param length The length of bytes to read.
2299
+ * @param reverse Reverse the combine direction.
2300
+ * @returns The array formatted as hex.
2301
+ */
2302
+ static bytesToHex(array, includePrefix = false, startIndex, length, reverse) {
2303
+ let hex = "";
2304
+ this.buildHexLookups();
2305
+ if (Converter._ENCODE_LOOKUP) {
2306
+ const len = length ?? array.length;
2307
+ const start = startIndex ?? 0;
2308
+ if (reverse) {
2309
+ for (let i = 0; i < len; i++) {
2310
+ hex = Converter._ENCODE_LOOKUP[array[start + i]] + hex;
2311
+ }
2312
+ }
2313
+ else {
2314
+ for (let i = 0; i < len; i++) {
2315
+ hex += Converter._ENCODE_LOOKUP[array[start + i]];
2316
+ }
2317
+ }
2082
2318
  }
2319
+ return includePrefix ? HexHelper.addPrefix(hex) : hex;
2083
2320
  }
2084
2321
  /**
2085
- * Get a locale dictionary.
2086
- * @param locale The locale.
2087
- * @returns The dictionary of undefined if it does not exist.
2322
+ * Decode a hex string to raw array.
2323
+ * @param hex The hex to decode.
2324
+ * @param reverse Store the characters in reverse.
2325
+ * @returns The array.
2088
2326
  */
2089
- static getDictionary(locale) {
2090
- return I18n._localeDictionaries[locale];
2327
+ static hexToBytes(hex, reverse) {
2328
+ const strippedHex = HexHelper.stripPrefix(hex);
2329
+ const sizeof = strippedHex.length >> 1;
2330
+ const length = sizeof << 1;
2331
+ const array = new Uint8Array(sizeof);
2332
+ this.buildHexLookups();
2333
+ if (Converter._DECODE_LOOKUP) {
2334
+ let i = 0;
2335
+ let n = 0;
2336
+ while (i < length) {
2337
+ array[n++] =
2338
+ (Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)] << 4) |
2339
+ Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)];
2340
+ }
2341
+ if (reverse) {
2342
+ array.reverse();
2343
+ }
2344
+ }
2345
+ return array;
2091
2346
  }
2092
2347
  /**
2093
- * Get all the locale dictionaries.
2094
- * @returns The dictionaries.
2348
+ * Convert the UTF8 to hex.
2349
+ * @param utf8 The text to convert.
2350
+ * @param includePrefix Include the 0x prefix on the returned hex.
2351
+ * @returns The hex version of the bytes.
2095
2352
  */
2096
- static getAllDictionaries() {
2097
- return I18n._localeDictionaries;
2353
+ static utf8ToHex(utf8, includePrefix = false) {
2354
+ const hex = Converter.bytesToHex(Converter.utf8ToBytes(utf8));
2355
+ return includePrefix ? HexHelper.addPrefix(hex) : hex;
2098
2356
  }
2099
2357
  /**
2100
- * Add a locale changed handler.
2101
- * @param id The id of the handler.
2102
- * @param handler The handler to add.
2358
+ * Convert the hex text to text.
2359
+ * @param hex The hex to convert.
2360
+ * @returns The UTF8 version of the bytes.
2103
2361
  */
2104
- static addLocaleHandler(id, handler) {
2105
- I18n._localeChangedHandlers[id] = handler;
2362
+ static hexToUtf8(hex) {
2363
+ return Converter.bytesToUtf8(Converter.hexToBytes(HexHelper.stripPrefix(hex)));
2106
2364
  }
2107
2365
  /**
2108
- * Remove a locale changed handler.
2109
- * @param id The id of the handler.
2366
+ * Convert bytes to binary string.
2367
+ * @param bytes The bytes to convert.
2368
+ * @returns A binary string of the bytes.
2110
2369
  */
2111
- static removeLocaleHandler(id) {
2112
- delete I18n._localeChangedHandlers[id];
2370
+ static bytesToBinary(bytes) {
2371
+ const b = [];
2372
+ for (let i = 0; i < bytes.length; i++) {
2373
+ b.push(bytes[i].toString(2).padStart(8, "0"));
2374
+ }
2375
+ return b.join("");
2113
2376
  }
2114
2377
  /**
2115
- * Add a dictionary changed handler.
2116
- * @param id The id of the handler.
2117
- * @param handler The handler to add.
2378
+ * Convert a binary string to bytes.
2379
+ * @param binary The binary string.
2380
+ * @returns The bytes.
2118
2381
  */
2119
- static addDictionaryHandler(id, handler) {
2120
- I18n._dictionaryChangedHandlers[id] = handler;
2382
+ static binaryToBytes(binary) {
2383
+ const bytes = new Uint8Array(Math.ceil(binary.length / 8));
2384
+ for (let i = 0; i < bytes.length; i++) {
2385
+ bytes[i] = Number.parseInt(binary.slice(i * 8, (i + 1) * 8), 2);
2386
+ }
2387
+ return bytes;
2121
2388
  }
2122
2389
  /**
2123
- * Remove a dictionary changed handler.
2124
- * @param id The id of the handler.
2390
+ * Convert bytes to base64 string.
2391
+ * @param bytes The bytes to convert.
2392
+ * @returns A base64 string of the bytes.
2125
2393
  */
2126
- static removeDictionaryHandler(id) {
2127
- delete I18n._dictionaryChangedHandlers[id];
2394
+ static bytesToBase64(bytes) {
2395
+ return Base64.encode(bytes);
2128
2396
  }
2129
2397
  /**
2130
- * Format a message.
2131
- * @param key The key of the message to format.
2132
- * @param values The values to substitute into the message.
2133
- * @param overrideLocale Override the locale.
2134
- * @returns The formatted string.
2398
+ * Convert a base64 string to bytes.
2399
+ * @param base64 The base64 string.
2400
+ * @returns The bytes.
2135
2401
  */
2136
- static formatMessage(key, values, overrideLocale) {
2137
- let cl = overrideLocale ?? I18n._currentLocale;
2138
- if (cl.startsWith("debug-")) {
2139
- cl = I18n.DEFAULT_LOCALE;
2140
- }
2141
- if (!I18n._localeDictionaries[cl]) {
2142
- return `!!Missing ${cl}`;
2143
- }
2144
- if (!I18n._localeDictionaries[cl][key]) {
2145
- return `!!Missing ${cl}.${key}`;
2146
- }
2147
- if (I18n._currentLocale === "debug-k") {
2148
- return key;
2149
- }
2150
- let ret = new IntlMessageFormat(I18n._localeDictionaries[cl][key], cl).format(values);
2151
- if (I18n._currentLocale === "debug-x") {
2152
- ret = ret.replace(/[a-z]/g, "x").replace(/[A-Z]/g, "x").replace(/\d/g, "n");
2153
- }
2154
- return ret;
2402
+ static base64ToBytes(base64) {
2403
+ return Base64.decode(base64);
2155
2404
  }
2156
2405
  /**
2157
- * Check if the dictionaries have a message for the given key.
2158
- * @param key The key to check for existence.
2159
- * @returns True if the key exists.
2406
+ * Convert bytes to base64 url string.
2407
+ * @param bytes The bytes to convert.
2408
+ * @returns A base64 url string of the bytes.
2160
2409
  */
2161
- static hasMessage(key) {
2162
- return Is.string(I18n._localeDictionaries[I18n._currentLocale]?.[key]);
2410
+ static bytesToBase64Url(bytes) {
2411
+ return Base64Url.encode(bytes);
2163
2412
  }
2164
2413
  /**
2165
- * Flatten the translation property paths for faster lookup.
2166
- * @param translation The translation to merge.
2167
- * @param propertyPath The current root path.
2168
- * @param mergedKeys The merged keys dictionary to populate.
2169
- * @internal
2414
+ * Convert a base64 url string to bytes.
2415
+ * @param base64Url The base64 url string.
2416
+ * @returns The bytes.
2170
2417
  */
2171
- static flattenTranslationKeys(translation, propertyPath, mergedKeys) {
2172
- for (const key in translation) {
2173
- const val = translation[key];
2174
- const mergedPath = propertyPath.length > 0 ? `${propertyPath}.${key}` : key;
2175
- if (Is.string(val)) {
2176
- mergedKeys[mergedPath] = val;
2177
- }
2178
- else if (Is.object(val)) {
2179
- I18n.flattenTranslationKeys(val, mergedPath, mergedKeys);
2180
- }
2181
- }
2418
+ static base64UrlToBytes(base64Url) {
2419
+ return Base64Url.decode(base64Url);
2182
2420
  }
2183
- }
2184
-
2185
- // Copyright 2024 IOTA Stiftung.
2186
- // SPDX-License-Identifier: Apache-2.0.
2187
- /**
2188
- * Error helper functions.
2189
- */
2190
- class ErrorHelper {
2191
2421
  /**
2192
- * Format Errors and returns just their messages.
2193
- * @param error The error to format.
2194
- * @returns The error formatted including any inner errors.
2422
+ * Convert bytes to base58 string.
2423
+ * @param bytes The bytes to convert.
2424
+ * @returns A base58 string of the bytes.
2195
2425
  */
2196
- static formatErrors(error) {
2197
- return ErrorHelper.localizeErrors(error).map(e => e.message);
2426
+ static bytesToBase58(bytes) {
2427
+ return Base58.encode(bytes);
2198
2428
  }
2199
2429
  /**
2200
- * Localize the content of an error and any inner errors.
2201
- * @param error The error to format.
2202
- * @returns The localized version of the errors flattened.
2430
+ * Convert a base58 string to bytes.
2431
+ * @param base58 The base58 string.
2432
+ * @returns The bytes.
2203
2433
  */
2204
- static localizeErrors(error) {
2205
- const formattedErrors = [];
2206
- if (Is.notEmpty(error)) {
2207
- const errors = BaseError.flatten(error);
2208
- for (const err of errors) {
2209
- const errorNameKey = `errorNames.${StringHelper.camelCase(err.name)}`;
2210
- const errorMessageKey = `error.${err.message}`;
2211
- // If there is no error message then it is probably
2212
- // from a 3rd party lib, so don't format it just display
2213
- const hasErrorName = I18n.hasMessage(errorNameKey);
2214
- const hasErrorMessage = I18n.hasMessage(errorMessageKey);
2215
- const localizedError = {
2216
- name: I18n.formatMessage(hasErrorName ? errorNameKey : "errorNames.error"),
2217
- message: hasErrorMessage
2218
- ? I18n.formatMessage(errorMessageKey, err.properties)
2219
- : err.message
2220
- };
2221
- if (Is.stringValue(err.source)) {
2222
- localizedError.source = err.source;
2223
- }
2224
- if (Is.stringValue(err.stack)) {
2225
- // Remove the first line from the stack traces as they
2226
- // just have the error type and message duplicated
2227
- const lines = err.stack.split("\n");
2228
- lines.shift();
2229
- localizedError.stack = lines.join("\n");
2230
- }
2231
- const additional = ErrorHelper.formatValidationErrors(err);
2232
- if (Is.stringValue(additional)) {
2233
- localizedError.additional = additional;
2234
- }
2235
- formattedErrors.push(localizedError);
2236
- }
2237
- }
2238
- return formattedErrors;
2434
+ static base58ToBytes(base58) {
2435
+ return Base58.decode(base58);
2239
2436
  }
2240
2437
  /**
2241
- * Localize the content of an error and any inner errors.
2242
- * @param error The error to format.
2243
- * @returns The localized version of the errors flattened.
2438
+ * Build the static lookup tables.
2439
+ * @internal
2244
2440
  */
2245
- static formatValidationErrors(error) {
2246
- if (Is.object(error.properties) &&
2247
- Object.keys(error.properties).length > 0 &&
2248
- Is.object(error.properties) &&
2249
- Is.arrayValue(error.properties.validationFailures)) {
2250
- const validationErrors = [];
2251
- for (const validationFailure of error.properties.validationFailures) {
2252
- const errorI18n = `error.${validationFailure.reason}`;
2253
- const errorMessage = I18n.hasMessage(errorI18n)
2254
- ? I18n.formatMessage(errorI18n, validationFailure.properties)
2255
- : errorI18n;
2256
- let v = `${validationFailure.property}: ${errorMessage}`;
2257
- if (Is.object(validationFailure.properties) &&
2258
- Is.notEmpty(validationFailure.properties.value)) {
2259
- v += ` = ${JSON.stringify(validationFailure.properties.value)}`;
2441
+ static buildHexLookups() {
2442
+ if (!Converter._ENCODE_LOOKUP || !Converter._DECODE_LOOKUP) {
2443
+ const alphabet = "0123456789abcdef";
2444
+ Converter._ENCODE_LOOKUP = [];
2445
+ Converter._DECODE_LOOKUP = [];
2446
+ for (let i = 0; i < 256; i++) {
2447
+ Converter._ENCODE_LOOKUP[i] = alphabet[(i >> 4) & 0xf] + alphabet[i & 0xf];
2448
+ if (i < 16) {
2449
+ if (i < 10) {
2450
+ Converter._DECODE_LOOKUP[0x30 + i] = i;
2451
+ }
2452
+ else {
2453
+ Converter._DECODE_LOOKUP[0x61 - 10 + i] = i;
2454
+ }
2260
2455
  }
2261
- validationErrors.push(v);
2262
2456
  }
2263
- return validationErrors.join("\n");
2264
2457
  }
2265
2458
  }
2266
2459
  }
2267
2460
 
2268
- // Copyright 2024 IOTA Stiftung.
2269
- // SPDX-License-Identifier: Apache-2.0.
2270
- /**
2271
- * Coerce an object from one type to another.
2272
- */
2273
- class Coerce {
2274
- /**
2275
- * Coerce the value to a string.
2276
- * @param value The value to coerce.
2277
- * @throws TypeError If the value can not be coerced.
2278
- * @returns The value if it can be coerced.
2279
- */
2280
- static string(value) {
2281
- if (Is.undefined(value)) {
2282
- return value;
2283
- }
2284
- if (Is.string(value)) {
2285
- return value;
2286
- }
2287
- if (Is.number(value)) {
2288
- return value.toString();
2289
- }
2290
- if (Is.boolean(value)) {
2291
- return value ? "true" : "false";
2292
- }
2293
- if (Is.date(value)) {
2294
- return value.toISOString();
2295
- }
2296
- }
2297
- /**
2298
- * Coerce the value to a number.
2299
- * @param value The value to coerce.
2300
- * @throws TypeError If the value can not be coerced.
2301
- * @returns The value if it can be coerced.
2302
- */
2303
- static number(value) {
2304
- if (Is.undefined(value)) {
2305
- return value;
2306
- }
2307
- if (Is.number(value)) {
2308
- return value;
2309
- }
2310
- if (Is.string(value)) {
2311
- const parsed = Number.parseFloat(value);
2312
- if (Is.number(parsed)) {
2313
- return parsed;
2314
- }
2315
- }
2316
- if (Is.boolean(value)) {
2317
- return value ? 1 : 0;
2318
- }
2319
- if (Is.date(value)) {
2320
- return value.getTime();
2321
- }
2322
- }
2323
- /**
2324
- * Coerce the value to a bigint.
2325
- * @param value The value to coerce.
2326
- * @throws TypeError If the value can not be coerced.
2327
- * @returns The value if it can be coerced.
2328
- */
2329
- static bigint(value) {
2330
- if (Is.undefined(value)) {
2331
- return value;
2332
- }
2333
- if (Is.bigint(value)) {
2334
- return value;
2335
- }
2336
- if (Is.number(value)) {
2337
- return BigInt(value);
2338
- }
2339
- if (Is.string(value)) {
2340
- const parsed = Number.parseFloat(value);
2341
- if (Is.integer(parsed)) {
2342
- return BigInt(parsed);
2343
- }
2344
- }
2345
- if (Is.boolean(value)) {
2346
- return value ? 1n : 0n;
2347
- }
2348
- }
2349
- /**
2350
- * Coerce the value to a boolean.
2351
- * @param value The value to coerce.
2352
- * @throws TypeError If the value can not be coerced.
2353
- * @returns The value if it can be coerced.
2354
- */
2355
- static boolean(value) {
2356
- if (Is.undefined(value)) {
2357
- return value;
2358
- }
2359
- if (Is.boolean(value)) {
2360
- return value;
2361
- }
2362
- if (Is.number(value)) {
2363
- // eslint-disable-next-line no-unneeded-ternary
2364
- return value ? true : false;
2365
- }
2366
- if (Is.string(value)) {
2367
- if (/true/i.test(value)) {
2368
- return true;
2369
- }
2370
- if (/false/i.test(value)) {
2371
- return false;
2372
- }
2373
- }
2374
- }
2375
- /**
2376
- * Coerce the value to a date.
2377
- * @param value The value to coerce.
2378
- * @throws TypeError If the value can not be coerced.
2379
- * @returns The value if it can be coerced.
2380
- */
2381
- static date(value) {
2382
- if (Is.undefined(value)) {
2383
- return value;
2384
- }
2385
- if (Is.date(value)) {
2386
- return value;
2387
- }
2388
- if (Is.number(value)) {
2389
- return new Date(value);
2390
- }
2391
- if (Is.string(value)) {
2392
- const dt = new Date(value);
2393
- if (!Number.isNaN(dt.getTime())) {
2394
- const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate());
2395
- return new Date(utc);
2396
- }
2397
- }
2398
- }
2399
- /**
2400
- * Coerce the value to a date/time.
2401
- * @param value The value to coerce.
2402
- * @throws TypeError If the value can not be coerced.
2403
- * @returns The value if it can be coerced.
2404
- */
2405
- static dateTime(value) {
2406
- if (Is.undefined(value)) {
2407
- return value;
2408
- }
2409
- if (Is.date(value)) {
2410
- return value;
2411
- }
2412
- if (Is.number(value)) {
2413
- return new Date(value);
2414
- }
2415
- if (Is.string(value)) {
2416
- const dt = new Date(value);
2417
- if (!Number.isNaN(dt.getTime())) {
2418
- const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate(), dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
2419
- return new Date(utc);
2420
- }
2421
- }
2422
- }
2423
- /**
2424
- * Coerce the value to a time.
2425
- * @param value The value to coerce.
2426
- * @throws TypeError If the value can not be coerced.
2427
- * @returns The value if it can be coerced.
2428
- */
2429
- static time(value) {
2430
- if (Is.undefined(value)) {
2431
- return value;
2432
- }
2433
- if (Is.date(value)) {
2434
- return value;
2435
- }
2436
- if (Is.number(value)) {
2437
- const dt = new Date(value);
2438
- dt.setFullYear(1970, 0, 1);
2439
- return dt;
2440
- }
2441
- if (Is.string(value)) {
2442
- const dt = new Date(value);
2443
- if (!Number.isNaN(dt.getTime())) {
2444
- const utc = Date.UTC(1970, 0, 1, dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
2445
- return new Date(utc);
2446
- }
2447
- }
2448
- }
2449
- /**
2450
- * Coerce the value to an object.
2451
- * @param value The value to coerce.
2452
- * @throws TypeError If the value can not be coerced.
2453
- * @returns The value if it can be coerced.
2454
- */
2455
- static object(value) {
2456
- if (Is.undefined(value)) {
2457
- return value;
2458
- }
2459
- if (Is.object(value)) {
2460
- return value;
2461
- }
2462
- if (Is.stringValue(value)) {
2463
- try {
2464
- return JSON.parse(value);
2465
- }
2466
- catch { }
2467
- }
2468
- }
2469
- }
2470
-
2471
- // Copyright 2024 IOTA Stiftung.
2472
- // SPDX-License-Identifier: Apache-2.0.
2473
- /**
2474
- * Class to help with filenames.
2475
- */
2476
- class FilenameHelper {
2477
- /**
2478
- * Replaces any unsafe characters in the filename.
2479
- * @param filename The filename to make safe.
2480
- * @returns The safe filename.
2481
- */
2482
- static safeFilename(filename) {
2483
- let safe = Coerce.string(filename);
2484
- if (Is.empty(safe)) {
2485
- return "";
2486
- }
2487
- // Common non filename characters
2488
- safe = safe.replace(/["*/:<>?\\|]/g, "_");
2489
- // Windows non filename characters
2490
- safe = safe.replace(/^(con|prn|aux|nul|com\d|lpt\d)$/i, "_");
2491
- // Control characters
2492
- safe = safe.replace(/[\u0000-\u001F\u0080-\u009F]/g, "_");
2493
- // Relative paths
2494
- safe = safe.replace(/^\.+/, "_");
2495
- // Trailing periods
2496
- safe = safe.replace(/\.+$/, "");
2497
- return safe;
2498
- }
2499
- }
2500
-
2501
- // Copyright 2024 IOTA Stiftung.
2502
- // SPDX-License-Identifier: Apache-2.0.
2503
2461
  /**
2504
2462
  * Helpers methods for JSON objects.
2505
2463
  */
2506
2464
  class JsonHelper {
2465
+ /**
2466
+ * Runtime name for the class.
2467
+ * @internal
2468
+ */
2469
+ static _CLASS_NAME = "JsonHelper";
2507
2470
  /**
2508
2471
  * Serializes in canonical format.
2509
2472
  * Based on https://www.rfc-editor.org/rfc/rfc8785.
@@ -2562,449 +2525,1043 @@ class JsonHelper {
2562
2525
  * @param object The object to patch.
2563
2526
  * @param patches The second object.
2564
2527
  * @returns The updated object.
2528
+ * @throws GeneralError if the patch fails.
2565
2529
  */
2566
2530
  static patch(object, patches) {
2567
- return applyPatch(object, patches);
2531
+ const clone = ObjectHelper.clone(object);
2532
+ const result = applyPatch(clone, patches);
2533
+ for (let i = 0; i < result.length; i++) {
2534
+ if (!Is.empty(result[i])) {
2535
+ throw new GeneralError(JsonHelper._CLASS_NAME, "failedPatch", { index: i }, result[i]);
2536
+ }
2537
+ }
2538
+ return clone;
2568
2539
  }
2569
- }
2570
-
2571
- // Copyright 2024 IOTA Stiftung.
2572
- // SPDX-License-Identifier: Apache-2.0.
2573
- /* eslint-disable no-bitwise */
2574
- /**
2575
- * Convert arrays to and from different formats.
2576
- */
2577
- class Converter {
2578
2540
  /**
2579
- * Lookup table for encoding.
2580
- * @internal
2541
+ * Stringify the JSON with support for extended data types date/bigint/uint8array.
2542
+ * @param object The object to stringify.
2543
+ * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
2544
+ * @returns The stringified object.
2581
2545
  */
2582
- static _ENCODE_LOOKUP;
2546
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2547
+ static stringifyEx(object, space) {
2548
+ // We want to keep the 'this' intact for the replacer
2549
+ // eslint-disable-next-line @typescript-eslint/unbound-method
2550
+ return JSON.stringify(object, JsonHelper.stringifyExReplacer, space);
2551
+ }
2583
2552
  /**
2584
- * Lookup table for decoding.
2585
- * @internal
2553
+ * Parse the JSON string with support for extended data types date/bigint/uint8array.
2554
+ * @param json The object to pause.
2555
+ * @returns The object.
2586
2556
  */
2587
- static _DECODE_LOOKUP;
2557
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2558
+ static parseEx(json) {
2559
+ // We want to keep the 'this' intact for the reviver
2560
+ // eslint-disable-next-line @typescript-eslint/unbound-method
2561
+ return JSON.parse(json, JsonHelper.parseExReviver);
2562
+ }
2563
+ /**
2564
+ * Replacer function to handle extended data types.
2565
+ * @param this The object.
2566
+ * @param key The key.
2567
+ * @param value The value.
2568
+ * @returns The value.
2569
+ */
2570
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2571
+ static stringifyExReplacer(key, value) {
2572
+ const rawValue = this[key];
2573
+ if (Is.bigint(rawValue)) {
2574
+ return {
2575
+ "@ext": "bigint",
2576
+ value: rawValue.toString()
2577
+ };
2578
+ }
2579
+ else if (Is.date(rawValue)) {
2580
+ return {
2581
+ "@ext": "date",
2582
+ value: rawValue.getTime()
2583
+ };
2584
+ }
2585
+ else if (Is.uint8Array(rawValue)) {
2586
+ return {
2587
+ "@ext": "uint8array",
2588
+ value: Converter.bytesToBase64(rawValue)
2589
+ };
2590
+ }
2591
+ return value;
2592
+ }
2593
+ /**
2594
+ * Reviver function to handle extended data types.
2595
+ * @param this The object.
2596
+ * @param key The key.
2597
+ * @param value The value.
2598
+ * @returns The value.
2599
+ */
2600
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2601
+ static parseExReviver(key, value) {
2602
+ if (Is.object(value)) {
2603
+ if (value["@ext"] === "bigint") {
2604
+ return BigInt(value.value);
2605
+ }
2606
+ else if (value["@ext"] === "date") {
2607
+ return new Date(value.value);
2608
+ }
2609
+ else if (value["@ext"] === "uint8array") {
2610
+ return Converter.base64ToBytes(value.value);
2611
+ }
2612
+ }
2613
+ return value;
2614
+ }
2615
+ }
2616
+
2617
+ /**
2618
+ * Class to help with objects.
2619
+ */
2620
+ class ObjectHelper {
2588
2621
  /**
2589
- * Encode a raw array to UTF8 string.
2590
- * @param array The bytes to encode.
2591
- * @param startIndex The index to start in the bytes.
2592
- * @param length The length of bytes to read.
2593
- * @returns The array formatted as UTF8.
2622
+ * Runtime name for the class.
2623
+ * @internal
2594
2624
  */
2595
- static bytesToUtf8(array, startIndex, length) {
2596
- const start = startIndex ?? 0;
2597
- const len = length ?? array.length;
2598
- let str = "";
2599
- for (let i = start; i < start + len; i++) {
2600
- const value = array[i];
2601
- if (value < 0x80) {
2602
- str += String.fromCharCode(value);
2625
+ static _CLASS_NAME = "ObjectHelper";
2626
+ /**
2627
+ * Convert an object to bytes.
2628
+ * @param obj The object to convert.
2629
+ * @param format Format the JSON content.
2630
+ * @returns The object as bytes.
2631
+ */
2632
+ static toBytes(obj, format = false) {
2633
+ if (obj === undefined) {
2634
+ return new Uint8Array();
2635
+ }
2636
+ const json = format ? JSON.stringify(obj, undefined, "\t") : JSON.stringify(obj);
2637
+ return Converter.utf8ToBytes(json);
2638
+ }
2639
+ /**
2640
+ * Convert a bytes to an object.
2641
+ * @param bytes The bytes to convert to an object.
2642
+ * @returns The object.
2643
+ * @throws GeneralError if there was an error parsing the JSON.
2644
+ */
2645
+ static fromBytes(bytes) {
2646
+ if (Is.empty(bytes) || bytes.length === 0) {
2647
+ return undefined;
2648
+ }
2649
+ try {
2650
+ const utf8 = Converter.bytesToUtf8(bytes);
2651
+ return JSON.parse(utf8);
2652
+ }
2653
+ catch (err) {
2654
+ throw new GeneralError(ObjectHelper._CLASS_NAME, "failedBytesToJSON", undefined, err);
2655
+ }
2656
+ }
2657
+ /**
2658
+ * Make a deep clone of an object.
2659
+ * @param obj The object to clone.
2660
+ * @returns The objects clone.
2661
+ */
2662
+ static clone(obj) {
2663
+ if (Is.undefined(obj)) {
2664
+ return undefined;
2665
+ }
2666
+ return structuredClone(obj);
2667
+ }
2668
+ /**
2669
+ * Deep merge objects.
2670
+ * @param obj1 The first object to merge.
2671
+ * @param obj2 The second object to merge.
2672
+ * @returns The combined deep merge of the objects.
2673
+ */
2674
+ static merge(obj1, obj2) {
2675
+ if (Is.empty(obj1)) {
2676
+ return ObjectHelper.clone(obj2);
2677
+ }
2678
+ if (Is.empty(obj2)) {
2679
+ return ObjectHelper.clone(obj1);
2680
+ }
2681
+ const obj1Clone = ObjectHelper.clone(obj1);
2682
+ if (Is.object(obj1Clone) && Is.object(obj2)) {
2683
+ const keys = Object.keys(obj2);
2684
+ for (const key of keys) {
2685
+ if (Is.object(obj1Clone[key]) && Is.object(obj2[key])) {
2686
+ ObjectHelper.propertySet(obj1Clone, key, ObjectHelper.merge(obj1Clone[key], obj2[key]));
2687
+ }
2688
+ else {
2689
+ ObjectHelper.propertySet(obj1Clone, key, obj2[key]);
2690
+ }
2603
2691
  }
2604
- else if (value > 0xbf && value < 0xe0) {
2605
- str += String.fromCharCode(((value & 0x1f) << 6) | (array[i + 1] & 0x3f));
2606
- i += 1;
2692
+ }
2693
+ return obj1Clone;
2694
+ }
2695
+ /**
2696
+ * Does one object equal another.
2697
+ * @param obj1 The first object to compare.
2698
+ * @param obj2 The second object to compare.
2699
+ * @param strictPropertyOrder Should the properties be in the same order, defaults to true.
2700
+ * @returns True is the objects are equal.
2701
+ */
2702
+ static equal(obj1, obj2, strictPropertyOrder) {
2703
+ if (strictPropertyOrder ?? true) {
2704
+ return JSON.stringify(obj1) === JSON.stringify(obj2);
2705
+ }
2706
+ return JsonHelper.canonicalize(obj1) === JsonHelper.canonicalize(obj2);
2707
+ }
2708
+ /**
2709
+ * Get the property of an unknown object.
2710
+ * @param obj The object to get the property from.
2711
+ * @param property The property to get, can be separated by dots for nested path.
2712
+ * @returns The property.
2713
+ */
2714
+ static propertyGet(obj, property) {
2715
+ const pathParts = property.split(".");
2716
+ let pathValue = obj;
2717
+ for (const pathPart of pathParts) {
2718
+ // Is the path part numeric i.e. an array index.
2719
+ const arrayMatch = /^(\d+)$/.exec(pathPart);
2720
+ if (arrayMatch) {
2721
+ const arrayIndex = Number.parseInt(arrayMatch[1], 10);
2722
+ if (Is.arrayValue(pathValue) && arrayIndex < pathValue.length) {
2723
+ // There is no prop name so this is a direct array index on the current object
2724
+ pathValue = pathValue[arrayIndex];
2725
+ }
2726
+ else {
2727
+ // Array index for non array object so return
2728
+ return undefined;
2729
+ }
2607
2730
  }
2608
- else if (value > 0xdf && value < 0xf0) {
2609
- str += String.fromCharCode(((value & 0x0f) << 12) | ((array[i + 1] & 0x3f) << 6) | (array[i + 2] & 0x3f));
2610
- i += 2;
2731
+ else if (Is.object(pathValue)) {
2732
+ // No array part in path so assume object sub property
2733
+ pathValue = pathValue[pathPart];
2611
2734
  }
2612
2735
  else {
2613
- // surrogate pair
2614
- const charCode = (((value & 0x07) << 18) |
2615
- ((array[i + 1] & 0x3f) << 12) |
2616
- ((array[i + 2] & 0x3f) << 6) |
2617
- (array[i + 3] & 0x3f)) -
2618
- 0x010000;
2619
- str += String.fromCharCode((charCode >> 10) | 0xd800, (charCode & 0x03ff) | 0xdc00);
2620
- i += 3;
2736
+ return undefined;
2621
2737
  }
2622
2738
  }
2623
- return str;
2739
+ return pathValue;
2624
2740
  }
2625
2741
  /**
2626
- * Convert a UTF8 string to raw array.
2627
- * @param utf8 The text to decode.
2628
- * @returns The array.
2742
+ * Set the property of an unknown object.
2743
+ * @param obj The object to set the property from.
2744
+ * @param property The property to set.
2745
+ * @param value The value to set.
2746
+ * @throws GeneralError if the property target is not an object.
2629
2747
  */
2630
- static utf8ToBytes(utf8) {
2631
- const bytes = [];
2632
- for (let i = 0; i < utf8.length; i++) {
2633
- let charCode = utf8.charCodeAt(i);
2634
- if (charCode < 0x80) {
2635
- bytes.push(charCode);
2748
+ static propertySet(obj, property, value) {
2749
+ const pathParts = property.split(".");
2750
+ let pathValue = obj;
2751
+ let parentObj;
2752
+ for (let i = 0; i < pathParts.length; i++) {
2753
+ const pathPart = pathParts[i];
2754
+ // Is the path part numeric i.e. an array index.
2755
+ const arrayMatch = /^(\d+)$/.exec(pathPart);
2756
+ const arrayIndex = arrayMatch ? Number.parseInt(arrayMatch[1], 10) : -1;
2757
+ if (i === pathParts.length - 1) {
2758
+ // Last part of path so set the value
2759
+ if (arrayIndex >= 0) {
2760
+ if (Is.array(pathValue)) {
2761
+ pathValue[arrayIndex] = value;
2762
+ }
2763
+ else if (Is.object(pathValue)) {
2764
+ pathValue[arrayIndex] = value;
2765
+ }
2766
+ else {
2767
+ throw new GeneralError(ObjectHelper._CLASS_NAME, "cannotSetArrayIndex", {
2768
+ property,
2769
+ index: arrayIndex
2770
+ });
2771
+ }
2772
+ }
2773
+ else if (Is.object(pathValue)) {
2774
+ pathValue[pathPart] = value;
2775
+ }
2776
+ else {
2777
+ throw new GeneralError(ObjectHelper._CLASS_NAME, "cannotSetProperty", { property });
2778
+ }
2636
2779
  }
2637
- else if (charCode < 0x800) {
2638
- bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
2780
+ else {
2781
+ parentObj = pathValue;
2782
+ if (Is.object(pathValue)) {
2783
+ pathValue = pathValue[pathPart];
2784
+ }
2785
+ else if (Is.array(pathValue)) {
2786
+ pathValue = pathValue[arrayIndex];
2787
+ }
2788
+ if (Is.empty(pathValue)) {
2789
+ const nextArrayMatch = /^(\d+)$/.exec(pathParts[i + 1]);
2790
+ const nextArrayIndex = nextArrayMatch ? Number.parseInt(nextArrayMatch[1], 10) : -1;
2791
+ if (nextArrayIndex >= 0) {
2792
+ pathValue = [];
2793
+ }
2794
+ else {
2795
+ pathValue = {};
2796
+ }
2797
+ if (Is.object(parentObj)) {
2798
+ parentObj[pathPart] = pathValue;
2799
+ }
2800
+ else if (Is.array(parentObj)) {
2801
+ parentObj[arrayIndex] = pathValue;
2802
+ }
2803
+ }
2639
2804
  }
2640
- else if (charCode < 0xd800 || charCode >= 0xe000) {
2641
- bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
2805
+ }
2806
+ }
2807
+ /**
2808
+ * Delete the property of an unknown object.
2809
+ * @param obj The object to set the property from.
2810
+ * @param property The property to set
2811
+ */
2812
+ static propertyDelete(obj, property) {
2813
+ if (Is.object(obj)) {
2814
+ delete obj[property];
2815
+ }
2816
+ }
2817
+ /**
2818
+ * Extract a property from the object, providing alternative names.
2819
+ * @param obj The object to extract from.
2820
+ * @param propertyNames The possible names for the property.
2821
+ * @param removeProperties Remove the properties from the object, defaults to true.
2822
+ * @returns The property if available.
2823
+ */
2824
+ static extractProperty(obj, propertyNames, removeProperties = true) {
2825
+ let retVal;
2826
+ if (Is.object(obj)) {
2827
+ const names = Is.string(propertyNames) ? [propertyNames] : propertyNames;
2828
+ for (const prop of names) {
2829
+ retVal ??= ObjectHelper.propertyGet(obj, prop);
2830
+ if (removeProperties) {
2831
+ ObjectHelper.propertyDelete(obj, prop);
2832
+ }
2642
2833
  }
2643
- else {
2644
- // surrogate pair
2645
- i++;
2646
- // UTF-16 encodes 0x10000-0x10FFFF by
2647
- // subtracting 0x10000 and splitting the
2648
- // 20 bits of 0x0-0xFFFFF into two halves
2649
- charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (utf8.charCodeAt(i) & 0x3ff));
2650
- bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
2834
+ }
2835
+ return retVal;
2836
+ }
2837
+ /**
2838
+ * Pick a subset of properties from an object.
2839
+ * @param obj The object to pick the properties from.
2840
+ * @param keys The property keys to pick.
2841
+ * @returns The partial object.
2842
+ */
2843
+ static pick(obj, keys) {
2844
+ if (Is.object(obj) && Is.arrayValue(keys)) {
2845
+ const result = {};
2846
+ for (const key of keys) {
2847
+ result[key] = obj[key];
2651
2848
  }
2849
+ return result;
2652
2850
  }
2653
- return Uint8Array.from(bytes);
2851
+ return obj;
2654
2852
  }
2655
2853
  /**
2656
- * Encode a raw array to hex string.
2657
- * @param array The bytes to encode.
2658
- * @param includePrefix Include the 0x prefix on the returned hex.
2659
- * @param startIndex The index to start in the bytes.
2660
- * @param length The length of bytes to read.
2661
- * @param reverse Reverse the combine direction.
2662
- * @returns The array formatted as hex.
2854
+ * Omit a subset of properties from an object.
2855
+ * @param obj The object to omit the properties from.
2856
+ * @param keys The property keys to omit.
2857
+ * @returns The partial object.
2663
2858
  */
2664
- static bytesToHex(array, includePrefix = false, startIndex, length, reverse) {
2665
- let hex = "";
2666
- this.buildHexLookups();
2667
- if (Converter._ENCODE_LOOKUP) {
2668
- const len = length ?? array.length;
2669
- const start = startIndex ?? 0;
2670
- if (reverse) {
2671
- for (let i = 0; i < len; i++) {
2672
- hex = Converter._ENCODE_LOOKUP[array[start + i]] + hex;
2859
+ static omit(obj, keys) {
2860
+ if (Is.object(obj) && Is.arrayValue(keys)) {
2861
+ const result = { ...obj };
2862
+ for (const key of keys) {
2863
+ delete result[key];
2864
+ }
2865
+ return result;
2866
+ }
2867
+ return obj;
2868
+ }
2869
+ /**
2870
+ * Converter the non JSON primitives to extended types.
2871
+ * @param obj The object to convert.
2872
+ * @returns The object with extended properties.
2873
+ */
2874
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2875
+ static toExtended(obj) {
2876
+ const jsonExtended = JsonHelper.stringifyEx(obj);
2877
+ return JSON.parse(jsonExtended);
2878
+ }
2879
+ /**
2880
+ * Converter the extended types to non JSON primitives.
2881
+ * @param obj The object to convert.
2882
+ * @returns The object with regular properties.
2883
+ */
2884
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2885
+ static fromExtended(obj) {
2886
+ const jsonExtended = JsonHelper.stringifyEx(obj);
2887
+ return JsonHelper.parseEx(jsonExtended);
2888
+ }
2889
+ /**
2890
+ * Remove empty properties from an object.
2891
+ * @param obj The object to remove the empty properties from.
2892
+ * @param options The options for the removal.
2893
+ * @param options.removeUndefined Remove undefined properties, defaults to true.
2894
+ * @param options.removeNull Remove null properties, defaults to false.
2895
+ * @returns The object with empty properties removed.
2896
+ */
2897
+ static removeEmptyProperties(obj, options) {
2898
+ if (Is.object(obj)) {
2899
+ const removeUndefined = options?.removeUndefined ?? true;
2900
+ const removeNull = options?.removeNull ?? false;
2901
+ const newObj = {};
2902
+ const keys = Object.keys(obj);
2903
+ for (const key of keys) {
2904
+ if (!((removeUndefined && Is.undefined(obj[key])) || (removeNull && Is.null(obj[key])))) {
2905
+ newObj[key] = ObjectHelper.removeEmptyProperties(obj[key], options);
2906
+ }
2907
+ }
2908
+ return newObj;
2909
+ }
2910
+ else if (Is.array(obj)) {
2911
+ const arr = [];
2912
+ for (const element of obj) {
2913
+ arr.push(ObjectHelper.removeEmptyProperties(element, options));
2914
+ }
2915
+ return arr;
2916
+ }
2917
+ return obj;
2918
+ }
2919
+ }
2920
+
2921
+ // Copyright 2024 IOTA Stiftung.
2922
+ // SPDX-License-Identifier: Apache-2.0.
2923
+ /**
2924
+ * Environment variable helper.
2925
+ */
2926
+ class EnvHelper {
2927
+ /**
2928
+ * Get the environment variable as an object with camel cased names.
2929
+ * @param envVars The environment variables.
2930
+ * @param prefix The prefix of the environment variables, if not provided gets all.
2931
+ * @returns The object with camel cased names.
2932
+ */
2933
+ static envToJson(envVars, prefix) {
2934
+ const result = {};
2935
+ if (!Is.empty(envVars)) {
2936
+ if (Is.empty(prefix)) {
2937
+ for (const envVar in envVars) {
2938
+ if (Is.stringValue(envVars[envVar])) {
2939
+ const camelCaseName = StringHelper.camelCase(envVar.toLowerCase());
2940
+ ObjectHelper.propertySet(result, camelCaseName, envVars[envVar]);
2941
+ }
2673
2942
  }
2674
2943
  }
2675
2944
  else {
2676
- for (let i = 0; i < len; i++) {
2677
- hex += Converter._ENCODE_LOOKUP[array[start + i]];
2945
+ for (const envVar in envVars) {
2946
+ if (envVar.startsWith(prefix) && Is.stringValue(envVars[envVar])) {
2947
+ const camelCaseName = StringHelper.camelCase(envVar.replace(prefix, "").toLowerCase());
2948
+ ObjectHelper.propertySet(result, camelCaseName, envVars[envVar]);
2949
+ }
2678
2950
  }
2679
2951
  }
2680
2952
  }
2681
- return includePrefix ? HexHelper.addPrefix(hex) : hex;
2953
+ return result;
2682
2954
  }
2955
+ }
2956
+
2957
+ // Copyright 2024 IOTA Stiftung.
2958
+ // SPDX-License-Identifier: Apache-2.0.
2959
+ /**
2960
+ * Class to perform internationalization.
2961
+ */
2962
+ class I18n {
2683
2963
  /**
2684
- * Decode a hex string to raw array.
2685
- * @param hex The hex to decode.
2686
- * @param reverse Store the characters in reverse.
2687
- * @returns The array.
2964
+ * The default translation.
2688
2965
  */
2689
- static hexToBytes(hex, reverse) {
2690
- const strippedHex = HexHelper.stripPrefix(hex);
2691
- const sizeof = strippedHex.length >> 1;
2692
- const length = sizeof << 1;
2693
- const array = new Uint8Array(sizeof);
2694
- this.buildHexLookups();
2695
- if (Converter._DECODE_LOOKUP) {
2696
- let i = 0;
2697
- let n = 0;
2698
- while (i < length) {
2699
- array[n++] =
2700
- (Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)] << 4) |
2701
- Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)];
2966
+ static DEFAULT_LOCALE = "en";
2967
+ /**
2968
+ * Set the locale.
2969
+ * @param locale The new locale.
2970
+ */
2971
+ static setLocale(locale) {
2972
+ const i18nShared = I18n.getI18nShared();
2973
+ i18nShared.currentLocale = locale;
2974
+ for (const callback in i18nShared.localeChangedHandlers) {
2975
+ i18nShared.localeChangedHandlers[callback](i18nShared.currentLocale);
2976
+ }
2977
+ }
2978
+ /**
2979
+ * Get the locale.
2980
+ * @returns The current locale.
2981
+ */
2982
+ static getLocale() {
2983
+ const i18nShared = I18n.getI18nShared();
2984
+ return i18nShared.currentLocale;
2985
+ }
2986
+ /**
2987
+ * Add a locale dictionary.
2988
+ * @param locale The locale.
2989
+ * @param dictionary The dictionary to add.
2990
+ */
2991
+ static addDictionary(locale, dictionary) {
2992
+ const i18nShared = I18n.getI18nShared();
2993
+ const mergedKeys = {};
2994
+ I18n.flattenTranslationKeys(dictionary, "", mergedKeys);
2995
+ i18nShared.localeDictionaries[locale] = mergedKeys;
2996
+ for (const callback in i18nShared.dictionaryChangedHandlers) {
2997
+ i18nShared.dictionaryChangedHandlers[callback](i18nShared.currentLocale);
2998
+ }
2999
+ }
3000
+ /**
3001
+ * Get a locale dictionary.
3002
+ * @param locale The locale.
3003
+ * @returns The dictionary of undefined if it does not exist.
3004
+ */
3005
+ static getDictionary(locale) {
3006
+ const i18nShared = I18n.getI18nShared();
3007
+ return i18nShared.localeDictionaries[locale];
3008
+ }
3009
+ /**
3010
+ * Get all the locale dictionaries.
3011
+ * @returns The dictionaries.
3012
+ */
3013
+ static getAllDictionaries() {
3014
+ const i18nShared = I18n.getI18nShared();
3015
+ return i18nShared.localeDictionaries;
3016
+ }
3017
+ /**
3018
+ * Add a locale changed handler.
3019
+ * @param id The id of the handler.
3020
+ * @param handler The handler to add.
3021
+ */
3022
+ static addLocaleHandler(id, handler) {
3023
+ const i18nShared = I18n.getI18nShared();
3024
+ i18nShared.localeChangedHandlers[id] = handler;
3025
+ }
3026
+ /**
3027
+ * Remove a locale changed handler.
3028
+ * @param id The id of the handler.
3029
+ */
3030
+ static removeLocaleHandler(id) {
3031
+ const i18nShared = I18n.getI18nShared();
3032
+ delete i18nShared.localeChangedHandlers[id];
3033
+ }
3034
+ /**
3035
+ * Add a dictionary changed handler.
3036
+ * @param id The id of the handler.
3037
+ * @param handler The handler to add.
3038
+ */
3039
+ static addDictionaryHandler(id, handler) {
3040
+ const i18nShared = I18n.getI18nShared();
3041
+ i18nShared.dictionaryChangedHandlers[id] = handler;
3042
+ }
3043
+ /**
3044
+ * Remove a dictionary changed handler.
3045
+ * @param id The id of the handler.
3046
+ */
3047
+ static removeDictionaryHandler(id) {
3048
+ const i18nShared = I18n.getI18nShared();
3049
+ delete i18nShared.dictionaryChangedHandlers[id];
3050
+ }
3051
+ /**
3052
+ * Format a message.
3053
+ * @param key The key of the message to format.
3054
+ * @param values The values to substitute into the message.
3055
+ * @param overrideLocale Override the locale.
3056
+ * @returns The formatted string.
3057
+ */
3058
+ static formatMessage(key, values, overrideLocale) {
3059
+ const i18nShared = I18n.getI18nShared();
3060
+ let cl = overrideLocale ?? i18nShared.currentLocale;
3061
+ if (cl.startsWith("debug-")) {
3062
+ cl = I18n.DEFAULT_LOCALE;
3063
+ }
3064
+ if (!i18nShared.localeDictionaries[cl]) {
3065
+ return `!!Missing ${cl}`;
3066
+ }
3067
+ if (!i18nShared.localeDictionaries[cl][key]) {
3068
+ return `!!Missing ${cl}.${key}`;
3069
+ }
3070
+ if (i18nShared.currentLocale === "debug-k") {
3071
+ return key;
3072
+ }
3073
+ let ret = new IntlMessageFormat(i18nShared.localeDictionaries[cl][key], cl).format(values);
3074
+ if (i18nShared.currentLocale === "debug-x") {
3075
+ ret = ret.replace(/[a-z]/g, "x").replace(/[A-Z]/g, "x").replace(/\d/g, "n");
3076
+ }
3077
+ return ret;
3078
+ }
3079
+ /**
3080
+ * Check if the dictionaries have a message for the given key.
3081
+ * @param key The key to check for existence.
3082
+ * @returns True if the key exists.
3083
+ */
3084
+ static hasMessage(key) {
3085
+ const i18nShared = I18n.getI18nShared();
3086
+ return Is.string(i18nShared.localeDictionaries[i18nShared.currentLocale]?.[key]);
3087
+ }
3088
+ /**
3089
+ * Flatten the translation property paths for faster lookup.
3090
+ * @param translation The translation to merge.
3091
+ * @param propertyPath The current root path.
3092
+ * @param mergedKeys The merged keys dictionary to populate.
3093
+ * @internal
3094
+ */
3095
+ static flattenTranslationKeys(translation, propertyPath, mergedKeys) {
3096
+ for (const key in translation) {
3097
+ const val = translation[key];
3098
+ const mergedPath = propertyPath.length > 0 ? `${propertyPath}.${key}` : key;
3099
+ if (Is.string(val)) {
3100
+ mergedKeys[mergedPath] = val;
2702
3101
  }
2703
- if (reverse) {
2704
- array.reverse();
3102
+ else if (Is.object(val)) {
3103
+ I18n.flattenTranslationKeys(val, mergedPath, mergedKeys);
3104
+ }
3105
+ }
3106
+ }
3107
+ /**
3108
+ * Get the I18n shared data.
3109
+ * @returns The I18n shared data.
3110
+ * @internal
3111
+ */
3112
+ static getI18nShared() {
3113
+ let i18nShared = SharedStore.get("i18n");
3114
+ if (Is.undefined(i18nShared)) {
3115
+ i18nShared = {
3116
+ localeDictionaries: {},
3117
+ currentLocale: I18n.DEFAULT_LOCALE,
3118
+ localeChangedHandlers: {},
3119
+ dictionaryChangedHandlers: {}
3120
+ };
3121
+ SharedStore.set("i18n", i18nShared);
3122
+ }
3123
+ return i18nShared;
3124
+ }
3125
+ }
3126
+
3127
+ // Copyright 2024 IOTA Stiftung.
3128
+ // SPDX-License-Identifier: Apache-2.0.
3129
+ /**
3130
+ * Error helper functions.
3131
+ */
3132
+ class ErrorHelper {
3133
+ /**
3134
+ * Format Errors and returns just their messages.
3135
+ * @param error The error to format.
3136
+ * @param includeDetails Whether to include error details, defaults to false.
3137
+ * @returns The error formatted including any inner errors.
3138
+ */
3139
+ static formatErrors(error, includeDetails) {
3140
+ const localizedErrors = ErrorHelper.localizeErrors(error);
3141
+ if (includeDetails ?? false) {
3142
+ const output = [];
3143
+ for (const err of localizedErrors) {
3144
+ let detailedError = err.message;
3145
+ if (Is.stringValue(err.stack)) {
3146
+ detailedError += `\n${err.stack}`;
3147
+ }
3148
+ output.push(detailedError);
3149
+ }
3150
+ return output;
3151
+ }
3152
+ return localizedErrors.map(e => e.message);
3153
+ }
3154
+ /**
3155
+ * Localize the content of an error and any inner errors.
3156
+ * @param error The error to format.
3157
+ * @returns The localized version of the errors flattened.
3158
+ */
3159
+ static localizeErrors(error) {
3160
+ const formattedErrors = [];
3161
+ if (Is.notEmpty(error)) {
3162
+ const errors = BaseError.flatten(error);
3163
+ for (const err of errors) {
3164
+ const errorNameKey = `errorNames.${StringHelper.camelCase(err.name)}`;
3165
+ const errorMessageKey = `error.${err.message}`;
3166
+ // If there is no error message then it is probably
3167
+ // from a 3rd party lib, so don't format it just display
3168
+ const hasErrorName = I18n.hasMessage(errorNameKey);
3169
+ const hasErrorMessage = I18n.hasMessage(errorMessageKey);
3170
+ const localizedError = {
3171
+ name: I18n.formatMessage(hasErrorName ? errorNameKey : "errorNames.error"),
3172
+ message: hasErrorMessage
3173
+ ? I18n.formatMessage(errorMessageKey, err.properties)
3174
+ : err.message
3175
+ };
3176
+ if (Is.stringValue(err.source)) {
3177
+ localizedError.source = err.source;
3178
+ }
3179
+ if (Is.stringValue(err.stack)) {
3180
+ // Remove the first line from the stack traces as they
3181
+ // just have the error type and message duplicated
3182
+ const lines = err.stack.split("\n");
3183
+ lines.shift();
3184
+ localizedError.stack = lines.join("\n");
3185
+ }
3186
+ const additional = ErrorHelper.formatValidationErrors(err);
3187
+ if (Is.stringValue(additional)) {
3188
+ localizedError.additional = additional;
3189
+ }
3190
+ formattedErrors.push(localizedError);
3191
+ }
3192
+ }
3193
+ return formattedErrors;
3194
+ }
3195
+ /**
3196
+ * Localize the content of an error and any inner errors.
3197
+ * @param error The error to format.
3198
+ * @returns The localized version of the errors flattened.
3199
+ */
3200
+ static formatValidationErrors(error) {
3201
+ if (Is.object(error.properties) &&
3202
+ Object.keys(error.properties).length > 0 &&
3203
+ Is.object(error.properties) &&
3204
+ Is.arrayValue(error.properties.validationFailures)) {
3205
+ const validationErrors = [];
3206
+ for (const validationFailure of error.properties.validationFailures) {
3207
+ const errorI18n = `error.${validationFailure.reason}`;
3208
+ const errorMessage = I18n.hasMessage(errorI18n)
3209
+ ? I18n.formatMessage(errorI18n, validationFailure.properties)
3210
+ : errorI18n;
3211
+ let v = `${validationFailure.property}: ${errorMessage}`;
3212
+ if (Is.object(validationFailure.properties) &&
3213
+ Is.notEmpty(validationFailure.properties.value)) {
3214
+ v += ` = ${JSON.stringify(validationFailure.properties.value)}`;
3215
+ }
3216
+ validationErrors.push(v);
2705
3217
  }
3218
+ return validationErrors.join("\n");
2706
3219
  }
2707
- return array;
2708
- }
2709
- /**
2710
- * Convert the UTF8 to hex.
2711
- * @param utf8 The text to convert.
2712
- * @param includePrefix Include the 0x prefix on the returned hex.
2713
- * @returns The hex version of the bytes.
2714
- */
2715
- static utf8ToHex(utf8, includePrefix = false) {
2716
- const hex = Converter.bytesToHex(Converter.utf8ToBytes(utf8));
2717
- return includePrefix ? HexHelper.addPrefix(hex) : hex;
2718
3220
  }
3221
+ }
3222
+
3223
+ // Copyright 2024 IOTA Stiftung.
3224
+ // SPDX-License-Identifier: Apache-2.0.
3225
+ /**
3226
+ * The types the extracted data can be coerced to.
3227
+ */
3228
+ // eslint-disable-next-line @typescript-eslint/naming-convention
3229
+ const CoerceType = {
2719
3230
  /**
2720
- * Convert the hex text to text.
2721
- * @param hex The hex to convert.
2722
- * @returns The UTF8 version of the bytes.
3231
+ * String.
2723
3232
  */
2724
- static hexToUtf8(hex) {
2725
- return Converter.bytesToUtf8(Converter.hexToBytes(HexHelper.stripPrefix(hex)));
2726
- }
3233
+ String: "string",
2727
3234
  /**
2728
- * Convert bytes to binary string.
2729
- * @param bytes The bytes to convert.
2730
- * @returns A binary string of the bytes.
3235
+ * Number.
2731
3236
  */
2732
- static bytesToBinary(bytes) {
2733
- const b = [];
2734
- for (let i = 0; i < bytes.length; i++) {
2735
- b.push(bytes[i].toString(2).padStart(8, "0"));
2736
- }
2737
- return b.join("");
2738
- }
3237
+ Number: "number",
2739
3238
  /**
2740
- * Convert a binary string to bytes.
2741
- * @param binary The binary string.
2742
- * @returns The bytes.
3239
+ * Integer.
2743
3240
  */
2744
- static binaryToBytes(binary) {
2745
- const bytes = new Uint8Array(Math.ceil(binary.length / 8));
2746
- for (let i = 0; i < bytes.length; i++) {
2747
- bytes[i] = Number.parseInt(binary.slice(i * 8, (i + 1) * 8), 2);
2748
- }
2749
- return bytes;
2750
- }
3241
+ Integer: "integer",
2751
3242
  /**
2752
- * Convert bytes to base64 string.
2753
- * @param bytes The bytes to convert.
2754
- * @returns A base64 string of the bytes.
3243
+ * Boolean.
2755
3244
  */
2756
- static bytesToBase64(bytes) {
2757
- return Base64.encode(bytes);
2758
- }
3245
+ Boolean: "boolean",
2759
3246
  /**
2760
- * Convert a base64 string to bytes.
2761
- * @param base64 The base64 string.
2762
- * @returns The bytes.
3247
+ * Big Integer.
2763
3248
  */
2764
- static base64ToBytes(base64) {
2765
- return Base64.decode(base64);
2766
- }
3249
+ BigInt: "bigint",
2767
3250
  /**
2768
- * Convert bytes to base64 url string.
2769
- * @param bytes The bytes to convert.
2770
- * @returns A base64 url string of the bytes.
3251
+ * Date.
2771
3252
  */
2772
- static bytesToBase64Url(bytes) {
2773
- return Base64Url.encode(bytes);
2774
- }
3253
+ Date: "date",
2775
3254
  /**
2776
- * Convert a base64 url string to bytes.
2777
- * @param base64Url The base64 url string.
2778
- * @returns The bytes.
3255
+ * Date Time.
2779
3256
  */
2780
- static base64UrlToBytes(base64Url) {
2781
- return Base64Url.decode(base64Url);
2782
- }
3257
+ DateTime: "datetime",
2783
3258
  /**
2784
- * Convert bytes to base58 string.
2785
- * @param bytes The bytes to convert.
2786
- * @returns A base58 string of the bytes.
3259
+ * Time.
2787
3260
  */
2788
- static bytesToBase58(bytes) {
2789
- return Base58.encode(bytes);
2790
- }
3261
+ Time: "time",
2791
3262
  /**
2792
- * Convert a base58 string to bytes.
2793
- * @param base58 The base58 string.
2794
- * @returns The bytes.
3263
+ * Object.
2795
3264
  */
2796
- static base58ToBytes(base58) {
2797
- return Base58.decode(base58);
2798
- }
3265
+ Object: "object",
2799
3266
  /**
2800
- * Build the static lookup tables.
2801
- * @internal
3267
+ * Uint8Array.
2802
3268
  */
2803
- static buildHexLookups() {
2804
- if (!Converter._ENCODE_LOOKUP || !Converter._DECODE_LOOKUP) {
2805
- const alphabet = "0123456789abcdef";
2806
- Converter._ENCODE_LOOKUP = [];
2807
- Converter._DECODE_LOOKUP = [];
2808
- for (let i = 0; i < 256; i++) {
2809
- Converter._ENCODE_LOOKUP[i] = alphabet[(i >> 4) & 0xf] + alphabet[i & 0xf];
2810
- if (i < 16) {
2811
- if (i < 10) {
2812
- Converter._DECODE_LOOKUP[0x30 + i] = i;
2813
- }
2814
- else {
2815
- Converter._DECODE_LOOKUP[0x61 - 10 + i] = i;
2816
- }
2817
- }
2818
- }
2819
- }
2820
- }
2821
- }
3269
+ Uint8Array: "uint8array"
3270
+ };
2822
3271
 
3272
+ // Copyright 2024 IOTA Stiftung.
3273
+ // SPDX-License-Identifier: Apache-2.0.
2823
3274
  /**
2824
- * Class to help with objects.
3275
+ * Coerce an object from one type to another.
2825
3276
  */
2826
- class ObjectHelper {
2827
- /**
2828
- * Runtime name for the class.
2829
- * @internal
2830
- */
2831
- static _CLASS_NAME = "ObjectHelper";
3277
+ class Coerce {
2832
3278
  /**
2833
- * Convert an object to bytes.
2834
- * @param obj The object to convert.
2835
- * @param format Format the JSON content.
2836
- * @returns The object as bytes.
3279
+ * Coerce the value to a string.
3280
+ * @param value The value to coerce.
3281
+ * @throws TypeError If the value can not be coerced.
3282
+ * @returns The value if it can be coerced.
2837
3283
  */
2838
- static toBytes(obj, format = false) {
2839
- if (obj === undefined) {
2840
- return new Uint8Array();
3284
+ static string(value) {
3285
+ if (Is.undefined(value)) {
3286
+ return value;
3287
+ }
3288
+ if (Is.string(value)) {
3289
+ return value;
3290
+ }
3291
+ if (Is.number(value)) {
3292
+ return value.toString();
3293
+ }
3294
+ if (Is.boolean(value)) {
3295
+ return value ? "true" : "false";
3296
+ }
3297
+ if (Is.date(value)) {
3298
+ return value.toISOString();
2841
3299
  }
2842
- const json = format ? JSON.stringify(obj, undefined, "\t") : JSON.stringify(obj);
2843
- return Converter.utf8ToBytes(json);
2844
3300
  }
2845
3301
  /**
2846
- * Convert a bytes to an object.
2847
- * @param bytes The bytes to convert to an object.
2848
- * @returns The object.
2849
- * @throws GeneralError if there was an error parsing the JSON.
3302
+ * Coerce the value to a number.
3303
+ * @param value The value to coerce.
3304
+ * @throws TypeError If the value can not be coerced.
3305
+ * @returns The value if it can be coerced.
2850
3306
  */
2851
- static fromBytes(bytes) {
2852
- if (Is.empty(bytes) || bytes.length === 0) {
2853
- return undefined;
3307
+ static number(value) {
3308
+ if (Is.undefined(value)) {
3309
+ return value;
2854
3310
  }
2855
- try {
2856
- const utf8 = Converter.bytesToUtf8(bytes);
2857
- return JSON.parse(utf8);
3311
+ if (Is.number(value)) {
3312
+ return value;
2858
3313
  }
2859
- catch (err) {
2860
- throw new GeneralError(ObjectHelper._CLASS_NAME, "failedBytesToJSON", undefined, err);
3314
+ if (Is.string(value)) {
3315
+ const parsed = Number.parseFloat(value);
3316
+ if (Is.number(parsed)) {
3317
+ return parsed;
3318
+ }
3319
+ }
3320
+ if (Is.boolean(value)) {
3321
+ return value ? 1 : 0;
3322
+ }
3323
+ if (Is.date(value)) {
3324
+ return value.getTime();
2861
3325
  }
2862
3326
  }
2863
3327
  /**
2864
- * Make a deep clone of an object.
2865
- * @param obj The object to clone.
2866
- * @returns The objects clone.
3328
+ * Coerce the value to an integer.
3329
+ * @param value The value to coerce.
3330
+ * @throws TypeError If the value can not be coerced.
3331
+ * @returns The value if it can be coerced.
2867
3332
  */
2868
- static clone(obj) {
2869
- if (Is.undefined(obj)) {
2870
- return undefined;
3333
+ static integer(value) {
3334
+ const num = Coerce.number(value);
3335
+ if (!Is.undefined(num)) {
3336
+ return Math.trunc(num);
2871
3337
  }
2872
- return structuredClone(obj);
2873
3338
  }
2874
3339
  /**
2875
- * Deep merge objects.
2876
- * @param obj1 The first object to merge.
2877
- * @param obj2 The second object to merge.
2878
- * @returns The combined deep merge of the objects.
3340
+ * Coerce the value to a bigint.
3341
+ * @param value The value to coerce.
3342
+ * @throws TypeError If the value can not be coerced.
3343
+ * @returns The value if it can be coerced.
2879
3344
  */
2880
- static merge(obj1, obj2) {
2881
- if (Is.empty(obj1)) {
2882
- return ObjectHelper.clone(obj2);
3345
+ static bigint(value) {
3346
+ if (Is.undefined(value)) {
3347
+ return value;
2883
3348
  }
2884
- if (Is.empty(obj2)) {
2885
- return ObjectHelper.clone(obj1);
3349
+ if (Is.bigint(value)) {
3350
+ return value;
2886
3351
  }
2887
- const obj1Clone = ObjectHelper.clone(obj1);
2888
- if (Is.object(obj1Clone) && Is.object(obj2)) {
2889
- const keys = Object.keys(obj2);
2890
- for (const key of keys) {
2891
- if (Is.object(obj1Clone[key]) && Is.object(obj2[key])) {
2892
- ObjectHelper.propertySet(obj1Clone, key, ObjectHelper.merge(obj1Clone[key], obj2[key]));
2893
- }
2894
- else {
2895
- ObjectHelper.propertySet(obj1Clone, key, obj2[key]);
2896
- }
3352
+ if (Is.number(value)) {
3353
+ return BigInt(value);
3354
+ }
3355
+ if (Is.string(value)) {
3356
+ const parsed = Number.parseFloat(value);
3357
+ if (Is.integer(parsed)) {
3358
+ return BigInt(parsed);
3359
+ }
3360
+ }
3361
+ if (Is.boolean(value)) {
3362
+ return value ? 1n : 0n;
3363
+ }
3364
+ }
3365
+ /**
3366
+ * Coerce the value to a boolean.
3367
+ * @param value The value to coerce.
3368
+ * @throws TypeError If the value can not be coerced.
3369
+ * @returns The value if it can be coerced.
3370
+ */
3371
+ static boolean(value) {
3372
+ if (Is.undefined(value)) {
3373
+ return value;
3374
+ }
3375
+ if (Is.boolean(value)) {
3376
+ return value;
3377
+ }
3378
+ if (Is.number(value)) {
3379
+ // eslint-disable-next-line no-unneeded-ternary
3380
+ return value ? true : false;
3381
+ }
3382
+ if (Is.string(value)) {
3383
+ if (/true/i.test(value)) {
3384
+ return true;
3385
+ }
3386
+ if (/false/i.test(value)) {
3387
+ return false;
2897
3388
  }
2898
3389
  }
2899
- return obj1Clone;
2900
3390
  }
2901
3391
  /**
2902
- * Does one object equal another.
2903
- * @param obj1 The first object to compare.
2904
- * @param obj2 The second object to compare.
2905
- * @param strictPropertyOrder Should the properties be in the same order, defaults to true.
2906
- * @returns True is the objects are equal.
3392
+ * Coerce the value to a date.
3393
+ * @param value The value to coerce.
3394
+ * @throws TypeError If the value can not be coerced.
3395
+ * @returns The value if it can be coerced.
2907
3396
  */
2908
- static equal(obj1, obj2, strictPropertyOrder) {
2909
- if (strictPropertyOrder ?? true) {
2910
- return JSON.stringify(obj1) === JSON.stringify(obj2);
3397
+ static date(value) {
3398
+ if (Is.undefined(value)) {
3399
+ return value;
3400
+ }
3401
+ if (Is.date(value)) {
3402
+ return value;
3403
+ }
3404
+ if (Is.number(value)) {
3405
+ return new Date(value);
3406
+ }
3407
+ if (Is.string(value)) {
3408
+ const dt = new Date(value);
3409
+ if (!Number.isNaN(dt.getTime())) {
3410
+ const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate());
3411
+ return new Date(utc);
3412
+ }
2911
3413
  }
2912
- return JsonHelper.canonicalize(obj1) === JsonHelper.canonicalize(obj2);
2913
3414
  }
2914
3415
  /**
2915
- * Get the property of an unknown object.
2916
- * @param obj The object to get the property from.
2917
- * @param property The property to get, can be separated by dots for nested path.
2918
- * @returns The property.
3416
+ * Coerce the value to a date/time.
3417
+ * @param value The value to coerce.
3418
+ * @throws TypeError If the value can not be coerced.
3419
+ * @returns The value if it can be coerced.
2919
3420
  */
2920
- static propertyGet(obj, property) {
2921
- if (property.includes(".")) {
2922
- const parts = property.split(".");
2923
- let value = obj;
2924
- for (const part of parts) {
2925
- if (Is.object(value)) {
2926
- value = value[part];
2927
- }
2928
- else {
2929
- return undefined;
2930
- }
2931
- }
3421
+ static dateTime(value) {
3422
+ if (Is.undefined(value)) {
2932
3423
  return value;
2933
3424
  }
2934
- return Is.object(obj) ? obj[property] : undefined;
3425
+ if (Is.date(value)) {
3426
+ return value;
3427
+ }
3428
+ if (Is.number(value)) {
3429
+ return new Date(value);
3430
+ }
3431
+ if (Is.string(value)) {
3432
+ const dt = new Date(value);
3433
+ if (!Number.isNaN(dt.getTime())) {
3434
+ const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate(), dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
3435
+ return new Date(utc);
3436
+ }
3437
+ }
2935
3438
  }
2936
3439
  /**
2937
- * Set the property of an unknown object.
2938
- * @param obj The object to set the property from.
2939
- * @param property The property to set.
2940
- * @param value The value to set.
3440
+ * Coerce the value to a time.
3441
+ * @param value The value to coerce.
3442
+ * @throws TypeError If the value can not be coerced.
3443
+ * @returns The value if it can be coerced.
2941
3444
  */
2942
- static propertySet(obj, property, value) {
2943
- if (Is.object(obj)) {
2944
- obj[property] = value;
3445
+ static time(value) {
3446
+ if (Is.undefined(value)) {
3447
+ return value;
3448
+ }
3449
+ if (Is.date(value)) {
3450
+ return value;
3451
+ }
3452
+ if (Is.number(value)) {
3453
+ const dt = new Date(value);
3454
+ dt.setFullYear(1970, 0, 1);
3455
+ return dt;
3456
+ }
3457
+ if (Is.string(value)) {
3458
+ const dt = new Date(value);
3459
+ if (!Number.isNaN(dt.getTime())) {
3460
+ const utc = Date.UTC(1970, 0, 1, dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
3461
+ return new Date(utc);
3462
+ }
2945
3463
  }
2946
3464
  }
2947
3465
  /**
2948
- * Delete the property of an unknown object.
2949
- * @param obj The object to set the property from.
2950
- * @param property The property to set
3466
+ * Coerce the value to an object.
3467
+ * @param value The value to coerce.
3468
+ * @throws TypeError If the value can not be coerced.
3469
+ * @returns The value if it can be coerced.
2951
3470
  */
2952
- static propertyDelete(obj, property) {
2953
- if (Is.object(obj)) {
2954
- delete obj[property];
3471
+ static object(value) {
3472
+ if (Is.undefined(value)) {
3473
+ return value;
3474
+ }
3475
+ if (Is.object(value)) {
3476
+ return value;
3477
+ }
3478
+ if (Is.stringValue(value)) {
3479
+ try {
3480
+ return JSON.parse(value);
3481
+ }
3482
+ catch { }
2955
3483
  }
2956
3484
  }
2957
3485
  /**
2958
- * Extract a property from the object, providing alternative names.
2959
- * @param obj The object to extract from.
2960
- * @param propertyNames The possible names for the property.
2961
- * @param removeProperties Remove the properties from the object, defaults to true.
2962
- * @returns The property if available.
3486
+ * Coerce the value to a Uint8Array.
3487
+ * @param value The value to coerce.
3488
+ * @throws TypeError If the value can not be coerced.
3489
+ * @returns The value if it can be coerced.
2963
3490
  */
2964
- static extractProperty(obj, propertyNames, removeProperties = true) {
2965
- let retVal;
2966
- if (Is.object(obj)) {
2967
- const names = Is.string(propertyNames) ? [propertyNames] : propertyNames;
2968
- for (const prop of names) {
2969
- retVal ??= ObjectHelper.propertyGet(obj, prop);
2970
- if (removeProperties) {
2971
- ObjectHelper.propertyDelete(obj, prop);
2972
- }
3491
+ static uint8Array(value) {
3492
+ if (Is.undefined(value)) {
3493
+ return value;
3494
+ }
3495
+ if (Is.string(value)) {
3496
+ if (Is.stringHex(value.toLowerCase(), true)) {
3497
+ return Converter.hexToBytes(value.toLowerCase());
3498
+ }
3499
+ if (Is.stringBase64(value)) {
3500
+ return Converter.base64ToBytes(value);
2973
3501
  }
2974
3502
  }
2975
- return retVal;
2976
3503
  }
2977
3504
  /**
2978
- * Pick a subset of properties from an object.
2979
- * @param obj The object to pick the properties from.
2980
- * @param keys The property keys to pick.
2981
- * @returns The partial object.
2982
- */
2983
- static pick(obj, keys) {
2984
- if (Is.object(obj) && Is.arrayValue(keys)) {
2985
- const result = {};
2986
- for (const key of keys) {
2987
- result[key] = obj[key];
2988
- }
2989
- return result;
3505
+ * Coerces a value based on the coercion type.
3506
+ * @param value The value to coerce.
3507
+ * @param type The coercion type to perform.
3508
+ * @returns The coerced value.
3509
+ */
3510
+ static byType(value, type) {
3511
+ switch (type) {
3512
+ case CoerceType.String:
3513
+ return Coerce.string(value);
3514
+ case CoerceType.Number:
3515
+ return Coerce.number(value);
3516
+ case CoerceType.Integer:
3517
+ return Coerce.integer(value);
3518
+ case CoerceType.BigInt:
3519
+ return Coerce.bigint(value);
3520
+ case CoerceType.Boolean:
3521
+ return Coerce.boolean(value);
3522
+ case CoerceType.Date:
3523
+ return Coerce.date(value);
3524
+ case CoerceType.DateTime:
3525
+ return Coerce.dateTime(value);
3526
+ case CoerceType.Time:
3527
+ return Coerce.time(value);
3528
+ case CoerceType.Object:
3529
+ return Coerce.object(value);
3530
+ case CoerceType.Uint8Array:
3531
+ return Coerce.uint8Array(value);
3532
+ default:
3533
+ return value;
2990
3534
  }
2991
- return obj;
2992
3535
  }
3536
+ }
3537
+
3538
+ // Copyright 2024 IOTA Stiftung.
3539
+ // SPDX-License-Identifier: Apache-2.0.
3540
+ /**
3541
+ * Class to help with filenames.
3542
+ */
3543
+ class FilenameHelper {
2993
3544
  /**
2994
- * Omit a subset of properties from an object.
2995
- * @param obj The object to omit the properties from.
2996
- * @param keys The property keys to omit.
2997
- * @returns The partial object.
3545
+ * Replaces any unsafe characters in the filename.
3546
+ * @param filename The filename to make safe.
3547
+ * @returns The safe filename.
2998
3548
  */
2999
- static omit(obj, keys) {
3000
- if (Is.object(obj) && Is.arrayValue(keys)) {
3001
- const result = { ...obj };
3002
- for (const key of keys) {
3003
- delete result[key];
3004
- }
3005
- return result;
3549
+ static safeFilename(filename) {
3550
+ let safe = Coerce.string(filename);
3551
+ if (Is.empty(safe)) {
3552
+ return "";
3006
3553
  }
3007
- return obj;
3554
+ // Common non filename characters
3555
+ safe = safe.replace(/["*/:<>?\\|]/g, "_");
3556
+ // Windows non filename characters
3557
+ safe = safe.replace(/^(con|prn|aux|nul|com\d|lpt\d)$/i, "_");
3558
+ // Control characters
3559
+ safe = safe.replace(/[\u0000-\u001F\u0080-\u009F]/g, "_");
3560
+ // Relative paths
3561
+ safe = safe.replace(/^\.+/, "_");
3562
+ // Trailing periods
3563
+ safe = safe.replace(/\.+$/, "");
3564
+ return safe;
3008
3565
  }
3009
3566
  }
3010
3567
 
@@ -3026,6 +3583,32 @@ class RandomHelper {
3026
3583
  }
3027
3584
  }
3028
3585
 
3586
+ // Copyright 2024 IOTA Stiftung.
3587
+ // SPDX-License-Identifier: Apache-2.0.
3588
+ /**
3589
+ * Class to help with uint8 arrays.
3590
+ */
3591
+ class Uint8ArrayHelper {
3592
+ /**
3593
+ * Concatenate multiple arrays.
3594
+ * @param arrays The array to concatenate.
3595
+ * @returns The combined array.
3596
+ */
3597
+ static concat(arrays) {
3598
+ let totalLength = 0;
3599
+ for (const array of arrays) {
3600
+ totalLength += array.length;
3601
+ }
3602
+ const concatBytes = new Uint8Array(totalLength);
3603
+ let offset = 0;
3604
+ for (const array of arrays) {
3605
+ concatBytes.set(array, offset);
3606
+ offset += array.length;
3607
+ }
3608
+ return concatBytes;
3609
+ }
3610
+ }
3611
+
3029
3612
  // Copyright 2024 IOTA Stiftung.
3030
3613
  // SPDX-License-Identifier: Apache-2.0.
3031
3614
  /**
@@ -3038,7 +3621,7 @@ const CompressionType = {
3038
3621
  */
3039
3622
  Gzip: "gzip",
3040
3623
  /**
3041
- * deflate.
3624
+ * Deflate.
3042
3625
  */
3043
3626
  Deflate: "deflate"
3044
3627
  };
@@ -3489,29 +4072,93 @@ class Urn {
3489
4072
  * Cache the results from asynchronous requests.
3490
4073
  */
3491
4074
  class AsyncCache {
3492
- /**
3493
- * Cache for the fetch requests.
3494
- * @internal
3495
- */
3496
- static _cache = {};
3497
4075
  /**
3498
4076
  * Execute an async request and cache the result.
3499
4077
  * @param key The key for the entry in the cache.
3500
4078
  * @param ttlMs The TTL of the entry in the cache.
3501
4079
  * @param requestMethod The method to call if not cached.
4080
+ * @param cacheFailures Cache failure results, defaults to false.
3502
4081
  * @returns The response.
3503
4082
  */
3504
- static exec(key, ttlMs, requestMethod) {
4083
+ static exec(key, ttlMs, requestMethod, cacheFailures) {
3505
4084
  const cacheEnabled = Is.integer(ttlMs) && ttlMs >= 0;
3506
4085
  if (cacheEnabled) {
3507
4086
  AsyncCache.cleanupExpired();
3508
- if (!this._cache[key]) {
3509
- this._cache[key] = {
3510
- response: requestMethod(),
3511
- expires: ttlMs === 0 ? 0 : Date.now() + ttlMs
3512
- };
4087
+ const cache = AsyncCache.getSharedCache();
4088
+ // Do we have a cache entry for the key
4089
+ if (cache[key]) {
4090
+ if (!Is.empty(cache[key].result)) {
4091
+ // If the cache has already resulted in a value, resolve it
4092
+ return Promise.resolve(cache[key].result);
4093
+ }
4094
+ else if (!Is.empty(cache[key].error)) {
4095
+ // If the cache has already resulted in an error, reject it
4096
+ return Promise.reject(cache[key].error);
4097
+ }
4098
+ // Otherwise create a promise to return and store the resolver
4099
+ // and rejector in the cache entry, so that we can call then
4100
+ // when the request is done
4101
+ let storedResolve;
4102
+ let storedReject;
4103
+ const wait = new Promise((resolve, reject) => {
4104
+ storedResolve = resolve;
4105
+ storedReject = reject;
4106
+ });
4107
+ if (!Is.empty(storedResolve) && !Is.empty(storedReject)) {
4108
+ cache[key].promiseQueue.push({
4109
+ requestMethod,
4110
+ resolve: storedResolve,
4111
+ reject: storedReject
4112
+ });
4113
+ }
4114
+ return wait;
3513
4115
  }
3514
- return this._cache[key].response;
4116
+ // If we don't have a cache entry, create a new one
4117
+ cache[key] = {
4118
+ promiseQueue: [],
4119
+ expires: ttlMs === 0 ? 0 : Date.now() + ttlMs
4120
+ };
4121
+ // Return a promise that wraps the original request method
4122
+ // so that we can store any results or errors in the cache
4123
+ return new Promise((resolve, reject) => {
4124
+ // Call the request method and store the result
4125
+ requestMethod()
4126
+ // eslint-disable-next-line promise/prefer-await-to-then
4127
+ .then(res => {
4128
+ // If the request was successful, store the result
4129
+ cache[key].result = res;
4130
+ // and resolve both this promise and all the waiters
4131
+ resolve(res);
4132
+ for (const wait of cache[key].promiseQueue) {
4133
+ wait.resolve(res);
4134
+ }
4135
+ return res;
4136
+ })
4137
+ // eslint-disable-next-line promise/prefer-await-to-then
4138
+ .catch((err) => {
4139
+ // Reject the promise
4140
+ reject(err);
4141
+ // Handle the waiters based on the cacheFailures flag
4142
+ if (cacheFailures ?? false) {
4143
+ // If we are caching failures, store the error and reject the waiters
4144
+ cache[key].error = err;
4145
+ for (const wait of cache[key].promiseQueue) {
4146
+ wait.reject(err);
4147
+ }
4148
+ // Clear the waiters so we don't call them again
4149
+ cache[key].promiseQueue = [];
4150
+ }
4151
+ else {
4152
+ // If not caching failures for any queued requests we
4153
+ // have no value to either resolve or reject, so we
4154
+ // just resolve with the original request method
4155
+ for (const wait of cache[key].promiseQueue) {
4156
+ wait.resolve(wait.requestMethod());
4157
+ }
4158
+ delete cache[key];
4159
+ }
4160
+ });
4161
+ });
3515
4162
  }
3516
4163
  }
3517
4164
  /**
@@ -3520,41 +4167,80 @@ class AsyncCache {
3520
4167
  * @returns The item from the cache if it exists.
3521
4168
  */
3522
4169
  static async get(key) {
3523
- return AsyncCache._cache[key]?.response;
4170
+ const cache = AsyncCache.getSharedCache();
4171
+ if (!Is.empty(cache[key].result)) {
4172
+ // If the cache has already resulted in a value, resolve it
4173
+ return cache[key].result;
4174
+ }
4175
+ else if (!Is.empty(cache[key].error)) {
4176
+ // If the cache has already resulted in an error, reject it
4177
+ throw cache[key].error;
4178
+ }
4179
+ }
4180
+ /**
4181
+ * Set an entry into the cache.
4182
+ * @param key The key to set in the cache.
4183
+ * @param value The value to set in the cache.
4184
+ * @param ttlMs The TTL of the entry in the cache in ms, defaults to 1s.
4185
+ * @returns Nothing.
4186
+ */
4187
+ static async set(key, value, ttlMs) {
4188
+ const cache = AsyncCache.getSharedCache();
4189
+ cache[key] = {
4190
+ result: value,
4191
+ promiseQueue: [],
4192
+ expires: Date.now() + (ttlMs ?? 1000)
4193
+ };
3524
4194
  }
3525
4195
  /**
3526
4196
  * Remove an entry from the cache.
3527
4197
  * @param key The key to remove from the cache.
3528
4198
  */
3529
4199
  static remove(key) {
3530
- delete AsyncCache._cache[key];
4200
+ const cache = AsyncCache.getSharedCache();
4201
+ delete cache[key];
3531
4202
  }
3532
4203
  /**
3533
4204
  * Clear the cache.
3534
4205
  * @param prefix Optional prefix to clear only entries with that prefix.
3535
4206
  */
3536
4207
  static clearCache(prefix) {
4208
+ const cache = AsyncCache.getSharedCache();
3537
4209
  if (Is.stringValue(prefix)) {
3538
- for (const entry in this._cache) {
4210
+ for (const entry in cache) {
3539
4211
  if (entry.startsWith(prefix)) {
3540
- delete this._cache[entry];
4212
+ delete cache[entry];
3541
4213
  }
3542
4214
  }
3543
4215
  }
3544
4216
  else {
3545
- AsyncCache._cache = {};
4217
+ SharedStore.set("asyncCache", {});
3546
4218
  }
3547
4219
  }
3548
4220
  /**
3549
4221
  * Perform a cleanup of the expired entries in the cache.
3550
4222
  */
3551
4223
  static cleanupExpired() {
3552
- for (const entry in this._cache) {
3553
- if (AsyncCache._cache[entry].expires > 0 && AsyncCache._cache[entry].expires < Date.now()) {
3554
- delete this._cache[entry];
4224
+ const cache = AsyncCache.getSharedCache();
4225
+ for (const entry in cache) {
4226
+ if (cache[entry].expires > 0 && cache[entry].expires < Date.now()) {
4227
+ delete cache[entry];
3555
4228
  }
3556
4229
  }
3557
4230
  }
4231
+ /**
4232
+ * Get the shared cache.
4233
+ * @returns The shared cache.
4234
+ * @internal
4235
+ */
4236
+ static getSharedCache() {
4237
+ let sharedCache = SharedStore.get("asyncCache");
4238
+ if (Is.undefined(sharedCache)) {
4239
+ sharedCache = {};
4240
+ SharedStore.set("asyncCache", sharedCache);
4241
+ }
4242
+ return sharedCache;
4243
+ }
3558
4244
  }
3559
4245
 
3560
4246
  /**
@@ -3576,15 +4262,14 @@ class Compression {
3576
4262
  Guards.uint8Array(Compression._CLASS_NAME, "bytes", bytes);
3577
4263
  Guards.arrayOneOf(Compression._CLASS_NAME, "type", type, Object.values(CompressionType));
3578
4264
  const blob = new Blob([bytes]);
3579
- const ds = new CompressionStream(type);
3580
- const compressedStream = blob.stream().pipeThrough(ds);
3581
- const compressedBlob = await new Response(compressedStream).blob();
3582
- const ab = await compressedBlob.arrayBuffer();
3583
- const compressedBytes = new Uint8Array(ab);
4265
+ const compressionStream = new CompressionStream(type);
4266
+ const compressionPipe = blob.stream().pipeThrough(compressionStream);
4267
+ const compressedBlob = await new Response(compressionPipe).blob();
4268
+ const compressedBytes = new Uint8Array(await compressedBlob.arrayBuffer());
3584
4269
  // GZIP header contains a byte which specifies the OS the
3585
4270
  // compression was performed on. We set this to 3 (Unix) to ensure
3586
4271
  // that we produce consistent results.
3587
- if (type === "gzip" && compressedBytes.length >= 10) {
4272
+ if (type === CompressionType.Gzip && compressedBytes.length >= 10) {
3588
4273
  compressedBytes[9] = 3;
3589
4274
  }
3590
4275
  return compressedBytes;
@@ -3599,11 +4284,10 @@ class Compression {
3599
4284
  Guards.uint8Array(Compression._CLASS_NAME, "compressedBytes", compressedBytes);
3600
4285
  Guards.arrayOneOf(Compression._CLASS_NAME, "type", type, Object.values(CompressionType));
3601
4286
  const blob = new Blob([compressedBytes]);
3602
- const ds = new DecompressionStream(type);
3603
- const decompressedStream = blob.stream().pipeThrough(ds);
3604
- const decompressedBlob = await new Response(decompressedStream).blob();
3605
- const ab = await decompressedBlob.arrayBuffer();
3606
- return new Uint8Array(ab);
4287
+ const decompressionStream = new DecompressionStream(type);
4288
+ const decompressionPipe = blob.stream().pipeThrough(decompressionStream);
4289
+ const decompressedBlob = await new Response(decompressionPipe).blob();
4290
+ return new Uint8Array(await decompressedBlob.bytes());
3607
4291
  }
3608
4292
  }
3609
4293
 
@@ -3661,6 +4345,7 @@ class Validation {
3661
4345
  * @param options Additional options for the validation.
3662
4346
  * @param options.minLength The minimum length of the string.
3663
4347
  * @param options.maxLength The maximum length of the string.
4348
+ * @param options.format Specific format to check.
3664
4349
  * @returns True if the value is a valid string.
3665
4350
  */
3666
4351
  static string(property, value, failures, fieldNameResource, options) {
@@ -3679,6 +4364,47 @@ class Validation {
3679
4364
  const maxLimitDefined = Is.integer(maxLength);
3680
4365
  const belowMin = minLimitDefined && value.length < minLength;
3681
4366
  const aboveMax = maxLimitDefined && value.length > maxLength;
4367
+ if (options?.format === "base58" && !Is.stringBase58(value)) {
4368
+ failures.push({
4369
+ property,
4370
+ reason: "validation.beTextBase58",
4371
+ properties: {
4372
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4373
+ value
4374
+ }
4375
+ });
4376
+ }
4377
+ else if (options?.format === "base64" && !Is.stringBase64(value)) {
4378
+ failures.push({
4379
+ property,
4380
+ reason: "validation.beTextBase64",
4381
+ properties: {
4382
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4383
+ value
4384
+ }
4385
+ });
4386
+ }
4387
+ else if (options?.format === "hex" && !Is.stringHex(value)) {
4388
+ failures.push({
4389
+ property,
4390
+ reason: "validation.beTextHex",
4391
+ properties: {
4392
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4393
+ value
4394
+ }
4395
+ });
4396
+ }
4397
+ else if (Is.regexp(options?.format) && !options.format.test(value)) {
4398
+ failures.push({
4399
+ property,
4400
+ reason: "validation.beTextRegExp",
4401
+ properties: {
4402
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4403
+ value,
4404
+ format: options?.format
4405
+ }
4406
+ });
4407
+ }
3682
4408
  if (minLimitDefined && maxLimitDefined && (belowMin || aboveMax)) {
3683
4409
  failures.push({
3684
4410
  property,
@@ -4338,4 +5064,4 @@ class Validation {
4338
5064
  }
4339
5065
  }
4340
5066
 
4341
- export { AlreadyExistsError, ArrayHelper, AsyncCache, Base32, Base58, Base64, Base64Url, BaseError, BitString, Coerce, ComponentFactory, Compression, CompressionType, ConflictError, Converter, ErrorHelper, Factory, FilenameHelper, GeneralError, GuardError, Guards, HexHelper, I18n, Is, JsonHelper, NotFoundError, NotImplementedError, NotSupportedError, ObjectHelper, RandomHelper, StringHelper, UnauthorizedError, UnprocessableError, Url, Urn, Validation, ValidationError };
5067
+ export { AlreadyExistsError, ArrayHelper, AsyncCache, Base32, Base58, Base64, Base64Url, BaseError, BitString, Coerce, CoerceType, ComponentFactory, Compression, CompressionType, ConflictError, Converter, EnvHelper, ErrorHelper, Factory, FilenameHelper, GeneralError, GuardError, Guards, HexHelper, I18n, Is, JsonHelper, NotFoundError, NotImplementedError, NotSupportedError, ObjectHelper, RandomHelper, SharedStore, StringHelper, Uint8ArrayHelper, UnauthorizedError, UnprocessableError, Url, Urn, Validation, ValidationError };