@fgv/ts-json-base 5.0.1-8 → 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 (46) hide show
  1. package/dist/index.browser.js +31 -0
  2. package/dist/index.js +29 -0
  3. package/dist/packlets/converters/converters.js +187 -0
  4. package/dist/packlets/converters/index.js +23 -0
  5. package/dist/packlets/file-tree/directoryItem.js +67 -0
  6. package/dist/packlets/file-tree/fileItem.js +126 -0
  7. package/dist/packlets/file-tree/fileTree.js +85 -0
  8. package/dist/packlets/file-tree/fileTreeAccessors.js +23 -0
  9. package/dist/packlets/file-tree/fileTreeHelpers.inMemory.js +28 -0
  10. package/dist/packlets/file-tree/fileTreeHelpers.js +29 -0
  11. package/dist/packlets/file-tree/fsTree.js +122 -0
  12. package/dist/packlets/file-tree/in-memory/inMemoryTree.js +177 -0
  13. package/dist/packlets/file-tree/in-memory/index.js +23 -0
  14. package/dist/packlets/file-tree/in-memory/treeBuilder.js +173 -0
  15. package/dist/packlets/file-tree/index.browser.js +34 -0
  16. package/dist/packlets/file-tree/index.js +35 -0
  17. package/dist/packlets/json/common.js +145 -0
  18. package/dist/packlets/json/index.js +23 -0
  19. package/dist/packlets/json-compatible/common.js +23 -0
  20. package/dist/packlets/json-compatible/converters.js +90 -0
  21. package/dist/packlets/json-compatible/index.js +26 -0
  22. package/dist/packlets/json-compatible/validators.js +54 -0
  23. package/dist/packlets/json-file/file.js +74 -0
  24. package/dist/packlets/json-file/index.browser.js +30 -0
  25. package/dist/packlets/json-file/index.js +30 -0
  26. package/dist/packlets/json-file/jsonFsHelper.js +166 -0
  27. package/dist/packlets/json-file/jsonLike.js +26 -0
  28. package/dist/packlets/json-file/jsonTreeHelper.js +116 -0
  29. package/dist/packlets/validators/index.js +23 -0
  30. package/dist/packlets/validators/validators.js +179 -0
  31. package/dist/test/fixtures/file-tree/config.json +1 -0
  32. package/dist/test/fixtures/file-tree/data/items.json +1 -0
  33. package/dist/test/fixtures/file-tree/docs/api/reference.json +1 -0
  34. package/dist/test/unit/data/file/bad/bad3.json +3 -0
  35. package/dist/test/unit/data/file/bad/thing1.json +4 -0
  36. package/dist/test/unit/data/file/bad/thing2.json +3 -0
  37. package/dist/test/unit/data/file/good/thing1.json +4 -0
  38. package/dist/test/unit/data/file/good/thing2.json +3 -0
  39. package/dist/test/unit/json-compatible/helpers.js +32 -0
  40. package/dist/ts-json-base.d.ts +51 -1
  41. package/dist/tsdoc-metadata.json +1 -1
  42. package/lib/packlets/json-file/index.browser.d.ts +1 -1
  43. package/lib/packlets/json-file/index.browser.js +2 -2
  44. package/lib/packlets/validators/validators.d.ts +41 -1
  45. package/lib/packlets/validators/validators.js +60 -1
  46. package/package.json +7 -5
