@fgv/ts-extras 2.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -0
  3. package/dist/ts-extras.d.ts +445 -0
  4. package/dist/tsdoc-metadata.json +11 -0
  5. package/lib/index.d.ts +7 -0
  6. package/lib/index.d.ts.map +1 -0
  7. package/lib/index.js +58 -0
  8. package/lib/index.js.map +1 -0
  9. package/lib/packlets/conversion/converters.d.ts +28 -0
  10. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  11. package/lib/packlets/conversion/converters.js +72 -0
  12. package/lib/packlets/conversion/converters.js.map +1 -0
  13. package/lib/packlets/conversion/index.d.ts +3 -0
  14. package/lib/packlets/conversion/index.d.ts.map +1 -0
  15. package/lib/packlets/conversion/index.js +50 -0
  16. package/lib/packlets/conversion/index.js.map +1 -0
  17. package/lib/packlets/csv/csvHelpers.d.ts +17 -0
  18. package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
  19. package/lib/packlets/csv/csvHelpers.js +69 -0
  20. package/lib/packlets/csv/csvHelpers.js.map +1 -0
  21. package/lib/packlets/csv/index.d.ts +2 -0
  22. package/lib/packlets/csv/index.d.ts.map +1 -0
  23. package/lib/packlets/csv/index.js +39 -0
  24. package/lib/packlets/csv/index.js.map +1 -0
  25. package/lib/packlets/experimental/extendedArray.d.ts +56 -0
  26. package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
  27. package/lib/packlets/experimental/extendedArray.js +106 -0
  28. package/lib/packlets/experimental/extendedArray.js.map +1 -0
  29. package/lib/packlets/experimental/formatter.d.ts +66 -0
  30. package/lib/packlets/experimental/formatter.d.ts.map +1 -0
  31. package/lib/packlets/experimental/formatter.js +75 -0
  32. package/lib/packlets/experimental/formatter.js.map +1 -0
  33. package/lib/packlets/experimental/index.d.ts +4 -0
  34. package/lib/packlets/experimental/index.d.ts.map +1 -0
  35. package/lib/packlets/experimental/index.js +41 -0
  36. package/lib/packlets/experimental/index.js.map +1 -0
  37. package/lib/packlets/experimental/rangeOf.d.ts +122 -0
  38. package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
  39. package/lib/packlets/experimental/rangeOf.js +185 -0
  40. package/lib/packlets/experimental/rangeOf.js.map +1 -0
  41. package/lib/packlets/hash/hash.d.ts +51 -0
  42. package/lib/packlets/hash/hash.d.ts.map +1 -0
  43. package/lib/packlets/hash/hash.js +166 -0
  44. package/lib/packlets/hash/hash.js.map +1 -0
  45. package/lib/packlets/hash/index.d.ts +2 -0
  46. package/lib/packlets/hash/index.d.ts.map +1 -0
  47. package/lib/packlets/hash/index.js +39 -0
  48. package/lib/packlets/hash/index.js.map +1 -0
  49. package/lib/packlets/record-jar/index.d.ts +2 -0
  50. package/lib/packlets/record-jar/index.d.ts.map +1 -0
  51. package/lib/packlets/record-jar/index.js +39 -0
  52. package/lib/packlets/record-jar/index.js.map +1 -0
  53. package/lib/packlets/record-jar/recordJarHelpers.d.ts +37 -0
  54. package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
  55. package/lib/packlets/record-jar/recordJarHelpers.js +263 -0
  56. package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
  57. package/package.json +69 -0
