« get me outta code hell

thing.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/thing.js
blob: b1a9a802ff1145bca3a911a278c3f90dc7328a59 (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
// Thing: base class for wiki data types, providing wiki-specific utility
// functions on top of essential CacheableObject behavior.

import {inspect} from 'node:util';

import {colors} from '#cli';
import find from '#find';
import {empty, stitchArrays, unique} from '#sugar';
import {filterMultipleArrays, getKebabCase} from '#wiki-data';

import {
  compositeFrom,
  exitWithoutDependency,
  exposeConstant,
  exposeDependency,
  exposeDependencyOrContinue,
  raiseWithoutDependency,
  withResultOfAvailabilityCheck,
  withPropertiesFromList,
  withUpdateValueAsDependency,
} from '#composite';

import {
  isAdditionalFileList,
  isBoolean,
  isCommentary,
  isColor,
  isContributionList,
  isDate,
  isDimensions,
  isDirectory,
  isDuration,
  isFileExtension,
  isName,
  isString,
  isURL,
  validateArrayItems,
  validateInstanceOf,
  validateReference,
  validateReferenceList,
} from '#validators';

import CacheableObject from './cacheable-object.js';

export default class Thing extends CacheableObject {
  static referenceType = Symbol('Thing.referenceType');

  static getPropertyDescriptors = Symbol('Thing.getPropertyDescriptors');
  static getSerializeDescriptors = Symbol('Thing.getSerializeDescriptors');

  // Default custom inspect function, which may be overridden by Thing
  // subclasses. This will be used when displaying aggregate errors and other
  // command-line logging - it's the place to provide information useful in
  // identifying the Thing being presented.
  [inspect.custom]() {
    const cname = this.constructor.name;

    return (
      (this.name ? `${cname} ${colors.green(`"${this.name}"`)}` : `${cname}`) +
      (this.directory ? ` (${colors.blue(Thing.getReference(this))})` : '')
    );
  }

  static getReference(thing) {
    if (!thing.constructor[Thing.referenceType]) {
      throw TypeError(`Passed Thing is ${thing.constructor.name}, which provides no [Thing.referenceType]`);
    }

    if (!thing.directory) {
      throw TypeError(`Passed ${thing.constructor.name} is missing its directory`);
    }

    return `${thing.constructor[Thing.referenceType]}:${thing.directory}`;
  }
}

// Property descriptor templates
//
// Regularly reused property descriptors, for ease of access and generally
// duplicating less code across wiki data types. These are specialized utility
// functions, so check each for how its own arguments behave!

export function name(defaultName) {
  return {
    flags: {update: true, expose: true},
    update: {validate: isName, default: defaultName},
  };
}

export function color() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isColor},
  };
}

export function directory() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isDirectory},
    expose: {
      dependencies: ['name'],
      transform(directory, {name}) {
        if (directory === null && name === null) return null;
        else if (directory === null) return getKebabCase(name);
        else return directory;
      },
    },
  };
}

export function urls() {
  return {
    flags: {update: true, expose: true},
    update: {validate: validateArrayItems(isURL)},
    expose: {transform: (value) => value ?? []},
  };
}

// A file extension! Or the default, if provided when calling this.
export function fileExtension(defaultFileExtension = null) {
  return {
    flags: {update: true, expose: true},
    update: {validate: isFileExtension},
    expose: {transform: (value) => value ?? defaultFileExtension},
  };
}

// Plain ol' image dimensions. This is a two-item array of positive integers,
// corresponding to width and height respectively.
export function dimensions() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isDimensions},
  };
}

// Duration! This is a number of seconds, possibly floating point, always
// at minimum zero.
export function duration() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isDuration},
  };
}

