@fgv/ts-utils 5.0.0-22 → 5.0.0-23

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 (80) hide show
  1. package/dist/ts-utils.d.ts +307 -33
  2. package/lib/index.d.ts +2 -1
  3. package/lib/index.js +3 -1
  4. package/lib/packlets/base/index.d.ts +0 -2
  5. package/lib/packlets/base/index.js +1 -25
  6. package/lib/packlets/base/result.d.ts +49 -0
  7. package/lib/packlets/base/result.js +36 -0
  8. package/lib/packlets/collections/collector.d.ts +9 -0
  9. package/lib/packlets/collections/collector.js +6 -0
  10. package/lib/packlets/collections/validatingCollector.d.ts +5 -1
  11. package/lib/packlets/hash/hashingNormalizer.js +4 -3
  12. package/lib/packlets/logging/index.d.ts +3 -0
  13. package/{src/packlets/hash/index.ts → lib/packlets/logging/index.js} +19 -3
  14. package/lib/packlets/logging/logReporter.d.ts +69 -0
  15. package/lib/packlets/logging/logReporter.js +72 -0
  16. package/lib/packlets/logging/logger.d.ts +183 -0
  17. package/lib/packlets/logging/logger.js +237 -0
  18. package/lib/test/unit/consoleLogger.test.d.ts +2 -0
  19. package/lib/test/unit/hashingNormalizerCollisions.test.d.ts +2 -0
  20. package/package.json +1 -1
  21. package/lib/packlets/base/logger.d.ts +0 -52
  22. package/lib/packlets/base/logger.js +0 -128
  23. package/src/index.ts +0 -63
  24. package/src/packlets/base/brand.ts +0 -28
  25. package/src/packlets/base/index.ts +0 -31
  26. package/src/packlets/base/logger.ts +0 -156
  27. package/src/packlets/base/mapResults.ts +0 -302
  28. package/src/packlets/base/messageAggregator.ts +0 -120
  29. package/src/packlets/base/normalize.ts +0 -144
  30. package/src/packlets/base/result.ts +0 -961
  31. package/src/packlets/base/utils.ts +0 -236
  32. package/src/packlets/collections/collectible.ts +0 -238
  33. package/src/packlets/collections/collector.ts +0 -273
  34. package/src/packlets/collections/collectorValidator.ts +0 -178
  35. package/src/packlets/collections/common.ts +0 -27
  36. package/src/packlets/collections/convertingCollector.ts +0 -223
  37. package/src/packlets/collections/convertingCollectorValidator.ts +0 -164
  38. package/src/packlets/collections/index.ts +0 -39
  39. package/src/packlets/collections/keyValueConverters.ts +0 -142
  40. package/src/packlets/collections/readonlyResultMap.ts +0 -99
  41. package/src/packlets/collections/resultMap.ts +0 -322
  42. package/src/packlets/collections/resultMapValidator.ts +0 -188
  43. package/src/packlets/collections/utils.ts +0 -33
  44. package/src/packlets/collections/validatingCollector.ts +0 -123
  45. package/src/packlets/collections/validatingConvertingCollector.ts +0 -113
  46. package/src/packlets/collections/validatingResultMap.ts +0 -94
  47. package/src/packlets/conversion/baseConverter.ts +0 -330
  48. package/src/packlets/conversion/converter.ts +0 -260
  49. package/src/packlets/conversion/converters.ts +0 -1039
  50. package/src/packlets/conversion/defaultingConverter.ts +0 -188
  51. package/src/packlets/conversion/index.ts +0 -30
  52. package/src/packlets/conversion/objectConverter.ts +0 -259
  53. package/src/packlets/conversion/stringConverter.ts +0 -165
  54. package/src/packlets/file-tree/directoryItem.ts +0 -84
  55. package/src/packlets/file-tree/fileItem.ts +0 -119
  56. package/src/packlets/file-tree/fileTree.ts +0 -152
  57. package/src/packlets/file-tree/fileTreeAccessors.ts +0 -176
  58. package/src/packlets/file-tree/fsTree.ts +0 -118
  59. package/src/packlets/file-tree/in-memory/inMemoryTree.ts +0 -171
  60. package/src/packlets/file-tree/in-memory/index.ts +0 -23
  61. package/src/packlets/file-tree/in-memory/treeBuilder.ts +0 -203
  62. package/src/packlets/file-tree/index.ts +0 -31
  63. package/src/packlets/hash/crcNormalizer.ts +0 -81
  64. package/src/packlets/hash/hashingNormalizer.ts +0 -102
  65. package/src/packlets/validation/array.ts +0 -84
  66. package/src/packlets/validation/boolean.ts +0 -63
  67. package/src/packlets/validation/classes.ts +0 -38
  68. package/src/packlets/validation/common.ts +0 -28
  69. package/src/packlets/validation/field.ts +0 -99
  70. package/src/packlets/validation/genericValidator.ts +0 -204
  71. package/src/packlets/validation/index.ts +0 -31
  72. package/src/packlets/validation/number.ts +0 -66
  73. package/src/packlets/validation/object.ts +0 -208
  74. package/src/packlets/validation/oneOf.ts +0 -78
  75. package/src/packlets/validation/string.ts +0 -66
  76. package/src/packlets/validation/traits.ts +0 -113
  77. package/src/packlets/validation/typeGuard.ts +0 -83
  78. package/src/packlets/validation/validator.ts +0 -157
  79. package/src/packlets/validation/validatorBase.ts +0 -66
  80. package/src/packlets/validation/validators.ts +0 -254
