@fgv/ts-extras 5.0.1-9 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/index.browser.js +35 -0
  2. package/dist/index.js +29 -0
  3. package/dist/packlets/conversion/converters.js +107 -0
  4. package/dist/packlets/conversion/index.js +24 -0
  5. package/dist/packlets/csv/csvFileHelpers.js +55 -0
  6. package/dist/packlets/csv/csvHelpers.js +37 -0
  7. package/dist/packlets/csv/index.browser.js +29 -0
  8. package/dist/packlets/csv/index.js +26 -0
  9. package/dist/packlets/experimental/extendedArray.js +102 -0
  10. package/dist/packlets/experimental/formatter.js +67 -0
  11. package/dist/packlets/experimental/index.js +25 -0
  12. package/dist/packlets/experimental/rangeOf.js +178 -0
  13. package/dist/packlets/hash/index.browser.js +24 -0
  14. package/dist/packlets/hash/index.js +23 -0
  15. package/dist/packlets/hash/index.node.js +26 -0
  16. package/dist/packlets/hash/md5Normalizer.browser.js +34 -0
  17. package/dist/packlets/hash/md5Normalizer.js +37 -0
  18. package/dist/packlets/record-jar/index.browser.js +29 -0
  19. package/dist/packlets/record-jar/index.js +26 -0
  20. package/dist/packlets/record-jar/recordJarFileHelpers.js +60 -0
  21. package/dist/packlets/record-jar/recordJarHelpers.js +216 -0
  22. package/dist/packlets/zip-file-tree/index.js +32 -0
  23. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +344 -0
  24. package/dist/tsdoc-metadata.json +1 -1
  25. package/lib/index.browser.d.ts +3 -1
  26. package/lib/index.browser.js +7 -1
  27. package/lib/packlets/csv/index.browser.d.ts +3 -0
  28. package/lib/packlets/csv/index.browser.js +47 -0
  29. package/lib/packlets/record-jar/index.browser.d.ts +3 -0
  30. package/lib/packlets/record-jar/index.browser.js +47 -0
  31. package/package.json +6 -5
