@fgv/ts-extras 5.0.0-2 → 5.0.0-21

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 (62) hide show
  1. package/.vscode/settings.json +27 -0
  2. package/config/api-extractor.json +343 -0
  3. package/config/rig.json +16 -0
  4. package/dist/ts-extras.d.ts +11 -4
  5. package/dist/tsdoc-metadata.json +1 -1
  6. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +11 -4
  7. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +57 -35
  8. package/lib/test/unit/converters.test.d.ts +2 -0
  9. package/lib/test/unit/csvHelpers.test.d.ts +2 -0
  10. package/lib/test/unit/extendedArray.test.d.ts +2 -0
  11. package/lib/test/unit/formatter.test.d.ts +2 -0
  12. package/lib/test/unit/md5Normalizer.test.d.ts +2 -0
  13. package/lib/test/unit/rangeOf.test.d.ts +2 -0
  14. package/lib/test/unit/recordJarHelpers.test.d.ts +2 -0
  15. package/lib/test/unit/zipFileTreeAccessors.test.d.ts +2 -0
  16. package/package.json +14 -15
  17. package/src/index.ts +31 -0
  18. package/src/packlets/conversion/converters.ts +124 -0
  19. package/src/packlets/conversion/index.ts +25 -0
  20. package/src/packlets/csv/csvHelpers.ts +58 -0
  21. package/src/packlets/csv/index.ts +23 -0
  22. package/src/packlets/experimental/extendedArray.ts +110 -0
  23. package/src/packlets/experimental/formatter.ts +114 -0
  24. package/src/packlets/experimental/index.ts +25 -0
  25. package/src/packlets/experimental/rangeOf.ts +222 -0
  26. package/src/packlets/hash/index.ts +23 -0
  27. package/src/packlets/hash/md5Normalizer.ts +38 -0
  28. package/src/packlets/record-jar/index.ts +23 -0
  29. package/src/packlets/record-jar/recordJarHelpers.ts +278 -0
  30. package/src/packlets/zip-file-tree/index.ts +33 -0
  31. package/src/packlets/zip-file-tree/zipFileTreeAccessors.ts +404 -0
  32. package/CHANGELOG.md +0 -98
  33. package/lib/index.d.ts.map +0 -1
  34. package/lib/index.js.map +0 -1
  35. package/lib/packlets/conversion/converters.d.ts.map +0 -1
  36. package/lib/packlets/conversion/converters.js.map +0 -1
  37. package/lib/packlets/conversion/index.d.ts.map +0 -1
  38. package/lib/packlets/conversion/index.js.map +0 -1
  39. package/lib/packlets/csv/csvHelpers.d.ts.map +0 -1
  40. package/lib/packlets/csv/csvHelpers.js.map +0 -1
  41. package/lib/packlets/csv/index.d.ts.map +0 -1
  42. package/lib/packlets/csv/index.js.map +0 -1
  43. package/lib/packlets/experimental/extendedArray.d.ts.map +0 -1
  44. package/lib/packlets/experimental/extendedArray.js.map +0 -1
  45. package/lib/packlets/experimental/formatter.d.ts.map +0 -1
  46. package/lib/packlets/experimental/formatter.js.map +0 -1
  47. package/lib/packlets/experimental/index.d.ts.map +0 -1
  48. package/lib/packlets/experimental/index.js.map +0 -1
  49. package/lib/packlets/experimental/rangeOf.d.ts.map +0 -1
  50. package/lib/packlets/experimental/rangeOf.js.map +0 -1
  51. package/lib/packlets/hash/index.d.ts.map +0 -1
  52. package/lib/packlets/hash/index.js.map +0 -1
  53. package/lib/packlets/hash/md5Normalizer.d.ts.map +0 -1
  54. package/lib/packlets/hash/md5Normalizer.js.map +0 -1
  55. package/lib/packlets/record-jar/index.d.ts.map +0 -1
  56. package/lib/packlets/record-jar/index.js.map +0 -1
  57. package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +0 -1
  58. package/lib/packlets/record-jar/recordJarHelpers.js.map +0 -1
  59. package/lib/packlets/zip-file-tree/index.d.ts.map +0 -1
  60. package/lib/packlets/zip-file-tree/index.js.map +0 -1
  61. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +0 -1
  62. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fgv/ts-extras",
3
- "version": "5.0.0-2",
3
+ "version": "5.0.0-21",
4
4
  "description": "Assorted Typescript Utilities",
