@fgv/ts-json-base 5.0.0-2 → 5.0.0-21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.vscode/launch.json +16 -0
  2. package/.vscode/settings.json +33 -0
  3. package/config/api-extractor.json +343 -0
  4. package/config/rig.json +16 -0
  5. package/dist/tsdoc-metadata.json +1 -1
  6. package/lib/packlets/validators/validators.js +4 -4
  7. package/lib/test/unit/common.test.d.ts +2 -0
  8. package/lib/test/unit/converters.test.d.ts +2 -0
  9. package/lib/test/unit/data/file/bad/bad3.json +3 -0
  10. package/lib/test/unit/data/file/bad/thing1.json +4 -0
  11. package/lib/test/unit/data/file/bad/thing2.json +3 -0
  12. package/lib/test/unit/data/file/good/thing1.json +4 -0
  13. package/lib/test/unit/data/file/good/thing2.json +3 -0
  14. package/lib/test/unit/file.test.d.ts +2 -0
  15. package/lib/test/unit/jsonFsHelper.test.d.ts +2 -0
  16. package/lib/test/unit/validators.test.d.ts +2 -0
  17. package/package.json +10 -10
  18. package/src/index.ts +28 -0
  19. package/src/packlets/converters/converters.ts +174 -0
  20. package/src/packlets/converters/index.ts +23 -0
  21. package/src/packlets/json/common.ts +187 -0
  22. package/src/packlets/json/index.ts +23 -0
  23. package/src/packlets/json-file/file.ts +97 -0
  24. package/src/packlets/json-file/index.ts +25 -0
  25. package/src/packlets/json-file/jsonFsHelper.ts +262 -0
  26. package/src/packlets/json-file/jsonLike.ts +56 -0
  27. package/src/packlets/validators/index.ts +23 -0
  28. package/src/packlets/validators/validators.ts +155 -0
  29. package/CHANGELOG.md +0 -100
  30. package/lib/index.d.ts.map +0 -1
  31. package/lib/index.js.map +0 -1
  32. package/lib/packlets/converters/converters.d.ts.map +0 -1
  33. package/lib/packlets/converters/converters.js.map +0 -1
  34. package/lib/packlets/converters/index.d.ts.map +0 -1
  35. package/lib/packlets/converters/index.js.map +0 -1
  36. package/lib/packlets/json/common.d.ts.map +0 -1
  37. package/lib/packlets/json/common.js.map +0 -1
  38. package/lib/packlets/json/index.d.ts.map +0 -1
  39. package/lib/packlets/json/index.js.map +0 -1
  40. package/lib/packlets/json-file/file.d.ts.map +0 -1
  41. package/lib/packlets/json-file/file.js.map +0 -1
  42. package/lib/packlets/json-file/index.d.ts.map +0 -1
  43. package/lib/packlets/json-file/index.js.map +0 -1
  44. package/lib/packlets/json-file/jsonFsHelper.d.ts.map +0 -1
  45. package/lib/packlets/json-file/jsonFsHelper.js.map +0 -1
  46. package/lib/packlets/json-file/jsonLike.d.ts.map +0 -1
  47. package/lib/packlets/json-file/jsonLike.js.map +0 -1
  48. package/lib/packlets/validators/index.d.ts.map +0 -1
  49. package/lib/packlets/validators/index.js.map +0 -1
  50. package/lib/packlets/validators/validators.d.ts.map +0 -1
  51. package/lib/packlets/validators/validators.js.map +0 -1
