« 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: d881aac23c6a6a54165e6cd26750992e2e8d45f6 (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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
import {inspect as nodeInspect} from 'node:util';

// Heresy.
import printable_characters from 'printable-characters';
const {strlen} = printable_characters;

import {colors, ENABLE_COLOR} from '#cli';
import {cut, empty, typeAppearance, withAggregate} from '#sugar';
import {commentaryRegex} from '#wiki-data';

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

export function getValidatorCreator(validator) {
  return validator[Symbol.for(`hsmusic.validator.creator`)] ?? null;
}

export function getValidatorCreatorMeta(validator) {
  return validator[Symbol.for(`hsmusic.validator.creatorMeta`)] ?? null;
}

export function setValidatorCreatorMeta(validator, creator, meta) {
  validator[Symbol.for(`hsmusic.validator.creator`)] = creator;
  validator[Symbol.for(`hsmusic.validator.creatorMeta`)] = meta;
  return validator;
}

// Basic types (primitives)

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

export function validateType(type) {
  const fn = value => {
    if (typeof value !== type)
      throw new TypeError(`Expected ${a(type)}, got ${typeAppearance(value)}`);

    return true;
  };

  setValidatorCreatorMeta(fn, validateType, {type});

  return fn;
}

export const isBoolean =
  validateType('boolean');

export const isFunction =
  validateType('function');

export const isNumber =
  validateType('number');

export const isString =
  validateType('string');

export const isSymbol =
  validateType('symbol');

// Use isObject instead, which disallows null.
export const isTypeofObject =
  validateType('object');

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 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) {
  isTypeofObject(value);

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

  const fn = (value) => {
    if (!values.has(value)) {
      throw new TypeError(`Expected one of ${Array.from(values).join(' ')}, got ${value}`);
    }

    return true;
  };

  setValidatorCreatorMeta(fn, is, {values});

  return fn;
}

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

      if (value !== true) {
        throw new Error(`Expected validator to return true`);
      }
    } catch (error) {
      const annotation = `(index: ${colors.yellow(`${index}`)}, item: ${inspect(item)})`;

      error.message =
        (error.message.includes('\n') || strlen(annotation) > 20
          ? annotation + '\n' +
            error.message
              .split('\n')
              .map(line => `  ${line}`)
              .join('\n')
          : `${annotation} ${error}`);

      error[Symbol.for('hsmusic.decorate.indexInSourceArray')] = index;

      throw error;
    }
  };
}

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

  return (array) => {
    isArray(array);

    withAggregate({message: 'Errors validating array items'}, ({call}) => {
      for (let index = 0; index < array.length; index++) {
        call(helper, array[index], index, array);
      }
    });

    return true;
  };
}

export function strictArrayOf(itemValidator) {
  return validateArrayItems(itemValidator);
}

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

    return itemValidator(item, index, array);
  });
}

export function looseArrayOf(itemValidator) {
  return validateArrayItems((item, index, array) => {
    if (item === false || item === null || item === undefined) {
      return true;
    }

    return itemValidator(item, index, array);
  });
}

export function validateInstanceOf(constructor) {
  const fn = (object) => isInstance(object, constructor);

  setValidatorCreatorMeta(fn, validateInstanceOf, {constructor});

  return fn;
}

// 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(commentaryText) {
  isString(commentaryText);

  const rawMatches =
    Array.from(commentaryText.matchAll(commentaryRegex));

  if (empty(rawMatches)) {
    throw new TypeError(`Expected at least one commentary heading`);
  }

  const niceMatches =
    rawMatches.map(match => ({
      position: match.index,
      length: match[0].length,
    }));

  validateArrayItems(({position, length}, index) => {
    if (index === 0 && position > 0) {
      throw new TypeError(`Expected first commentary heading to be at top`);
    }

    const ownInput = commentaryText.slice(position, position + length);
    const restOfInput = commentaryText.slice(position + length);
    const nextLineBreak = restOfInput.indexOf('\n');
    const upToNextLineBreak = restOfInput.slice(0, nextLineBreak);

    if (/\S/.test(upToNextLineBreak)) {
      throw new TypeError(
        `Expected commentary heading to occupy entire line, got extra text:\n` +
        `${colors.green(`"${cut(ownInput, 40)}"`)} (<- heading)\n` +
        `(extra on same line ->) ${colors.red(`"${cut(upToNextLineBreak, 30)}"`)}\n` +
        `(Check for missing "|-" in YAML, or a misshapen annotation)`);
    }

    const nextHeading =
      (index === niceMatches.length - 1
        ? commentaryText.length
        : niceMatches[index + 1].position);

    const upToNextHeading =
      commentaryText.slice(position + length, nextHeading);

    if (!/\S/.test(upToNextHeading)) {
      throw new TypeError(
        `Expected commentary entry to have body text, only got a heading`);
    }

    return true;
  })(niceMatches);

  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 function validateAllPropertyValues(validator) {
  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 key of Reflect.ownKeys(object)) {
        call(() => {
          const value = object[key];
          try {
            validator(value);
          } catch (error) {
            error.message = `(key: ${colors.green(key)}, value: ${inspect(value)}) ${error.message}`;
            throw error;
          }
        });
      }
    });

    return true;
  };
}