5
5
  "main": "lib/index.js",
6
6
  "types": "dist/ts-extras.d.ts",
@@ -17,10 +17,10 @@
17
17
  "homepage": "https://github.com/ErikFortune/fgv/tree/main/libraries/ts-extras#ts-utils",
18
18
  "devDependencies": {
19
19
  "@jest/expect-utils": "^29.7.0",
20
- "@microsoft/api-documenter": "^7.26.29",
21
- "@microsoft/api-extractor": "^7.49.1",
20
+ "@microsoft/api-documenter": "^7.26.31",
21
+ "@microsoft/api-extractor": "^7.52.10",
22
22
  "@types/jest": "^29.5.14",
23
- "@types/luxon": "^3.6.2",
23
+ "@types/luxon": "^3.7.1",
24
24
  "@types/mustache": "^4.2.5",
25
25
  "@types/node": "^20.14.9",
26
26
  "@types/papaparse": "^5.3.14",
@@ -34,29 +34,28 @@
34
34
  "jest-extended": "^4.0.2",
35
35
  "jest-matcher-utils": "^29.7.0",
36
36
  "rimraf": "^5.0.7",
37
- "ts-jest": "^29.4.0",
37
+ "ts-jest": "^29.4.1",
38
38
  "ts-node": "^10.9.2",
39
- "typescript": "^5.7.3",
39
+ "typescript": "^5.8.3",
40
40
  "eslint-plugin-n": "^16.6.2",
41
41
  "jest-snapshot": "~29.7.0",
42
- "@rushstack/heft": "~0.74.0",
43
- "@rushstack/heft-node-rig": "~2.9.0",
42
+ "@rushstack/heft": "~0.74.2",
43
+ "@rushstack/heft-node-rig": "~2.9.3",
44
44
  "@rushstack/eslint-config": "~4.4.0",
45
45
  "@types/heft-jest": "1.0.6",
46
- "@rushstack/heft-jest-plugin": "~0.16.9",
46
+ "@rushstack/heft-jest-plugin": "~0.16.11",
47
47
  "eslint-plugin-tsdoc": "~0.4.0",
48
- "@fgv/ts-utils-jest": "5.0.0-2",
49
- "@fgv/ts-utils": "5.0.0-2"
48
+ "@fgv/ts-utils-jest": "5.0.0-21",
49
+ "@fgv/ts-utils": "5.0.0-21"
50
50
  },
51
51
  "dependencies": {
52
- "luxon": "^3.6.1",
52
+ "luxon": "^3.7.1",
53
53
  "mustache": "^4.2.0",
54
54
  "papaparse": "^5.4.1",
55
- "@types/adm-zip": "~0.5.7",
56
- "adm-zip": "~0.5.16"
55
+ "fflate": "~0.8.2"
57
56
  },
58
57
  "peerDependencies": {
59
- "@fgv/ts-utils": "5.0.0-2"
58
+ "@fgv/ts-utils": "5.0.0-21"
60
59
  },