// Straightforward flag descriptor for a variety of property purposes.
// Provide a default value, true or false!
export function flag(defaultValue = false) {
  // TODO:                        ^ Are you actually kidding me
  if (typeof defaultValue !== 'boolean') {
    throw new TypeError(`Always set explicit defaults for flags!`);
  }

  return {
    flags: {update: true, expose: true},
    update: {validate: isBoolean, default: defaultValue},
  };
}

// General date type, used as the descriptor for a bunch of properties.
// This isn't dynamic though - it won't inherit from a date stored on
// another object, for example.
export function simpleDate() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isDate},
  };
}

// General string type. This should probably generally be avoided in favor
// of more specific validation, but using it makes it easy to find where we
// might want to improve later, and it's a useful shorthand meanwhile.
export function simpleString() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isString},
  };
}

// External function. These should only be used as dependencies for other
// properties, so they're left unexposed.
export function externalFunction() {
  return {
    flags: {update: true},
    update: {validate: (t) => typeof t === 'function'},
  };
}

// Strong 'n sturdy contribution list, rolling a list of references (provided
// as this property's update value) and the resolved results (as get exposed)
// into one property. Update value will look something like this:
//
//   [
//     {who: 'Artist Name', what: 'Viola'},
//     {who: 'artist:john-cena', what: null},
//     ...
//   ]
//
// ...typically as processed from YAML, spreadsheet, or elsewhere.
// Exposes as the same, but with the "who" replaced with matches found in
// artistData - which means this always depends on an `artistData` property
// also existing on this object!
//
export function contributionList() {
  return compositeFrom(`contributionList`, [
    withUpdateValueAsDependency(),
    withResolvedContribs({from: '#updateValue'}),
    exposeDependencyOrContinue({dependency: '#resolvedContribs'}),
    exposeConstant({
      value: [],
      update: {validate: isContributionList},
    }),
  ]);
}

// Artist commentary! Generally present on tracks and albums.
export function commentary() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isCommentary},
  };
}

// This is a somewhat more involved data structure - it's for additional
// or "bonus" files associated with albums or tracks (or anything else).
// It's got this form:
//
//     [
//         {title: 'Booklet', files: ['Booklet.pdf']},
//         {
//             title: 'Wallpaper',
//             description: 'Cool Wallpaper!',
//             files: ['1440x900.png', '1920x1080.png']
//         },
//         {title: 'Alternate Covers', description: null, files: [...]},
//         ...
//     ]
//
export function additionalFiles() {
  return {
    flags: {update: true, expose: true},
    update: {validate: isAdditionalFileList},
    expose: {
      transform: (additionalFiles) =>
        additionalFiles ?? [],
    },
  };
}

// A reference list! Keep in mind this is for general references to wiki
// objects of (usually) other Thing subclasses, not specifically leitmotif
// references in tracks (although that property uses referenceList too!).
//
// The underlying function validateReferenceList expects a string like
// 'artist' or 'track', but this utility keeps from having to hard-code the
// string in multiple places by referencing the value saved on the class
// instead.
export function referenceList({
  class: thingClass,
  data,
  find,
}) {
  if (!thingClass) {
    throw new TypeError(`Expected a Thing class`);
  }

  const {[Thing.referenceType]: referenceType} = thingClass;
  if (!referenceType) {
    throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
  }

  return compositeFrom(`referenceList`, [
    withUpdateValueAsDependency(),

    withResolvedReferenceList({
      data, find,
      list: '#updateValue',
      notFoundMode: 'filter',
    }),

    exposeDependency({
      dependency: '#resolvedReferenceList',
      update: {
        validate: validateReferenceList(referenceType),
      },
    }),
  ]);
}

// Corresponding function for a single reference.
export function singleReference({
  class: thingClass,
  data,
  find,
}) {
  if (!thingClass) {
    throw new TypeError(`Expected a Thing class`);
  }

  const {[Thing.referenceType]: referenceType} = thingClass;
  if (!referenceType) {
    throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
  }

  return compositeFrom(`singleReference`, [
    withUpdateValueAsDependency(),

    withResolvedReference({ref: '#updateValue', data, find}),

    exposeDependency({
      dependency: '#resolvedReference',
      update: {
        validate: validateReference(referenceType),
      },
    }),
  ]);
}