export const isContribution = validateProperties({
  who: isArtistRef,
  what: optional(isStringNonEmpty),
});

export const isContributionList = validateArrayItems(isContribution);

export const isAdditionalFile = validateProperties({
  title: isString,
  description: optional(isStringNonEmpty),
  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);
    }
  };
}

export const isAdditionalName = validateProperties({
  name: isName,
  annotation: optional(isStringNonEmpty),

  // TODO: This only allows indicating sourcing from a track.
  // That's okay for the current limited use of "from", but
  // could be expanded later.
  from:
    // Double TODO: Explicitly allowing both references and
    // live objects to co-exist is definitely weird, and
    // altogether questions the way we define validators...
    optional(oneOf(
      validateReferenceList('track'),
      validateWikiData({referenceType: 'track'}))),
});

export const isAdditionalNameList = validateArrayItems(isAdditionalName);

// Compositional utilities

export function oneOf(...validators) {
  const validConstants = new Set();
  const validConstructors = new Set();
  const validTypes = new Set();

  const leftoverValidators = [];

  for (const validator of validators) {
    const creator = getValidatorCreator(validator);
    const creatorMeta = getValidatorCreatorMeta(validator);

    switch (creator) {
      case is:
        for (const value of creatorMeta.values) {
          validConstants.add(value);
        }
        break;

      case validateInstanceOf:
        validConstructors.add(creatorMeta.constructor);
        break;

      case validateType:
        validTypes.add(creatorMeta.type);
        break;

      default:
        leftoverValidators.push(validator);
        break;
    }
  }

  return (value) => {
    const errorInfo = [];

    if (validConstants.has(value)) {
      return true;
    }

    if (!empty(validTypes)) {
      if (validTypes.has(typeof value)) {
        return true;
      }
    }

    for (const constructor of validConstructors) {
      if (value instanceof constructor) {
        return true;
      }
    }

    for (const [i, validator] of leftoverValidators.entries()) {
      try {
        const result = validator(value);

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

        return true;
      } catch (error) {
        errorInfo.push([validator, i, error]);
      }
    }

    // Don't process error messages until every validator has failed.

    const errors = [];
    const prefaceErrorInfo = [];

    let offset = 0;

    if (!empty(validConstants)) {
      const constants =
        Array.from(validConstants);

      const gotPart = `, got ${value}`;

      prefaceErrorInfo.push([
        null,
        offset++,
        new TypeError(
          `Expected one of ${constants.join(' ')}` + gotPart),
      ]);
    }

    if (!empty(validTypes)) {
      const types =
        Array.from(validTypes);

      const gotType = typeAppearance(value);
      const gotPart = `, got ${gotType}`;

      prefaceErrorInfo.push([
        null,
        offset++,
        new TypeError(
          `Expected one of ${types.join(', ')}` + gotPart),
      ]);
    }

    if (!empty(validConstructors)) {
      const names =
        Array.from(validConstructors)
          .map(constructor => constructor.name);

      const gotName = value?.constructor?.name;
      const gotPart = (gotName ? `, got ${gotName}` : ``);

      prefaceErrorInfo.push([
        null,
        offset++,
        new TypeError(
          `Expected one of ${names.join(', ')}` + gotPart),
      ]);
    }

    for (const info of errorInfo) {
      info[1] += offset;
    }

    for (const [validator, i, error] of prefaceErrorInfo.concat(errorInfo)) {
      error.message =
        (validator?.name
          ? `(#${i + 1} "${validator.name}") ${error.message}`
          : `(#${i + 1}) ${error.message}`);

      error.check = validator;

      errors.push(error);
    }

    throw new AggregateError(errors,
      `Expected one of ${validators.length} possible checks, ` +
      `but none were true`);
  };
}