@@ -0,0 +1,178 @@
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 { captureResult } from '@fgv/ts-utils';
23
+ import Mustache from 'mustache';
24
+ /**
25
+ * Default {@link Experimental.RangeOfFormats | formats} to use for both
26
+ * open-ended and complete {@link Experimental.RangeOf | RangeOf<T>}.
27
+ * @public
28
+ */
29
+ export const DEFAULT_RANGEOF_FORMATS = {
30
+ minOnly: '{{min}}-',
31
+ maxOnly: '-{{max}}',
32
+ minMax: '{{min}}-{{max}}'
33
+ };
34
+ /**
35
+ * Simple implementation of a possibly open-ended range of some comparable
36
+ * type `<T>` with test and formatting.
37
+ * @public
38
+ */
39
+ export class RangeOf {
40
+ /**
41
+ * Creates a new {@link Experimental.RangeOf | RangeOf<T>}.
42
+ * @param min - Optional minimum extent of the range.
43
+ * @param max - Optional maximum extent of the range.
44
+ */
45
+ constructor(min, max) {
46
+ if (min !== undefined && max !== undefined && this._compare(min, max) === 'greater') {
47
+ throw new Error(`Inverted range - ${JSON.stringify(min)} must be <= ${JSON.stringify(max)}.`);
48
+ }
49
+ this.min = min;
50
+ this.max = max;
51
+ }
52
+ /**
53
+ * Static constructor for a {@link Experimental.RangeOf | RangeOf<T>}.
54
+ * @param init - {@link Experimental.RangeOfProperties | Range initializer}.
55
+ * @returns A new {@link Experimental.RangeOf | RangeOf<T>}.
56
+ */
57
+ static createRange(init) {
58
+ return captureResult(() => new RangeOf(init === null || init === void 0 ? void 0 : init.min, init === null || init === void 0 ? void 0 : init.max));
59
+ }
60
+ /**
61
+ * Gets a formatted description of a {@link Experimental.RangeOfProperties | RangeOfProperties<T>} given an
62
+ * optional set of formats and 'empty' value to use.
63
+ * @param range - The {@link Experimental.RangeOfProperties | RangeOfProperties<T>} to be formatted.
64
+ * @param formats - Optional {@link Experimental.RangeOfFormats | formats} to use. Default is
65
+ * {@link Experimental.DEFAULT_RANGEOF_FORMATS | DEFAULT_RANGEOF_FORMATS}.
66
+ * @param emptyValue - Value which represents unbounded minimum or maximum for this range. Default is `undefined`.
67
+ * @returns A string representation of the range.
68
+ */
69
+ static propertiesToString(range, formats, emptyValue) {
70
+ formats = formats !== null && formats !== void 0 ? formats : DEFAULT_RANGEOF_FORMATS;
71
+ if (range.min !== undefined && range.min !== emptyValue) {
72
+ if (range.max !== undefined && range.max !== emptyValue) {
73
+ return Mustache.render(formats.minMax, range);
74
+ }
75
+ else {
76
+ return Mustache.render(formats.minOnly, range);
77
+ }
78
+ }
79
+ else if (range.max !== undefined && range.max !== emptyValue) {
80
+ return Mustache.render(formats.maxOnly, range);
81
+ }
82
+ return undefined;
83
+ }
84
+ /**
85
+ * Default comparison uses javascript built-in comparison.
86
+ * @param t1 - First value to be compared.
87
+ * @param t2 - Second value to be compared.
88
+ * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger
89
+ * and `'equal'` if `t1` and `t2` are equal.
90
+ * @internal
91
+ */
92
+ static _defaultCompare(t1, t2) {
93
+ if (t1 < t2) {
94
+ return 'less';
95
+ }
96
+ else if (t1 > t2) {
97
+ return 'greater';
98
+ }
99
+ return 'equal';
100
+ }
101
+ /**
102
+ * Checks if a supplied value is within this range.
103
+ * @param t - The value to be tested.
104
+ * @returns `'included'` if `t` falls within the range, `'less'` if `t` falls
105
+ * below the minimum extent of the range and `'greater'` if `t` is above the
106
+ * maximum extent.
107
+ */
108
+ check(t) {
109
+ if (this.min !== undefined && this._compare(t, this.min) === 'less') {
110
+ return 'less';
111
+ }
112
+ if (this.max !== undefined && this._compare(t, this.max) !== 'less') {
113
+ return 'greater';
114
+ }
115
+ return 'included';
116
+ }
117
+ /**
118
+ * Determines if a supplied value is within this range.
119
+ * @param t - The value to be tested.
120
+ * @returns Returns `true` if `t` falls within the range, `false` otherwise.
121
+ */
122
+ includes(t) {
123
+ return this.check(t) === 'included';
124
+ }
125
+ /**
126
+ * Finds the transition value that would bring a supplied value `t` into
127
+ * range.
128
+ * @param t - The value to be tested.
129
+ * @returns The minimum extent of the range if `t` is below the range or
130
+ * the maximum extent of the range if `t` is above the range. Returns
131
+ * `undefined` if `t` already falls within the range.
132
+ */
133
+ findTransition(t) {
134
+ switch (this.check(t)) {
135
+ case 'less':
136
+ return this.min;
137
+ case 'included':
138
+ return this.max;
139
+ }
140
+ return undefined;
141
+ }
142
+ /**
143
+ * Formats the minimum and maximum values of this range.
144
+ * @param format - A format function used to format the values.
145
+ * @returns A {@link Experimental.RangeOfProperties | RangeOfProperties<string>} containing the
146
+ * formatted representation of the {@link Experimental.RangeOf.min | minimum} and
147
+ * {@link Experimental.RangeOf.max | maximum}
148
+ * extent of the range, or `undefined` for an extent that is not present.
149
+ */
150
+ toFormattedProperties(format) {
151
+ return {
152
+ min: this.min !== undefined ? format(this.min) : undefined,
153
+ max: this.max !== undefined ? format(this.max) : undefined
154
+ };
155
+ }
156
+ /**
157
+ * Formats this range using the supplied format function.
158
+ * @param format - Format function used to format minimum and maximum extent values.
159
+ * @param formats - The {@link Experimental.RangeOfFormats | format strings} used to format the range
160
+ * (default {@link Experimental.DEFAULT_RANGEOF_FORMATS}).
161
+ * @returns Returns a formatted representation of this range.
162
+ */
163
+ format(format, formats) {
164
+ return RangeOf.propertiesToString(this.toFormattedProperties(format), formats);
165
+ }
166
+ /**
167
+ * Inner compare method can be overridden by a derived class.
168
+ * @param t1 - First value to compare.
169
+ * @param t2 - Second value to compare.
170
+ * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger
171
+ * and `'equal'` if `t1` and `t2` are equal.
172
+ * @internal
173
+ */
174
+ _compare(t1, t2) {
175
+ return RangeOf._defaultCompare(t1, t2);
176
+ }
177
+ }
178
+ //# sourceMappingURL=rangeOf.js.map
@@ -0,0 +1,24 @@
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
+ // Browser-safe hash exports - excludes Node.js crypto dependencies
23
+ export * from './md5Normalizer.browser';
24
+ //# sourceMappingURL=index.browser.js.map
@@ -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
+ export * from './md5Normalizer';
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,26 @@
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
+ /* c8 ignore start - Node.js-specific export used conditionally in package.json */
23
+ // Node.js hash exports - includes crypto-based implementations
24
+ export * from './md5Normalizer';
25
+ /* c8 ignore stop */
26
+ //# sourceMappingURL=index.node.js.map
@@ -0,0 +1,34 @@
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
+ import { Hash } from '@fgv/ts-utils';
23
+ /**
24
+ * Browser-compatible MD5 normalizer that uses CRC32 hashing for cross-platform compatibility.
25
+ * This provides the same interface as the Node.js MD5 version but uses CRC32 algorithm
26
+ * which works consistently across both Node.js and browser environments.
27
+ *
28
+ * Note: While this is named Md5Normalizer for API compatibility, it actually uses CRC32
29
+ * hashing to ensure cross-platform compatibility between Node.js and browser environments.
30
+ * @public
31
+ */
32
+ export class Md5Normalizer extends Hash.Crc32Normalizer {
33
+ }
34
+ //# sourceMappingURL=md5Normalizer.browser.js.map
@@ -0,0 +1,37 @@
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
+ import { Hash } from '@fgv/ts-utils';
23
+ import * as crypto from 'crypto';
24
+ /**
25
+ * A hashing normalizer which computes object
26
+ * hash using the MD5 algorithm.
27
+ * @public
28
+ */
29
+ export class Md5Normalizer extends Hash.HashingNormalizer {
30
+ constructor() {
31
+ super(Md5Normalizer.md5Hash);
32
+ }
33
+ static md5Hash(parts) {
34
+ return crypto.createHash('md5').update(parts.join('|'), 'utf8').digest('hex');
35
+ }
36
+ }
37
+ //# sourceMappingURL=md5Normalizer.js.map
@@ -0,0 +1,29 @@
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
+ // Browser-safe RecordJar exports - excludes Node.js filesystem dependencies
23
+ // Export all browser-safe parsing functionality
24
+ export * from './recordJarHelpers';
25
+ // Export FileTree-based reading (web-compatible)
26
+ export { readRecordJarFromTree } from './recordJarFileHelpers';
27
+ // Exclude:
28
+ // - readRecordJarFileSync (requires Node.js fs/path)
29
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1,26 @@
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
+ // Export tree-shakeable functions
23
+ export * from './recordJarHelpers';
24
+ // Filesystem helpers in separate module for tree-shaking
25
+ export * from './recordJarFileHelpers';
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,60 @@
1
+ /*
2
+ * Copyright (c) 2022 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 * as fs from 'fs';
23
+ import * as path from 'path';
24
+ import { captureResult } from '@fgv/ts-utils';
25
+ import { parseRecordJarLines } from './recordJarHelpers';
26
+ /**
27
+ * Reads a record-jar file from a supplied path.
28
+ * @param srcPath - Source path from which the file is read.
29
+ * @param options - Optional parser configuration
30
+ * @returns The contents of the file as an array of `Record<string, string>`
31
+ * @see https://datatracker.ietf.org/doc/html/draft-phillips-record-jar-01
32
+ * @public
33
+ */
34
+ export function readRecordJarFileSync(srcPath, options) {
35
+ return captureResult(() => {
36
+ const fullPath = path.resolve(srcPath);
37
+ return fs.readFileSync(fullPath, 'utf8').toString().split(/\r?\n/);
38
+ }).onSuccess((lines) => {
39
+ return parseRecordJarLines(lines, options);
40
+ });
41
+ }
42
+ /**
43
+ * Reads a record-jar file from a FileTree.
44
+ * @param fileTree - The FileTree to read from.
45
+ * @param filePath - Path of the file within the tree.
46
+ * @param options - Optional parser configuration
47
+ * @returns The contents of the file as an array of `Record<string, string>`
48
+ * @see https://datatracker.ietf.org/doc/html/draft-phillips-record-jar-01
49
+ * @public
50
+ */
51
+ export function readRecordJarFromTree(fileTree, filePath, options) {
52
+ return fileTree
53
+ .getFile(filePath)
54
+ .onSuccess((file) => file.getRawContents())
55
+ .onSuccess((contents) => {
56
+ const lines = contents.split(/\r?\n/);
57
+ return parseRecordJarLines(lines, options);
58
+ });
59
+ }
60
+ //# sourceMappingURL=recordJarFileHelpers.js.map
@@ -0,0 +1,216 @@
1
+ /*
2
+ * Copyright (c) 2022 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 { fail, isKeyOf, succeed } from '@fgv/ts-utils';
23
+ class RecordParser {
24
+ constructor(options) {
25
+ this.records = [];
26
+ this._fields = {};
27
+ this._name = undefined;
28
+ this._body = undefined;
29
+ this.options = options !== null && options !== void 0 ? options : {};
30
+ }
31
+ static parse(lines, options) {
32
+ return new RecordParser(options)._parse(lines);
33
+ }
34
+ static _parseRecordBody(body) {
35
+ const isContinuation = body.endsWith('\\');
36
+ if (isContinuation) {
37
+ body = body.slice(0, body.length - 1);
38
+ }
39
+ if (this._hasEscapes(body)) {
40
+ const result = this._replaceEscapes(body);
41
+ if (result.isFailure()) {
42
+ return fail(result.message);
43
+ }
44
+ body = result.value;
45
+ }
46
+ return succeed({ body, isContinuation });
47
+ }
48
+ static _hasEscapes(from) {
49
+ return from.includes('\\') || from.includes('&');
50
+ }
51
+ static _replaceEscapes(body) {
52
+ const invalid = [];
53
+ const escaped = body.replace(/(\\.)|(&#x[a-fA-F0-9]{2,6};)/g, (match) => {
54
+ switch (match) {
55
+ case '\\\\':
56
+ return '\\';
57
+ case '\\&':
58
+ return '&';
59
+ case '\\r':
60
+ return '\r';
61
+ case '\\n':
62
+ return '\n';
63
+ case '\\t':
64
+ return '\t';
65
+ }
66
+ if (match.startsWith('&')) {
67
+ const hexCode = `0x${match.slice(3, match.length - 1)}`;
68
+ const charCode = Number.parseInt(hexCode, 16);
69
+ return String.fromCharCode(charCode);
70
+ }
71
+ invalid.push(match);
72
+ return '\\';
73
+ });
74
+ if (invalid.length > 0) {
75
+ return fail(`unrecognized escape "${invalid.join(', ')}" in record-jar body`);
76
+ }
77
+ return succeed(escaped);
78
+ }
79
+ static _applyOptions(record, options) {
80
+ if (options.arrayFields) {
81
+ record = Object.assign({}, record); // don't edit incoming values
82
+ const arrayFields = Array.isArray(options.arrayFields)
83
+ ? options.arrayFields
84
+ : options.arrayFields(record);
85
+ for (const field of arrayFields) {
86
+ if (isKeyOf(field, record) && typeof record[field] === 'string') {
87
+ const current = record[field];
88
+ record[field] = [current];
89
+ }
90
+ }
91
+ }
92
+ return record;
93
+ }
94
+ _parse(lines) {
95
+ var _a, _b;
96
+ for (let n = 0; n < lines.length; n++) {
97
+ const line = lines[n];
98
+ if (line.startsWith('%%') && !((_a = this._body) === null || _a === void 0 ? void 0 : _a.isContinuation)) {
99
+ const result = this._writePendingRecord();
100
+ if (result.isFailure()) {
101
+ return fail(`${n}: ${result.message}`);
102
+ }
103
+ }
104
+ else if (/^\s*$/.test(line)) {
105
+ // ignore blank lines but cancel continuation
106
+ if (this._body) {
107
+ this._body.isContinuation = false;
108
+ }
109
+ continue;
110
+ }
111
+ else if (((_b = this._body) === null || _b === void 0 ? void 0 : _b.isContinuation) || /^\s+/.test(line)) {
112
+ // explicit continuation on previous line or implicit starts with whitespace
113
+ if (this._body === undefined) {
114
+ return fail(`${n}: continuation ("${line}") without prior value.`);
115
+ }
116
+ const result = this._parseContinuation(line);
117
+ if (result.isFailure()) {
118
+ return fail(`${n}: ${result.message}`);
119
+ }
120
+ this._body = result.value;
121
+ }
122
+ else {
123
+ const result = this._parseField(line);
124
+ if (result.isFailure()) {
125
+ return fail(`${n}: ${result.message}`);
126
+ }
127
+ }
128
+ }
129
+ const result = this._writePendingRecord();
130
+ if (result.isFailure()) {
131
+ return fail(`${lines.length}: ${result.message}`);
132
+ }
133
+ return succeed(this.records);
134
+ }
135
+ _parseField(line) {
136
+ const separatorIndex = line.indexOf(':');
137
+ if (separatorIndex < 1) {
138
+ return fail(`malformed line ("${line}") in record-jar.`);
139
+ }
140
+ const parts = [line.slice(0, separatorIndex), line.slice(separatorIndex + 1)];
141
+ return this._writePendingField().onSuccess(() => {
142
+ this._name = parts[0].trimEnd();
143
+ return RecordParser._parseRecordBody(parts[1].trim()).onSuccess((body) => {
144
+ this._body = body;
145
+ return succeed(true);
146
+ });
147
+ });
148
+ }
149
+ _parseContinuation(line) {
150
+ var _a, _b;
151
+ let trimmed = line.trim();
152
+ if (!this._body.isContinuation) {
153
+ /* c8 ignore next */
154
+ const fixedSize = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.fixedContinuationSize) !== null && _b !== void 0 ? _b : 0;
155
+ if (fixedSize > 0) {
156
+ if (trimmed.length < line.length - fixedSize) {
157
+ // oops, took too much
158
+ trimmed = line.slice(fixedSize);
159
+ }
160
+ }
161
+ }
162
+ return RecordParser._parseRecordBody(trimmed).onSuccess((newBody) => {
163
+ return succeed({
164
+ body: `${this._body.body}${newBody.body}`,
165
+ isContinuation: newBody.isContinuation
166
+ });
167
+ });
168
+ }
169
+ _havePendingRecord() {
170
+ return Object.keys(this._fields).length > 0;
171
+ }
172
+ _writePendingRecord() {
173
+ return this._writePendingField().onSuccess(() => {
174
+ let record = this._havePendingRecord() ? this._fields : undefined;
175
+ if (record !== undefined) {
176
+ record = RecordParser._applyOptions(record, this.options);
177
+ this.records.push(record);
178
+ this._fields = {};
179
+ }
180
+ return succeed(undefined);
181
+ });
182
+ }
183
+ _writePendingField() {
184
+ if (this._name !== undefined) {
185
+ if (this._body.body.length < 1) {
186
+ return fail('empty body value not allowed');
187
+ }
188
+ if (!isKeyOf(this._name, this._fields)) {
189
+ this._fields[this._name] = this._body.body;
190
+ }
191
+ else if (typeof this._fields[this._name] === 'string') {
192
+ const current = this._fields[this._name];
193
+ this._fields[this._name] = [current, this._body.body];
194
+ }
195
+ else {
196
+ const current = this._fields[this._name];
197
+ current.push(this._body.body);
198
+ }
199
+ this._name = undefined;
200
+ this._body = undefined;
201
+ }
202
+ return succeed(true);
203
+ }
204
+ }
205
+ /**
206
+ * Reads a record-jar from an array of strings, each of which represents one
207
+ * line in the source file.
208
+ * @param lines - the array of strings to be parsed
209
+ * @param options - Optional parser configuration
210
+ * @returns a corresponding array of `Record<string, string>`
211
+ * @public
212
+ */
213
+ export function parseRecordJarLines(lines, options) {
214
+ return RecordParser.parse(lines, options);
215
+ }
216
+ //# sourceMappingURL=recordJarHelpers.js.map