@@ -0,0 +1,262 @@
1
+ /*
2
+ * Copyright (c) 2020 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { Converter, Result, Validator, captureResult, fail, mapResults, succeed } from '@fgv/ts-utils';
24
+ import * as fs from 'fs';
25
+ import * as path from 'path';
26
+
27
+ import { JsonValue } from '../json';
28
+ import { DefaultJsonLike, IJsonLike } from './jsonLike';
29
+
30
+ /**
31
+ * Options for directory conversion.
32
+ * TODO: add filtering, allowed and excluded.
33
+ * @public
34
+ */
35
+ export interface IJsonFsDirectoryOptions<T, TC = unknown> {
36
+ /**
37
+ * The converter used to convert incoming JSON objects.
38
+ */
39
+ converter: Converter<T, TC> | Validator<T, TC>;
40
+
41
+ /**
42
+ * Filter applied to items in the directory
43
+ */
44
+ files?: RegExp[];
45
+ }
46
+
47
+ /**
48
+ * Return value for one item in a directory conversion.
49
+ * @public
50
+ */
51
+ export interface IReadDirectoryItem<T> {
52
+ /**
53
+ * Relative name of the file that was processed
54
+ */
55
+ filename: string;
56
+
57
+ /**
58
+ * The payload of the file.
59
+ */
60
+ item: T;
61
+ }
62
+
63
+ /**
64
+ * Function to transform the name of a some entity, given an original name
65
+ * and the contents of the entity.
66
+ * @public
67
+ */
68
+ export type ItemNameTransformFunction<T> = (name: string, item: T) => Result<string>;
69
+
70
+ /**
71
+ * Options controlling conversion of a directory to a `Map`.
72
+ * @public
73
+ */
74
+ export interface IJsonFsDirectoryToMapOptions<T, TC = unknown> extends IJsonFsDirectoryOptions<T, TC> {
75
+ transformName?: ItemNameTransformFunction<T>;
76
+ }
77
+
78
+ /**
79
+ * Function to transform the name of some entity, given only a previous name. This
80
+ * default implementation always returns `Success` with the value that was passed in.
81
+ * @param n - The name to be transformed.
82
+ * @returns - `Success` with the string that was passed in.
83
+ * @public
84
+ */
85
+ const defaultNameTransformer = (n: string): Result<string> => succeed(n);
86
+
87
+ /**
88
+ * Configuration for {@link JsonFile.JsonFsHelper | JsonFsHelper}.
89
+ * @public
90
+ */
91
+ export interface IJsonFsHelperConfig {
92
+ json: IJsonLike;
93
+ allowUndefinedWrite: boolean;
94
+ defaultFiles: RegExp[];
95
+ }
96
+
97
+ /**
98
+ * Initialization options for {@link JsonFile.JsonFsHelper | JsonFsHelper}.
99
+ * @public
100
+ */
101
+ export type JsonFsHelperInitOptions = Partial<IJsonFsHelperConfig>;
102
+
103
+ /**
104
+ * Default configuration for {@link JsonFile.JsonFsHelper | JsonFsHelper}.
105
+ * @public
106
+ */
107
+ export const DefaultJsonFsHelperConfig: IJsonFsHelperConfig = {
108
+ json: DefaultJsonLike,
109
+ allowUndefinedWrite: false,
110
+ defaultFiles: [/.*.json/]
111
+ };
112
+
113
+ /**
114
+ * Helper class to simplify common filesystem operations involving JSON (or JSON-like)
115
+ * files.
116
+ * @public
117
+ */
118
+ export class JsonFsHelper {
119
+ /**
120
+ * Configuration for this {@link JsonFile.JsonFsHelper | JsonFsHelper}.
121
+ */
122
+ public readonly config: IJsonFsHelperConfig;
123
+
124
+ /**
125
+ * Construct a new {@link JsonFile.JsonFsHelper | JsonFsHelper}.
126
+ * @param json - Optional {@link JsonFile.IJsonLike | IJsonLike} used to process strings
127
+ * and JSON values.
128
+ */
129
+ public constructor(init?: JsonFsHelperInitOptions) {
130
+ this.config = {
131
+ ...DefaultJsonFsHelperConfig,
132
+ ...(init ?? {})
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Read type-safe JSON from a file.
138
+ * @param srcPath - Path of the file to read
139
+ * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`
140
+ * with a message if an error occurs.
141
+ */
142
+ public readJsonFileSync(srcPath: string): Result<JsonValue> {
143
+ return captureResult(() => {
144
+ const fullPath = path.resolve(srcPath);
145
+ const body = fs.readFileSync(fullPath, 'utf8').toString();
146
+ return this.config.json.parse(body) as JsonValue;
147
+ });
148
+ }
149
+
150
+ /**
151
+ * Read a JSON file and apply a supplied converter or validator.
152
+ * @param srcPath - Path of the file to read.
153
+ * @param cv - Converter or validator used to process the file.
154
+ * @returns `Success` with a result of type `<T>`, or `Failure`
155
+ * with a message if an error occurs.
156
+ */
157
+ public convertJsonFileSync<T, TC = unknown>(
158
+ srcPath: string,
159
+ cv: Converter<T, TC> | Validator<T, TC>,
160
+ context?: TC
161
+ ): Result<T> {
162
+ return this.readJsonFileSync(srcPath).onSuccess((json) => {
163
+ return cv.convert(json, context);
164
+ });
165
+ }
166
+
167
+ /**
168
+ * Reads all JSON files from a directory and apply a supplied converter or validator.
169
+ * @param srcPath - The path of the folder to be read.
170
+ * @param options - {@link JsonFile.IJsonFsDirectoryOptions | Options} to control
171
+ * conversion and filtering
172
+ */
173
+ public convertJsonDirectorySync<T, TC = unknown>(
174
+ srcPath: string,
175
+ options: IJsonFsDirectoryOptions<T>,
176
+ context?: TC
177
+ ): Result<IReadDirectoryItem<T>[]> {
178
+ return captureResult<IReadDirectoryItem<T>[]>(() => {
179
+ const fullPath = path.resolve(srcPath);
180
+ if (!fs.statSync(fullPath).isDirectory()) {
181
+ throw new Error(`${fullPath}: Not a directory`);
182
+ }
183
+ const files = fs.readdirSync(fullPath, { withFileTypes: true });
184
+ const results = files
185
+ .map((fi) => {
186
+ if (fi.isFile() && this._pathMatchesOptions(options, fi.name)) {
187
+ const filePath = path.resolve(fullPath, fi.name);
188
+ return this.convertJsonFileSync(filePath, options.converter, context)
189
+ .onSuccess((payload) => {
190
+ return succeed({
191
+ filename: fi.name,
192
+ item: payload
193
+ });
194
+ })
195
+ .onFailure((message) => {
196
+ return fail(`${fi.name}: ${message}`);
197
+ });
198
+ }
199
+ return undefined;
200
+ })
201
+ .filter((r): r is Result<IReadDirectoryItem<T>> => r !== undefined);
202
+ return mapResults(results).orThrow();
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Reads and converts or validates all JSON files from a directory, returning a
208
+ * `Map<string, T>` indexed by file base name (i.e. minus the extension)
209
+ * with an optional name transformation applied if present.
210
+ * @param srcPath - The path of the folder to be read.
211
+ * @param options - {@link JsonFile.IJsonFsDirectoryToMapOptions | Options} to control conversion,
212
+ * filtering and naming.
213
+ */
214
+ public convertJsonDirectoryToMapSync<T, TC = unknown>(
215
+ srcPath: string,
216
+ options: IJsonFsDirectoryToMapOptions<T, TC>,
217
+ context?: unknown
218
+ ): Result<Map<string, T>> {
219
+ return this.convertJsonDirectorySync(srcPath, options, context).onSuccess((items) => {
220
+ const transformName = options.transformName ?? defaultNameTransformer;
221
+ return mapResults(
222
+ items.map((item) => {
223
+ const basename = path.basename(item.filename, '.json');
224
+ return transformName(basename, item.item).onSuccess((name) => {
225
+ return succeed<[string, T]>([name, item.item]);
226
+ });
227
+ })
228
+ ).onSuccess((items) => {
229
+ return succeed(new Map<string, T>(items));
230
+ });
231
+ });
232
+ }
233
+
234
+ /**
235
+ * Write type-safe JSON to a file.
236
+ * @param srcPath - Path of the file to write.
237
+ * @param value - The {@link JsonValue | JsonValue} to be written.
238
+ */
239
+ public writeJsonFileSync(srcPath: string, value: JsonValue): Result<boolean> {
240
+ return captureResult(() => {
241
+ const fullPath = path.resolve(srcPath);
242
+ const stringified = this.config.json.stringify(value, undefined, 2);
243
+ /* c8 ignore next 3 */
244
+ if (stringified === undefined && this.config.allowUndefinedWrite !== true) {
245
+ throw new Error(`Could not stringify ${value}`);
246
+ }
247
+ fs.writeFileSync(fullPath, stringified!);
248
+ return true;
249
+ });
250
+ }
251
+
252
+ protected _pathMatchesOptions<T, TC>(options: IJsonFsDirectoryOptions<T, TC>, path: string): boolean {
253
+ /* c8 ignore next 1 */
254
+ const match = options.files ?? this.config.defaultFiles;
255
+ return match.some((m) => m.exec(path));
256
+ }
257
+ }
258
+
259
+ /**
260
+ * @public
261
+ */
262
+ export const DefaultJsonFsHelper: JsonFsHelper = new JsonFsHelper();
@@ -0,0 +1,56 @@
1
+ /*
2
+ * Copyright (c) 2024 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { JsonValue } from '../json';
24
+
25
+ /**
26
+ * @public
27
+ */
28
+ export type JsonReviver = (key: string, value: JsonValue) => JsonValue;
29
+
30
+ /**
31
+ * @public
32
+ */
33
+ export type JsonReplacerFunction = (key: string, value: JsonValue) => JsonValue;
34
+
35
+ /**
36
+ * @public
37
+ */
38
+ export type JsonReplacerArray = (string | number)[];
39
+
40
+ /**
41
+ * @public
42
+ */
43
+ export type JsonReplacer = JsonReplacerFunction | JsonReplacerArray;
44
+
45
+ /**
46
+ * @public
47
+ */
48
+ export interface IJsonLike {
49
+ parse(text: string, reviver?: JsonReviver, options?: unknown): JsonValue | undefined;
50
+ stringify(value: JsonValue, replacer?: JsonReplacer, space?: string | number): string | undefined;
51
+ }
52
+
53
+ /**
54
+ * @public
55
+ */
56
+ export const DefaultJsonLike: IJsonLike = JSON;
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright (c) 2020 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ export * from './validators';
@@ -0,0 +1,155 @@
1
+ /*
2
+ * Copyright (c) 2023 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { Failure, Validation, Validator, fail } from '@fgv/ts-utils';
24
+ import { JsonArray, JsonObject, JsonPrimitive, JsonValue, isJsonArray, isJsonObject } from '../json';
25
+
26
+ /* eslint-disable no-use-before-define, @typescript-eslint/no-use-before-define */
27
+
28
+ /**
29
+ * Validation context for in-place JSON validators.
30
+ * @public
31
+ */
32
+ export interface IJsonValidatorContext {
33
+ ignoreUndefinedProperties?: boolean;
34
+ }
35
+
36
+ /**
37
+ * An in-place validator which validates that a supplied `unknown` value is
38
+ * a valid {@link JsonPrimitive | JsonPrimitive}.
39
+ * @public
40
+ */
41
+ export const jsonPrimitive: Validator<JsonPrimitive, IJsonValidatorContext> =
42
+ new Validation.Base.GenericValidator({
43
+ validator: (
44
+ from: unknown,
45
+ ctx?: IJsonValidatorContext,
46
+ self?: Validator<JsonPrimitive, IJsonValidatorContext>
47
+ ): boolean | Failure<JsonPrimitive> => {
48
+ if (from === null) {
49
+ return true;
50
+ }
51
+ switch (typeof from) {
52
+ case 'boolean':
53
+ case 'string':
54
+ return true;
55
+ case 'number':
56
+ if (!Number.isNaN(from)) {
57
+ return true;
58
+ }
59
+ break;
60
+ }
61
+ if (from === undefined && ctx?.ignoreUndefinedProperties === true) {
62
+ return true;
63
+ }
64
+ return fail(`"${String(from)}": not a valid JSON primitive.`);
65
+ }
66
+ });
67
+
68
+ /**
69
+ * An in-place validator which validates that a supplied `unknown` value is
70
+ * a valid {@link JsonObject | JsonObject}. Fails by default if any properties or array elements
71
+ * are `undefined` - this default behavior can be overridden by supplying an appropriate
72
+ * {@link Validators.IJsonValidatorContext | context} at runtime.
73
+ * @public
74
+ */
75
+ export const jsonObject: Validator<JsonObject, IJsonValidatorContext> = new Validation.Base.GenericValidator({
76
+ validator: (
77
+ from: unknown,
78
+ ctx?: IJsonValidatorContext,
79
+ self?: Validator<JsonObject, IJsonValidatorContext>
80
+ ) => {
81
+ if (!isJsonObject(from)) {
82
+ return fail('not a valid JSON object.');
83
+ }
84
+ const errors: string[] = [];
85
+ for (const [name, value] of Object.entries(from)) {
86
+ jsonValue.validate(value, ctx).onFailure((m) => {
87
+ errors.push(`${name}: ${m}`);
88
+ return fail(m);
89
+ });
90
+ }
91
+ if (errors.length > 0) {
92
+ return fail(`not a valid JSON object:\n${errors.join('\n')}`);
93
+ }
94
+ return true;
95
+ }
96
+ });
97
+
98
+ /**
99
+ * An in-place validator which validates that a supplied `unknown` value is
100
+ * a valid {@link JsonArray | JsonArray}. Fails by default if any properties or array elements
101
+ * are `undefined` - this default behavior can be overridden by supplying an appropriate
102
+ * {@link Validators.IJsonValidatorContext | context} at runtime.
103
+ * @public
104
+ */
105
+ export const jsonArray: Validator<JsonArray, IJsonValidatorContext> = new Validation.Base.GenericValidator({
106
+ validator: (
107
+ from: unknown,
108
+ ctx?: IJsonValidatorContext,
109
+ self?: Validator<JsonArray, IJsonValidatorContext>
110
+ ) => {
111
+ if (!isJsonArray(from)) {
112
+ return fail('not an array');
113
+ }
114
+ const errors: string[] = [];
115
+ for (let i = 0; i < from.length; i++) {
116
+ const value = from[i];
117
+ jsonValue.validate(value, ctx).onFailure((m) => {
118
+ errors.push(`${i}: ${m}`);
119
+ return fail(m);
120
+ });
121
+ }
122
+ if (errors.length > 0) {
123
+ return fail(`array contains non-json elements:\n${errors.join('\n')}`);
124
+ }
125
+ return true;
126
+ }
127
+ });
128
+
129
+ /**
130
+ * An in-place validator which validates that a supplied `unknown` value is
131
+ * a valid {@link JsonValue | JsonValue}. Fails by default if any properties or array elements
132
+ * are `undefined` - this default behavior can be overridden by supplying an appropriate
133
+ * {@link Validators.IJsonValidatorContext | context} at runtime.
134
+ * @public
135
+ */
136
+ export const jsonValue: Validator<JsonValue, IJsonValidatorContext> = new Validation.Base.GenericValidator<
137
+ JsonValue,
138
+ IJsonValidatorContext
139
+ >({
140
+ validator: (
141
+ from: unknown,
142
+ ctx?: IJsonValidatorContext,
143
+ self?: Validator<JsonValue, IJsonValidatorContext>
144
+ ) => {
145
+ if (isJsonArray(from)) {
146
+ const result = jsonArray.validate(from, ctx);
147
+ return result.success === true ? true : result;
148
+ } else if (isJsonObject(from)) {
149
+ const result = jsonObject.validate(from, ctx);
150
+ return result.success === true ? true : result;
151
+ }
152
+ const result = jsonPrimitive.validate(from, ctx);
153
+ return result.success === true ? true : result;
154
+ }
155
+ });
package/CHANGELOG.md DELETED
@@ -1,100 +0,0 @@
1
- # Change Log - @fgv/ts-json-base
2
-
3
- This log was last generated on Thu, 17 Jul 2025 00:13:24 GMT and should not be manually modified.
4
-
5
- ## 5.0.0
6
- Thu, 17 Jul 2025 00:13:24 GMT
7
-
8
- ### Updates
9
-
10
- - add sanitizeJsonObject
11
- - upgrade dependencies
12
- - bump version
13
-
14
- ## 4.6.0
15
- Wed, 02 Jul 2025 05:48:16 GMT
16
-
17
- _Version update only_
18
-
19
- ## 4.5.1
20
- Wed, 02 Jul 2025 05:47:11 GMT
21
-
22
- ### Updates
23
-
24
- - update rushstack
25
-
26
- ## 4.5.0
27
- Tue, 01 Jul 2025 03:26:11 GMT
28
-
29
- _Version update only_
30
-
31
- ## 4.4.0
32
- Sat, 01 Feb 2025 17:13:10 GMT
33
-
34
- _Version update only_
35
-
36
- ## 4.3.0
37
- Thu, 30 Jan 2025 00:35:17 GMT
38
-
39
- _Version update only_
40
-
41
- ## 4.2.2
42
- Thu, 23 Jan 2025 06:19:32 GMT
43
-
44
- _Version update only_
45
-
46
- ## 4.2.1
47
- Tue, 21 Jan 2025 04:19:21 GMT
48
-
49
- _Version update only_
50
-
51
- ## 4.2.0
52
- Mon, 20 Jan 2025 09:46:53 GMT
53
-
54
- ### Updates
55
-
56
- - plumb conversion context through
57
-
58
- ## 4.1.0
59
- Thu, 09 Jan 2025 05:33:39 GMT
60
-
61
- ### Updates
62
-
63
- - update dependencies
64
-
65
- ## 4.0.2
66
- Tue, 14 May 2024 14:45:53 GMT
67
-
68
- _Version update only_
69
-
70
- ## 4.0.1
71
- Tue, 14 May 2024 05:02:20 GMT
72
-
73
- ### Updates
74
-
75
- - publish
76
-
77
- ## 4.0.0
78
- Tue, 14 May 2024 03:09:27 GMT
79
-
80
- ### Updates
81
-
82
- - clean up and renaming in JSON file helpers
83
- - update generated api docs
84
- - generalize fs helper to enable yaml
85
-
86
- ## 3.0.0
87
- Mon, 22 Jan 2024 07:00:18 GMT
88
-
89
- ### Updates
90
-
91
- - add validators
92
- - initial refactor
93
-
94
- ## 2.2.0
95
- Thu, 18 Jan 2024 05:45:04 GMT
96
-
97
- ### Updates
98
-
99
- - initial refactor
100
-
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,UAAU,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AACjD,OAAO,KAAK,UAAU,MAAM,uBAAuB,CAAC;AAEpD,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC"}
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,kEAAoD;AAK3C,gCAAU;AAJnB,+DAAiD;AAI5B,4BAAQ;AAH7B,kEAAoD;AAGrB,gCAAU;AADzC,kDAAgC","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\nimport * as Converters from './packlets/converters';\nimport * as JsonFile from './packlets/json-file';\nimport * as Validators from './packlets/validators';\n\nexport * from './packlets/json';\nexport { Converters, JsonFile, Validators };\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"converters.d.ts","sourceRoot":"","sources":["../../../src/packlets/converters/converters.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAc,SAAS,EAAyB,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAA6B,MAAM,SAAS,CAAC;AAIrG;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,yBAAyB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,aAAa,EAAE,qBAAqB,CAqBzE,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,UAAU,EAAE,SAAS,CAAC,UAAU,EAAE,qBAAqB,CAgCnE,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,qBAAqB,CAkCjE,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,qBAAqB,CAgBjE,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"converters.js","sourceRoot":"","sources":["../../../src/packlets/converters/converters.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAA6E;AAC7E,kCAAqG;AAYrG;;;GAGG;AACU,QAAA,aAAa,GAAoD,IAAI,qBAAU,CAAC,aAAa,CACxG,CACE,IAAa,EACb,MAAuD,EACvD,GAA2B,EACJ,EAAE;IACzB,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAClB,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IACD,QAAQ,OAAO,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS,CAAC;QACf,KAAK,QAAQ;YACX,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;QACvB,KAAK,QAAQ;YACX,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBACxB,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,MAAM;IACV,CAAC;IACD,OAAO,IAAA,eAAI,EAAC,IAAI,MAAM,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;AAChE,CAAC,CACF,CAAC;AAEF;;;;;;;;GAQG;AACU,QAAA,UAAU,GAAiD,IAAI,qBAAU,CAAC,aAAa,CAClG,CACE,IAAa,EACb,MAAoD,EACpD,GAA2B,EACP,EAAE;IACtB,IAAI,CAAC,IAAA,mBAAY,EAAC,IAAI,CAAC,EAAE,CAAC;QACxB,OAAO,IAAA,eAAI,EAAC,0BAA0B,CAAC,CAAC;IAC1C,CAAC;IACD,MAAM,GAAG,GAAe,EAAE,CAAC;IAC3B,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,CAAC,IAA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C,EAAE,CAAC;QAC9B,OAAO,kBAAU,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,qBAAa,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAC1C,CAAC,CACF,CAAC","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\nimport { Conversion, Converter, Result, fail, succeed } from '@fgv/ts-utils';\nimport { JsonArray, JsonObject, JsonPrimitive, JsonValue, isJsonArray, isJsonObject } from '../json';\n\n/* eslint-disable no-use-before-define, @typescript-eslint/no-use-before-define */\n\n/**\n * Conversion context for JSON converters.\n * @public\n */\nexport interface IJsonConverterContext {\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * An converter which converts a supplied `unknown` value to a valid {@link JsonPrimitive | JsonPrimitive}.\n * @public\n */\nexport const jsonPrimitive: Converter<JsonPrimitive, IJsonConverterContext> = new Conversion.BaseConverter(\n (\n from: unknown,\n __self: Converter<JsonPrimitive, IJsonConverterContext>,\n ctx?: IJsonConverterContext\n ): Result<JsonPrimitive> => {\n if (from === null) {\n return succeed(null);\n }\n switch (typeof from) {\n case 'boolean':\n case 'string':\n return succeed(from);\n case 'number':\n if (!Number.isNaN(from)) {\n return succeed(from);\n }\n break;\n }\n return fail(`\"${String(from)}\": not a valid JSON primitive.`);\n }\n);\n\n/**\n * An copying converter which converts a supplied `unknown` value into\n * a valid {@link JsonObject | JsonObject}. Fails by default if any properties or array elements\n * are `undefined` - this default behavior can be overridden by supplying an appropriate\n * {@link Converters.IJsonConverterContext | context} at runtime.\n *\n * Guaranteed to return a new object.\n * @public\n */\nexport const jsonObject: Converter<JsonObject, IJsonConverterContext> = new Conversion.BaseConverter(\n (\n from: unknown,\n __self: Converter<JsonObject, IJsonConverterContext>,\n ctx?: IJsonConverterContext\n ): Result<JsonObject> => {\n if (!isJsonObject(from)) {\n return fail('not a valid JSON object.');\n }\n const obj: JsonObject = {};\n const errors: string[] = [];\n for (const [name, value] of Object.entries(from)) {\n if (value === undefined && ctx?.ignoreUndefinedProperties === true) {\n // optionally ignore undefined values\n continue;\n }\n jsonValue\n .convert(value, ctx)\n .onSuccess((v: JsonValue) => {\n obj[name] = v;\n return succeed(v);\n })\n .onFailure((m) => {\n errors.push(`${name}: ${m}`);\n return fail(m);\n });\n }\n if (errors.length > 0) {\n return fail(`not a valid JSON object:\\n${errors.join('\\n')}`);\n }\n return succeed(obj);\n }\n);\n\n/**\n * An copying converter which converts a supplied `unknown` value to\n * a valid {@link JsonArray | JsonArray}. Fails by default if any properties or array elements\n * are `undefined` - this default behavior can be overridden by supplying an appropriate\n * {@link Converters.IJsonConverterContext | context} at runtime.\n *\n * Guaranteed to return a new array.\n * @public\n */\nexport const jsonArray: Converter<JsonArray, IJsonConverterContext> = new Conversion.BaseConverter(\n (\n from: unknown,\n __self: Converter<JsonArray, IJsonConverterContext>,\n ctx?: IJsonConverterContext\n ): Result<JsonArray> => {\n if (!isJsonArray(from)) {\n return fail('not an array');\n }\n const arr: JsonValue[] = [];\n const errors: string[] = [];\n for (let i = 0; i < from.length; i++) {\n const value = from[i];\n if (value === undefined && ctx?.ignoreUndefinedProperties === true) {\n // convert undefined to 'null' for parity with JSON.stringify\n arr.push(null);\n continue;\n }\n jsonValue\n .convert(value, ctx)\n .onSuccess((v) => {\n arr.push(v);\n return succeed(v);\n })\n .onFailure((m) => {\n errors.push(`${i}: ${m}`);\n return fail(m);\n });\n }\n if (errors.length > 0) {\n return fail(`array contains non-json elements:\\n${errors.join('\\n')}`);\n }\n return succeed(arr);\n }\n);\n\n/**\n * An copying converter which converts a supplied `unknown` value to a\n * valid {@link JsonValue | JsonValue}. Fails by default if any properties or array elements\n * are `undefined` - this default behavior can be overridden by supplying an appropriate\n * {@link Converters.IJsonConverterContext | context} at runtime.\n * @public\n */\nexport const jsonValue: Converter<JsonValue, IJsonConverterContext> = new Conversion.BaseConverter<\n JsonValue,\n IJsonConverterContext\n>(\n (\n from: unknown,\n __self: Converter<JsonValue, IJsonConverterContext>,\n ctx?: IJsonConverterContext\n ): Result<JsonValue> => {\n if (isJsonArray(from)) {\n return jsonArray.convert(from, ctx);\n } else if (isJsonObject(from)) {\n return jsonObject.convert(from, ctx);\n }\n return jsonPrimitive.convert(from, ctx);\n }\n);\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/converters/index.ts"],"names":[],"mappings":"AAsBA,cAAc,cAAc,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/converters/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH,+CAA6B","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 './converters';\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../src/packlets/json/common.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,EAAgC,MAAM,eAAe,CAAC;AAIrE;;;GAGG;AAEH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;AAE7D;;;;GAIG;AAEH,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,SAAS,CAAC;AAE/D;;;GAGG;AAEH,MAAM,WAAW,SAAU,SAAQ,KAAK,CAAC,SAAS,CAAC;CAAG;AAEtD;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAE7D;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,aAAa,CAEpE;AAED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;QACH,CAAC;aAAM,CAAC;YACN,OAAO,IAAA,eAAI,EAAC,GAAG,IAAI,YAAY,IAAI,kBAAkB,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,MAAM,CAAC,CAAC;AACzB,CAAC;AAED;;;;;;;;;GASG;AACH,SAAgB,cAAc,CAAC,GAAe,EAAE,IAAY;IAC1D,OAAO,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE;QAC9C,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YACrB,OAAO,IAAA,eAAI,EAAC,GAAG,IAAI,iBAAiB,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,YAAY,CAAC,IAAa;IACxC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC/D,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAAI,IAAO;IAC3C,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC/D,CAAC","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\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Primitive (terminal) values allowed in by JSON.\n * @public\n */\n// eslint-disable-next-line @rushstack/no-new-null\nexport type JsonPrimitive = boolean | number | string | null;\n\n/**\n * A {@link JsonObject | JsonObject} is a string-keyed object\n * containing only valid {@link JsonValue | JSON values}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\n/**\n * A {@link JsonValue | JsonValue} is one of: a {@link JsonPrimitive | JsonPrimitive},\n * a {@link JsonObject | JsonObject} or an {@link JsonArray | JsonArray}.\n * @public\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * A {@link JsonArray | JsonArray} is an array containing only valid {@link JsonValue | JsonValues}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/naming-convention\nexport interface JsonArray extends Array<JsonValue> {}\n\n/**\n * Classes of {@link JsonValue | JsonValue}.\n * @public\n */\nexport type JsonValueType = 'primitive' | 'object' | 'array';\n\n/**\n * Test if an `unknown` is a {@link JsonValue | JsonValue}.\n * @param from - The `unknown` to be tested\n * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},\n * `false` otherwise.\n * @public\n */\nexport function isJsonPrimitive(from: unknown): from is JsonPrimitive {\n return typeof from === 'boolean' || typeof from === 'number' || typeof from === 'string' || from === null;\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is a non-array, non-special object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonObject(from: unknown): from is JsonObject {\n return (\n typeof from === 'object' &&\n from !== null &&\n !Array.isArray(from) &&\n !(from instanceof RegExp) &&\n !(from instanceof Date)\n );\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is an array object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonArray(from: unknown): from is JsonArray {\n return typeof from === 'object' && Array.isArray(from);\n}\n\n/**\n * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},\n * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value\n * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -\n * it does not test the properties of an object or elements in an array.\n * @param from - The `unknown` value to be tested\n * @public\n */\nexport function classifyJsonValue(from: unknown): Result<JsonValueType> {\n if (isJsonPrimitive(from)) {\n return succeed('primitive');\n } else if (isJsonObject(from)) {\n return succeed('object');\n } else if (isJsonArray(from)) {\n return succeed('array');\n }\n return fail(`Invalid JSON: ${from}`);\n}\n\n/**\n * Picks a nested field from a supplied {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid, `Failure`\n * with an error message otherwise.\n * @public\n */\nexport function pickJsonValue(src: JsonObject, path: string): Result<JsonValue> {\n let result: JsonValue = src;\n for (const part of path.split('.')) {\n if (result && isJsonObject(result)) {\n result = result[part];\n if (result === undefined) {\n return fail(`${path}: child '${part}' does not exist`);\n }\n } else {\n return fail(`${path}: child '${part}' does not exist`);\n }\n }\n return succeed(result);\n}\n\n/**\n * Picks a nested {@link JsonObject | JsonObject} from a supplied\n * {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is\n * to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid and the value\n * is an object. Returns `Failure` with details if an error occurs.\n * @public\n */\nexport function pickJsonObject(src: JsonObject, path: string): Result<JsonObject> {\n return pickJsonValue(src, path).onSuccess((v) => {\n if (!isJsonObject(v)) {\n return fail(`${path}: not an object`);\n }\n return succeed(v);\n });\n}\n\n/**\n * \"Sanitizes\" an `unknown` by stringifying and then parsing it. Guarantees a\n * valid {@link JsonValue | JsonValue} but is not idempotent and gives no guarantees\n * about fidelity. Fails if the supplied value cannot be stringified as Json.\n * @param from - The `unknown` to be sanitized.\n * @returns `Success` with a {@link JsonValue | JsonValue} if conversion succeeds,\n * `Failure` with details if an error occurs.\n * @public\n */\nexport function sanitizeJson(from: unknown): Result<JsonValue> {\n return captureResult(() => JSON.parse(JSON.stringify(from)));\n}\n\n/**\n * Sanitizes some value using JSON stringification and parsing, returning an\n * returning a matching strongly-typed value.\n * @param from - The value to be sanitized.\n * @returns `Success` with a {@link JsonObject | JsonObject} if conversion succeeds,\n * `Failure` with details if an error occurs.\n * @public\n */\nexport function sanitizeJsonObject<T>(from: T): Result<T> {\n return captureResult(() => JSON.parse(JSON.stringify(from)));\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/json/index.ts"],"names":[],"mappings":"AAsBA,cAAc,UAAU,CAAC"}