@keeex/utils 7.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 (183) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +105 -0
  3. package/lib/array.d.ts +28 -0
  4. package/lib/array.js +36 -0
  5. package/lib/arraybuffer.d.ts +138 -0
  6. package/lib/arraybuffer.js +141 -0
  7. package/lib/async/asynctrigger.d.ts +50 -0
  8. package/lib/async/asynctrigger.js +108 -0
  9. package/lib/async/deferredpromise.d.ts +32 -0
  10. package/lib/async/deferredpromise.js +66 -0
  11. package/lib/async/keycache.d.ts +56 -0
  12. package/lib/async/keycache.js +103 -0
  13. package/lib/async/queues.d.ts +69 -0
  14. package/lib/async/queues.js +135 -0
  15. package/lib/async/timecache.d.ts +58 -0
  16. package/lib/async/timecache.js +118 -0
  17. package/lib/base58.d.ts +27 -0
  18. package/lib/base58.js +83 -0
  19. package/lib/base64.d.ts +51 -0
  20. package/lib/base64.js +126 -0
  21. package/lib/benchmark.d.ts +126 -0
  22. package/lib/benchmark.js +177 -0
  23. package/lib/bits/arraybuffer.d.ts +35 -0
  24. package/lib/bits/arraybuffer.js +64 -0
  25. package/lib/bits/base64.d.ts +35 -0
  26. package/lib/bits/base64.js +70 -0
  27. package/lib/bits/hex.d.ts +17 -0
  28. package/lib/bits/hex.js +30 -0
  29. package/lib/bits/uint8array.d.ts +28 -0
  30. package/lib/bits/uint8array.js +42 -0
  31. package/lib/bytebuffer.d.ts +27 -0
  32. package/lib/bytebuffer.js +29 -0
  33. package/lib/consts.d.ts +33 -0
  34. package/lib/consts.js +33 -0
  35. package/lib/cron/logger.d.ts +22 -0
  36. package/lib/cron/logger.js +31 -0
  37. package/lib/cron/scheduledtask.d.ts +71 -0
  38. package/lib/cron/scheduledtask.js +137 -0
  39. package/lib/cron/types.d.ts +53 -0
  40. package/lib/cron/types.js +31 -0
  41. package/lib/cron.d.ts +29 -0
  42. package/lib/cron.js +47 -0
  43. package/lib/dict.d.ts +56 -0
  44. package/lib/dict.js +74 -0
  45. package/lib/error.d.ts +25 -0
  46. package/lib/error.js +41 -0
  47. package/lib/global.d.ts +27 -0
  48. package/lib/global.js +53 -0
  49. package/lib/hex.d.ts +32 -0
  50. package/lib/hex.js +58 -0
  51. package/lib/idx.d.ts +51 -0
  52. package/lib/idx.js +81 -0
  53. package/lib/json.d.ts +57 -0
  54. package/lib/json.js +116 -0
  55. package/lib/marshalling/marshaller.d.ts +51 -0
  56. package/lib/marshalling/marshaller.js +155 -0
  57. package/lib/marshalling/unmarshaller.d.ts +53 -0
  58. package/lib/marshalling/unmarshaller.js +124 -0
  59. package/lib/marshalling/util.d.ts +25 -0
  60. package/lib/marshalling/util.js +25 -0
  61. package/lib/number.d.ts +17 -0
  62. package/lib/number.js +21 -0
  63. package/lib/path.d.ts +25 -0
  64. package/lib/path.js +29 -0
  65. package/lib/promise.d.ts +42 -0
  66. package/lib/promise.js +78 -0
  67. package/lib/starttime.d.ts +23 -0
  68. package/lib/starttime.js +29 -0
  69. package/lib/string.d.ts +65 -0
  70. package/lib/string.js +108 -0
  71. package/lib/types/array.d.ts +34 -0
  72. package/lib/types/array.js +64 -0
  73. package/lib/types/enum.d.ts +30 -0
  74. package/lib/types/enum.js +44 -0
  75. package/lib/types/predicateerror.d.ts +40 -0
  76. package/lib/types/predicateerror.js +107 -0
  77. package/lib/types/primitive.d.ts +23 -0
  78. package/lib/types/primitive.js +34 -0
  79. package/lib/types/record.d.ts +67 -0
  80. package/lib/types/record.js +235 -0
  81. package/lib/types/types.d.ts +64 -0
  82. package/lib/types/types.js +115 -0
  83. package/lib/types/utils.d.ts +18 -0
  84. package/lib/types/utils.js +67 -0
  85. package/lib/uint8array.d.ts +176 -0
  86. package/lib/uint8array.js +438 -0
  87. package/lib/units.d.ts +159 -0
  88. package/lib/units.js +290 -0
  89. package/lib/utils/buffer.d.ts +49 -0
  90. package/lib/utils/buffer.js +79 -0
  91. package/lib/utils/fourbytes.d.ts +29 -0
  92. package/lib/utils/fourbytes.js +45 -0
  93. package/package.json +1 -0
  94. package/web/array.d.ts +28 -0
  95. package/web/array.js +34 -0
  96. package/web/arraybuffer.d.ts +138 -0
  97. package/web/arraybuffer.js +141 -0
  98. package/web/async/asynctrigger.d.ts +50 -0
  99. package/web/async/asynctrigger.js +106 -0
  100. package/web/async/deferredpromise.d.ts +32 -0
  101. package/web/async/deferredpromise.js +65 -0
  102. package/web/async/keycache.d.ts +56 -0
  103. package/web/async/keycache.js +97 -0
  104. package/web/async/queues.d.ts +69 -0
  105. package/web/async/queues.js +131 -0
  106. package/web/async/timecache.d.ts +58 -0
  107. package/web/async/timecache.js +107 -0
  108. package/web/base58.d.ts +27 -0
  109. package/web/base58.js +78 -0
  110. package/web/base64.d.ts +51 -0
  111. package/web/base64.js +136 -0
  112. package/web/benchmark.d.ts +126 -0
  113. package/web/benchmark.js +183 -0
  114. package/web/bits/arraybuffer.d.ts +35 -0
  115. package/web/bits/arraybuffer.js +59 -0
  116. package/web/bits/base64.d.ts +35 -0
  117. package/web/bits/base64.js +67 -0
  118. package/web/bits/hex.d.ts +17 -0
  119. package/web/bits/hex.js +27 -0
  120. package/web/bits/uint8array.d.ts +28 -0
  121. package/web/bits/uint8array.js +41 -0
  122. package/web/bytebuffer.d.ts +27 -0
  123. package/web/bytebuffer.js +29 -0
  124. package/web/consts.d.ts +33 -0
  125. package/web/consts.js +33 -0
  126. package/web/cron/logger.d.ts +22 -0
  127. package/web/cron/logger.js +30 -0
  128. package/web/cron/scheduledtask.d.ts +71 -0
  129. package/web/cron/scheduledtask.js +136 -0
  130. package/web/cron/types.d.ts +53 -0
  131. package/web/cron/types.js +31 -0
  132. package/web/cron.d.ts +29 -0
  133. package/web/cron.js +47 -0
  134. package/web/dict.d.ts +56 -0
  135. package/web/dict.js +67 -0
  136. package/web/error.d.ts +25 -0
  137. package/web/error.js +39 -0
  138. package/web/global.d.ts +27 -0
  139. package/web/global.js +49 -0
  140. package/web/hex.d.ts +32 -0
  141. package/web/hex.js +52 -0
  142. package/web/idx.d.ts +51 -0
  143. package/web/idx.js +76 -0
  144. package/web/json.d.ts +57 -0
  145. package/web/json.js +98 -0
  146. package/web/marshalling/marshaller.d.ts +51 -0
  147. package/web/marshalling/marshaller.js +150 -0
  148. package/web/marshalling/unmarshaller.d.ts +53 -0
  149. package/web/marshalling/unmarshaller.js +115 -0
  150. package/web/marshalling/util.d.ts +25 -0
  151. package/web/marshalling/util.js +25 -0
  152. package/web/number.d.ts +17 -0
  153. package/web/number.js +21 -0
  154. package/web/path.d.ts +25 -0
  155. package/web/path.js +26 -0
  156. package/web/promise.d.ts +42 -0
  157. package/web/promise.js +74 -0
  158. package/web/starttime.d.ts +23 -0
  159. package/web/starttime.js +29 -0
  160. package/web/string.d.ts +65 -0
  161. package/web/string.js +101 -0
  162. package/web/types/array.d.ts +34 -0
  163. package/web/types/array.js +63 -0
  164. package/web/types/enum.d.ts +30 -0
  165. package/web/types/enum.js +40 -0
  166. package/web/types/predicateerror.d.ts +40 -0
  167. package/web/types/predicateerror.js +128 -0
  168. package/web/types/primitive.d.ts +23 -0
  169. package/web/types/primitive.js +33 -0
  170. package/web/types/record.d.ts +67 -0
  171. package/web/types/record.js +213 -0
  172. package/web/types/types.d.ts +64 -0
  173. package/web/types/types.js +123 -0
  174. package/web/types/utils.d.ts +18 -0
  175. package/web/types/utils.js +30 -0
  176. package/web/uint8array.d.ts +176 -0
  177. package/web/uint8array.js +412 -0
  178. package/web/units.d.ts +159 -0
  179. package/web/units.js +312 -0
  180. package/web/utils/buffer.d.ts +49 -0
  181. package/web/utils/buffer.js +76 -0
  182. package/web/utils/fourbytes.d.ts +29 -0
  183. package/web/utils/fourbytes.js +45 -0
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ const startTime = Date.now();
17
+ const CENTI = 100;
18
+ const DECI = 10;
19
+ /**
20
+ * Return the number of seconds since the program/JavaScript environment started.
21
+ *
22
+ * The result is always rounded to a decisecond at most.
23
+ *
24
+ * @public
25
+ */
26
+ export const getElapsedTime = () => {
27
+ const resultValue = Date.now() - startTime;
28
+ return Math.round(resultValue / CENTI) / DECI;
29
+ };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /**
17
+ * JavaScript implementation of Java's hashCode
18
+ *
19
+ * Source: https://stackoverflow.com/a/7616484
20
+ *
21
+ * @public
22
+ */
23
+ export declare const hashCode: (str: string) => number;
24
+ export type HashCallback = (value: string) => string;
25
+ /**
26
+ * Simplify a string, removing all characters outside of a restricted subset.
27
+ *
28
+ * @param replacement - The replacement for each character removed.
29
+ * Defaults to ""
30
+ *
31
+ * @param subset - A regex to be used as the filter subset.
32
+ * Defaults to /[^[a-zA-Z0-9_]/g
33
+ *
34
+ * @param hash - A hash function to use as fallback.
35
+ * Defaults to hashCode().
36
+ *
37
+ * @returns
38
+ * The stripped down string. If the string ends empty after stripping, it will
39
+ * fall back to the hash function to not return an empty string.
40
+ *
41
+ * If the hash function is used, its result is converted to a string but is not
42
+ * subject to the restriction of subset.
43
+ *
44
+ * @public
45
+ */
46
+ export declare const simplify: (str: string, replacement?: string, subset?: RegExp, hash?: HashCallback) => string;
47
+ /**
48
+ * Encode a string containing multi-bytes characters using URI encoding.
49
+ *
50
+ * Only the multi-bytes characters are encoded; any ASCII (\<127) character is
51
+ * kept as-is, except for the "%" character.
52
+ *
53
+ * @public
54
+ */
55
+ export declare const encodeUTF8: (str: string) => string;
56
+ /**
57
+ * Decode a string containing escaped UTF-8 sequences
58
+ *
59
+ * This is almost an alias to decodeURIComponent
60
+ *
61
+ * @public
62
+ */
63
+ export declare const decodeUTF8: (str: string, skipErrors?: boolean) => string;
64
+ /** Capitalize (or uncapitalize) the first character of a string */
65
+ export declare const capitalize: (str: string, upperFirstLetter: boolean) => string;
package/web/string.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ const hashCodeShift = 5;
17
+ /**
18
+ * JavaScript implementation of Java's hashCode
19
+ *
20
+ * Source: https://stackoverflow.com/a/7616484
21
+ *
22
+ * @public
23
+ */
24
+ export const hashCode = str => Array.from(str).reduce((hash, chr) => (hash << hashCodeShift) - hash + chr.charCodeAt(0), 0);
25
+ /**
26
+ * Simplify a string, removing all characters outside of a restricted subset.
27
+ *
28
+ * @param replacement - The replacement for each character removed.
29
+ * Defaults to ""
30
+ *
31
+ * @param subset - A regex to be used as the filter subset.
32
+ * Defaults to /[^[a-zA-Z0-9_]/g
33
+ *
34
+ * @param hash - A hash function to use as fallback.
35
+ * Defaults to hashCode().
36
+ *
37
+ * @returns
38
+ * The stripped down string. If the string ends empty after stripping, it will
39
+ * fall back to the hash function to not return an empty string.
40
+ *
41
+ * If the hash function is used, its result is converted to a string but is not
42
+ * subject to the restriction of subset.
43
+ *
44
+ * @public
45
+ */
46
+ export const simplify = (str, replacement, subset, hash) => {
47
+ const result = str.replace(subset ?? /[^[a-zA-Z0-9_]/gu, replacement ?? "");
48
+ return result.length > 0 ? result : String((hash ?? hashCode)(str));
49
+ };
50
+ // Only filter character point higher than 127
51
+ const FILTER_LIMIT = 127;
52
+ /**
53
+ * Encode a string containing multi-bytes characters using URI encoding.
54
+ *
55
+ * Only the multi-bytes characters are encoded; any ASCII (\<127) character is
56
+ * kept as-is, except for the "%" character.
57
+ *
58
+ * @public
59
+ */
60
+ export const encodeUTF8 = str => Array.from(str).map(chr => {
61
+ if (chr.charCodeAt(0) > FILTER_LIMIT || chr.startsWith("%") || chr.length > 1) {
62
+ return encodeURIComponent(chr);
63
+ }
64
+ return chr;
65
+ }).join("");
66
+ /**
67
+ * Decode a string containing escaped UTF-8 sequences
68
+ *
69
+ * This is almost an alias to decodeURIComponent
70
+ *
71
+ * @public
72
+ */
73
+ export const decodeUTF8 = (str, skipErrors) => {
74
+ try {
75
+ const fixedString = str.replace(/%(?<trailer>[0-9a-fA-F][^0-9a-fA-F]|[^0-9a-fA-F]|[0-9a-fA-F]$|$)/gu, "%25$<trailer>");
76
+ return decodeURIComponent(fixedString);
77
+ } catch (error) {
78
+ if (!skipErrors) throw error;
79
+ }
80
+ const outputParts = [];
81
+ let cursor = 0;
82
+ while (cursor < str.length) {
83
+ try {
84
+ const part = decodeURIComponent(str.substring(cursor));
85
+ outputParts.push(part);
86
+ cursor = str.length;
87
+ } catch {
88
+ const nextPercentPosition = str.indexOf("%", cursor);
89
+ outputParts.push(str.substring(cursor, nextPercentPosition + 1));
90
+ cursor = nextPercentPosition + 1;
91
+ }
92
+ }
93
+ return outputParts.join("");
94
+ };
95
+ /** Capitalize (or uncapitalize) the first character of a string */
96
+ export const capitalize = (str, upperFirstLetter) => {
97
+ const firstLetter = str.charAt(0);
98
+ const transformedFirstLetter = upperFirstLetter ? firstLetter.toUpperCase() : firstLetter.toLowerCase();
99
+ const rest = str.slice(1);
100
+ return `${transformedFirstLetter}${rest}`;
101
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateOptions, TypePredicate } from "./types.js";
17
+ /** Shorthand for an object that can be either T or an array of T */
18
+ export type Arrayable<T> = Array<T> | T;
19
+ /**
20
+ * Check that a given object is an array of string
21
+ *
22
+ * @public
23
+ */
24
+ export declare const isStringArray: TypePredicate<Array<string>>;
25
+ /**
26
+ * Check that a given object is an array where each value have the given type.
27
+ *
28
+ * @public
29
+ */
30
+ export declare const isArrayOfType: <T>(obj: unknown, predicate: TypePredicate<T>, options?: PredicateOptions) => obj is Array<T>;
31
+ export declare const isArrayableOfType: <T>(obj: unknown, predicate: TypePredicate<T>, options?: PredicateOptions) => obj is Arrayable<T>;
32
+ /** @public */
33
+ export declare const makeArrayOfTypePredicate: <ValueType>(valuePredicate: TypePredicate<ValueType>) => TypePredicate<Array<ValueType>>;
34
+ export declare const makeArrayableOfTypePredicate: <ValueType>(valuePredicate: TypePredicate<ValueType>) => TypePredicate<Arrayable<ValueType>>;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateError } from "./predicateerror.js";
17
+ import { getPredicateOptions } from "./types.js";
18
+ // #endregion
19
+ /**
20
+ * Check that a given object is an array of string
21
+ *
22
+ * @public
23
+ */
24
+ export const isStringArray = (obj, options = false) => {
25
+ const opt = getPredicateOptions(options);
26
+ if (!Array.isArray(obj)) {
27
+ PredicateError.expected(opt.raise, undefined, "an array");
28
+ return false;
29
+ }
30
+ for (const value of obj) {
31
+ if (typeof value !== "string") {
32
+ PredicateError.expected(opt.raise, "<array>", "a string");
33
+ return false;
34
+ }
35
+ }
36
+ return true;
37
+ };
38
+ /**
39
+ * Check that a given object is an array where each value have the given type.
40
+ *
41
+ * @public
42
+ */
43
+ export const isArrayOfType = (obj, predicate, options = false) => {
44
+ const opt = getPredicateOptions(options);
45
+ if (!Array.isArray(obj)) {
46
+ PredicateError.expected(opt.raise, undefined, "an array");
47
+ return false;
48
+ }
49
+ for (const value of obj) {
50
+ if (!predicate(value, opt)) {
51
+ PredicateError.predicateFailed(opt.raise, "<array>");
52
+ return false;
53
+ }
54
+ }
55
+ return true;
56
+ };
57
+ export const isArrayableOfType = (obj, predicate, options = false) => {
58
+ if (Array.isArray(obj)) return isArrayOfType(obj, predicate, options);
59
+ return predicate(obj, options);
60
+ };
61
+ /** @public */
62
+ export const makeArrayOfTypePredicate = valuePredicate => (obj, options = false) => isArrayOfType(obj, valuePredicate, options);
63
+ export const makeArrayableOfTypePredicate = valuePredicate => (obj, options = false) => isArrayableOfType(obj, valuePredicate, options);
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateOptions, TypePredicate } from "./types.js";
17
+ /**
18
+ * Return an enum-type value whose key matches the provided key string.
19
+ *
20
+ * @public
21
+ */
22
+ export declare const keyToEnum: <EnumType>(key: string, enumType: Record<string, EnumType>) => EnumType;
23
+ /**
24
+ * Check if an object is of the given enum type.
25
+ *
26
+ * @public
27
+ */
28
+ export declare const isEnumType: <EnumType>(obj: unknown, enumType: unknown, options?: PredicateOptions) => obj is EnumType;
29
+ /** @public */
30
+ export declare const makeEnumTypePredicate: <EnumType>(enumType: unknown) => TypePredicate<EnumType>;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateError } from "./predicateerror.js";
17
+ import { getPredicateOptions } from "./types.js";
18
+ /**
19
+ * Return an enum-type value whose key matches the provided key string.
20
+ *
21
+ * @public
22
+ */
23
+ export const keyToEnum = (key, enumType) => {
24
+ if (typeof enumType !== "object") throw new Error("Invalid enum type");
25
+ for (const enumKey of Object.keys(enumType)) if (key === enumKey) return enumType[enumKey];
26
+ throw new Error("Invalid enum key");
27
+ };
28
+ /**
29
+ * Check if an object is of the given enum type.
30
+ *
31
+ * @public
32
+ */
33
+ export const isEnumType = (obj, enumType, options = false) => {
34
+ const opt = getPredicateOptions(options);
35
+ const res = Object.values(enumType).includes(obj);
36
+ if (!res) PredicateError.expected(opt.raise, undefined, "value from enum");
37
+ return res;
38
+ };
39
+ /** @public */
40
+ export const makeEnumTypePredicate = enumType => (obj, options = false) => isEnumType(obj, enumType, options);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ interface PredicateErrorCtor {
17
+ keyName?: string;
18
+ error?: string;
19
+ cause?: Array<Error> | Error;
20
+ }
21
+ /**
22
+ * Construct an error whose message indicate what property failed to validate and why
23
+ *
24
+ * The static function provided will raise the appropriate error if the `raise` parameter is true,
25
+ * and do nothing otherwise.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare class PredicateError extends Error {
30
+ #private;
31
+ constructor(params: PredicateErrorCtor);
32
+ get keyName(): string | undefined;
33
+ get error(): string | undefined;
34
+ static readonly mandatory: (raise: boolean, keyName: string) => void;
35
+ static readonly expected: (raise: boolean, keyName: string | undefined, expectedMessage: string, value?: unknown) => void;
36
+ static readonly predicateFailed: (raise: boolean, keyName: string | undefined) => void;
37
+ static readonly allTryFailed: (raise: boolean, keyName: string | undefined, cause: Array<Error>) => void;
38
+ static readonly keyError: (raise: boolean, keyName: string, cause: Error) => void;
39
+ }
40
+ export {};
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ const getErrorPath = ({
17
+ keyName,
18
+ error,
19
+ cause
20
+ }) => {
21
+ const res = {
22
+ key: keyName
23
+ };
24
+ if (Array.isArray(cause)) {
25
+ res.cause = cause.map(singleCause => getErrorPath({
26
+ cause: singleCause
27
+ }));
28
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
29
+ } else if (cause instanceof PredicateError) {
30
+ res.cause = getErrorPath({
31
+ cause: cause.cause,
32
+ error: cause.error,
33
+ keyName: cause.keyName
34
+ });
35
+ } else if (error) {
36
+ res.cause = error;
37
+ } else if (cause) {
38
+ res.cause = cause.message;
39
+ } else {
40
+ res.cause = "<unknown error>";
41
+ }
42
+ return res;
43
+ };
44
+ const createMessage = ({
45
+ keyName,
46
+ error,
47
+ cause
48
+ }) => {
49
+ const errorPath = getErrorPath({
50
+ cause,
51
+ error,
52
+ keyName
53
+ });
54
+ return JSON.stringify(errorPath);
55
+ };
56
+ /**
57
+ * Construct an error whose message indicate what property failed to validate and why
58
+ *
59
+ * The static function provided will raise the appropriate error if the `raise` parameter is true,
60
+ * and do nothing otherwise.
61
+ *
62
+ * @internal
63
+ */
64
+ export class PredicateError extends Error {
65
+ #keyName;
66
+ #error;
67
+ constructor(params) {
68
+ super(createMessage(params), {
69
+ cause: params.cause
70
+ });
71
+ this.#keyName = params.keyName;
72
+ this.#error = params.error;
73
+ }
74
+ get keyName() {
75
+ return this.#keyName;
76
+ }
77
+ get error() {
78
+ return this.#error;
79
+ }
80
+ static mandatory = (raise, keyName) => {
81
+ if (raise) throw new PredicateError({
82
+ keyName,
83
+ error: "mandatory property missing"
84
+ });
85
+ };
86
+ static expected = (raise, keyName, expectedMessage, value) => {
87
+ if (raise) {
88
+ // eslint-disable-next-line @typescript-eslint/init-declarations
89
+ let valueStr;
90
+ if (value !== undefined) {
91
+ try {
92
+ valueStr = JSON.stringify(value);
93
+ } catch {
94
+ try {
95
+ valueStr = value.toString();
96
+ } catch {
97
+ valueStr = "<value>";
98
+ }
99
+ }
100
+ }
101
+ const msg = valueStr === undefined ? expectedMessage : `${expectedMessage} (${valueStr})`;
102
+ throw new PredicateError({
103
+ keyName,
104
+ error: `expected ${msg}`
105
+ });
106
+ }
107
+ };
108
+ static predicateFailed = (raise, keyName) => {
109
+ if (raise) throw new PredicateError({
110
+ keyName,
111
+ error: "predicate failed"
112
+ });
113
+ };
114
+ static allTryFailed = (raise, keyName, cause) => {
115
+ if (raise) throw new PredicateError({
116
+ cause,
117
+ error: "all possibilities failed",
118
+ keyName
119
+ });
120
+ };
121
+ static keyError = (raise, keyName, cause) => {
122
+ if (raise) throw new PredicateError({
123
+ cause,
124
+ error: cause.message,
125
+ keyName
126
+ });
127
+ };
128
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import * as types from "./types.js";
17
+ export declare const isPrimitive: <T>(obj: unknown, primitiveType: string, options?: types.PredicateOptions) => obj is T;
18
+ export declare const makePrimitivePredicate: <T>(primitiveType: string) => types.TypePredicate<T>;
19
+ export declare const isBoolean: types.TypePredicate<boolean>;
20
+ export declare const isNumber: types.TypePredicate<number>;
21
+ export declare const isString: types.TypePredicate<string>;
22
+ export declare const isSymbol: types.TypePredicate<symbol>;
23
+ export declare const isBigInt: types.TypePredicate<bigint>;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ // #region Imports
17
+ import { PredicateError } from "./predicateerror.js";
18
+ import * as types from "./types.js";
19
+ // #endregion
20
+ // #region Predicates
21
+ export const isPrimitive = (obj, primitiveType, options = false) => {
22
+ if (typeof obj === primitiveType) return true;
23
+ const opt = types.getPredicateOptions(options);
24
+ PredicateError.predicateFailed(opt.raise, undefined);
25
+ return false;
26
+ };
27
+ export const makePrimitivePredicate = primitiveType => (obj, options = false) => isPrimitive(obj, primitiveType, options);
28
+ export const isBoolean = makePrimitivePredicate("boolean");
29
+ export const isNumber = makePrimitivePredicate("number");
30
+ export const isString = makePrimitivePredicate("string");
31
+ export const isSymbol = makePrimitivePredicate("symbol");
32
+ export const isBigInt = makePrimitivePredicate("bigint");
33
+ // #endregion
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateOptions, TypePredicate } from "./types.js";
17
+ interface ProfileValue<T = unknown> {
18
+ value: T;
19
+ optional?: boolean;
20
+ shortcut?: boolean;
21
+ }
22
+ interface InstanceOfValue {
23
+ clazz: any;
24
+ optional?: boolean;
25
+ shortcut?: boolean;
26
+ }
27
+ interface PredicateValue<T = unknown> {
28
+ predicate: TypePredicate<T>;
29
+ optional?: boolean;
30
+ shortcut?: boolean;
31
+ }
32
+ type AdvancedProfileValue = ProfileValue | InstanceOfValue | PredicateValue;
33
+ type ProfileEntryType = string | TypePredicate | AdvancedProfileValue;
34
+ /**
35
+ * Simple profile to check.
36
+ *
37
+ * Keys are property names, values are typeof values.
38
+ * A value prefixed or suffixed with '?' is optional.
39
+ */
40
+ export type Profile<T> = Record<keyof T, ProfileEntryType | Array<ProfileEntryType>>;
41
+ /**
42
+ * Check if an object's properties fit the basic types profile.
43
+ *
44
+ * Only fit to check primitive types, equality and using other predicates.
45
+ * If `shortcut: true` is used in the options, only properties marked as "shortcut" are checked.
46
+ * For structured properties like instanceof and predicate this is indicated by the `shortcut`
47
+ * property; for primary type predicate this is indicated by the "!" character either before or
48
+ * after the type name.
49
+ *
50
+ * @public
51
+ */
52
+ export declare const isObjectProfile: <T>(obj: unknown, profile: Profile<T>, options?: PredicateOptions) => obj is T;
53
+ /**
54
+ * Create a predicate function based on the given profile.
55
+ *
56
+ * @public
57
+ */
58
+ export declare const makeProfilePredicate: <TargetType>(profile: Profile<TargetType>) => TypePredicate<TargetType>;
59
+ /**
60
+ * Check if all of an object properties match a given type.
61
+ *
62
+ * @public
63
+ */
64
+ export declare const isKeyValueOfType: <ValueType>(obj: unknown, typePredicate: TypePredicate<ValueType>, options?: PredicateOptions) => obj is Record<string, ValueType>;
65
+ /** @public */
66
+ export declare const makeKeyValueOfTypePredicate: <ValueType>(typePredicate: TypePredicate<ValueType>) => TypePredicate<Record<string, ValueType>>;
67
+ export {};