@ls-stack/utils 1.0.0

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 (97) hide show
  1. package/README.md +1 -0
  2. package/dist/arrayUtils.d.ts +50 -0
  3. package/dist/arrayUtils.js +13 -0
  4. package/dist/arrayUtils.js.map +1 -0
  5. package/dist/assertions.d.ts +17 -0
  6. package/dist/assertions.js +25 -0
  7. package/dist/assertions.js.map +1 -0
  8. package/dist/castValues.d.ts +4 -0
  9. package/dist/castValues.js +16 -0
  10. package/dist/castValues.js.map +1 -0
  11. package/dist/chunk-4DRNU53E.js +70 -0
  12. package/dist/chunk-4DRNU53E.js.map +1 -0
  13. package/dist/chunk-5FQYH3ZJ.js +106 -0
  14. package/dist/chunk-5FQYH3ZJ.js.map +1 -0
  15. package/dist/chunk-5SB253CL.js +54 -0
  16. package/dist/chunk-5SB253CL.js.map +1 -0
  17. package/dist/chunk-HLFWWIDK.js +9 -0
  18. package/dist/chunk-HLFWWIDK.js.map +1 -0
  19. package/dist/chunk-HYFUWQ2E.js +218 -0
  20. package/dist/chunk-HYFUWQ2E.js.map +1 -0
  21. package/dist/chunk-J66LUDLH.js +13 -0
  22. package/dist/chunk-J66LUDLH.js.map +1 -0
  23. package/dist/chunk-JT3EBBCA.js +69 -0
  24. package/dist/chunk-JT3EBBCA.js.map +1 -0
  25. package/dist/chunk-JZUOIOMU.js +75 -0
  26. package/dist/chunk-JZUOIOMU.js.map +1 -0
  27. package/dist/chunk-MMKMF4GG.js +21 -0
  28. package/dist/chunk-MMKMF4GG.js.map +1 -0
  29. package/dist/chunk-SNAAKCTH.js +40 -0
  30. package/dist/chunk-SNAAKCTH.js.map +1 -0
  31. package/dist/consoleFmt.d.ts +48 -0
  32. package/dist/consoleFmt.js +60 -0
  33. package/dist/consoleFmt.js.map +1 -0
  34. package/dist/conversions.d.ts +3 -0
  35. package/dist/conversions.js +7 -0
  36. package/dist/conversions.js.map +1 -0
  37. package/dist/createThrottleController.d.ts +16 -0
  38. package/dist/createThrottleController.js +66 -0
  39. package/dist/createThrottleController.js.map +1 -0
  40. package/dist/dedent.d.ts +4 -0
  41. package/dist/dedent.js +33 -0
  42. package/dist/dedent.js.map +1 -0
  43. package/dist/deepEqual.d.ts +4 -0
  44. package/dist/deepEqual.js +7 -0
  45. package/dist/deepEqual.js.map +1 -0
  46. package/dist/enhancedMap.d.ts +22 -0
  47. package/dist/enhancedMap.js +10 -0
  48. package/dist/enhancedMap.js.map +1 -0
  49. package/dist/exhaustiveMatch.d.ts +5 -0
  50. package/dist/exhaustiveMatch.js +27 -0
  51. package/dist/exhaustiveMatch.js.map +1 -0
  52. package/dist/main.d.ts +25 -0
  53. package/dist/main.js +3 -0
  54. package/dist/main.js.map +1 -0
  55. package/dist/mathUtils.d.ts +4 -0
  56. package/dist/mathUtils.js +9 -0
  57. package/dist/mathUtils.js.map +1 -0
  58. package/dist/objUtils.d.ts +7 -0
  59. package/dist/objUtils.js +15 -0
  60. package/dist/objUtils.js.map +1 -0
  61. package/dist/parallelAsyncResultCalls.d.ts +76 -0
  62. package/dist/parallelAsyncResultCalls.js +126 -0
  63. package/dist/parallelAsyncResultCalls.js.map +1 -0
  64. package/dist/promiseUtils.d.ts +8 -0
  65. package/dist/promiseUtils.js +14 -0
  66. package/dist/promiseUtils.js.map +1 -0
  67. package/dist/rsResult.d.ts +118 -0
  68. package/dist/rsResult.js +21 -0
  69. package/dist/rsResult.js.map +1 -0
  70. package/dist/runShellCmd.d.ts +15 -0
  71. package/dist/runShellCmd.js +71 -0
  72. package/dist/runShellCmd.js.map +1 -0
  73. package/dist/shallowEqual.d.ts +4 -0
  74. package/dist/shallowEqual.js +74 -0
  75. package/dist/shallowEqual.js.map +1 -0
  76. package/dist/sleep.d.ts +3 -0
  77. package/dist/sleep.js +7 -0
  78. package/dist/sleep.js.map +1 -0
  79. package/dist/stringUtils.d.ts +18 -0
  80. package/dist/stringUtils.js +17 -0
  81. package/dist/stringUtils.js.map +1 -0
  82. package/dist/testUtils.d.ts +24 -0
  83. package/dist/testUtils.js +171 -0
  84. package/dist/testUtils.js.map +1 -0
  85. package/dist/typingFnUtils.d.ts +5 -0
  86. package/dist/typingFnUtils.js +8 -0
  87. package/dist/typingFnUtils.js.map +1 -0
  88. package/dist/typingTestUtils.d.ts +12 -0
  89. package/dist/typingTestUtils.js +19 -0
  90. package/dist/typingTestUtils.js.map +1 -0
  91. package/dist/typingUtils.d.ts +11 -0
  92. package/dist/typingUtils.js +1 -0
  93. package/dist/typingUtils.js.map +1 -0
  94. package/dist/yamlStringify.d.ts +8 -0
  95. package/dist/yamlStringify.js +292 -0
  96. package/dist/yamlStringify.js.map +1 -0
  97. package/package.json +235 -0
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # Generic typescript utils
@@ -0,0 +1,50 @@
1
+ /**
2
+ * allow to filter and map with better typing ergonomics
3
+ *
4
+ * In the `mapFilter` function return `false` to reject the item, or any other
5
+ * value to map it.
6
+ *
7
+ * @example
8
+ * // Filter reject and turn value into `value mapped`
9
+ * const items = ['value', 'value', 'reject', 'reject'];
10
+ *
11
+ * const mappedItems = filterAndMap(items, (item) =>
12
+ * item === 'reject'
13
+ * ? false
14
+ * : `${item} mapped`,
15
+ * );
16
+ *
17
+ * mappedItems; // ['value mapped', 'value mapped']
18
+ */
19
+ declare function filterAndMap<T, R>(array: IterableIterator<T> | readonly T[], mapFilter: (item: T, index: number) => false | R): R[];
20
+ type FilterAndMapReturn<T> = false | T;
21
+ type SortOrder = 'desc' | 'asc';
22
+ /**
23
+ * Sort an array based on a value
24
+ *
25
+ * Sort by `ascending` order by default
26
+ *
27
+ * Use `Infinity` as as wildcard to absulute max and min values
28
+ *
29
+ * @example
30
+ * const items = [1, 3, 2, 4];
31
+ *
32
+ * const sortedItems = sortBy(items, (item) => item);
33
+ * // [1, 2, 3, 4]
34
+ *
35
+ * const items2 = [{ a: 1, b: 2 }, { a: 2, b: 1 }, { a: 1, b: 1}]
36
+ *
37
+ * // return a array to sort by multiple values
38
+ * const sortedItems = sortBy(items, (item) => [item.a, item.b]);
39
+ **/
40
+ declare function sortBy<T>(arr: T[], sortByValue: (item: T) => (number | string)[] | number | string, { order }?: {
41
+ order?: SortOrder | SortOrder[];
42
+ }): T[];
43
+ declare function arrayWithPrev<T>(array: T[]): [current: T, prev: T | null][];
44
+ declare function arrayWithPrevAndIndex<T>(array: T[]): {
45
+ item: T;
46
+ prev: T | null;
47
+ index: number;
48
+ }[];
49
+
50
+ export { type FilterAndMapReturn, arrayWithPrev, arrayWithPrevAndIndex, filterAndMap, sortBy };
@@ -0,0 +1,13 @@
1
+ import {
2
+ arrayWithPrev,
3
+ arrayWithPrevAndIndex,
4
+ filterAndMap,
5
+ sortBy
6
+ } from "./chunk-5SB253CL.js";
7
+ export {
8
+ arrayWithPrev,
9
+ arrayWithPrevAndIndex,
10
+ filterAndMap,
11
+ sortBy
12
+ };
13
+ //# sourceMappingURL=arrayUtils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,17 @@
1
+ type NotUndefined<T> = T extends undefined ? never : T;
2
+ type StrictNonUndefined<T, N = unknown> = undefined extends T ? NotUndefined<T> : N;
3
+ declare function notUndefined<T>(value: T): StrictNonUndefined<T>;
4
+ type StrictNonNullable<T, N = unknown> = undefined extends T ? NonNullable<T> : null extends T ? NonNullable<T> : N;
5
+ declare function notNullish<T>(value: T): StrictNonNullable<T>;
6
+ declare function assertIsNotNullish<T>(value: T, errorMsg?: string): asserts value is StrictNonNullable<T, never>;
7
+ declare function assertIsNotUndefined<T>(value: T, errorMsg?: string): asserts value is StrictNonUndefined<T, never>;
8
+ /** Use this function to assert that a certain condition is always true. */
9
+ declare function invariant(condition: any, errorMsg?: string): asserts condition;
10
+ /** ensures all type possibilities are being handled */
11
+ declare function exhaustiveCheck<Except = never>(narrowedType: NoInfer<Except>): Error;
12
+ declare function isObject(value: unknown): value is Record<string, unknown>;
13
+ declare function isFunction(value: unknown): value is (...args: any[]) => any;
14
+ declare function isPromise(value: unknown): value is Promise<unknown>;
15
+ declare function isPlainObject(value: any): value is Record<string, unknown>;
16
+
17
+ export { assertIsNotNullish, assertIsNotUndefined, exhaustiveCheck, invariant, isFunction, isObject, isPlainObject, isPromise, notNullish, notUndefined };
@@ -0,0 +1,25 @@
1
+ import {
2
+ assertIsNotNullish,
3
+ assertIsNotUndefined,
4
+ exhaustiveCheck,
5
+ invariant,
6
+ isFunction,
7
+ isObject,
8
+ isPlainObject,
9
+ isPromise,
10
+ notNullish,
11
+ notUndefined
12
+ } from "./chunk-JT3EBBCA.js";
13
+ export {
14
+ assertIsNotNullish,
15
+ assertIsNotUndefined,
16
+ exhaustiveCheck,
17
+ invariant,
18
+ isFunction,
19
+ isObject,
20
+ isPlainObject,
21
+ isPromise,
22
+ notNullish,
23
+ notUndefined
24
+ };
25
+ //# sourceMappingURL=assertions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,4 @@
1
+ declare function castToString(value: unknown): string | null;
2
+ declare function castToNumber(value: unknown): number | null;
3
+
4
+ export { castToNumber, castToString };
@@ -0,0 +1,16 @@
1
+ // src/castValues.ts
2
+ function castToString(value) {
3
+ return value !== null && value !== void 0 ? String(value) : null;
4
+ }
5
+ function castToNumber(value) {
6
+ return isNumeric(value) ? Number(value) : null;
7
+ }
8
+ function isNumeric(num) {
9
+ const str = String(num);
10
+ return !isNaN(str) && !isNaN(parseFloat(str));
11
+ }
12
+ export {
13
+ castToNumber,
14
+ castToString
15
+ };
16
+ //# sourceMappingURL=castValues.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/castValues.ts"],"sourcesContent":["export function castToString(value: unknown): string | null {\n return value !== null && value !== undefined ? String(value) : null;\n}\n\nexport function castToNumber(value: unknown): number | null {\n return isNumeric(value) ? Number(value) : null;\n}\n\nfunction isNumeric(num: unknown) {\n const str = String(num);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return !isNaN(str as any) && !isNaN(parseFloat(str));\n}\n"],"mappings":";AAAO,SAAS,aAAa,OAA+B;AAC1D,SAAO,UAAU,QAAQ,UAAU,SAAY,OAAO,KAAK,IAAI;AACjE;AAEO,SAAS,aAAa,OAA+B;AAC1D,SAAO,UAAU,KAAK,IAAI,OAAO,KAAK,IAAI;AAC5C;AAEA,SAAS,UAAU,KAAc;AAC/B,QAAM,MAAM,OAAO,GAAG;AAGtB,SAAO,CAAC,MAAM,GAAU,KAAK,CAAC,MAAM,WAAW,GAAG,CAAC;AACrD;","names":[]}
@@ -0,0 +1,70 @@
1
+ // src/stringUtils.ts
2
+ function joinStrings(...args) {
3
+ const strings = [];
4
+ for (let i = 0; i < args.length; i++) {
5
+ const arg = args[i];
6
+ if (!arg)
7
+ continue;
8
+ if (Array.isArray(arg)) {
9
+ strings.push(joinStrings(...arg));
10
+ continue;
11
+ }
12
+ strings.push(arg);
13
+ }
14
+ return strings.join("");
15
+ }
16
+ function dedent(strings, ...values) {
17
+ const raw = typeof strings === "string" ? [strings] : strings.raw;
18
+ let result = "";
19
+ for (let i = 0; i < raw.length; i++) {
20
+ result += raw[i].replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`");
21
+ if (i < values.length) {
22
+ result += values[i];
23
+ }
24
+ }
25
+ const lines = result.split("\n");
26
+ let mindent = null;
27
+ lines.forEach((l) => {
28
+ const m = l.match(/^(\s+)\S+/);
29
+ if (m) {
30
+ const indent = m[1].length;
31
+ if (!mindent) {
32
+ mindent = indent;
33
+ } else {
34
+ mindent = Math.min(mindent, indent);
35
+ }
36
+ }
37
+ });
38
+ if (mindent !== null) {
39
+ const m = mindent;
40
+ result = lines.map((l) => l.startsWith(" ") ? l.slice(m) : l).join("\n");
41
+ }
42
+ return result.trim().replace(/\\n/g, "\n");
43
+ }
44
+ function formatNum(num) {
45
+ return num.toLocaleString("en-US", {
46
+ minimumFractionDigits: 2,
47
+ maximumFractionDigits: 2
48
+ });
49
+ }
50
+ function isSnakeCase(str) {
51
+ return /^[a-z0-9_]+$/.test(str);
52
+ }
53
+ function convertToSnakeCase(str) {
54
+ return str.replace(/([A-Z])/g, "_$1").replace(/[^a-z0-9_]/g, "").toLowerCase();
55
+ }
56
+ function truncateString(str, length, ellipsis = "\u2026") {
57
+ if (str.length <= length)
58
+ return str;
59
+ return str.slice(0, length - 1) + ellipsis;
60
+ }
61
+
62
+ export {
63
+ joinStrings,
64
+ dedent,
65
+ formatNum,
66
+ isSnakeCase,
67
+ convertToSnakeCase,
68
+ truncateString
69
+ };
70
+ //# sourceMappingURL=chunk-4DRNU53E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stringUtils.ts"],"sourcesContent":["type Arg = string | false | undefined | null;\n\n/**\n * A util to create more legible conditional concatenated strings\n *\n * @example\n * joinStrings('a', 'b', 'c') // 'abc'\n * joinStrings('a', false, 'c') // 'ac'\n * joinStrings('a', addBString ? 'b' : null, 'c') // 'ac' if addBString is false, 'abc' if addBString is true\n */\nexport function joinStrings(...args: (Arg | Arg[])[]) {\n const strings: string[] = [];\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n\n if (!arg) continue;\n\n if (Array.isArray(arg)) {\n strings.push(joinStrings(...arg));\n continue;\n }\n\n strings.push(arg);\n }\n\n return strings.join('');\n}\n\n// fork of https://github.com/dmnd/dedent\nexport function dedent(strings: string): string;\nexport function dedent(\n strings: TemplateStringsArray,\n ...values: string[]\n): string;\nexport function dedent(\n strings: TemplateStringsArray | string,\n ...values: string[]\n) {\n // $FlowFixMe: Flow doesn't undestand .raw\n const raw = typeof strings === 'string' ? [strings] : strings.raw;\n\n // first, perform interpolation\n let result = '';\n for (let i = 0; i < raw.length; i++) {\n result += raw[i]! // join lines when there is a suppressed newline\n .replace(/\\\\\\n[ \\t]*/g, '')\n // handle escaped backticks\n .replace(/\\\\`/g, '`');\n\n if (i < values.length) {\n result += values[i];\n }\n }\n\n // now strip indentation\n const lines = result.split('\\n');\n let mindent: number | null = null;\n lines.forEach((l) => {\n const m = l.match(/^(\\s+)\\S+/);\n if (m) {\n const indent = m[1]!.length;\n if (!mindent) {\n // this is the first indented line\n mindent = indent;\n } else {\n mindent = Math.min(mindent, indent);\n }\n }\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (mindent !== null) {\n const m = mindent; // appease Flow\n result = lines.map((l) => (l.startsWith(' ') ? l.slice(m) : l)).join('\\n');\n }\n\n return (\n result\n // dedent eats leading and trailing whitespace too\n .trim()\n // handle escaped newlines at the end to ensure they don't get stripped too\n .replace(/\\\\n/g, '\\n')\n );\n}\n\nexport function formatNum(num: number) {\n return num.toLocaleString('en-US', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n });\n}\n\nexport function isSnakeCase(str: string) {\n return /^[a-z0-9_]+$/.test(str);\n}\n\nexport function convertToSnakeCase(str: string) {\n return str\n .replace(/([A-Z])/g, '_$1')\n .replace(/[^a-z0-9_]/g, '')\n .toLowerCase();\n}\n\nexport function truncateString(str: string, length: number, ellipsis = '…') {\n if (str.length <= length) return str;\n\n return str.slice(0, length - 1) + ellipsis;\n}\n"],"mappings":";AAUO,SAAS,eAAe,MAAuB;AACpD,QAAM,UAAoB,CAAC;AAE3B,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,MAAM,KAAK,CAAC;AAElB,QAAI,CAAC;AAAK;AAEV,QAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,cAAQ,KAAK,YAAY,GAAG,GAAG,CAAC;AAChC;AAAA,IACF;AAEA,YAAQ,KAAK,GAAG;AAAA,EAClB;AAEA,SAAO,QAAQ,KAAK,EAAE;AACxB;AAQO,SAAS,OACd,YACG,QACH;AAEA,QAAM,MAAM,OAAO,YAAY,WAAW,CAAC,OAAO,IAAI,QAAQ;AAG9D,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;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symbol();
7
+ var EnhancedMap = class _EnhancedMap extends Map {
8
+ find(predicate) {
9
+ for (const [key, value] of this) {
10
+ if (predicate(value, key)) {
11
+ return { key, value };
12
+ }
13
+ }
14
+ return void 0;
15
+ }
16
+ setMultiple(...values) {
17
+ if (Array.isArray(values[0])) {
18
+ for (const [key, value] of values) {
19
+ this.set(key, value);
20
+ }
21
+ } else {
22
+ for (const [key, value] of Object.entries(values[0])) {
23
+ this.set(key, value);
24
+ }
25
+ }
26
+ return this;
27
+ }
28
+ getOrThrow(key) {
29
+ const value = this.get(key);
30
+ if (value === void 0) {
31
+ throw new Error(`Key ${key} not found in EnhancedMap`);
32
+ }
33
+ return value;
34
+ }
35
+ getOrInsert(key, fallback) {
36
+ if (!this.has(key)) {
37
+ this.set(key, fallback());
38
+ }
39
+ return this.getOrThrow(key);
40
+ }
41
+ toFilteredValues(predicate) {
42
+ const values = [];
43
+ for (const [key, value] of this) {
44
+ if (predicate(value, key)) {
45
+ values.push(value);
46
+ }
47
+ }
48
+ return values;
49
+ }
50
+ toMap(mapFunction) {
51
+ const values = [];
52
+ for (const [key, value] of this) {
53
+ const result = mapFunction(value, key, enhancedMapReject);
54
+ if (result !== enhancedMapReject) {
55
+ values.push(result);
56
+ }
57
+ }
58
+ return values;
59
+ }
60
+ toObjMap(mapFunction) {
61
+ const values = {};
62
+ for (const [key, value] of this) {
63
+ const result = mapFunction(value, key);
64
+ if (result) {
65
+ values[result[0]] = result[1];
66
+ }
67
+ }
68
+ return values;
69
+ }
70
+ toValues() {
71
+ return [...this.values()];
72
+ }
73
+ toKeys() {
74
+ return [...this.keys()];
75
+ }
76
+ /** @deprecated, will be removed in v5 use `from` method instead */
77
+ static fromIterMap(array, mapFunction) {
78
+ return this.from(array, mapFunction);
79
+ }
80
+ static from(array, mapFunction) {
81
+ const map = new _EnhancedMap();
82
+ if (!array)
83
+ return map;
84
+ const isFn = isFunction(mapFunction);
85
+ for (const item of array) {
86
+ if (isFn) {
87
+ const result = mapFunction(item);
88
+ if (result) {
89
+ map.set(result[0], result[1]);
90
+ }
91
+ } else {
92
+ const key = item[mapFunction];
93
+ if (key !== void 0) {
94
+ map.set(key, item);
95
+ }
96
+ }
97
+ }
98
+ return map;
99
+ }
100
+ };
101
+
102
+ export {
103
+ enhancedMapReject,
104
+ EnhancedMap
105
+ };
106
+ //# sourceMappingURL=chunk-5FQYH3ZJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/enhancedMap.ts"],"sourcesContent":["import { isFunction } from './assertions';\n\nexport const enhancedMapReject = Symbol();\n\nexport class EnhancedMap<K, V> extends Map<K, V> {\n find(\n predicate: (value: V, key: K) => boolean,\n ): { key: K; value: V } | undefined {\n for (const [key, value] of this) {\n if (predicate(value, key)) {\n return { key, value };\n }\n }\n\n return undefined;\n }\n\n setMultiple(values: Record<K & string, V>): this;\n setMultiple(...values: [key: K, value: V][]): this;\n setMultiple(...values: [key: K, value: V][] | [Record<K & string, V>]): this {\n if (Array.isArray(values[0])) {\n for (const [key, value] of values as [key: K, value: V][]) {\n this.set(key, value);\n }\n } else {\n for (const [key, value] of Object.entries(values[0])) {\n this.set(key as K, value as V);\n }\n }\n\n return this;\n }\n\n getOrThrow(key: K): V {\n const value = this.get(key);\n\n if (value === undefined) {\n throw new Error(`Key ${key} not found in EnhancedMap`);\n }\n\n return value;\n }\n\n getOrInsert(key: K, fallback: () => V): V {\n if (!this.has(key)) {\n this.set(key, fallback());\n }\n\n return this.getOrThrow(key);\n }\n\n toFilteredValues(predicate: (value: V, key: K) => boolean): V[] {\n const values: V[] = [];\n\n for (const [key, value] of this) {\n if (predicate(value, key)) {\n values.push(value);\n }\n }\n\n return values;\n }\n\n toMap<T>(\n mapFunction: (\n value: V,\n key: K,\n reject: typeof enhancedMapReject,\n ) => T | typeof enhancedMapReject,\n ): T[] {\n const values: T[] = [];\n\n for (const [key, value] of this) {\n const result = mapFunction(value, key, enhancedMapReject);\n\n if (result !== enhancedMapReject) {\n values.push(result);\n }\n }\n\n return values;\n }\n\n toObjMap<ObjKey extends PropertyKey, ObjValue>(\n mapFunction: (value: V, key: K) => [key: ObjKey, value: ObjValue] | false,\n ): Record<ObjKey, ObjValue> {\n const values: Record<ObjKey, ObjValue> = {} as any;\n\n for (const [key, value] of this) {\n const result = mapFunction(value, key);\n\n if (result) {\n values[result[0]] = result[1];\n }\n }\n\n return values;\n }\n\n toValues(): V[] {\n return [...this.values()];\n }\n\n toKeys(): K[] {\n return [...this.keys()];\n }\n\n /** @deprecated, will be removed in v5 use `from` method instead */\n static fromIterMap<T, K, V>(\n array: T[] | Iterable<T>,\n mapFunction: (item: T) => [key: K, value: V] | false,\n ): EnhancedMap<K, V> {\n return this.from(array, mapFunction);\n }\n\n static from<T extends Record<string, unknown>, K extends keyof T>(\n array: T[] | Iterable<T> | null | undefined,\n key: K,\n ): EnhancedMap<T[K], T>;\n static from<T, K, V>(\n array: T[] | Iterable<T> | null | undefined,\n mapFunction: (item: T) => [key: K, value: V] | false,\n ): EnhancedMap<K, V>;\n static from(\n array: any[] | Iterable<any> | null | undefined,\n mapFunction: ((item: any) => [key: any, value: any] | false) | string,\n ): EnhancedMap<any, any> {\n const map = new EnhancedMap<any, any>();\n\n if (!array) return map;\n\n const isFn = isFunction(mapFunction);\n\n for (const item of array) {\n if (isFn) {\n const result = mapFunction(item);\n\n if (result) {\n map.set(result[0], result[1]);\n }\n } else {\n const key = item[mapFunction];\n\n if (key !== undefined) {\n map.set(key, item);\n }\n }\n }\n\n return map;\n }\n}\n"],"mappings":";;;;;AAEO,IAAM,oBAAoB,OAAO;AAEjC,IAAM,cAAN,MAAM,qBAA0B,IAAU;AAAA,EAC/C,KACE,WACkC;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,MAAM;AAC/B,UAAI,UAAU,OAAO,GAAG,GAAG;AACzB,eAAO,EAAE,KAAK,MAAM;AAAA,MACtB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAIA,eAAe,QAA8D;AAC3E,QAAI,M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AC,IAAI,OAAO,CAAC;AAAA,MAC9B;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,WAAgB;AACd,WAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAAA,EAC1B;AAAA,EAEA,SAAc;AACZ,WAAO,CAAC,GAAG,KAAK,KAAK,CAAC;AAAA,EACxB;AAAA;AAAA,EAGA,OAAO,YACL,OACA,aACmB;AACnB,WAAO,KAAK,KAAK,OAAO,WAAW;AAAA,EACrC;AAAA,EAUA,OAAO,KACL,OACA,aACuB;AACvB,UAAM,MAAM,IAAI,aAAsB;AAEtC,QAAI,CAAC;AAAO,aAAO;AAEnB,UAAM,OAAO,WAAW,WAAW;AAEnC,eAAW,QAAQ,OAAO;AACxB,UAAI,MAAM;AACR,cAAM,SAAS,YAAY,IAAI;AAE/B,YAAI,QAAQ;AACV,cAAI,IAAI,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;AAAA,QAC9B;AAAA,MACF,OAAO;AACL,cAAM,MAAM,KAAK,WAAW;AAE5B,YAAI,QAAQ,QAAW;AACrB,cAAI,IAAI,KAAK,IAAI;AAAA,QACnB;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,54 @@
1
+ // src/arrayUtils.ts
2
+ function filterAndMap(array, mapFilter) {
3
+ const result = [];
4
+ let i = -1;
5
+ for (const item of array) {
6
+ i += 1;
7
+ const filterResult = mapFilter(item, i);
8
+ if (filterResult !== false) {
9
+ result.push(filterResult);
10
+ }
11
+ }
12
+ return result;
13
+ }
14
+ function sortBy(arr, sortByValue, { order = "asc" } = {}) {
15
+ return [...arr].sort((a, b) => {
16
+ const _aPriority = sortByValue(a);
17
+ const _bPriority = sortByValue(b);
18
+ const aPriority = Array.isArray(_aPriority) ? _aPriority : [_aPriority];
19
+ const bPriority = Array.isArray(_bPriority) ? _bPriority : [_bPriority];
20
+ for (let i = 0; i < aPriority.length; i++) {
21
+ const levelOrder = typeof order === "string" ? order : order[i] ?? "asc";
22
+ const aP = aPriority[i] ?? 0;
23
+ const bP = bPriority[i] ?? 0;
24
+ if (aP === bP) {
25
+ continue;
26
+ }
27
+ if (bP === Infinity || aP === -Infinity || aP < bP) {
28
+ return levelOrder === "asc" ? -1 : 1;
29
+ }
30
+ if (aP === Infinity || bP === -Infinity || aP > bP) {
31
+ return levelOrder === "asc" ? 1 : -1;
32
+ }
33
+ }
34
+ return 0;
35
+ });
36
+ }
37
+ function arrayWithPrev(array) {
38
+ return array.map((item, i) => [item, array[i - 1] ?? null]);
39
+ }
40
+ function arrayWithPrevAndIndex(array) {
41
+ return array.map((item, i) => ({
42
+ item,
43
+ prev: array[i - 1] ?? null,
44
+ index: i
45
+ }));
46
+ }
47
+
48
+ export {
49
+ filterAndMap,
50
+ sortBy,
51
+ arrayWithPrev,
52
+ arrayWithPrevAndIndex
53
+ };
54
+ //# sourceMappingURL=chunk-5SB253CL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/arrayUtils.ts"],"sourcesContent":["/**\n * allow to filter and map with better typing ergonomics\n *\n * In the `mapFilter` function return `false` to reject the item, or any other\n * value to map it.\n *\n * @example\n * // Filter reject and turn value into `value mapped`\n * const items = ['value', 'value', 'reject', 'reject'];\n *\n * const mappedItems = filterAndMap(items, (item) =>\n * item === 'reject'\n * ? false\n * : `${item} mapped`,\n * );\n *\n * mappedItems; // ['value mapped', 'value mapped']\n */\nexport function filterAndMap<T, R>(\n array: IterableIterator<T> | readonly T[],\n mapFilter: (item: T, index: number) => false | R,\n): R[] {\n const result: R[] = [];\n\n let i = -1;\n for (const item of array) {\n i += 1;\n const filterResult = mapFilter(item, i);\n\n if (filterResult !== false) {\n result.push(filterResult);\n }\n }\n\n return result;\n}\n\nexport type FilterAndMapReturn<T> = false | T;\n\ntype SortOrder = 'desc' | 'asc';\n\n/**\n * Sort an array based on a value\n *\n * Sort by `ascending` order by default\n *\n * Use `Infinity` as as wildcard to absulute max and min values\n *\n * @example\n * const items = [1, 3, 2, 4];\n *\n * const sortedItems = sortBy(items, (item) => item);\n * // [1, 2, 3, 4]\n *\n * const items2 = [{ a: 1, b: 2 }, { a: 2, b: 1 }, { a: 1, b: 1}]\n *\n * // return a array to sort by multiple values\n * const sortedItems = sortBy(items, (item) => [item.a, item.b]);\n **/\nexport function sortBy<T>(\n arr: T[],\n sortByValue: (item: T) => (number | string)[] | number | string,\n { order = 'asc' }: { order?: SortOrder | SortOrder[] } = {},\n) {\n return [...arr].sort((a, b) => {\n const _aPriority = sortByValue(a);\n const _bPriority = sortByValue(b);\n\n const aPriority = Array.isArray(_aPriority) ? _aPriority : [_aPriority];\n const bPriority = Array.isArray(_bPriority) ? _bPriority : [_bPriority];\n\n for (let i = 0; i < aPriority.length; i++) {\n const levelOrder: SortOrder =\n typeof order === 'string' ? order : order[i] ?? 'asc';\n\n const aP = aPriority[i] ?? 0;\n const bP = bPriority[i] ?? 0;\n\n if (aP === bP) {\n continue;\n }\n\n if (bP === Infinity || aP === -Infinity || aP < bP) {\n return levelOrder === 'asc' ? -1 : 1;\n }\n\n if (aP === Infinity || bP === -Infinity || aP > bP) {\n return levelOrder === 'asc' ? 1 : -1;\n }\n }\n\n return 0;\n });\n}\n\nexport function arrayWithPrev<T>(array: T[]): [current: T, prev: T | null][] {\n return array.map((item, i) => [item, array[i - 1] ?? null]);\n}\n\nexport function arrayWithPrevAndIndex<T>(\n array: T[],\n): { item: T; prev: T | null; index: number }[] {\n return array.map((item, i) => ({\n item,\n prev: array[i - 1] ?? null,\n index: i,\n }));\n}\n"],"mappings":";AAkBO,SAAS,aACd,OACA,WACK;AACL,QAAM,SAAc,CAAC;AAErB,MAAI,IAAI;AACR,aAAW,QAAQ,OAAO;AACxB,SAAK;AACL,UAAM,eAAe,UAAU,MAAM,CAAC;AAEtC,QAAI,iBAAiB,OAAO;AAC1B,aAAO,KAAK,YAAY;AAAA,IAC1B;AAAA,EACF;AAEA,SAAO;AACT;AAwBO,SAAS,OACd,KACA,aACA,EAAE,QAAQ,MAAM,IAAyC,CAAC,GAC1D;AACA,SAAO,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,GAAG,MAAM;AAC7B,UAAM,aAAa,YAAY,CAAC;AAChC,UAAM,aAAa,YAAY,CAAC;AAEhC,UAAM,YAAY,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AACtE,UAAM,YAAY,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAEtE,aAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,YAAM,aACJ,OAAO,UAAU,WAAW,QAAQ,MAAM,CAAC,KAAK;AAElD,YAAM,KAAK,UAAU,CAAC,KAAK;AAC3B,YAAM,KAAK,UAAU,CAAC,KAAK;AAE3B,UAAI,OAAO,IAAI;AACb;AAAA,MACF;AAEA,UAAI,OAAO,YAAY,OAAO,aAAa,KAAK,IAAI;AAClD,eAAO,eAAe,QAAQ,KAAK;AAAA,MACrC;AAEA,UAAI,OAAO,YAAY,OAAO,aAAa,KAAK,IAAI;AAClD,eAAO,eAAe,QAAQ,IAAI;AAAA,MACpC;AAAA,IACF;AAEA,WAAO;AAAA,EACT,CAAC;AACH;AAEO,SAAS,cAAiB,OAA4C;AAC3E,SAAO,MAAM,IAAI,CAAC,MAAM,MAAM,CAAC,MAAM,MAAM,IAAI,CAAC,KAAK,IAAI,CAAC;AAC5D;AAEO,SAAS,sBACd,OAC8C;AAC9C,SAAO,MAAM,IAAI,CAAC,MAAM,OAAO;AAAA,IAC7B;AAAA,IACA,MAAM,MAAM,IAAI,CAAC,KAAK;AAAA,IACtB,OAAO;AAAA,EACT,EAAE;AACJ;","names":[]}
@@ -0,0 +1,9 @@
1
+ // src/sleep.ts
2
+ function sleep(ms) {
3
+ return new Promise((resolve) => setTimeout(resolve, ms));
4
+ }
5
+
6
+ export {
7
+ sleep
8
+ };
9
+ //# sourceMappingURL=chunk-HLFWWIDK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sleep.ts"],"sourcesContent":["export function sleep(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n"],"mappings":";AAAO,SAAS,MAAM,IAAY;AAChC,SAAO,IAAI,QAAQ,aAAW,WAAW,SAAS,EAAE,CAAC;AACvD;","names":[]}
@@ -0,0 +1,218 @@
1
+ import {
2
+ joinStrings
3
+ } from "./chunk-4DRNU53E.js";
4
+ import {
5
+ isObject
6
+ } from "./chunk-JT3EBBCA.js";
7
+
8
+ // src/rsResult.ts
9
+ function okUnwrapOr() {
10
+ return this.value;
11
+ }
12
+ function ok(value = void 0) {
13
+ return {
14
+ ok: true,
15
+ error: false,
16
+ value,
17
+ unwrapOrNull: okUnwrapOr,
18
+ unwrapOr: okUnwrapOr,
19
+ unwrap: okUnwrapOr
20
+ };
21
+ }
22
+ function err(error) {
23
+ return {
24
+ ok: false,
25
+ error,
26
+ unwrapOrNull: () => null,
27
+ unwrapOr: (defaultValue) => defaultValue,
28
+ errorResult() {
29
+ return err(error);
30
+ },
31
+ normalizedErrorResult(normalizedErr2) {
32
+ return err(
33
+ "withMetadata" in normalizedErr2 && error instanceof NormalizedError ? new NormalizedErrorWithMetadata({
34
+ error,
35
+ metadata: {
36
+ ...error.metadata,
37
+ ...normalizedErr2.withMetadata
38
+ }
39
+ }) : new NormalizedError({
40
+ id: normalizedErr2.id,
41
+ message: normalizedErr2.message,
42
+ code: normalizedErr2.code,
43
+ cause: error instanceof Error ? error : void 0
44
+ })
45
+ );
46
+ },
47
+ unwrap: () => {
48
+ throw error;
49
+ }
50
+ };
51
+ }
52
+ function normalizedUnknownErr(error) {
53
+ return err(normalizeError(error));
54
+ }
55
+ function normalizedErr(idOrMessageOrErr, message) {
56
+ if (typeof idOrMessageOrErr === "object") {
57
+ return err(
58
+ new NormalizedError({
59
+ id: idOrMessageOrErr.id,
60
+ message: idOrMessageOrErr.message,
61
+ code: idOrMessageOrErr.code,
62
+ cause: idOrMessageOrErr.cause,
63
+ metadata: idOrMessageOrErr.metadata
64
+ })
65
+ );
66
+ }
67
+ if (message !== void 0) {
68
+ return err(
69
+ new NormalizedError({
70
+ id: idOrMessageOrErr,
71
+ message
72
+ })
73
+ );
74
+ }
75
+ return err(
76
+ new NormalizedError({
77
+ id: "unknown",
78
+ message: idOrMessageOrErr
79
+ })
80
+ );
81
+ }
82
+ async function unwrap(result) {
83
+ const unwrapped = await result;
84
+ if (unwrapped.ok) {
85
+ return unwrapped.value;
86
+ }
87
+ throw unwrapped.error;
88
+ }
89
+ var Result = {
90
+ ok,
91
+ err,
92
+ normalizedErr,
93
+ normalizedUnknownErr,
94
+ unwrap
95
+ };
96
+ function resultify(fn, errorNormalizer) {
97
+ try {
98
+ return ok(fn());
99
+ } catch (error) {
100
+ return err(
101
+ errorNormalizer ? errorNormalizer(error) : normalizeError(error)
102
+ );
103
+ }
104
+ }
105
+ async function asyncResultify(fn, errorNormalizer) {
106
+ try {
107
+ return ok(await fn());
108
+ } catch (error) {
109
+ return err(
110
+ errorNormalizer ? errorNormalizer(error) : normalizeError(error)
111
+ );
112
+ }
113
+ }
114
+ var normalizedErrorSideEffects = void 0;
115
+ function setNormalizedErrorSideEffects(callback) {
116
+ normalizedErrorSideEffects = callback;
117
+ }
118
+ var NormalizedError = class extends Error {
119
+ id;
120
+ metadata;
121
+ cause;
122
+ code;
123
+ constructor({
124
+ id,
125
+ message,
126
+ metadata,
127
+ cause,
128
+ code = 0
129
+ }) {
130
+ super(message);
131
+ this.id = id;
132
+ this.name = "NormalizedError";
133
+ this.metadata = metadata;
134
+ this.cause = cause;
135
+ this.code = code;
136
+ setTimeout(() => {
137
+ if (normalizedErrorSideEffects) {
138
+ normalizedErrorSideEffects(this);
139
+ }
140
+ }, 1);
141
+ }
142
+ toString() {
143
+ return joinStrings(
144
+ !!this.code && `${this.code}#`,
145
+ String(this.id),
146
+ `: ${this.message}`,
147
+ !!this.cause && `
148
+ Caused by: ${this.cause}`,
149
+ !!this.metadata && `
150
+ Metadata: ${JSON.stringify(this.metadata)}`
151
+ );
152
+ }
153
+ toJSON() {
154
+ return {
155
+ id: this.id,
156
+ message: this.message,
157
+ metadata: this.metadata,
158
+ code: this.code,
159
+ cause: this.cause ? "toJSON" in this.cause ? this.cause : String(this.cause) : void 0
160
+ };
161
+ }
162
+ };
163
+ var NormalizedErrorWithMetadata = class extends NormalizedError {
164
+ metadata;
165
+ constructor(props) {
166
+ if ("error" in props) {
167
+ super({
168
+ id: props.error.id,
169
+ message: props.error.message,
170
+ cause: props.error.cause
171
+ });
172
+ this.metadata = props.metadata;
173
+ this.stack = props.error.stack;
174
+ } else {
175
+ super(props);
176
+ this.metadata = props.metadata;
177
+ }
178
+ }
179
+ };
180
+ function normalizeError(error) {
181
+ if (error instanceof NormalizedError)
182
+ return error;
183
+ if (typeof error === "string") {
184
+ return new NormalizedError({
185
+ id: "unknown",
186
+ message: error
187
+ });
188
+ }
189
+ if (error instanceof Error) {
190
+ return new NormalizedError({
191
+ id: error.name,
192
+ message: error.message,
193
+ cause: error
194
+ });
195
+ }
196
+ if (isObject(error)) {
197
+ return new NormalizedError({
198
+ id: "id" in error ? String(error.id) : "unknown",
199
+ message: "message" in error ? String(error.message) : JSON.stringify(error),
200
+ metadata: error
201
+ });
202
+ }
203
+ return new NormalizedError({
204
+ message: JSON.stringify(error),
205
+ id: "unknown"
206
+ });
207
+ }
208
+
209
+ export {
210
+ Result,
211
+ resultify,
212
+ asyncResultify,
213
+ setNormalizedErrorSideEffects,
214
+ NormalizedError,
215
+ NormalizedErrorWithMetadata,
216
+ normalizeError
217
+ };
218
+ //# sourceMappingURL=chunk-HYFUWQ2E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rsResult.ts"],"sourcesContent":["import { isObject } from './assertions';\nimport { joinStrings } from './stringUtils';\n\ntype Ok<T> = {\n ok: true;\n error: false;\n value: T;\n};\n\ntype NormalizedErrorResultProps = {\n id: string;\n message: string;\n code?: number;\n metadata?: ValidErrorMetadata;\n};\n\ntype IsExactlyAny<T> =\n boolean extends (T extends never ? true : false) ? true : false;\n\ntype Err<E extends ResultValidErrors> = {\n ok: false;\n error: E;\n errorResult: () => Result<any, E>;\n normalizedErrorResult: (\n normalizedErr: E extends NormalizedError ?\n { withMetadata: ValidErrorMetadata } | NormalizedErrorResultProps\n : NormalizedErrorResultProps,\n ) => Result<any, NormalizedError>;\n};\n\ntype Unwrap<E, T> =\n IsExactlyAny<E> extends true ? any\n : E extends Error ? () => T\n : unknown;\n\ntype ResultMethods<T, E> = {\n /** Returns the value if the result is Ok, otherwise returns null */\n unwrapOrNull: () => T | null;\n /** Returns the value if the result is Ok, otherwise returns the provided default value */\n unwrapOr: <R extends T>(defaultValue: R) => T | R;\n unwrap: Unwrap<E, T>;\n};\n\n/**\n * Util for implementing something similar to Result<T, E> in Rust, for better error handling.\n *\n * Usage:\n *\n * @example\n * function doSomething(): Result<string, Error> {\n * if (something) {\n * return ok('success');\n * }\n *\n * return err(new Error('something went wrong'));\n * }\n *\n * const result = doSomething();\n *\n * if (result.ok) {\n * // result.value is a string\n * } else {\n * // result.error is an Error\n * }\n */\nexport type Result<T, E extends ResultValidErrors = NormalizedError> =\n | OkResult<T, E, T>\n | ErrResult<E, T>;\n\nfunction okUnwrapOr<T>(this: Ok<T>) {\n return this.value;\n}\n\ntype OkResult<T, E extends ResultValidErrors, M = any> = Ok<T> &\n ResultMethods<M, E>;\n\ntype ResultValidErrors = Error | Record<string, unknown> | [string];\n\nfunction ok(): OkResult<void, any>;\nfunction ok<T>(value: T): OkResult<T, any>;\nfunction ok(value: any = undefined): OkResult<any, any> {\n return {\n ok: true,\n error: false,\n value,\n unwrapOrNull: okUnwrapOr,\n unwrapOr: okUnwrapOr,\n unwrap: okUnwrapOr,\n };\n}\n\ntype ErrResult<E extends ResultValidErrors, T = any> = Err<E> &\n ResultMethods<T, E>;\n\nfunction err<E extends ResultValidErrors>(error: E): ErrResult<E> {\n return {\n ok: false,\n error,\n unwrapOrNull: () => null,\n unwrapOr: (defaultValue) => defaultValue,\n errorResult() {\n return err(error);\n },\n normalizedErrorResult(normalizedErr) {\n return err(\n 'withMetadata' in normalizedErr && error instanceof NormalizedError ?\n new NormalizedErrorWithMetadata({\n error,\n metadata: {\n ...error.metadata,\n ...normalizedErr.withMetadata,\n },\n })\n : new NormalizedError({\n id: (normalizedErr as NormalizedErrorResultProps).id,\n message: (normalizedErr as NormalizedErrorResultProps).message,\n code: (normalizedErr as NormalizedErrorResultProps).code,\n cause: error instanceof Error ? error : undefined,\n }),\n );\n },\n unwrap: (() => {\n throw error;\n }) as any,\n };\n}\n\nfunction normalizedUnknownErr(error: unknown) {\n return err(normalizeError(error));\n}\n\nfunction normalizedErr(message: string): ErrResult<NormalizedError>;\nfunction normalizedErr<T extends string>(\n id: T,\n message: string,\n): ErrResult<NormalizedError<T>>;\nfunction normalizedErr<T extends string>(errorProps: {\n id: T;\n message: string;\n code?: number;\n cause?: Error;\n metadata?: ValidErrorMetadata;\n}): ErrResult<NormalizedError<T>>;\nfunction normalizedErr(\n idOrMessageOrErr:\n | string\n | {\n id: string;\n message: string;\n code?: number;\n metadata?: ValidErrorMetadata;\n cause?: Error;\n },\n message?: string,\n): ErrResult<NormalizedError> {\n if (typeof idOrMessageOrErr === 'object') {\n return err(\n new NormalizedError({\n id: idOrMessageOrErr.id,\n message: idOrMessageOrErr.message,\n code: idOrMessageOrErr.code,\n cause: idOrMessageOrErr.cause,\n metadata: idOrMessageOrErr.metadata,\n }),\n );\n }\n\n if (message !== undefined) {\n return err(\n new NormalizedError({\n id: idOrMessageOrErr,\n message,\n }),\n );\n }\n\n return err(\n new NormalizedError({\n id: 'unknown',\n message: idOrMessageOrErr,\n }),\n );\n}\n\n/** Unwraps a promise result */\nasync function unwrap<T>(result: Promise<Result<T, Error>>): Promise<T> {\n const unwrapped = await result;\n\n if (unwrapped.ok) {\n return unwrapped.value;\n }\n\n throw unwrapped.error;\n}\n\nexport const Result = {\n ok,\n err,\n normalizedErr,\n normalizedUnknownErr,\n unwrap,\n};\n\n/** transfor a function in a result function */\nexport function resultify<T, E extends ResultValidErrors = NormalizedError>(\n fn: () => T,\n errorNormalizer?: (err: unknown) => E,\n): Result<T, E> {\n try {\n return ok(fn());\n } catch (error) {\n return err(\n errorNormalizer ?\n errorNormalizer(error)\n : (normalizeError(error) as unknown as E),\n );\n }\n}\n\n/** transform a async function in a result function */\nexport async function asyncResultify<T, E extends Error = NormalizedError>(\n fn: () => Promise<T>,\n errorNormalizer?: (err: unknown) => E,\n): Promise<Result<Awaited<T>, E>> {\n try {\n return ok(await fn());\n } catch (error) {\n return err(\n errorNormalizer ?\n errorNormalizer(error)\n : (normalizeError(error) as unknown as E),\n );\n }\n}\n\nexport type ValidErrorMetadata = Record<string, unknown> | undefined;\n\nlet normalizedErrorSideEffects:\n | ((normalizedError: NormalizedError) => void)\n | undefined = undefined;\n\nexport function setNormalizedErrorSideEffects(\n callback: (normalizedError: NormalizedError) => void,\n) {\n normalizedErrorSideEffects = callback;\n}\n\nexport class NormalizedError<T = string> extends Error {\n id: T;\n metadata?: ValidErrorMetadata;\n cause?: Error;\n code: number;\n\n constructor({\n id,\n message,\n metadata,\n cause,\n code = 0,\n }: {\n id: T;\n message: string;\n metadata?: ValidErrorMetadata;\n cause?: Error;\n code?: number;\n }) {\n super(message);\n this.id = id;\n this.name = 'NormalizedError';\n this.metadata = metadata;\n this.cause = cause;\n this.code = code;\n\n setTimeout(() => {\n if (normalizedErrorSideEffects) {\n normalizedErrorSideEffects(this as NormalizedError);\n }\n }, 1);\n }\n\n toString() {\n return joinStrings(\n !!this.code && `${this.code}#`,\n String(this.id),\n `: ${this.message}`,\n !!this.cause && `\\n Caused by: ${this.cause}`,\n !!this.metadata && `\\n Metadata: ${JSON.stringify(this.metadata)}`,\n );\n }\n\n toJSON() {\n return {\n id: this.id,\n message: this.message,\n metadata: this.metadata,\n code: this.code,\n cause:\n this.cause ?\n 'toJSON' in this.cause ?\n this.cause\n : String(this.cause)\n : undefined,\n };\n }\n}\n\nexport class NormalizedErrorWithMetadata<\n M extends ValidErrorMetadata,\n T = string,\n> extends NormalizedError<T> {\n metadata: M;\n\n constructor(\n props:\n | {\n id: T;\n message: string;\n metadata: M;\n cause?: Error;\n }\n | {\n error: NormalizedError<T>;\n metadata: M;\n },\n ) {\n if ('error' in props) {\n super({\n id: props.error.id,\n message: props.error.message,\n cause: props.error.cause,\n });\n this.metadata = props.metadata;\n this.stack = props.error.stack;\n } else {\n super(props);\n this.metadata = props.metadata;\n }\n }\n}\n\nexport function normalizeError(error: unknown): NormalizedError {\n if (error instanceof NormalizedError) return error;\n\n if (typeof error === 'string') {\n return new NormalizedError({\n id: 'unknown',\n message: error,\n });\n }\n\n if (error instanceof Error) {\n return new NormalizedError({\n id: error.name,\n message: error.message,\n cause: error,\n });\n }\n\n if (isObject(error)) {\n return new NormalizedError({\n id: 'id' in error ? String(error.id) : 'unknown',\n message:\n 'message' in error ? String(error.message) : JSON.stringify(error),\n metadata: error,\n });\n }\n\n return new NormalizedError({\n message: JSON.stringify(error),\n id: 'unknown',\n });\n}\n"],"mappings":";;;;;;;;AAqEA,SAAS,aAA2B;AAClC,SAAO,KAAK;AACd;AASA,SAAS,GAAG,QAAa,QAA+B;AACtD,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,OAAO;AAAA,IACP;AAAA,IACA,cAAc;AAAA,IACd,UAAU;AAAA,IACV,QAAQ;AAAA,EACV;AACF;AAKA,SAAS,IAAiC,OAAwB;AAChE,SAAO;AAAA,IACL,IAAI;AAAA,IACJ;AAAA,IACA,cAAc,MAAM;AAAA,IACpB,UAAU,CAAC,iBAAiB;AAAA,IAC5B,cAAc;AACZ,aAAO,IAAI,KAAK;AAAA,IAClB;AAAA,IACA,sBAAsBA,gBAAe;AACnC,aAAO;AAAA,QACL,kBAAkBA,kBAAiB,iBAAiB,kBAClD,IAAI,4BAA4B;AAAA,UAC9B;AAAA,UACA,UAAU;AAAA,YACR,GAAG,MAAM;AAAA,YACT,GAAGA,eAAc;AAAA,UACn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