@@ -0,0 +1,2 @@
1
+ export * from './hash';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/hash/index.ts"],"names":[],"mappings":"AAsBA,cAAc,QAAQ,CAAC"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
35
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ __exportStar(require("./hash"), exports);
39
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/hash/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH,yCAAuB","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport * from './hash';\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './recordJarHelpers';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/record-jar/index.ts"],"names":[],"mappings":"AAsBA,cAAc,oBAAoB,CAAC"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2023 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
35
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ __exportStar(require("./recordJarHelpers"), exports);
39
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/record-jar/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH,qDAAmC","sourcesContent":["/*\n * Copyright (c) 2023 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport * from './recordJarHelpers';\n"]}
@@ -0,0 +1,37 @@
1
+ import { Result } from '@fgv/ts-utils';
2
+ /**
3
+ * Represents a single record in a JAR file
4
+ * @public
5
+ */
6
+ export type JarRecord = Record<string, string | string[]>;
7
+ /**
8
+ * @public
9
+ */
10
+ export type JarFieldPicker<T extends JarRecord = JarRecord> = (record: T) => (keyof T)[];
11
+ /**
12
+ * Options for a JAR record parser.
13
+ * @public
14
+ */
15
+ export interface JarRecordParserOptions {
16
+ readonly arrayFields?: string[] | JarFieldPicker;
17
+ readonly fixedContinuationSize?: number;
18
+ }
19
+ /**
20
+ * Reads a record-jar from an array of strings, each of which represents one
21
+ * line in the source file.
22
+ * @param lines - the array of strings to be parsed
23
+ * @param options - Optional parser configuration
24
+ * @returns a corresponding array of `Record<string, string>`
25
+ * @public
26
+ */
27
+ export declare function parseRecordJarLines(lines: string[], options?: JarRecordParserOptions): Result<JarRecord[]>;
28
+ /**
29
+ * Reads a record-jar file from a supplied path.
30
+ * @param srcPath - Source path from which the file is read.
31
+ * @param options - Optional parser configuration
32
+ * @returns The contents of the file as an array of `Record<string, string>`
33
+ * @see https://datatracker.ietf.org/doc/html/draft-phillips-record-jar-01
34
+ * @public
35
+ */
36
+ export declare function readRecordJarFileSync(srcPath: string, options?: JarRecordParserOptions): Result<JarRecord[]>;
37
+ //# sourceMappingURL=recordJarHelpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recordJarHelpers.d.ts","sourceRoot":"","sources":["../../../src/packlets/record-jar/recordJarHelpers.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,MAAM,EAAyC,MAAM,eAAe,CAAC;AAO9E;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAE1D;;GAEG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;AAEzF;;;GAGG;AAEH,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,cAAc,CAAC;IACjD,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;CACzC;AAoMD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,sBAAsB,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC,CAE1G;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,sBAAsB,GAC/B,MAAM,CAAC,SAAS,EAAE,CAAC,CAOrB"}
@@ -0,0 +1,263 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2022 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
35
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
36
+ }) : function(o, v) {
37
+ o["default"] = v;
38
+ });
39
+ var __importStar = (this && this.__importStar) || function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.readRecordJarFileSync = exports.parseRecordJarLines = void 0;
48
+ const fs = __importStar(require("fs"));
49
+ const path = __importStar(require("path"));
50
+ const ts_utils_1 = require("@fgv/ts-utils");
51
+ class RecordParser {
52
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
53
+ constructor(options) {
54
+ this.records = [];
55
+ this._fields = {};
56
+ this._name = undefined;
57
+ this._body = undefined;
58
+ this.options = options !== null && options !== void 0 ? options : {};
59
+ }
60
+ static parse(lines, options) {
61
+ return new RecordParser(options)._parse(lines);
62
+ }
63
+ static _parseRecordBody(body) {
64
+ const isContinuation = body.endsWith('\\');
65
+ if (isContinuation) {
66
+ body = body.slice(0, body.length - 1);
67
+ }
68
+ if (this._hasEscapes(body)) {
69
+ const result = this._replaceEscapes(body);
70
+ if (result.isFailure()) {
71
+ return (0, ts_utils_1.fail)(result.message);
72
+ }
73
+ body = result.value;
74
+ }
75
+ return (0, ts_utils_1.succeed)({ body, isContinuation });
76
+ }
77
+ static _hasEscapes(from) {
78
+ return from.includes('\\') || from.includes('&');
79
+ }
80
+ static _replaceEscapes(body) {
81
+ const invalid = [];
82
+ const escaped = body.replace(/(\\.)|(&#x[a-fA-F0-9]{2,6};)/g, (match) => {
83
+ switch (match) {
84
+ case '\\\\':
85
+ return '\\';
86
+ case '\\&':
87
+ return '&';
88
+ case '\\r':
89
+ return '\r';
90
+ case '\\n':
91
+ return '\n';
92
+ case '\\t':
93
+ return '\t';
94
+ }
95
+ if (match.startsWith('&')) {
96
+ const hexCode = `0x${match.slice(3, match.length - 1)}`;
97
+ const charCode = Number.parseInt(hexCode, 16);
98
+ return String.fromCharCode(charCode);
99
+ }
100
+ invalid.push(match);
101
+ return '\\';
102
+ });
103
+ if (invalid.length > 0) {
104
+ return (0, ts_utils_1.fail)(`unrecognized escape "${invalid.join(', ')}" in record-jar body`);
105
+ }
106
+ return (0, ts_utils_1.succeed)(escaped);
107
+ }
108
+ static _applyOptions(record, options) {
109
+ if (options.arrayFields) {
110
+ record = Object.assign({}, record); // don't edit incoming values
111
+ const arrayFields = Array.isArray(options.arrayFields)
112
+ ? options.arrayFields
113
+ : options.arrayFields(record);
114
+ for (const field of arrayFields) {
115
+ if ((0, ts_utils_1.isKeyOf)(field, record) && typeof record[field] === 'string') {
116
+ const current = record[field];
117
+ record[field] = [current];
118
+ }
119
+ }
120
+ }
121
+ return record;
122
+ }
123
+ _parse(lines) {
124
+ var _a, _b;
125
+ for (let n = 0; n < lines.length; n++) {
126
+ const line = lines[n];
127
+ if (line.startsWith('%%') && !((_a = this._body) === null || _a === void 0 ? void 0 : _a.isContinuation)) {
128
+ const result = this._writePendingRecord();
129
+ if (result.isFailure()) {
130
+ return (0, ts_utils_1.fail)(`${n}: ${result.message}`);
131
+ }
132
+ }
133
+ else if (/^\s*$/.test(line)) {
134
+ // ignore blank lines but cancel continuation
135
+ if (this._body) {
136
+ this._body.isContinuation = false;
137
+ }
138
+ continue;
139
+ }
140
+ else if (((_b = this._body) === null || _b === void 0 ? void 0 : _b.isContinuation) || /^\s+/.test(line)) {
141
+ // explicit continuation on previous line or implicit starts with whitespace
142
+ if (this._body === undefined) {
143
+ return (0, ts_utils_1.fail)(`${n}: continuation ("${line}") without prior value.`);
144
+ }
145
+ const result = this._parseContinuation(line);
146
+ if (result.isFailure()) {
147
+ return (0, ts_utils_1.fail)(`${n}: ${result.message}`);
148
+ }
149
+ this._body = result.value;
150
+ }
151
+ else {
152
+ const result = this._parseField(line);
153
+ if (result.isFailure()) {
154
+ return (0, ts_utils_1.fail)(`${n}: ${result.message}`);
155
+ }
156
+ }
157
+ }
158
+ const result = this._writePendingRecord();
159
+ if (result.isFailure()) {
160
+ return (0, ts_utils_1.fail)(`${lines.length}: ${result.message}`);
161
+ }
162
+ return (0, ts_utils_1.succeed)(this.records);
163
+ }
164
+ _parseField(line) {
165
+ const separatorIndex = line.indexOf(':');
166
+ if (separatorIndex < 1) {
167
+ return (0, ts_utils_1.fail)(`malformed line ("${line}") in record-jar.`);
168
+ }
169
+ const parts = [line.slice(0, separatorIndex), line.slice(separatorIndex + 1)];
170
+ return this._writePendingField().onSuccess(() => {
171
+ this._name = parts[0].trimEnd();
172
+ return RecordParser._parseRecordBody(parts[1].trim()).onSuccess((body) => {
173
+ this._body = body;
174
+ return (0, ts_utils_1.succeed)(true);
175
+ });
176
+ });
177
+ }
178
+ _parseContinuation(line) {
179
+ var _a, _b;
180
+ let trimmed = line.trim();
181
+ if (!this._body.isContinuation) {
182
+ /* c8 ignore next */
183
+ const fixedSize = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.fixedContinuationSize) !== null && _b !== void 0 ? _b : 0;
184
+ if (fixedSize > 0) {
185
+ if (trimmed.length < line.length - fixedSize) {
186
+ // oops, took too much
187
+ trimmed = line.slice(fixedSize);
188
+ }
189
+ }
190
+ }
191
+ return RecordParser._parseRecordBody(trimmed).onSuccess((newBody) => {
192
+ return (0, ts_utils_1.succeed)({
193
+ body: `${this._body.body}${newBody.body}`,
194
+ isContinuation: newBody.isContinuation
195
+ });
196
+ });
197
+ }
198
+ _havePendingRecord() {
199
+ return Object.keys(this._fields).length > 0;
200
+ }
201
+ _writePendingRecord() {
202
+ return this._writePendingField().onSuccess(() => {
203
+ let record = this._havePendingRecord() ? this._fields : undefined;
204
+ if (record !== undefined) {
205
+ record = RecordParser._applyOptions(record, this.options);
206
+ this.records.push(record);
207
+ this._fields = {};
208
+ }
209
+ return (0, ts_utils_1.succeed)(undefined);
210
+ });
211
+ }
212
+ _writePendingField() {
213
+ if (this._name !== undefined) {
214
+ if (this._body.body.length < 1) {
215
+ return (0, ts_utils_1.fail)('empty body value not allowed');
216
+ }
217
+ if (!(0, ts_utils_1.isKeyOf)(this._name, this._fields)) {
218
+ this._fields[this._name] = this._body.body;
219
+ }
220
+ else if (typeof this._fields[this._name] === 'string') {
221
+ const current = this._fields[this._name];
222
+ this._fields[this._name] = [current, this._body.body];
223
+ }
224
+ else {
225
+ const current = this._fields[this._name];
226
+ current.push(this._body.body);
227
+ }
228
+ this._name = undefined;
229
+ this._body = undefined;
230
+ }
231
+ return (0, ts_utils_1.succeed)(true);
232
+ }
233
+ }
234
+ /**
235
+ * Reads a record-jar from an array of strings, each of which represents one
236
+ * line in the source file.
237
+ * @param lines - the array of strings to be parsed
238
+ * @param options - Optional parser configuration
239
+ * @returns a corresponding array of `Record<string, string>`
240
+ * @public
241
+ */
242
+ function parseRecordJarLines(lines, options) {
243
+ return RecordParser.parse(lines, options);
244
+ }
245
+ exports.parseRecordJarLines = parseRecordJarLines;
246
+ /**
247
+ * Reads a record-jar file from a supplied path.
248
+ * @param srcPath - Source path from which the file is read.
249
+ * @param options - Optional parser configuration
250
+ * @returns The contents of the file as an array of `Record<string, string>`
251
+ * @see https://datatracker.ietf.org/doc/html/draft-phillips-record-jar-01
252
+ * @public
253
+ */
254
+ function readRecordJarFileSync(srcPath, options) {
255
+ return (0, ts_utils_1.captureResult)(() => {
256
+ const fullPath = path.resolve(srcPath);
257
+ return fs.readFileSync(fullPath, 'utf8').toString().split(/\r?\n/);
258
+ }).onSuccess((lines) => {
259
+ return parseRecordJarLines(lines, options);
260
+ });
261
+ }
262
+ exports.readRecordJarFileSync = readRecordJarFileSync;
263
+ //# sourceMappingURL=recordJarHelpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recordJarHelpers.js","sourceRoot":"","sources":["../../../src/packlets/record-jar/recordJarHelpers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,uCAAyB;AACzB,2CAA6B;AAE7B,4CAA8E;AA4B9E,MAAM,YAAY;IAQhB,gEAAgE;IAChE,YAAoB,OAAgC;QARpC,YAAO,GAAgB,EAAE,CAAC;QAGhC,YAAO,GAAc,EAAE,CAAC;QACxB,UAAK,GAAuB,SAAS,CAAC;QACtC,UAAK,GAA4B,SAAS,CAAC;QAInD,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;IAC/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IAAI,CAAC,CAAC;YACzD,CAAC;iBAAM,CAAC;gBACN,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAa,CAAC;gBACrD,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,KAAM,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;YACD,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;YACvB,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACzB,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;IACvB,CAAC;CACF;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CAAC,KAAe,EAAE,OAAgC;IACnF,OAAO,YAAY,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAC5C,CAAC;AAFD,kDAEC;AAED;;;;;;;GAOG;AACH,SAAgB,qBAAqB,CACnC,OAAe,EACf,OAAgC;IAEhC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvC,OAAO,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACrE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;QACrB,OAAO,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC,CAAC,CAAC;AACL,CAAC;AAVD,sDAUC","sourcesContent":["/*\n * Copyright (c) 2022 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { Result, captureResult, fail, isKeyOf, succeed } from '@fgv/ts-utils';\n\ninterface IRecordBody {\n body: string;\n isContinuation: boolean;\n}\n\n/**\n * Represents a single record in a JAR file\n * @public\n */\nexport type JarRecord = Record<string, string | string[]>;\n\n/**\n * @public\n */\nexport type JarFieldPicker<T extends JarRecord = JarRecord> = (record: T) => (keyof T)[];\n\n/**\n * Options for a JAR record parser.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface JarRecordParserOptions {\n readonly arrayFields?: string[] | JarFieldPicker;\n readonly fixedContinuationSize?: number;\n}\n\nclass RecordParser {\n public readonly records: JarRecord[] = [];\n public readonly options: JarRecordParserOptions;\n\n protected _fields: JarRecord = {};\n protected _name: string | undefined = undefined;\n protected _body: IRecordBody | undefined = undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n private constructor(options?: JarRecordParserOptions) {\n this.options = options ?? {};\n }\n\n public static parse(lines: string[], options?: JarRecordParserOptions): Result<JarRecord[]> {\n return new RecordParser(options)._parse(lines);\n }\n\n protected static _parseRecordBody(body: string): Result<IRecordBody> {\n const isContinuation = body.endsWith('\\\\');\n if (isContinuation) {\n body = body.slice(0, body.length - 1);\n }\n if (this._hasEscapes(body)) {\n const result = this._replaceEscapes(body);\n if (result.isFailure()) {\n return fail(result.message);\n }\n body = result.value;\n }\n return succeed({ body, isContinuation });\n }\n\n protected static _hasEscapes(from: string): boolean {\n return from.includes('\\\\') || from.includes('&');\n }\n\n protected static _replaceEscapes(body: string): Result<string> {\n const invalid: string[] = [];\n const escaped = body.replace(/(\\\\.)|(&#x[a-fA-F0-9]{2,6};)/g, (match) => {\n switch (match) {\n case '\\\\\\\\':\n return '\\\\';\n case '\\\\&':\n return '&';\n case '\\\\r':\n return '\\r';\n case '\\\\n':\n return '\\n';\n case '\\\\t':\n return '\\t';\n }\n if (match.startsWith('&')) {\n const hexCode = `0x${match.slice(3, match.length - 1)}`;\n const charCode = Number.parseInt(hexCode, 16);\n return String.fromCharCode(charCode);\n }\n invalid.push(match);\n return '\\\\';\n });\n if (invalid.length > 0) {\n return fail(`unrecognized escape \"${invalid.join(', ')}\" in record-jar body`);\n }\n return succeed(escaped);\n }\n\n protected static _applyOptions(record: JarRecord, options: JarRecordParserOptions): JarRecord {\n if (options.arrayFields) {\n record = { ...record }; // don't edit incoming values\n const arrayFields = Array.isArray(options.arrayFields)\n ? options.arrayFields\n : options.arrayFields(record);\n\n for (const field of arrayFields) {\n if (isKeyOf(field, record) && typeof record[field] === 'string') {\n const current = record[field] as string;\n record[field] = [current];\n }\n }\n }\n return record;\n }\n\n protected _parse(lines: string[]): Result<JarRecord[]> {\n for (let n = 0; n < lines.length; n++) {\n const line = lines[n];\n if (line.startsWith('%%') && !this._body?.isContinuation) {\n const result = this._writePendingRecord();\n if (result.isFailure()) {\n return fail(`${n}: ${result.message}`);\n }\n } else if (/^\\s*$/.test(line)) {\n // ignore blank lines but cancel continuation\n if (this._body) {\n this._body.isContinuation = false;\n }\n continue;\n } else if (this._body?.isContinuation || /^\\s+/.test(line)) {\n // explicit continuation on previous line or implicit starts with whitespace\n if (this._body === undefined) {\n return fail(`${n}: continuation (\"${line}\") without prior value.`);\n }\n const result = this._parseContinuation(line);\n if (result.isFailure()) {\n return fail(`${n}: ${result.message}`);\n }\n this._body = result.value;\n } else {\n const result = this._parseField(line);\n if (result.isFailure()) {\n return fail(`${n}: ${result.message}`);\n }\n }\n }\n\n const result = this._writePendingRecord();\n if (result.isFailure()) {\n return fail(`${lines.length}: ${result.message}`);\n }\n return succeed(this.records);\n }\n\n protected _parseField(line: string): Result<boolean> {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 1) {\n return fail(`malformed line (\"${line}\") in record-jar.`);\n }\n const parts = [line.slice(0, separatorIndex), line.slice(separatorIndex + 1)];\n\n return this._writePendingField().onSuccess(() => {\n this._name = parts[0].trimEnd();\n return RecordParser._parseRecordBody(parts[1].trim()).onSuccess((body) => {\n this._body = body;\n return succeed(true);\n });\n });\n }\n\n protected _parseContinuation(line: string): Result<IRecordBody> {\n let trimmed = line.trim();\n if (!this._body!.isContinuation) {\n /* c8 ignore next */\n const fixedSize = this.options?.fixedContinuationSize ?? 0;\n if (fixedSize > 0) {\n if (trimmed.length < line.length - fixedSize) {\n // oops, took too much\n trimmed = line.slice(fixedSize);\n }\n }\n }\n return RecordParser._parseRecordBody(trimmed).onSuccess((newBody) => {\n return succeed({\n body: `${this._body!.body}${newBody.body}`,\n isContinuation: newBody.isContinuation\n });\n });\n }\n\n protected _havePendingRecord(): boolean {\n return Object.keys(this._fields).length > 0;\n }\n\n protected _writePendingRecord(): Result<JarRecord | undefined> {\n return this._writePendingField().onSuccess(() => {\n let record = this._havePendingRecord() ? this._fields : undefined;\n if (record !== undefined) {\n record = RecordParser._applyOptions(record, this.options);\n this.records.push(record);\n this._fields = {};\n }\n return succeed(undefined);\n });\n }\n\n protected _writePendingField(): Result<boolean> {\n if (this._name !== undefined) {\n if (this._body!.body.length < 1) {\n return fail('empty body value not allowed');\n }\n if (!isKeyOf(this._name, this._fields)) {\n this._fields[this._name] = this._body!.body;\n } else if (typeof this._fields[this._name] === 'string') {\n const current = this._fields[this._name] as string;\n this._fields[this._name] = [current, this._body!.body];\n } else {\n const current = this._fields[this._name] as string[];\n current.push(this._body!.body);\n }\n this._name = undefined;\n this._body = undefined;\n }\n return succeed(true);\n }\n}\n\n/**\n * Reads a record-jar from an array of strings, each of which represents one\n * line in the source file.\n * @param lines - the array of strings to be parsed\n * @param options - Optional parser configuration\n * @returns a corresponding array of `Record<string, string>`\n * @public\n */\nexport function parseRecordJarLines(lines: string[], options?: JarRecordParserOptions): Result<JarRecord[]> {\n return RecordParser.parse(lines, options);\n}\n\n/**\n * Reads a record-jar file from a supplied path.\n * @param srcPath - Source path from which the file is read.\n * @param options - Optional parser configuration\n * @returns The contents of the file as an array of `Record<string, string>`\n * @see https://datatracker.ietf.org/doc/html/draft-phillips-record-jar-01\n * @public\n */\nexport function readRecordJarFileSync(\n srcPath: string,\n options?: JarRecordParserOptions\n): Result<JarRecord[]> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n return fs.readFileSync(fullPath, 'utf8').toString().split(/\\r?\\n/);\n }).onSuccess((lines) => {\n return parseRecordJarLines(lines, options);\n });\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@fgv/ts-extras",
3
+ "version": "2.0.1",
4
+ "description": "Assorted Typescript Utilities",
5
+ "main": "lib/index.js",
6
+ "types": "dist/ts-extras.d.ts",
7
+ "scripts": {
8
+ "build": "heft test --clean",
9
+ "clean": "heft clean",
10
+ "test": "heft test",
11
+ "build-docs": "api-documenter markdown --input-folder ./temp --output-folder docs",
12
+ "build-all": "rushx build; rushx build-docs",
13
+ "test-handles": "jest --runInBand --detectOpenHandles",
14
+ "clean-jest": "jest --clear-cache",
15
+ "coverage": "jest --coverage",
16
+ "lint": "eslint src --ext .ts",
17
+ "fixlint": "eslint src --ext .ts --fix"
18
+ },
19
+ "sideEffects": false,
20
+ "keywords": [
21
+ "typescript",
22
+ "json"
23
+ ],
24
+ "author": "Erik Fortune",
25
+ "license": "MIT",
26
+ "bugs": {
27
+ "url": "https://github.com/ErikFortune/fgv/issues"
28
+ },
29
+ "homepage": "https://github.com/ErikFortune/fgv#readme",
30
+ "devDependencies": {
31
+ "@jest/expect-utils": "^29.7.0",
32
+ "@microsoft/api-documenter": "^7.23.17",
33
+ "@microsoft/api-extractor": "^7.39.1",
34
+ "@types/jest": "^29.5.11",
35
+ "@types/luxon": "^3.4.1",
36
+ "@types/mustache": "^4.2.5",
37
+ "@types/node": "^20.11.5",
38
+ "@types/papaparse": "^5.3.14",
39
+ "@typescript-eslint/eslint-plugin": "^6.19.0",
40
+ "@typescript-eslint/parser": "^6.19.0",
41
+ "eslint": "^8.56.0",
42
+ "eslint-config-standard": "^17.1.0",
43
+ "eslint-plugin-import": "^2.29.1",
44
+ "eslint-plugin-node": "^11.1.0",
45
+ "eslint-plugin-promise": "^6.1.1",
46
+ "jest": "^29.7.0",
47
+ "jest-extended": "^4.0.2",
48
+ "jest-matcher-utils": "^29.7.0",
49
+ "rimraf": "^5.0.5",
50
+ "ts-jest": "^29.1.1",
51
+ "ts-node": "^10.9.2",
52
+ "typescript": "^5.3.3",
53
+ "eslint-plugin-n": "^16.6.2",
54
+ "jest-snapshot": "~29.7.0",
55
+ "@rushstack/heft": "~0.64.0",
56
+ "@rushstack/heft-node-rig": "~2.4.0",
57
+ "@rushstack/eslint-config": "~3.6.0",
58
+ "@types/heft-jest": "1.0.6",
59
+ "@rushstack/heft-jest-plugin": "~0.11.0",
60
+ "eslint-plugin-tsdoc": "~0.2.17",
61
+ "@fgv/ts-utils-jest": "workspace:*"
62
+ },
63
+ "dependencies": {
64
+ "luxon": "^3.4.4",
65
+ "mustache": "^4.2.0",
66
+ "papaparse": "^5.4.1",
67
+ "@fgv/ts-utils": "workspace:*"
68
+ }
69
+ }