@fgv/ts-json-base 5.0.0-22 → 5.0.0-24

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.
@@ -1,262 +0,0 @@
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();
@@ -1,56 +0,0 @@
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;
@@ -1,23 +0,0 @@
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';
@@ -1,155 +0,0 @@
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
- });