// Nice 'n simple shorthand for an exposed-only flag which is true when any
// contributions are present in the specified property.
export function contribsPresent({contribs}) {
  return compositeFrom(`contribsPresent`, [
    withResultOfAvailabilityCheck({fromDependency: contribs, mode: 'empty'}),
    exposeDependency({dependency: '#availability'}),
  ]);
}

// Neat little shortcut for "reversing" the reference lists stored on other
// things - for example, tracks specify a "referenced tracks" property, and
// you would use this to compute a corresponding "referenced *by* tracks"
// property. Naturally, the passed ref list property is of the things in the
// wiki data provided, not the requesting Thing itself.
export function reverseReferenceList({data, list}) {
  return compositeFrom(`reverseReferenceList`, [
    withReverseReferenceList({data, list}),
    exposeDependency({dependency: '#reverseReferenceList'}),
  ]);
}

// General purpose wiki data constructor, for properties like artistData,
// trackData, etc.
export function wikiData(thingClass) {
  return {
    flags: {update: true},
    update: {
      validate: validateArrayItems(validateInstanceOf(thingClass)),
    },
  };
}

// This one's kinda tricky: it parses artist "references" from the
// commentary content, and finds the matching artist for each reference.
// This is mostly useful for credits and listings on artist pages.
export function commentatorArtists() {
  return compositeFrom(`commentatorArtists`, [
    exitWithoutDependency({dependency: 'commentary', mode: 'falsy', value: []}),

    {
      dependencies: ['commentary'],
      compute: ({commentary}, continuation) =>
        continuation({
          '#artistRefs':
            Array.from(
              commentary
                .replace(/<\/?b>/g, '')
                .matchAll(/<i>(?<who>.*?):<\/i>/g))
              .map(({groups: {who}}) => who),
        }),
    },

    withResolvedReferenceList({
      list: '#artistRefs',
      data: 'artistData',
      into: '#artists',
      find: find.artist,
    }),

    {
      flags: {expose: true},

      expose: {
        dependencies: ['#artists'],
        compute: ({'#artists': artists}) =>
          unique(artists),
      },
    },
  ]);
}

// Compositional utilities

// Resolves the contribsByRef contained in the provided dependency,
// providing (named by the second argument) the result. "Resolving"
// means mapping the "who" reference of each contribution to an artist
// object, and filtering out those whose "who" doesn't match any artist.
export function withResolvedContribs({
  from,
  into = '#resolvedContribs',
}) {
  return compositeFrom(`withResolvedContribs`, [
    raiseWithoutDependency({
      dependency: from,
      mode: 'empty',
      map: {into},
      raise: {into: []},
    }),

    withPropertiesFromList({
      list: from,
      properties: ['who', 'what'],
      prefix: '#contribs',
    }),

    withResolvedReferenceList({
      list: '#contribs.who',
      data: 'artistData',
      into: '#contribs.who',
      find: find.artist,
      notFoundMode: 'null',
    }),

    {
      dependencies: ['#contribs.who', '#contribs.what'],
      mapContinuation: {into},
      compute({'#contribs.who': who, '#contribs.what': what}, continuation) {
        filterMultipleArrays(who, what, (who, _what) => who);
        return continuation({
          into: stitchArrays({who, what}),
        });
      },
    },
  ]);
}

// Shorthand for exiting if the contribution list (usually a property's update
// value) resolves to empty - ensuring that the later computed results are only
// returned if these contributions are present.
export function exitWithoutContribs({
  contribs,
  value = null,
}) {
  return compositeFrom(`exitWithoutContribs`, [
    withResolvedContribs({from: contribs}),
    exitWithoutDependency({
      dependency: '#resolvedContribs',
      mode: 'empty',
      value,
    }),
  ]);
}

