« get me outta code hell

validators.js « things « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things/validators.js
blob: f60c363c175f5da99f8ae22c2c96d5cf89c6303c (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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
import {inspect as nodeInspect} from 'node:util';

import {colors, ENABLE_COLOR} from '#cli';
import {empty, typeAppearance, withAggregate} from '#sugar';

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

// Basic types (primitives)

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

export function isType(value, type) {
  if (typeof value !== type)
    throw new TypeError(`Expected ${a(type)}, got ${typeAppearance(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 isWholeNumber(number) {
  isInteger(number);
  isPositiveOrZero(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;
}

export function optional(validator) {
  return value => value === null || value === undefined || validator(value);
}

// 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) {
  isInstance(value, Date);

  if (isNaN(value))
    throw new TypeError(`Expected valid date`);

  return true;
}

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) {
  if (typeof value !== 'object' || value === null || !Array.isArray(value))
    throw new TypeError(`Expected an array, got ${typeAppearance(value)}`);

  return true;
}

// This one's shaped a bit different from other "is" functions.
// More like validate functions, it returns a function.
export function is(...values) {
  if (Array.isArray(values)) {
    values = new Set(values);
  }

  if (values.size === 1) {
    const expected = Array.from(values)[0];

    return (value) => {
      if (value !== expected) {
        throw new TypeError(`Expected ${expected}, got ${value}`);
      }

      return true;
    };
  }

  return (value) => {
    if (!values.has(value)) {
      throw new TypeError(`Expected one of ${Array.from(values).join(' ')}, 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: ${colors.yellow(`${index}`)}, item: ${inspect(item)}) ${error.message}`;
      error[Symbol.for('hsmusic.decorate.indexInSourceArray')] = index;
      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 strictArrayOf(itemValidator) {
  return validateArrayItems(itemValidator);
}

export function sparseArrayOf(itemValidator) {
  return validateArrayItems(item => {
    if (item === false || item === null) {
      return true;
    }

    return itemValidator(item);
  });
}

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

// Wiki data (primitives & non-primitives)

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

  if (color.startsWith('#')) {
    if (![4, 5, 7, 9].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) {
  isString(commentary);

  const [firstLine] = commentary.match(/.*/);
  if (!firstLine.replace(/<\/b>/g, '').includes(':</i>')) {
    throw new TypeError(`Missing commentary citation: "${
      firstLine.length > 40
        ? firstLine.slice(0, 40) + '...'
        : firstLine
    }"`);
  }

  return true;
}

const isArtistRef = validateReference('artist');

export function validateProperties(spec) {
  const specEntries = Object.entries(spec);
  const specKeys = Object.keys(spec);

  return (object) => {
    isObject(object);

    if (Array.isArray(object))
      throw new TypeError(`Expected an object, got array`);

    withAggregate({message: `Errors validating object properties`}, ({call}) => {
      for (const [specKey, specValidator] of specEntries) {
        call(() => {
          const value = object[specKey];
          try {
            specValidator(value);
          } catch (error) {
            error.message = `(key: ${colors.green(specKey)}, value: ${inspect(value)}) ${error.message}`;
            throw error;
          }
        });
      }

      const unknownKeys = Object.keys(object).filter((key) => !specKeys.includes(key));
      if (unknownKeys.length > 0) {
        call(() => {
          throw new Error(`Unknown keys present (${unknownKeys.length}): [${unknownKeys.join(', ')}]`);
        });
      }
    });

    return true;
  };
}

export const isContribution = validateProperties({
  who: isArtistRef,
  what: (value) =>
    value === undefined ||
    value === null ||
    isStringNonEmpty(value),
});

export const isContributionList = validateArrayItems(isContribution);

export const isAdditionalFile = validateProperties({
  title: isString,
  description: (value) =>
    value === undefined ||
    value === null ||
    isString(value),
  files: validateArrayItems(isString),
});

export const isAdditionalFileList = validateArrayItems(isAdditionalFile);

export const isTrackSection = validateProperties({
  name: optional(isString),
  color: optional(isColor),
  dateOriginallyReleased: optional(isDate),
  isDefaultTrackSection: optional(isBoolean),
  tracks: optional(validateReferenceList('track')),
});

export const isTrackSectionList = validateArrayItems(isTrackSection);

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) {
      if (typePart !== type)
        throw new TypeError(`Expected ref to begin with "${type}:", got "${typePart}:"`);

      isDirectory(directoryPart);
    }

    isName(ref);

    return true;
  };
}

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

const validateWikiData_cache = {};

export function validateWikiData({
  referenceType = '',
  allowMixedTypes = false,
}) {
  if (referenceType && allowMixedTypes) {
    throw new TypeError(`Don't specify both referenceType and allowMixedTypes`);
  }

  validateWikiData_cache[referenceType] ??= {};
  validateWikiData_cache[referenceType][allowMixedTypes] ??= new WeakMap();

  const isArrayOfObjects = validateArrayItems(isObject);

  return (array) => {
    const subcache = validateWikiData_cache[referenceType][allowMixedTypes];
    if (subcache.has(array)) return subcache.get(array);

    let OK = false;

    try {
      isArrayOfObjects(array);

      if (empty(array)) {
        OK = true; return true;
      }

      const allRefTypes = new Set();

      let foundThing = false;
      let foundOtherObject = false;

      for (const object of array) {
        const {[Symbol.for('Thing.referenceType')]: referenceType} = object.constructor;

        if (referenceType === undefined) {
          foundOtherObject = true;

          // Early-exit if a Thing has been found - nothing more can be learned.
          if (foundThing) {
            throw new TypeError(`Expected array of wiki data objects, got mixed items`);
          }
        } else {
          foundThing = true;

          // Early-exit if a non-Thing object has been found - nothing more can
          // be learned.
          if (foundOtherObject) {
            throw new TypeError(`Expected array of wiki data objects, got mixed items`);
          }

          allRefTypes.add(referenceType);
        }
      }

      if (foundOtherObject && !foundThing) {
        throw new TypeError(`Expected array of wiki data objects, got array of other objects`);
      }

      if (allRefTypes.size > 1) {
        if (allowMixedTypes) {
          OK = true; return true;
        }

        const types = () => Array.from(allRefTypes).join(', ');

        if (referenceType) {
          if (allRefTypes.has(referenceType)) {
            allRefTypes.remove(referenceType);
            throw new TypeError(`Expected array of only ${referenceType}, also got other types: ${types()}`)
          } else {
            throw new TypeError(`Expected array of only ${referenceType}, got other types: ${types()}`);
          }
        }

        throw new TypeError(`Expected array of unmixed reference types, got multiple: ${types()}`);
      }

      const onlyRefType = Array.from(allRefTypes)[0];

      if (referenceType && onlyRefType !== referenceType) {
        throw new TypeError(`Expected array of ${referenceType}, got array of ${onlyRefType}`)
      }

      OK = true; return true;
    } finally {
      subcache.set(array, OK);
    }
  };
}

// 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`);
  };
}