61
60
  "scripts": {
62
61
  "build": "heft test --clean",
package/src/index.ts ADDED
@@ -0,0 +1,31 @@
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 * as Csv from './packlets/csv';
24
+ import * as Experimental from './packlets/experimental';
25
+ import * as Hash from './packlets/hash';
26
+ import * as RecordJar from './packlets/record-jar';
27
+ import * as ZipFileTree from './packlets/zip-file-tree';
28
+
29
+ import { Converters } from './packlets/conversion';
30
+
31
+ export { Converters, Csv, Experimental, Hash, RecordJar, ZipFileTree };
@@ -0,0 +1,124 @@
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 { Conversion, Converter, Converters, Result, captureResult, fail, succeed } from '@fgv/ts-utils';
24
+ import { DateTime } from 'luxon';
25
+ import Mustache from 'mustache';
26
+ import { ExtendedArray, RangeOf, RangeOfProperties } from '../experimental';
27
+
28
+ /**
29
+ * Helper function to create a `StringConverter` which converts
30
+ * `unknown` to `string`, applying template conversions supplied at construction time or at
31
+ * runtime as context.
32
+ * @remarks
33
+ * Template conversions are applied using `mustache` syntax.
34
+ * @param defaultContext - Optional default context to use for template values.
35
+ * @returns A new `Converter` returning `string`.
36
+ * @public
37
+ */
38
+ export function templateString(defaultContext?: unknown): Conversion.StringConverter<string, unknown> {
39
+ return new Conversion.StringConverter<string, unknown>(
40
+ defaultContext,
41
+ undefined,
42
+ (from: unknown, __self: Converter<string, unknown>, context?: unknown) => {
43
+ if (typeof from !== 'string') {
44
+ return fail(`Not a string: ${JSON.stringify(from)}`);
45
+ }
46
+ return captureResult(() => Mustache.render(from, context));
47
+ }
48
+ );
49
+ }
50
+
51
+ /**
52
+ * A `Converter` which converts an iso formatted string, a number or a `Date` object to
53
+ * a `Date` object.
54
+ * @public
55
+ */
56
+ export const isoDate: Converter<Date, unknown> = new Conversion.BaseConverter<Date>((from: unknown) => {
57
+ if (typeof from === 'string') {
58
+ const dt = DateTime.fromISO(from);
59
+ if (dt.isValid) {
60
+ return succeed(dt.toJSDate());
61
+ }
62
+ return fail(`Invalid date: ${dt.invalidExplanation}`);
63
+ } else if (typeof from === 'number') {
64
+ return succeed(new Date(from));
65
+ } else if (from instanceof Date) {
66
+ return succeed(from);
67
+ }
68
+ return fail(`Cannot convert ${JSON.stringify(from)} to Date`);
69
+ });
70
+
71
+ /**
72
+ * A helper function to create a `Converter` which converts `unknown` to {@link Experimental.ExtendedArray | ExtendedArray<T>}.
73
+ * @remarks
74
+ * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
75
+ * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
76
+ * @param converter - `Converter` used to convert each item in the array
77
+ * @param ignoreErrors - Specifies treatment of unconvertible elements
78
+ * @beta
79
+ */
80
+ export function extendedArrayOf<T, TC = undefined>(
81
+ label: string,
82
+ converter: Converter<T, TC>,
83
+ onError: Conversion.OnError = 'failOnError'
84
+ ): Converter<ExtendedArray<T>, TC> {
85
+ return Converters.arrayOf(converter, onError).map((items: T[]) => {
86
+ return captureResult(() => new ExtendedArray(label, ...items));
87
+ });
88
+ }
89
+
90
+ /**
91
+ * A helper wrapper to construct a `Converter` which converts to an arbitrary strongly-typed
92
+ * range of some comparable type.
93
+ * @param converter - `Converter` used to convert `min` and `max` extent of the range.
94
+ * @param constructor - Static constructor to instantiate the object.
95
+ * @public
96
+ */
97
+ export function rangeTypeOf<T, RT extends RangeOf<T>, TC = unknown>(
98
+ converter: Converter<T, TC>,
99
+ constructor: (init: RangeOfProperties<T>) => Result<RT>
100
+ ): Converter<RT, TC> {
101
+ return new Conversion.BaseConverter((from: unknown, __self, context?: TC) => {
102
+ const result = Converters.object(
103
+ {
104
+ min: converter,
105
+ max: converter
106
+ },
107
+ { optionalFields: ['min', 'max'] }
108
+ ).convert(from, context);
109
+ if (result.isSuccess()) {
110
+ return constructor({ min: result.value.min, max: result.value.max });
111
+ }
112
+ return fail(result.message);
113
+ });
114
+ }
115
+
116
+ /**
117
+ * A helper wrapper to construct a `Converter` which converts to {@link Experimental.RangeOf | RangeOf<T>}
118
+ * where `<T>` is some comparable type.
119
+ * @param converter - `Converter` used to convert `min` and `max` extent of the range.
120
+ * @public
121
+ */
122
+ export function rangeOf<T, TC = unknown>(converter: Converter<T, TC>): Converter<RangeOf<T>, TC> {
123
+ return rangeTypeOf<T, RangeOf<T>, TC>(converter, RangeOf.createRange);
124
+ }
@@ -0,0 +1,25 @@
1
+ /*
2
+ * Copyright (c) 2023 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 * as Converters from './converters';
24
+
25
+ export { Converters };
@@ -0,0 +1,58 @@
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 { Result, captureResult } from '@fgv/ts-utils';
24
+ import * as fs from 'fs';
25
+ import { parse } from 'papaparse';
26
+ import * as path from 'path';
27
+
28
+ /**
29
+ * Options for {@link Csv.readCsvFileSync | readCsvFileSync}
30
+ * @beta
31
+ */
32
+ // eslint-disable-next-line @typescript-eslint/naming-convention
33
+ export interface CsvOptions {
34
+ delimiter?: string;
35
+ }
36
+
37
+ /**
38
+ * Reads a CSV file from a supplied path.
39
+ * @param srcPath - Source path from which the file is read.
40
+ * @param options - optional parameters to control the processing
41
+ * @returns The contents of the file.
42
+ * @beta
43
+ */
44
+ export function readCsvFileSync(srcPath: string, options?: CsvOptions): Result<unknown> {
45
+ return captureResult(() => {
46
+ const fullPath = path.resolve(srcPath);
47
+ const body = fs.readFileSync(fullPath, 'utf8').toString();
48
+ options = options ?? {};
49
+ // eslint-disable-next-line
50
+ return parse(body, {
51
+ transform: (s: string) => s.trim(),
52
+ header: false,
53
+ dynamicTyping: false,
54
+ skipEmptyLines: 'greedy',
55
+ ...options
56
+ }).data.slice(1);
57
+ });
58
+ }
@@ -0,0 +1,23 @@
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
+ export * from './csvHelpers';
@@ -0,0 +1,110 @@
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 { Result, fail, succeed } from '@fgv/ts-utils';
24
+
25
+ /**
26
+ * An experimental array template which extend built-in `Array` to include a handful
27
+ * of predicates which return `Result<T>`.
28
+ * @beta
29
+ */
30
+ export class ExtendedArray<T> extends Array<T> {
31
+ public readonly itemDescription: string;
32
+
33
+ /**
34
+ * Constructs an {@link Experimental.ExtendedArray | ExtendedArray}.
35
+ * @param itemDescription - Brief description of the type of each item in this array.
36
+ * @param items - The initial contents of the array.
37
+ */
38
+ public constructor(itemDescription: string, ...items: T[]) {
39
+ super(...items);
40
+ this.itemDescription = itemDescription;
41
+ }
42
+
43
+ /**
44
+ * Type guard to determine if some arbitrary array is an
45
+ * {@link Experimental.ExtendedArray}
46
+ * @param a - The `Array` to be tested.
47
+ * @returns Returns `true` if `a` is an {@link Experimental.ExtendedArray | ExtendedArray},
48
+ * `false` otherwise.
49
+ */
50
+ public static isExtendedArray<T>(a?: T[]): a is ExtendedArray<T> {
51
+ return a instanceof ExtendedArray;
52
+ }
53
+
54
+ /**
55
+ * Determines if this array contains exactly one element which matches
56
+ * a supplied predicate.
57
+ * @param predicate - The predicate function to be applied.
58
+ * @returns Returns `Success<T>` with the single matching
59
+ * result if exactly one item matches `predicate`. Returns `Failure<T>`
60
+ * with an error message if there are no matches or more than one match.
61
+ */
62
+ public single(predicate?: (item: T) => boolean): Result<T> {
63
+ const match = predicate ? this.filter(predicate) : this;
64
+ if (match.length === 1) {
65
+ return succeed(match[0]);
66
+ }
67
+ if (match.length === 0) {
68
+ return fail(`${this.itemDescription} not found`);
69
+ }
70
+ return fail(`${this.itemDescription} matches ${match.length} items`);
71
+ }
72
+
73
+ /**
74
+ * Returns the first element of an {@link Experimental.ExtendedArray | ExtendedArray}. Fails with an
75
+ * error message if the array is empty.
76
+ * @param failMessage - Optional message to be displayed in the event of failure.
77
+ * @returns Returns `Success<T>` with the value of the first element
78
+ * in the array, or `Failure<T>` with an error message if the array is empty.
79
+ */
80
+ public first(failMessage?: string): Result<T> {
81
+ if (this.length > 0) {
82
+ return succeed(this[0]);
83
+ }
84
+ return fail(failMessage ?? `${this.itemDescription} not found`);
85
+ }
86
+
87
+ /**
88
+ * Returns an array containing all elements of an {@link Experimental.ExtendedArray | ExtendedArray}.
89
+ * Fails with an error message if the array is empty.
90
+ * @param failMessage - Optional message to be displayed in the event of failure.
91
+ * @returns Returns `Success<T>` with a new (non-extended) `Array`
92
+ * containing the elements of this array, or `Failure<T>` with an error message
93
+ * if the array is empty.
94
+ */
95
+ public atLeastOne(failMessage?: string): Result<T[]> {
96
+ if (this.length > 0) {
97
+ return succeed(Array.from(this));
98
+ }
99
+ return fail(failMessage ?? `${this.itemDescription} not found`);
100
+ }
101
+
102
+ /**
103
+ * Gets a new (non-extended) `Array` containing all of the elements from this
104
+ * {@link Experimental.ExtendedArray | ExtendedArray}.
105
+ * @returns A new (non-extended) `Array<T>`.
106
+ */
107
+ public all(): T[] {
108
+ return Array.from(this);
109
+ }
110
+ }
@@ -0,0 +1,114 @@
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 { Result, captureResult, mapResults, succeed } from '@fgv/ts-utils';
24
+ import Mustache from 'mustache';
25
+
26
+ Mustache.escape = (s: string) => s;
27
+
28
+ /**
29
+ * Destination format for some formatted string.
30
+ * @beta
31
+ */
32
+ export type FormatTargets = 'text' | 'markdown' | 'embed';
33
+
34
+ /**
35
+ * Interface for an object that can be formatted.
36
+ * @beta
37
+ */
38
+ // eslint-disable-next-line @typescript-eslint/naming-convention
39
+ export interface Formattable {
40
+ /**
41
+ * Formats an object using the supplied mustache template.
42
+ * @param format - A mustache template used to format the object.
43
+ * @returns `Success<string>` with the resulting string, or `Failure<string>`
44
+ * with an error message if an error occurs.
45
+ */
46
+ format(format: string): Result<string>;
47
+ }
48
+
49
+ /**
50
+ * Base class which adds common formatting.
51
+ * @beta
52
+ */
53
+ export class FormattableBase {
54
+ /**
55
+ * Helper enables derived classes to add named details to a formatted presentation.
56
+ * @param details - An array of detail description strings.
57
+ * @param label - Label to use for the new detail.
58
+ * @param value - Value to use for the new detail.
59
+ * @internal
60
+ */
61
+ protected static _tryAddDetail(details: string[], label: string, value: string | undefined): void {
62
+ if (value !== undefined) {
63
+ const padded = ` ${label}:`.padEnd(20, ' ');
64
+ details.push(`${padded} ${value}`);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * {@inheritdoc Experimental.Formattable.format}
70
+ */
71
+ public format(template: string): Result<string> {
72
+ return captureResult(() => Mustache.render(template, this));
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Type definition for a formatting function, which takes a `string` and an
78
+ * item and returns `Result<string>`.
79
+ * @beta
80
+ */
81
+ export type Formatter<T> = (format: string, item: T) => Result<string>;
82
+
83
+ /**
84
+ * A collection of {@link Experimental.Formatter | formatters} indexed by target name, to enable
85
+ * different format methods per output target.
86
+ * @beta
87
+ */
88
+ export type FormattersByExtendedTarget<TFT extends FormatTargets, T> = Record<TFT, Formatter<T>>;
89
+ /**
90
+ * A collection of {@link Experimental.Formatter | formatters} indexed by the
91
+ * {@link Experimental.FormatTargets | default supported target formats}.
92
+ * @beta
93
+ */
94
+ export type FormattersByTarget<T> = FormattersByExtendedTarget<FormatTargets, T>;
95
+
96
+ /**
97
+ * Formats a list of items using the supplied template and formatter, one result
98
+ * per output line.
99
+ * @param format - A mustache template used to format each item.
100
+ * @param items - The items to be formatted.
101
+ * @param itemFormatter - The {@link Experimental.Formatter | Formatter<T>} used to format each item.
102
+ * @returns The resulting string.
103
+ * @beta
104
+ */
105
+ export function formatList<T>(format: string, items: T[], itemFormatter: Formatter<T>): Result<string> {
106
+ return mapResults(
107
+ items.map((item) => {
108
+ return itemFormatter(format, item);
109
+ })
110
+ ).onSuccess((results: string[]) => {
111
+ const filtered = results.filter((s) => s !== '');
112
+ return succeed(filtered.join('\n'));
113
+ });
114
+ }
@@ -0,0 +1,25 @@
1
+ /*
2
+ * Copyright (c) 2023 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
+ export * from './extendedArray';
24
+ export * from './formatter';
25
+ export * from './rangeOf';