@@ -1,156 +0,0 @@
1
- /*
2
- * Copyright (c) 2020 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
- import { Failure, Success, fail, succeed } from './result';
23
-
24
- /**
25
- * @public
26
- */
27
- export type LogLevel = 'detail' | 'info' | 'warning' | 'error' | 'silent';
28
-
29
- /**
30
- * @public
31
- */
32
- // eslint-disable-next-line @typescript-eslint/naming-convention
33
- export interface Logger {
34
- log(message?: unknown, ...parameters: unknown[]): Success<string | undefined>;
35
- detail(message?: unknown, ...parameters: unknown[]): Success<string | undefined>;
36
- info(message?: unknown, ...parameters: unknown[]): Success<string | undefined>;
37
- warn(message?: unknown, ...parameters: unknown[]): Success<string | undefined>;
38
- warnAndFail<T>(message?: unknown, ...parameters: unknown[]): Failure<T>;
39
- error<T>(message?: unknown, ...parameters: unknown[]): Failure<T>;
40
- }
41
-
42
- /**
43
- * @public
44
- */
45
- export abstract class LoggerBase {
46
- public logLevel: LogLevel = 'info';
47
-
48
- public constructor(logLevel?: LogLevel) {
49
- this.logLevel = logLevel ?? 'info';
50
- }
51
-
52
- public detail(message?: unknown, ...parameters: unknown[]): Success<string | undefined> {
53
- if (this.logLevel === 'detail') {
54
- return this.log(message, parameters);
55
- }
56
- return succeed(undefined);
57
- }
58
-
59
- public info(message?: unknown, ...parameters: unknown[]): Success<string | undefined> {
60
- if (this.logLevel === 'detail' || this.logLevel === 'info') {
61
- return this.log(message, parameters);
62
- }
63
- return succeed(undefined);
64
- }
65
-
66
- public warn(message?: unknown, ...parameters: unknown[]): Success<string | undefined> {
67
- if (this.logLevel !== 'error' && this.logLevel !== 'silent') {
68
- return this.log(message, parameters);
69
- }
70
- return succeed(undefined);
71
- }
72
-
73
- public warnAndFail<T>(message?: unknown, ...parameters: unknown[]): Failure<T> {
74
- const formatted = this._format(message, ...parameters);
75
- if (this.logLevel !== 'error' && this.logLevel !== 'silent') {
76
- const result = this.log(formatted);
77
- return fail(result.value ?? formatted);
78
- }
79
- return fail(formatted);
80
- }
81
-
82
- public error<T>(message?: unknown, ...parameters: unknown[]): Failure<T> {
83
- const formatted = this._format(message, ...parameters);
84
- if (this.logLevel !== 'silent') {
85
- const result = this.log(formatted);
86
- return fail(result.value ?? formatted);
87
- }
88
- return fail(formatted);
89
- }
90
-
91
- public log(message?: unknown, ...parameters: unknown[]): Success<string | undefined> {
92
- const messageString = this._format(message, ...parameters);
93
- if (this.logLevel === 'silent') {
94
- return this._innerSilent(messageString);
95
- }
96
- return this._innerLog(messageString);
97
- }
98
-
99
- protected _format(message?: unknown, ...parameters: unknown[]): string {
100
- const raw = [message, ...parameters];
101
- const filtered = raw.filter((m): m is string => m !== undefined);
102
- const strings = filtered.map((m) => m.toString());
103
- const joined = strings.join('');
104
- return joined;
105
- }
106
-
107
- protected _innerSilent(__message: string): Success<string | undefined> {
108
- return succeed(undefined);
109
- }
110
-
111
- protected abstract _innerLog(message: string): Success<string | undefined>;
112
- }
113
-
114
- /**
115
- * @public
116
- */
117
- export class InMemoryLogger extends LoggerBase {
118
- protected _messages: string[] = [];
119
- protected _silent: string[] = [];
120
-
121
- public constructor(logLevel?: LogLevel) {
122
- super(logLevel);
123
- }
124
-
125
- public get messages(): string[] {
126
- return this._messages;
127
- }
128
- public get silent(): string[] {
129
- return this._silent;
130
- }
131
-
132
- public clear(): void {
133
- this._messages = [];
134
- this._silent = [];
135
- }
136
-
137
- protected _innerLog(message: string): Success<string | undefined> {
138
- this._messages.push(message);
139
- return succeed(message);
140
- }
141
-
142
- protected _innerSilent(message: string): Success<string | undefined> {
143
- this._silent.push(message);
144
- return succeed(undefined);
145
- }
146
- }
147
-
148
- /**
149
- * @public
150
- */
151
- export class NoOpLogger extends LoggerBase {
152
- protected _innerLog(message: string): Success<string | undefined> {
153
- // no-op
154
- return succeed(message);
155
- }
156
- }
@@ -1,302 +0,0 @@
1
- /*
2
- * Copyright (c) 2020 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { DetailedResult, IMessageAggregator, Result, fail, succeed } from './result';
24
-
25
- /**
26
- * Aggregates successful result values from a collection of {@link Result | Result<T>}.
27
- * @param results - The collection of {@link Result | Result<T>} to be mapped.
28
- * @param aggregatedErrors - Optional string array to which any error messages will be
29
- * appended. Each error is appended as an individual string.
30
- * @returns If all {@link Result | results} are successful, returns {@link Success} with an
31
- * array containing all returned values. If any {@link Result | results} failed, returns
32
- * {@link Failure} with a concatenated summary of all error messages.
33
- * @public
34
- */
35
- export function mapResults<T>(
36
- results: Iterable<Result<T>>,
37
- aggregatedErrors?: IMessageAggregator
38
- ): Result<T[]> {
39
- const errors: string[] = [];
40
- const elements: T[] = [];
41
-
42
- for (const result of results) {
43
- if (result.isSuccess()) {
44
- elements.push(result.value);
45
- } else {
46
- errors.push(result.message);
47
- }
48
- }
49
-
50
- if (errors.length > 0) {
51
- aggregatedErrors?.addMessages(errors);
52
- return fail(errors.join('\n'));
53
- }
54
- return succeed(elements);
55
- }
56
-
57
- /**
58
- * Aggregates successful results from a collection of {@link DetailedResult | DetailedResult<T, TD>},
59
- * optionally ignoring certain error details.
60
- * @param results - The collection of {@link DetailedResult | DetailedResult<T, TD>} to be mapped.
61
- * @param ignore - An array of error detail values (of type `<TD>`) that should be ignored.
62
- * @param aggregatedErrors - Optional string array to which any non-ignorable error messages will be
63
- * appended. Each error is appended as an individual string.
64
- * @returns {@link Success} with an array containing all successful results if all results either
65
- * succeeded or returned error details listed in `ignore`. If any results failed with details
66
- * that cannot be ignored, returns {@link Failure} with an concatenated summary of all non-ignorable
67
- * error messages.
68
- * @public
69
- */
70
- export function mapDetailedResults<T, TD>(
71
- results: Iterable<DetailedResult<T, TD>>,
72
- ignore: TD[],
73
- aggregatedErrors?: IMessageAggregator
74
- ): Result<T[]> {
75
- const errors: string[] = [];
76
- const elements: T[] = [];
77
-
78
- for (const result of results) {
79
- if (result.isSuccess()) {
80
- elements.push(result.value);
81
- } else if (result.detail && !ignore.includes(result.detail)) {
82
- errors.push(result.message);
83
- }
84
- }
85
-
86
- if (errors.length > 0) {
87
- aggregatedErrors?.addMessages(errors);
88
- return fail(errors.join('\n'));
89
- }
90
- return succeed(elements);
91
- }
92
-
93
- /**
94
- * Aggregates successful results from a a collection of {@link Result | Result<T>}.
95
- * @param results - An `Iterable` of {@link Result | Result<T>} from which success
96
- * results are to be aggregated.
97
- * @param aggregatedErrors - Optional string array to which any returned error messages will be
98
- * appended. Each error is appended as an individual string.
99
- * @returns {@link Success} with an array of `<T>` if any results were successful. If
100
- * all {@link Result | results} failed, returns {@link Failure} with a concatenated
101
- * summary of all error messages.
102
- * @public
103
- */
104
- export function mapSuccess<T>(
105
- results: Iterable<Result<T>>,
106
- aggregatedErrors?: IMessageAggregator
107
- ): Result<T[]> {
108
- const errors: string[] = [];
109
- const elements: T[] = [];
110
-
111
- for (const result of results) {
112
- if (result.isSuccess()) {
113
- elements.push(result.value);
114
- } else {
115
- errors.push(result.message);
116
- }
117
- }
118
-
119
- if (elements.length === 0 && errors.length > 0) {
120
- aggregatedErrors?.addMessages(errors);
121
- return fail(errors.join('\n'));
122
- }
123
- return succeed(elements);
124
- }
125
-
126
- /**
127
- * Aggregates error messages from a collection of {@link Result | Result<T>}.
128
- * @param results - An iterable collection of {@link Result | Result<T>} for which
129
- * error messages are aggregated.
130
- * @param aggregatedErrors - Optional string array to which any returned error messages will be
131
- * appended. Each error is appended as an individual string.
132
- * @returns An array of strings consisting of all error messages returned by
133
- * {@link Result | results} in the source collection. Ignores {@link Success}
134
- * results and returns an empty array if there were no errors.
135
- * @public
136
- */
137
- export function mapFailures<T>(
138
- results: Iterable<Result<T>>,
139
- aggregatedErrors?: IMessageAggregator
140
- ): string[] {
141
- const errors: string[] = [];
142
- for (const result of results) {
143
- if (result.isFailure()) {
144
- errors.push(result.message);
145
- aggregatedErrors?.addMessage(result.message);
146
- }
147
- }
148
- return errors;
149
- }
150
-
151
- /**
152
- * Determines if an iterable collection of {@link Result | Result<T>} were all successful.
153
- * @param results - The collection of {@link Result | Result<T>} to be tested.
154
- * @param successValue - The value to be returned if results are successful.
155
- * @param aggregatedErrors - Optional string array to which any returned error messages will be
156
- * appended. Each error is appended as an individual string.
157
- * @returns Returns {@link Success} with `successValue` if all {@link Result | results} are successful.
158
- * If any are unsuccessful, returns {@link Failure} with a concatenated summary of the error
159
- * messages from all failed elements.
160
- * @public
161
- */
162
- export function allSucceed<T>(
163
- results: Iterable<Result<unknown>>,
164
- successValue: T,
165
- aggregatedErrors?: IMessageAggregator
166
- ): Result<T> {
167
- const errors: string[] = [];
168
-
169
- if (results !== undefined) {
170
- for (const result of results) {
171
- if (result.isFailure()) {
172
- errors.push(result.message);
173
- }
174
- }
175
- }
176
-
177
- if (errors.length > 0) {
178
- aggregatedErrors?.addMessages(errors);
179
- return fail(errors.join('\n'));
180
- }
181
- return succeed(successValue);
182
- }
183
-
184
- /**
185
- * String-keyed record of initialization functions to be passed to {@link (populateObject:1)}
186
- * or {@link (populateObject:2)}.
187
- * @public
188
- */
189
- export type FieldInitializers<T> = { [key in keyof T]: (state: Partial<T>) => Result<T[key]> };
190
-
191
- /**
192
- * Options for the {@link (populateObject:1)} function.
193
- * @public
194
- */
195
- // eslint-disable-next-line @typescript-eslint/naming-convention
196
- export interface PopulateObjectOptions<T> {
197
- /**
198
- * If present, specifies the order in which property values should
199
- * be evaluated. Any keys not listed are evaluated after all listed
200
- * keys in indeterminate order. If 'order' is not present, keys
201
- * are evaluated in indeterminate order.
202
- */
203
- order?: (keyof T)[];
204
-
205
- /**
206
- * Specify handling of `undefined` values. By default, successful
207
- * `undefined` results are written to the result object. If this value
208
- * is `true` then `undefined` results are suppressed for all properties.
209
- * If this value is an array of property keys then `undefined` results
210
- * are suppressed for those properties only.
211
- */
212
- suppressUndefined?: boolean | (keyof T)[];
213
- }
214
-
215
- /**
216
- * Populates an an object based on a prototype full of field initializers that return {@link Result | Result<T[key]>}.
217
- * Returns {@link Success} with the populated object if all initializers succeed, or {@link Failure} with a
218
- * concatenated list of all error messages.
219
- * @param initializers - An object with the shape of the target but with initializer functions for
220
- * each property.
221
- * @param options - An optional {@link PopulateObjectOptions | set of options} which
222
- * modify the behavior of this call.
223
- * @param aggregatedErrors - Optional string array to which any returned error messages will be
224
- * appended. Each error is appended as an individual string.
225
- * {@label WITH_OPTIONS}
226
- * @public
227
- */
228
- export function populateObject<T>(
229
- initializers: FieldInitializers<T>,
230
- options?: PopulateObjectOptions<T>,
231
- aggregatedErrors?: IMessageAggregator
232
- ): Result<T>;
233
-
234
- /**
235
- * Populates an an object based on a prototype full of field initializers that return {@link Result | Result<T[key]>}.
236
- * Returns {@link Success} with the populated object if all initializers succeed, or {@link Failure} with a
237
- * concatenated list of all error messages.
238
- * @param initializers - An object with the shape of the target but with initializer functions for
239
- * each property.
240
- * @param order - Optional order in which keys should be written.
241
- * @param aggregatedErrors - Optional string array to which any returned error messages will be
242
- * appended. Each error is appended as an individual string.
243
- * @public
244
- * {@label WITH_ORDER}
245
- * @deprecated Pass {@link PopulateObjectOptions} instead.
246
- */
247
- export function populateObject<T>(
248
- initializers: FieldInitializers<T>,
249
- order: (keyof T)[] | undefined,
250
- aggregatedErrors?: IMessageAggregator
251
- ): Result<T>;
252
-
253
- export function populateObject<T>(
254
- initializers: FieldInitializers<T>,
255
- optionsOrOrder?: PopulateObjectOptions<T> | (keyof T)[],
256
- aggregatedErrors?: IMessageAggregator
257
- ): Result<T> {
258
- const options: PopulateObjectOptions<T> = optionsOrOrder
259
- ? Array.isArray(optionsOrOrder)
260
- ? { order: optionsOrOrder }
261
- : optionsOrOrder
262
- : {};
263
- const state = {} as { [key in keyof T]: T[key] };
264
- const errors: string[] = [];
265
- const keys: (keyof T)[] = Array.from(options.order ?? []);
266
- const foundKeys = new Set<keyof T>(options.order);
267
-
268
- // start with the supplied order then append anything else we find
269
- for (const key in initializers) {
270
- if (!foundKeys.has(key)) {
271
- keys.push(key);
272
- foundKeys.add(key);
273
- }
274
- }
275
-
276
- for (const key of keys) {
277
- if (initializers[key]) {
278
- const result = initializers[key](state);
279
- if (result.isSuccess()) {
280
- if (result.value === undefined) {
281
- if (
282
- options.suppressUndefined === true ||
283
- (Array.isArray(options.suppressUndefined) && options.suppressUndefined.includes(key))
284
- ) {
285
- continue;
286
- }
287
- }
288
- state[key] = result.value;
289
- } else {
290
- errors.push(result.message);
291
- }
292
- } else {
293
- errors.push(`populateObject: Key ${String(key)} is present but has no initializer`);
294
- }
295
- }
296
-
297
- if (errors.length > 0) {
298
- aggregatedErrors?.addMessages(errors);
299
- return fail(errors.join('\n'));
300
- }
301
- return succeed(state as T);
302
- }
@@ -1,120 +0,0 @@
1
- /*
2
- * Copyright (c) 2024 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { IMessageAggregator, Result, fail } from './result';
24
-
25
- /**
26
- * A simple error aggregator to simplify collecting and reporting all errors in
27
- * a flow.
28
- * @public
29
- */
30
- export class MessageAggregator implements IMessageAggregator {
31
- private readonly _messages: string[];
32
-
33
- /**
34
- * Constructs a new {@link MessageAggregator | ErrorAggregator} with an
35
- * optionally specified initial set of error messages.
36
- * @param errors - optional array of errors to be included
37
- * in the aggregation.
38
- */
39
- public constructor(errors?: string[]) {
40
- this._messages = errors ? Array.from(errors) : [];
41
- }
42
-
43
- /**
44
- * {@inheritdoc IMessageAggregator.hasMessages}
45
- */
46
- public get hasMessages(): boolean {
47
- return this._messages.length > 0;
48
- }
49
-
50
- /**
51
- * {@inheritdoc IMessageAggregator.numMessages}
52
- */
53
- public get numMessages(): number {
54
- return this._messages.length;
55
- }
56
-
57
- /**
58
- * {@inheritdoc IMessageAggregator.messages}
59
- */
60
- public get messages(): string[] {
61
- return this._messages;
62
- }
63
-
64
- /**
65
- * {@inheritdoc IMessageAggregator.addMessage}
66
- */
67
- public addMessage(message: string | undefined): this {
68
- if (message) {
69
- this._messages.push(message);
70
- }
71
- return this;
72
- }
73
-
74
- /**
75
- * {@inheritdoc IMessageAggregator.addMessages}
76
- */
77
- public addMessages(messages: string[] | undefined): this {
78
- if (messages && messages.length > 0) {
79
- this._messages.push(...messages);
80
- }
81
- return this;
82
- }
83
-
84
- /**
85
- * {@inheritdoc IMessageAggregator.toString}
86
- */
87
- public toString(separator?: string): string {
88
- return this._messages.join(separator ?? '\n');
89
- }
90
-
91
- /**
92
- * If any error messages have been aggregated, returns
93
- * {@link Failure | Failure<T>} with the aggregated
94
- * messages concatenated using the optionally-supplied
95
- * separator, or newline. If the supplied {@link Result | Result<T>}
96
- * contains an error message that has not already been aggregated,
97
- * it will be included in the aggregated messages.
98
- *
99
- * If no error messages have been aggregated, returns
100
- * the supplied {@link Result | Result<T>}.
101
- * @param result - The {@link Result | Result<T>} to be returned
102
- * if no messages have been aggregated.
103
- * @param separator - Optional string separator used to construct
104
- * the error message.
105
- * @returns {@link Failure | Failure<T>} with an aggregated message
106
- * if any error messages were collected, the supplied
107
- * {@link Result | Result<T>} otherwise.
108
- */
109
- public returnOrReport<T>(result: Result<T>, separator?: string): Result<T> {
110
- if (!this.hasMessages) {
111
- return result;
112
- }
113
- if (!result.success) {
114
- if (!this._messages.find((s) => s === result.message)) {
115
- return fail([...this._messages, result.message].join(separator ?? '\n'));
116
- }
117
- }
118
- return fail(this.toString(separator));
119
- }
120
- }