@@ -0,0 +1,145 @@
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, fail, succeed } from '@fgv/ts-utils';
23
+ /**
24
+ * Test if an `unknown` is a {@link JsonValue | JsonValue}.
25
+ * @param from - The `unknown` to be tested
26
+ * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},
27
+ * `false` otherwise.
28
+ * @public
29
+ */
30
+ export function isJsonPrimitive(from) {
31
+ return typeof from === 'boolean' || typeof from === 'number' || typeof from === 'string' || from === null;
32
+ }
33
+ /**
34
+ * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.
35
+ * @param from - The `unknown` to be tested.
36
+ * @returns `true` if the supplied parameter is a non-array, non-special object
37
+ * with no symbol keys, `false` otherwise.
38
+ * @public
39
+ */
40
+ export function isJsonObject(from) {
41
+ return (typeof from === 'object' &&
42
+ from !== null &&
43
+ !Array.isArray(from) &&
44
+ !(from instanceof RegExp) &&
45
+ !(from instanceof Date) &&
46
+ !(from instanceof Map) &&
47
+ !(from instanceof Set) &&
48
+ !(from instanceof Error) &&
49
+ Object.getOwnPropertySymbols(from).length === 0);
50
+ }
51
+ /**
52
+ * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.
53
+ * @param from - The `unknown` to be tested.
54
+ * @returns `true` if the supplied parameter is an array object,
55
+ * `false` otherwise.
56
+ * @public
57
+ */
58
+ export function isJsonArray(from) {
59
+ return typeof from === 'object' && Array.isArray(from);
60
+ }
61
+ /**
62
+ * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},
63
+ * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value
64
+ * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -
65
+ * it does not test the properties of an object or elements in an array.
66
+ * @param from - The `unknown` value to be tested
67
+ * @public
68
+ */
69
+ export function classifyJsonValue(from) {
70
+ if (isJsonPrimitive(from)) {
71
+ return succeed('primitive');
72
+ }
73
+ else if (isJsonObject(from)) {
74
+ return succeed('object');
75
+ }
76
+ else if (isJsonArray(from)) {
77
+ return succeed('array');
78
+ }
79
+ return fail(`Invalid JSON: ${from}`);
80
+ }
81
+ /**
82
+ * Picks a nested field from a supplied {@link JsonObject | JsonObject}.
83
+ * @param src - The {@link JsonObject | object} from which the field is to be picked.
84
+ * @param path - Dot-separated path of the member to be picked.
85
+ * @returns `Success` with the property if the path is valid, `Failure`
86
+ * with an error message otherwise.
87
+ * @public
88
+ */
89
+ export function pickJsonValue(src, path) {
90
+ let result = src;
91
+ for (const part of path.split('.')) {
92
+ if (result && isJsonObject(result)) {
93
+ result = result[part];
94
+ if (result === undefined) {
95
+ return fail(`${path}: child '${part}' does not exist`);
96
+ }
97
+ }
98
+ else {
99
+ return fail(`${path}: child '${part}' does not exist`);
100
+ }
101
+ }
102
+ return succeed(result);
103
+ }
104
+ /**
105
+ * Picks a nested {@link JsonObject | JsonObject} from a supplied
106
+ * {@link JsonObject | JsonObject}.
107
+ * @param src - The {@link JsonObject | object} from which the field is
108
+ * to be picked.
109
+ * @param path - Dot-separated path of the member to be picked.
110
+ * @returns `Success` with the property if the path is valid and the value
111
+ * is an object. Returns `Failure` with details if an error occurs.
112
+ * @public
113
+ */
114
+ export function pickJsonObject(src, path) {
115
+ return pickJsonValue(src, path).onSuccess((v) => {
116
+ if (!isJsonObject(v)) {
117
+ return fail(`${path}: not an object`);
118
+ }
119
+ return succeed(v);
120
+ });
121
+ }
122
+ /**
123
+ * "Sanitizes" an `unknown` by stringifying and then parsing it. Guarantees a
124
+ * valid {@link JsonValue | JsonValue} but is not idempotent and gives no guarantees
125
+ * about fidelity. Fails if the supplied value cannot be stringified as Json.
126
+ * @param from - The `unknown` to be sanitized.
127
+ * @returns `Success` with a {@link JsonValue | JsonValue} if conversion succeeds,
128
+ * `Failure` with details if an error occurs.
129
+ * @public
130
+ */
131
+ export function sanitizeJson(from) {
132
+ return captureResult(() => JSON.parse(JSON.stringify(from)));
133
+ }
134
+ /**
135
+ * Sanitizes some value using JSON stringification and parsing, returning an
136
+ * returning a matching strongly-typed value.
137
+ * @param from - The value to be sanitized.
138
+ * @returns `Success` with a {@link JsonObject | JsonObject} if conversion succeeds,
139
+ * `Failure` with details if an error occurs.
140
+ * @public
141
+ */
142
+ export function sanitizeJsonObject(from) {
143
+ return captureResult(() => JSON.parse(JSON.stringify(from)));
144
+ }
145
+ //# sourceMappingURL=common.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 './common';
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright (c) 2025 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 {};
23
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1,90 @@
1
+ /*
2
+ * Copyright (c) 2025 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 { Conversion, Converters } from '@fgv/ts-utils';
23
+ /**
24
+ * A helper function to create a {@link JsonCompatible.ArrayConverter | JSON-compatible ArrayConverter<T, TC>}
25
+ * which converts a supplied `unknown` value to a valid array of {@link JsonCompatibleType | JsonCompatibleType<T>}.
26
+ * @param converter - {@link JsonCompatible.Converter | JSON-compatible Converter<T, TC>} or {@link JsonCompatible.Validator | JSON-compatible Validator<T>} used for each item in the source array.
27
+ * @param onError - The error handling option to use for the conversion.
28
+ * @returns A {@link JsonCompatible.ArrayConverter | JSON-compatible ArrayConverter<T, TC>} which returns `JsonCompatibleType<T>[]`.
29
+ * @public
30
+ */
31
+ export function arrayOf(converter, onError = 'failOnError') {
32
+ return Converters.arrayOf(converter, onError);
33
+ }
34
+ /**
35
+ * A helper function to create a {@link JsonCompatible.RecordConverter | JSON-compatible RecordConverter<T, TC, TK>}
36
+ * which converts the `string`-keyed properties using a supplied {@link JsonCompatible.Converter | JSON-compatible Converter<T, TC>} or
37
+ * {@link JsonCompatible.Validator | JSON-compatible Validator<T>} to produce a
38
+ * `Record<TK, JsonCompatibleType<T>>`.
39
+ * @remarks
40
+ * If present, the supplied `Converters.KeyedConverterOptions` can provide a strongly-typed
41
+ * converter for keys and/or control the handling of elements that fail conversion.
42
+ * @param converter - {@link JsonCompatible.Converter | JSON-compatible Converter<T, TC>}
43
+ * or {@link JsonCompatible.Validator | JSON-compatible Validator<T>} used for each item in the source object.
44
+ * @param options - Optional `Converters.KeyedConverterOptions<TK, TC>` which
45
+ * supplies a key converter and/or error-handling options.
46
+ * @returns A {@link JsonCompatible.RecordConverter | JSON-compatible RecordConverter<T, TC, TK>} which
47
+ * converts a supplied `unknown` value to a valid record of {@link JsonCompatibleType | JsonCompatible} values.
48
+ * @public
49
+ */
50
+ export function recordOf(converter, options) {
51
+ return Converters.recordOf(converter, options !== null && options !== void 0 ? options : { onError: 'fail' });
52
+ }
53
+ /**
54
+ * A helper function to create a {@link JsonCompatible.ObjectConverter | JSON-compatible ObjectConverter<T, TC>} which converts a
55
+ * supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatibleType<T>} value.
56
+ * @param properties - The properties to convert.
57
+ * @param options - The options to use for the conversion.
58
+ * @returns A {@link JsonCompatible.ObjectConverter | JSON-compatible ObjectConverter<T, TC>} which
59
+ * converts a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatibleType<T>} value.
60
+ * @public
61
+ */
62
+ export function object(properties, options) {
63
+ return new Conversion.ObjectConverter(properties, options);
64
+ }
65
+ /**
66
+ * A helper function to create a {@link JsonCompatible.ObjectConverter | JSON-compatible ObjectConverter<T, TC>} which converts a
67
+ * supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatibleType<T>} value.
68
+ * @param properties - The properties to convert.
69
+ * @param options - The options to use for the conversion.
70
+ * @returns A {@link JsonCompatible.ObjectConverter | JSON-compatible ObjectConverter<T, TC>} which
71
+ * converts a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatibleType<T>} value.
72
+ * @public
73
+ */
74
+ export function strictObject(properties, options) {
75
+ const objectOptions = Object.assign(Object.assign({}, options), { strict: true });
76
+ return new Conversion.ObjectConverter(properties, objectOptions);
77
+ }
78
+ /**
79
+ * A helper function to create a {@link JsonCompatible.Converter | JSON-compatible Converter<T, TC>} which converts a
80
+ * supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatibleType<T>} value.
81
+ * @param discriminatorProp - The name of the property used to discriminate types.
82
+ * @param converters - The converters to use for the conversion.
83
+ * @returns A {@link JsonCompatible.Converter | JSON-compatible Converter<T, TC>} which
84
+ * converts a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatibleType<T>} value.
85
+ * @public
86
+ */
87
+ export function discriminatedObject(discriminatorProp, converters) {
88
+ return Converters.discriminatedObject(discriminatorProp, converters);
89
+ }
90
+ //# sourceMappingURL=converters.js.map
@@ -0,0 +1,26 @@
1
+ /*
2
+ * Copyright (c) 2025 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 './common';
23
+ import * as Converters from './converters';
24
+ import * as Validators from './validators';
25
+ export { Converters, Validators };
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,54 @@
1
+ /*
2
+ * Copyright (c) 2025 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 { Validators } from '@fgv/ts-utils';
23
+ /**
24
+ * A helper function to create a {@link JsonCompatible.ArrayValidator | JSON-compatible ArrayValidator<T, TC>} which validates a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatible} value.
25
+ * @param validateElement - The element validator to use.
26
+ * @param params - The parameters to use for the validation.
27
+ * @returns A {@link JsonCompatible.ArrayValidator | JSON-compatible ArrayValidator<T, TC>} which validates a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatible} value.
28
+ * @public
29
+ */
30
+ export function arrayOf(validateElement, params) {
31
+ return Validators.arrayOf(validateElement, params !== null && params !== void 0 ? params : {});
32
+ }
33
+ /**
34
+ * A helper function to create a {@link JsonCompatible.RecordValidator | JSON-compatible RecordValidator<T, TC, TK>} which validates a supplied `unknown` value
35
+ * to a valid {@link JsonCompatibleType | JsonCompatible} value.
36
+ * @param validateElement - The element validator to use.
37
+ * @param options - The options to use for the validation.
38
+ * @returns A `Validation.Validator<Record<TK, JsonCompatibleType<T>>, TC>` which validates a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatible} value.
39
+ * @public
40
+ */
41
+ export function recordOf(validateElement, options) {
42
+ return Validators.recordOf(validateElement, options !== null && options !== void 0 ? options : {});
43
+ }
44
+ /**
45
+ * A helper function to create a {@link JsonCompatible.ObjectValidator | JSON-compatible ObjectValidator<T, TC>} which validates a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatible} value.
46
+ * @param properties - The properties to validate.
47
+ * @param params - The parameters to use for the validation.
48
+ * @returns A {@link JsonCompatible.ObjectValidator | JSON-compatible ObjectValidator<T, TC>} which validates a supplied `unknown` value to a valid {@link JsonCompatibleType | JsonCompatible} value.
49
+ * @public
50
+ */
51
+ export function object(properties, params) {
52
+ return Validators.object(properties, params !== null && params !== void 0 ? params : {});
53
+ }
54
+ //# sourceMappingURL=validators.js.map
@@ -0,0 +1,74 @@
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 { DefaultJsonFsHelper, JsonFsHelper } from './jsonFsHelper';
23
+ import { DefaultJsonLike } from './jsonLike';
24
+ /**
25
+ * {@inheritdoc JsonFile.JsonFsHelper.readJsonFileSync}
26
+ * @public
27
+ */
28
+ export function readJsonFileSync(srcPath) {
29
+ return DefaultJsonFsHelper.readJsonFileSync(srcPath);
30
+ }
31
+ /**
32
+ * Read a JSON file and apply a supplied converter.
33
+ * @param srcPath - Path of the file to read.
34
+ * @param converter - `Converter` used to convert the file contents
35
+ * @returns `Success` with a result of type `<T>`, or `Failure`* with a message if an error occurs.
36
+ * @public
37
+ */
38
+ export function convertJsonFileSync(srcPath, converter) {
39
+ return DefaultJsonFsHelper.convertJsonFileSync(srcPath, converter);
40
+ }
41
+ /**
42
+ * Reads all JSON files from a directory and apply a supplied converter.
43
+ * @param srcPath - The path of the folder to be read.
44
+ * @param options - {@link JsonFile.IJsonFsDirectoryOptions | Options} to control
45
+ * conversion and filtering
46
+ * @public
47
+ */
48
+ export function convertJsonDirectorySync(srcPath, options) {
49
+ return DefaultJsonFsHelper.convertJsonDirectorySync(srcPath, options);
50
+ }
51
+ /**
52
+ * Reads and converts all JSON files from a directory, returning a
53
+ * `Map<string, T>` indexed by file base name (i.e. minus the extension)
54
+ * with an optional name transformation applied if present.
55
+ * @param srcPath - The path of the folder to be read.
56
+ * @param options - {@link JsonFile.IJsonFsDirectoryToMapOptions | Options} to control conversion,
57
+ * filtering and naming.
58
+ * @public
59
+ */
60
+ export function convertJsonDirectoryToMapSync(srcPath, options) {
61
+ return DefaultJsonFsHelper.convertJsonDirectoryToMapSync(srcPath, options);
62
+ }
63
+ const CompatJsonFsHelper = new JsonFsHelper({
64
+ json: DefaultJsonLike,
65
+ allowUndefinedWrite: true // for compatibility
66
+ });
67
+ /**
68
+ * {@inheritDoc JsonFile.JsonFsHelper.writeJsonFileSync}
69
+ * @public
70
+ */
71
+ export function writeJsonFileSync(srcPath, value) {
72
+ return CompatJsonFsHelper.writeJsonFileSync(srcPath, value);
73
+ }
74
+ //# sourceMappingURL=file.js.map
@@ -0,0 +1,30 @@
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 JSON file exports - excludes Node.js filesystem dependencies
23
+ // Export browser-safe core functionality
24
+ export * from './jsonLike';
25
+ // Export FileTree-based helper (web-compatible)
26
+ export * from './jsonTreeHelper';
27
+ // Exclude:
28
+ // - file.ts (wraps jsonFsHelper - requires Node.js fs/path)
29
+ // - jsonFsHelper (requires Node.js fs/path)
30
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1,30 @@
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 core JSON functionality (no filesystem deps)
23
+ export * from './file';
24
+ export * from './jsonLike';
25
+ // Export FileTree-based helper (web-compatible)
26
+ export * from './jsonTreeHelper';
27
+ // Export filesystem helpers separately for tree-shaking
28
+ // Web apps that don't import JsonFsHelper won't bundle fs/path
29
+ export * from './jsonFsHelper';
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,166 @@
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, fail, mapResults, succeed } from '@fgv/ts-utils';
23
+ import fs from 'fs';
24
+ import path from 'path';
25
+ import { DefaultJsonLike } from './jsonLike';
26
+ /**
27
+ * Function to transform the name of some entity, given only a previous name. This
28
+ * default implementation always returns `Success` with the value that was passed in.
29
+ * @param n - The name to be transformed.
30
+ * @returns - `Success` with the string that was passed in.
31
+ * @public
32
+ */
33
+ const defaultNameTransformer = (n) => succeed(n);
34
+ /**
35
+ * Default configuration for {@link JsonFile.JsonFsHelper | JsonFsHelper}.
36
+ * @public
37
+ */
38
+ export const DefaultJsonFsHelperConfig = {
39
+ json: DefaultJsonLike,
40
+ allowUndefinedWrite: false,
41
+ defaultFiles: [/.*.json/]
42
+ };
43
+ /**
44
+ * Helper class to simplify common filesystem operations involving JSON (or JSON-like)
45
+ * files.
46
+ * @public
47
+ */
48
+ export class JsonFsHelper {
49
+ /**
50
+ * Construct a new {@link JsonFile.JsonFsHelper | JsonFsHelper}.
51
+ * @param json - Optional {@link JsonFile.IJsonLike | IJsonLike} used to process strings
52
+ * and JSON values.
53
+ */
54
+ constructor(init) {
55
+ this.config = Object.assign(Object.assign({}, DefaultJsonFsHelperConfig), (init !== null && init !== void 0 ? init : {}));
56
+ }
57
+ /**
58
+ * Read type-safe JSON from a file.
59
+ * @param srcPath - Path of the file to read
60
+ * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`
61
+ * with a message if an error occurs.
62
+ */
63
+ readJsonFileSync(srcPath) {
64
+ return captureResult(() => {
65
+ const fullPath = path.resolve(srcPath);
66
+ const body = fs.readFileSync(fullPath, 'utf8').toString();
67
+ return this.config.json.parse(body);
68
+ });
69
+ }
70
+ /**
71
+ * Read a JSON file and apply a supplied converter or validator.
72
+ * @param srcPath - Path of the file to read.
73
+ * @param cv - Converter or validator used to process the file.
74
+ * @returns `Success` with a result of type `<T>`, or `Failure`
75
+ * with a message if an error occurs.
76
+ */
77
+ convertJsonFileSync(srcPath, cv, context) {
78
+ return this.readJsonFileSync(srcPath).onSuccess((json) => {
79
+ return cv.convert(json, context);
80
+ });
81
+ }
82
+ /**
83
+ * Reads all JSON files from a directory and apply a supplied converter or validator.
84
+ * @param srcPath - The path of the folder to be read.
85
+ * @param options - {@link JsonFile.IJsonFsDirectoryOptions | Options} to control
86
+ * conversion and filtering
87
+ */
88
+ convertJsonDirectorySync(srcPath, options, context) {
89
+ return captureResult(() => {
90
+ const fullPath = path.resolve(srcPath);
91
+ if (!fs.statSync(fullPath).isDirectory()) {
92
+ throw new Error(`${fullPath}: Not a directory`);
93
+ }
94
+ const files = fs.readdirSync(fullPath, { withFileTypes: true });
95
+ const results = files
96
+ .map((fi) => {
97
+ if (fi.isFile() && this._pathMatchesOptions(options, fi.name)) {
98
+ const filePath = path.resolve(fullPath, fi.name);
99
+ return this.convertJsonFileSync(filePath, options.converter, context)
100
+ .onSuccess((payload) => {
101
+ return succeed({
102
+ filename: fi.name,
103
+ item: payload
104
+ });
105
+ })
106
+ .onFailure((message) => {
107
+ return fail(`${fi.name}: ${message}`);
108
+ });
109
+ }
110
+ return undefined;
111
+ })
112
+ .filter((r) => r !== undefined);
113
+ return mapResults(results).orThrow();
114
+ });
115
+ }
116
+ /**
117
+ * Reads and converts or validates all JSON files from a directory, returning a
118
+ * `Map<string, T>` indexed by file base name (i.e. minus the extension)
119
+ * with an optional name transformation applied if present.
120
+ * @param srcPath - The path of the folder to be read.
121
+ * @param options - {@link JsonFile.IJsonFsDirectoryToMapOptions | Options} to control conversion,
122
+ * filtering and naming.
123
+ */
124
+ convertJsonDirectoryToMapSync(srcPath, options, context) {
125
+ return this.convertJsonDirectorySync(srcPath, options, context).onSuccess((items) => {
126
+ var _a;
127
+ const transformName = (_a = options.transformName) !== null && _a !== void 0 ? _a : defaultNameTransformer;
128
+ return mapResults(items.map((item) => {
129
+ const basename = path.basename(item.filename, '.json');
130
+ return transformName(basename, item.item).onSuccess((name) => {
131
+ return succeed([name, item.item]);
132
+ });
133
+ })).onSuccess((items) => {
134
+ return succeed(new Map(items));
135
+ });
136
+ });
137
+ }
138
+ /**
139
+ * Write type-safe JSON to a file.
140
+ * @param srcPath - Path of the file to write.
141
+ * @param value - The {@link JsonValue | JsonValue} to be written.
142
+ */
143
+ writeJsonFileSync(srcPath, value) {
144
+ return captureResult(() => {
145
+ const fullPath = path.resolve(srcPath);
146
+ const stringified = this.config.json.stringify(value, undefined, 2);
147
+ /* c8 ignore next 3 */
148
+ if (stringified === undefined && this.config.allowUndefinedWrite !== true) {
149
+ throw new Error(`Could not stringify ${value}`);
150
+ }
151
+ fs.writeFileSync(fullPath, stringified);
152
+ return true;
153
+ });
154
+ }
155
+ _pathMatchesOptions(options, path) {
156
+ var _a;
157
+ /* c8 ignore next 1 */
158
+ const match = (_a = options.files) !== null && _a !== void 0 ? _a : this.config.defaultFiles;
159
+ return match.some((m) => m.exec(path));
160
+ }
161
+ }
162
+ /**
163
+ * @public
164
+ */
165
+ export const DefaultJsonFsHelper = new JsonFsHelper();
166
+ //# sourceMappingURL=jsonFsHelper.js.map