« get me outta code hell

validators.js « thing « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/thing/validators.js
blob: 83922229c80d7030df9b32f4a26837e7a8185059 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { withAggregate } from '../util/sugar.js';

import { color, ENABLE_COLOR } from '../util/cli.js';

import { inspect as nodeInspect } from 'util';

function inspect(value) {
    return nodeInspect(value, {colors: ENABLE_COLOR});
}

// Basic types (primitives)

function a(noun) {
    return (/[aeiou]/.test(noun[0]) ? `an ${noun}` : `a ${noun}`);
}

function isType(value, type) {
    if (typeof value !== type)
        throw new TypeError(`Expected ${a(type)}, got ${typeof value}`);

    return true;
}

export function isBoolean(value) {
    return isType(value, 'boolean');
}

export function isNumber(value) {
    return isType(value, 'number');
}

export function isPositive(number) {
    isNumber(number);

    if (number <= 0)
        throw new TypeError(`Expected positive number`);

    return true;
}

export function isNegative(number) {
    isNumber(number);

    if (number >= 0)
        throw new TypeError(`Expected negative number`);

    return true;
}

export function isPositiveOrZero(number) {
    isNumber(number);

    if (number < 0)
        throw new TypeError(`Expected positive number or zero`);

    return true;
}

export function isNegativeOrZero(number) {
    isNumber(number);

    if (number > 0)
        throw new TypeError(`Expected negative number or zero`);

    return true;
}

export function isInteger(number) {
    isNumber(number);

    if (number % 1 !== 0)
        throw new TypeError(`Expected integer`);

    return true;
}

export function isCountingNumber(number) {
    isInteger(number);
    isPositive(number);

    return true;
}

export function isString(value) {
    return isType(value, 'string');
}

export function isStringNonEmpty(value) {
    isString(value);

    if (value.trim().length === 0)
        throw new TypeError(`Expected non-empty string`);

    return true;
}

// Complex types (non-primitives)

export function isInstance(value, constructor) {
    isObject(value);

    if (!(value instanceof constructor))
        throw new TypeError(`Expected ${constructor.name}, got ${value.constructor.name}`);

    return true;
}

export function isDate(value) {
    return isInstance(value, Date);
}

export function isObject(value) {
    isType(value, 'object');

    // Note: Please remember that null is always a valid value for properties
    // held by a CacheableObject. This assertion is exclusively for use in other
    // contexts.
    if (value === null)
        throw new TypeError(`Expected an object, got null`);

    return true;
}

export function isArray(value) {
    isObject(value);

    if (!Array.isArray(value))
        throw new TypeError(`Expected an array, got ${value}`);

    return true;
}

function validateArrayItemsHelper(itemValidator) {
    return (item, index) => {
        try {
            const value = itemValidator(item);

            if (value !== true) {
                throw new Error(`Expected validator to return true`);
            }
        } catch (error) {
            error.message = `(index: ${color.green(index)}, item: ${inspect(item)}) ${error.message}`;
            throw error;
        }
    };
}

export function validateArrayItems(itemValidator) {
    const fn = validateArrayItemsHelper(itemValidator);

    return array => {
        isArray(array);

        withAggregate({message: 'Errors validating array items'}, ({ wrap }) => {
            array.forEach(wrap(fn));
        });

        return true;
    };
}

export function validateInstanceOf(constructor) {
    return object => isInstance(object, constructor);
}

// Wiki data (primitives & non-primitives)

export function isColor(color) {
    isStringNonEmpty(color);

    if (color.startsWith('#')) {
        if (![1 + 3, 1 + 4, 1 + 6, 1 + 8].includes(color.length))
            throw new TypeError(`Expected #rgb, #rgba, #rrggbb, or #rrggbbaa, got length ${color.length}`);

        if (/[^0-9a-fA-F]/.test(color.slice(1)))
            throw new TypeError(`Expected hexadecimal digits`);

        return true;
    }

    throw new TypeError(`Unknown color format`);
}

export function isCommentary(commentary) {
    return isString(commentary);
}

const isArtistRef = validateReference('artist');

export function isContribution(contrib) {
    // TODO: Use better object validation for this (supporting aggregates etc)

    isObject(contrib);

    isArtistRef(contrib.who);

    if (contrib.what !== null) {
        isStringNonEmpty(contrib.what);
    }

    return true;
}

export const isContributionList = validateArrayItems(isContribution);

export function isDimensions(dimensions) {
    isArray(dimensions);

    if (dimensions.length !== 2)
        throw new TypeError(`Expected 2 item array`);

    isPositive(dimensions[0]);
    isInteger(dimensions[0]);
    isPositive(dimensions[1]);
    isInteger(dimensions[1]);

    return true;
}

export function isDirectory(directory) {
    isStringNonEmpty(directory);

    if (directory.match(/[^a-zA-Z0-9_\-]/))
        throw new TypeError(`Expected only letters, numbers, dash, and underscore, got "${directory}"`);

    return true;
}

export function isDuration(duration) {
    isNumber(duration);
    isPositiveOrZero(duration);

    return true;
}

export function isFileExtension(string) {
    isStringNonEmpty(string);

    if (string[0] === '.')
        throw new TypeError(`Expected no dot (.) at the start of file extension`);

    if (string.match(/[^a-zA-Z0-9_]/))
        throw new TypeError(`Expected only alphanumeric and underscore`);

    return true;
}

export function isLanguageCode(string) {
    // TODO: This is a stub function because really we don't need a detailed
    // is-language-code parser right now.

    isString(string);

    return true;
}

export function isName(name) {
    return isString(name);
}

export function isURL(string) {
    isStringNonEmpty(string);

    new URL(string);

    return true;
}

export function validateReference(type = 'track') {
    return ref => {
        isStringNonEmpty(ref);

        const match = ref.trim().match(/^(?:(?<typePart>\S+):(?=\S))?(?<directoryPart>.+)(?<!:)$/);

        if (!match)
            throw new TypeError(`Malformed reference`);

        const { groups: { typePart, directoryPart } } = match;

        if (typePart && typePart !== type)
            throw new TypeError(`Expected ref to begin with "${type}:", got "${typePart}:"`);

        if (typePart)
            isDirectory(directoryPart);

        isName(ref);

        return true;
    };
}

export function validateReferenceList(type = '') {
    return validateArrayItems(validateReference(type));
}

// Compositional utilities

export function oneOf(...checks) {
    return value => {
        const errorMeta = [];

        for (let i = 0, check; check = checks[i]; i++) {
            try {
                const result = check(value);

                if (result !== true) {
                    throw new Error(`Check returned false`);
                }

                return true;
            } catch (error) {
                errorMeta.push([check, i, error]);
            }
        }

        // Don't process error messages until every check has failed.
        const errors = [];
        for (const [ check, i, error ] of errorMeta) {
            error.message = (check.name
                ? `(#${i} "${check.name}") ${error.message}`
                : `(#${i}) ${error.message}`);
            error.check = check;
            errors.push(error);
        }
        throw new AggregateError(errors, `Expected one of ${checks.length} possible checks, but none were true`);
    };
}