// Resolves a reference by using the provided find function to match it
// within the provided thingData dependency. This will early exit if the
// data dependency is null, or, if notFoundMode is set to 'exit', if the find
// function doesn't match anything for the reference. Otherwise, the data
// object is provided on the output dependency; or null, if the reference
// doesn't match anything or itself was null to begin with.
export function withResolvedReference({
  ref,
  data,
  find: findFunction,
  into = '#resolvedReference',
  notFoundMode = 'null',
}) {
  if (!['exit', 'null'].includes(notFoundMode)) {
    throw new TypeError(`Expected notFoundMode to be exit or null`);
  }

  return compositeFrom(`withResolvedReference`, [
    raiseWithoutDependency({
      dependency: ref,
      map: {into},
      raise: {into: null},
    }),

    exitWithoutDependency({
      dependency: data,
    }),

    {
      options: {findFunction, notFoundMode},
      mapDependencies: {ref, data},
      mapContinuation: {match: into},

      compute({ref, data, '#options': {findFunction, notFoundMode}}, continuation) {
        const match = findFunction(ref, data, {mode: 'quiet'});

        if (match === null && notFoundMode === 'exit') {
          return continuation.exit(null);
        }

        return continuation.raise({match});
      },
    },
  ]);
}

// Resolves a list of references, with each reference matched with provided
// data in the same way as withResolvedReference. This will early exit if the
// data dependency is null (even if the reference list is empty). By default
// it will filter out references which don't match, but this can be changed
// to early exit ({notFoundMode: 'exit'}) or leave null in place ('null').
export function withResolvedReferenceList({
  list,
  data,
  find: findFunction,
  into = '#resolvedReferenceList',
  notFoundMode = 'filter',
}) {
  if (!['filter', 'exit', 'null'].includes(notFoundMode)) {
    throw new TypeError(`Expected notFoundMode to be filter, exit, or null`);
  }

  return compositeFrom(`withResolvedReferenceList`, [
    exitWithoutDependency({
      dependency: data,
      value: [],
    }),

    raiseWithoutDependency({
      dependency: list,
      mode: 'empty',
      map: {into},
      raise: {into: []},
    }),

    {
      mapDependencies: {list, data},
      options: {findFunction},

      compute: ({list, data, '#options': {findFunction}}, continuation) =>
        continuation({
          '#matches': list.map(ref => findFunction(ref, data, {mode: 'quiet'})),
        }),
    },

    {
      dependencies: ['#matches'],
      mapContinuation: {into},

      compute: ({'#matches': matches}, continuation) =>
        (matches.every(match => match)
          ? continuation.raise({into: matches})
          : continuation()),
    },

    {
      dependencies: ['#matches'],
      options: {notFoundMode},
      mapContinuation: {into},

      compute({
        '#matches': matches,
        '#options': {notFoundMode},
      }, continuation) {
        switch (notFoundMode) {
          case 'exit':
            return continuation.exit([]);

          case 'filter':
            matches = matches.filter(match => match);
            return continuation.raise({into: matches});

          case 'null':
            matches = matches.map(match => match ?? null);
            return continuation.raise({into: matches});
        }
      },
    },
  ]);
}

// Check out the info on reverseReferenceList!
// This is its composable form.
export function withReverseReferenceList({
  data,
  list: refListProperty,
  into = '#reverseReferenceList',
}) {
  return compositeFrom(`withReverseReferenceList`, [
    exitWithoutDependency({
      dependency: data,
      value: [],
    }),

    {
      dependencies: ['this'],
      mapDependencies: {data},
      mapContinuation: {into},
      options: {refListProperty},

      compute: ({this: thisThing, data, '#options': {refListProperty}}, continuation) =>
        continuation({
          into: data.filter(thing => thing[refListProperty].includes(thisThing)),
        }),
    },
  ]);
}