« get me outta code hell

things.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things.js
blob: 8f460e49ff04205e51f1c86c2af4724d4c278a23 (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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
// things.js: class definitions for various object types used across the wiki,
// most of which correspond to an output page, such as Track, Album, Artist

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

import {
    isAdditionalFileList,
    isBoolean,
    isColor,
    isCommentary,
    isCountingNumber,
    isContributionList,
    isDate,
    isDimensions,
    isDirectory,
    isDuration,
    isInstance,
    isFileExtension,
    isLanguageCode,
    isName,
    isNumber,
    isURL,
    isString,
    isWholeNumber,
    oneOf,
    validateArrayItems,
    validateInstanceOf,
    validateReference,
    validateReferenceList,
} from './validators.js';

import * as S from './serialize.js';

import {
    getKebabCase,
    sortByArtDate,
} from '../util/wiki-data.js';

import find from '../util/find.js';

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

// Stub classes (and their exports) at the top of the file - these are
// referenced later when we actually define static class fields. We deliberately
// define the classes and set their static fields in two separate steps so that
// every class coexists from the outset, and can be directly referenced in field
// definitions later.

// This list also acts as a quick table of contents for this JS file - use
// ctrl+F or similar to skip to a section.

// -> Thing
export class Thing extends CacheableObject {}

// -> Album
export class Album extends Thing {}
export class TrackGroup extends CacheableObject {}

// -> Track
export class Track extends Thing {}

// -> Artist
export class Artist extends Thing {}

// -> Group
export class Group extends Thing {}
export class GroupCategory extends CacheableObject {}

// -> ArtTag
export class ArtTag extends Thing {}

// -> NewsEntry
export class NewsEntry extends Thing {}

// -> StaticPage
export class StaticPage extends Thing {}

// -> HomepageLayout
export class HomepageLayout extends CacheableObject {}
export class HomepageLayoutRow extends CacheableObject {}
export class HomepageLayoutAlbumsRow extends HomepageLayoutRow {}

// -> Flash
export class Flash extends Thing {}
export class FlashAct extends CacheableObject {}

// -> WikiInfo
export class WikiInfo extends CacheableObject {}

// -> Language
export class Language extends CacheableObject {}

// Before initializing property descriptors, set additional independent
// constants on the classes (which are referenced later).

Thing.referenceType = Symbol('Thing.referenceType');

Album[Thing.referenceType] = 'album';
Track[Thing.referenceType] = 'track';
Artist[Thing.referenceType] = 'artist';
Group[Thing.referenceType] = 'group';
ArtTag[Thing.referenceType] = 'tag';
NewsEntry[Thing.referenceType] = 'news-entry';
StaticPage[Thing.referenceType] = 'static';
Flash[Thing.referenceType] = 'flash';

// -> Thing: base class for wiki data types, providing wiki-specific utility
// functions on top of essential CacheableObject behavior.

// 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!
Thing.common = {
    name: (defaultName) => ({
        flags: {update: true, expose: true},
        update: {validate: isName, default: defaultName}
    }),

    color: () => ({
        flags: {update: true, expose: true},
        update: {validate: isColor}
    }),

    directory: () => ({
        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;
            }
        }
    }),

    urls: () => ({
        flags: {update: true, expose: true},
        update: {validate: validateArrayItems(isURL)}
    }),

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

    // Straightforward flag descriptor for a variety of property purposes.
    // Provide a default value, true or false!
    flag: (defaultValue = false) => {
        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.
    simpleDate: () => ({
        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.
    simpleString: () => ({
        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.
    externalFunction: () => ({
        flags: {update: true},
        update: {validate: t => typeof t === 'function'}
    }),

    // Super simple "contributions by reference" list, used for a variety of
    // properties (Artists, Cover Artists, etc). This is the property which is
    // externally provided, in the form:
    //
    //     [
    //         {who: 'Artist Name', what: 'Viola'},
    //         {who: 'artist:john-cena', what: null},
    //         ...
    //     ]
    //
    // ...processed from YAML, spreadsheet, or any other kind of input.
    contribsByRef: () => ({
        flags: {update: true, expose: true},
        update: {validate: isContributionList}
    }),

    // Artist commentary! Generally present on tracks and albums.
    commentary: () => ({
        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: [...]},
    //         ...
    //     ]
    //
    additionalFiles: () => ({
        flags: {update: true, expose: true},
        update: {validate: isAdditionalFileList}
    }),

    // 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.
    referenceList: thingClass => {
        const { [Thing.referenceType]: referenceType } = thingClass;
        if (!referenceType) {
            throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
        }

        return {
            flags: {update: true, expose: true},
            update: {validate: validateReferenceList(referenceType)}
        };
    },

    // Corresponding function for a single reference.
    singleReference: thingClass => {
        const { [Thing.referenceType]: referenceType } = thingClass;
        if (!referenceType) {
            throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
        }

        return {
            flags: {update: true, expose: true},
            update: {validate: validateReference(referenceType)}
        };
    },

    // Corresponding dynamic property to referenceList, which takes the values
    // in the provided property and searches the specified wiki data for
    // matching actual Thing-subclass objects.
    dynamicThingsFromReferenceList: (
        referenceListProperty,
        thingDataProperty,
        findFn
    ) => ({
        flags: {expose: true},

        expose: {
            dependencies: [referenceListProperty, thingDataProperty],
            compute: ({ [referenceListProperty]: refs, [thingDataProperty]: thingData }) => (
                (refs && thingData
                    ? (refs
                        .map(ref => findFn(ref, thingData, {mode: 'quiet'}))
                        .filter(Boolean))
                    : [])
            )
        }
    }),

    // Corresponding function for a single reference.
    dynamicThingFromSingleReference: (
        singleReferenceProperty,
        thingDataProperty,
        findFn
    ) => ({
        flags: {expose: true},

        expose: {
            dependencies: [singleReferenceProperty, thingDataProperty],
            compute: ({ [singleReferenceProperty]: ref, [thingDataProperty]: thingData }) => (
                (ref && thingData ? findFn(ref, thingData, {mode: 'quiet'}) : [])
            )
        }
    }),

    // Corresponding dynamic property to contribsByRef, which takes the values
    // in the provided property and searches the object's artistData for
    // matching actual Artist objects. The computed structure has the same form
    // as contribsByRef, but with Artist objects instead of string references:
    //
    //     [
    //         {who: (an Artist), what: 'Viola'},
    //         {who: (an Artist), what: null},
    //         ...
    //     ]
    //
    // Contributions whose "who" values don't match anything in artistData are
    // filtered out. (So if the list is all empty, chances are that either the
    // reference list is somehow messed up, or artistData isn't being provided
    // properly.)
    dynamicContribs: (contribsByRefProperty) => ({
        flags: {expose: true},
        expose: {
            dependencies: ['artistData', contribsByRefProperty],
            compute: ({ artistData, [contribsByRefProperty]: contribsByRef }) => (
                ((contribsByRef && artistData)
                    ? (contribsByRef
                        .map(({ who: ref, what }) => ({
                            who: find.artist(ref, artistData),
                            what
                        }))
                        .filter(({ who }) => who))
                    : [])
            )
        }
    }),

    // Dynamically inherit a contribution list from some other object, if it
    // hasn't been overridden on this object. This is handy for solo albums
    // where all tracks have the same artist, for example.
    //
    // Note: The arguments of this function aren't currently final! The final
    // format will look more like (contribsByRef, parentContribsByRef), e.g.
    // ('artistContribsByRef', '@album/artistContribsByRef').
    dynamicInheritContribs: (
        contribsByRefProperty,
        parentContribsByRefProperty,
        thingDataProperty,
        findFn
    ) => ({
        flags: {expose: true},
        expose: {
            dependencies: [contribsByRefProperty, thingDataProperty, 'artistData'],
            compute({
                [Thing.instance]: thing,
                [contribsByRefProperty]: contribsByRef,
                [thingDataProperty]: thingData,
                artistData
            }) {
                if (!artistData) return [];
                const refs = (contribsByRef ?? findFn(thing, thingData, {mode: 'quiet'})?.[parentContribsByRefProperty]);
                if (!refs) return [];
                return (refs
                    .map(({ who: ref, what }) => ({
                        who: find.artist(ref, artistData),
                        what
                    }))
                    .filter(({ who }) => who));
            }
        }
    }),

    // 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.
    reverseReferenceList: (wikiDataProperty, referencerRefListProperty) => ({
        flags: {expose: true},

        expose: {
            dependencies: [wikiDataProperty],

            compute: ({ [wikiDataProperty]: wikiData, [Thing.instance]: thing }) => (
                (wikiData
                    ? wikiData.filter(t => t[referencerRefListProperty]?.includes(thing))
                    : [])
            )
        }
    }),

    // Corresponding function for single references. Note that the return value
    // is still a list - this is for matching all the objects whose single
    // reference (in the given property) matches this Thing.
    reverseSingleReference: (wikiDataProperty, referencerRefListProperty) => ({
        flags: {expose: true},

        expose: {
            dependencies: [wikiDataProperty],

            compute: ({ [wikiDataProperty]: wikiData, [Thing.instance]: thing }) => (
                wikiData?.filter(t => t[referencerRefListProperty] === thing))
        }
    }),

    // General purpose wiki data constructor, for properties like artistData,
    // trackData, etc.
    wikiData: (thingClass) => ({
        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.
    commentatorArtists: () => ({
        flags: {expose: true},

        expose: {
            dependencies: ['artistData', 'commentary'],

            compute: ({ artistData, commentary }) => (
                (artistData && commentary
                    ? Array.from(new Set((Array
                        .from(commentary
                            .replace(/<\/?b>/g, '')
                            .matchAll(/<i>(?<who>.*?):<\/i>/g))
                        .map(({ groups: {who} }) => find.artist(who, artistData, {mode: 'quiet'})))))
                    : []))
        }
    }),
};

// Get a reference to a thing (e.g. track:showtime-piano-refrain), using its
// constructor's [Thing.referenceType] as the prefix. This will throw an error
// if the thing's directory isn't yet provided/computable.
Thing.getReference = function(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}`;
};

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

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

// -> Album

Album.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Album'),
    color: Thing.common.color(),
    directory: Thing.common.directory(),
    urls: Thing.common.urls(),

    date: Thing.common.simpleDate(),
    trackArtDate: Thing.common.simpleDate(),
    dateAddedToWiki: Thing.common.simpleDate(),

    coverArtDate: {
        flags: {update: true, expose: true},

        update: {validate: isDate},

        expose: {
            dependencies: ['date'],
            transform: (coverArtDate, { date }) => coverArtDate ?? date ?? null
        }
    },

    artistContribsByRef: Thing.common.contribsByRef(),
    coverArtistContribsByRef: Thing.common.contribsByRef(),
    trackCoverArtistContribsByRef: Thing.common.contribsByRef(),
    wallpaperArtistContribsByRef: Thing.common.contribsByRef(),
    bannerArtistContribsByRef: Thing.common.contribsByRef(),

    groupsByRef: Thing.common.referenceList(Group),
    artTagsByRef: Thing.common.referenceList(ArtTag),

    trackGroups: {
        flags: {update: true, expose: true},

        update: {
            validate: validateArrayItems(validateInstanceOf(TrackGroup))
        }
    },

    coverArtFileExtension: Thing.common.fileExtension('jpg'),
    trackCoverArtFileExtension: Thing.common.fileExtension('jpg'),

    wallpaperStyle: Thing.common.simpleString(),
    wallpaperFileExtension: Thing.common.fileExtension('jpg'),

    bannerStyle: Thing.common.simpleString(),
    bannerFileExtension: Thing.common.fileExtension('jpg'),
    bannerDimensions: {
        flags: {update: true, expose: true},
        update: {validate: isDimensions}
    },

    hasCoverArt: Thing.common.flag(true),
    hasTrackArt: Thing.common.flag(true),
    hasTrackNumbers: Thing.common.flag(true),
    isMajorRelease: Thing.common.flag(false),
    isListedOnHomepage: Thing.common.flag(true),

    commentary: Thing.common.commentary(),
    additionalFiles: Thing.common.additionalFiles(),

    // Update only

    artistData: Thing.common.wikiData(Artist),
    artTagData: Thing.common.wikiData(ArtTag),
    groupData: Thing.common.wikiData(Group),
    trackData: Thing.common.wikiData(Track),

    // Expose only

    artistContribs: Thing.common.dynamicContribs('artistContribsByRef'),
    coverArtistContribs: Thing.common.dynamicContribs('coverArtistContribsByRef'),
    trackCoverArtistContribs: Thing.common.dynamicContribs('trackCoverArtistContribsByRef'),
    wallpaperArtistContribs: Thing.common.dynamicContribs('wallpaperArtistContribsByRef'),
    bannerArtistContribs: Thing.common.dynamicContribs('bannerArtistContribsByRef'),

    commentatorArtists: Thing.common.commentatorArtists(),

    tracks: {
        flags: {expose: true},

        expose: {
            dependencies: ['trackGroups', 'trackData'],
            compute: ({ trackGroups, trackData }) => (
                (trackGroups && trackData
                    ? (trackGroups
                        .flatMap(group => group.tracksByRef ?? [])
                        .map(ref => find.track(ref, trackData, {mode: 'quiet'}))
                        .filter(Boolean))
                    : [])
            )
        }
    },

    groups: Thing.common.dynamicThingsFromReferenceList('groupsByRef', 'groupData', find.group),

    artTags: Thing.common.dynamicThingsFromReferenceList('artTagsByRef', 'artTagData', find.artTag),
};

Album[S.serializeDescriptors] = {
    name: S.id,
    color: S.id,
    directory: S.id,
    urls: S.id,

    date: S.id,
    coverArtDate: S.id,
    trackArtDate: S.id,
    dateAddedToWiki: S.id,

    artistContribs: S.toContribRefs,
    coverArtistContribs: S.toContribRefs,
    trackCoverArtistContribs: S.toContribRefs,
    wallpaperArtistContribs: S.toContribRefs,
    bannerArtistContribs: S.toContribRefs,

    coverArtFileExtension: S.id,
    trackCoverArtFileExtension: S.id,
    wallpaperStyle: S.id,
    wallpaperFileExtension: S.id,
    bannerStyle: S.id,
    bannerFileExtension: S.id,
    bannerDimensions: S.id,

    hasTrackArt: S.id,
    isMajorRelease: S.id,
    isListedOnHomepage: S.id,

    commentary: S.id,
    additionalFiles: S.id,

    tracks: S.toRefs,
    groups: S.toRefs,
    artTags: S.toRefs,
    commentatorArtists: S.toRefs,
};

TrackGroup.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Track Group'),

    color: {
        flags: {update: true, expose: true},

        update: {validate: isColor},

        expose: {
            dependencies: ['album'],

            transform(color, { album }) {
                return color ?? album?.color ?? null;
            }
        }
    },

    dateOriginallyReleased: Thing.common.simpleDate(),

    tracksByRef: Thing.common.referenceList(Track),

    isDefaultTrackGroup: Thing.common.flag(false),

    // Update only

    album: {
        flags: {update: true},
        update: {validate: validateInstanceOf(Album)}
    },

    trackData: Thing.common.wikiData(Track),

    // Expose only

    tracks: {
        flags: {expose: true},

        expose: {
            dependencies: ['tracksByRef', 'trackData'],
            compute: ({ tracksByRef, trackData }) => (
                (tracksByRef && trackData
                    ? (tracksByRef
                        .map(ref => find.track(ref, trackData))
                        .filter(Boolean))
                    : [])
            )
        }
    },

    startIndex: {
        flags: {expose: true},

        expose: {
            dependencies: ['album'],
            compute: ({ album, [TrackGroup.instance]: trackGroup }) => (album.trackGroups
                .slice(0, album.trackGroups.indexOf(trackGroup))
                .reduce((acc, tg) => acc + tg.tracks.length, 0))
        }
    },
};

// -> Track

// This is a quick utility function for now, since the same code is reused in
// several places. Ideally it wouldn't be - we'd just reuse the `album` property
// - but support for that hasn't been coded yet :P
Track.findAlbum = (track, albumData) => {
    return albumData?.find(album => album.tracks.includes(track));
};

// Another reused utility function. This one's logic is a bit more complicated.
Track.hasCoverArt = (track, albumData, coverArtistContribsByRef, hasCoverArt) => {
    return (
        hasCoverArt ??
        (coverArtistContribsByRef?.length > 0 || null) ??
        Track.findAlbum(track, albumData)?.hasTrackArt ??
        true);
};

Track.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Track'),
    directory: Thing.common.directory(),

    duration: {
        flags: {update: true, expose: true},
        update: {validate: isDuration}
    },

    urls: Thing.common.urls(),
    dateFirstReleased: Thing.common.simpleDate(),

    hasURLs: Thing.common.flag(true),

    artistContribsByRef: Thing.common.contribsByRef(),
    contributorContribsByRef: Thing.common.contribsByRef(),
    coverArtistContribsByRef: Thing.common.contribsByRef(),

    referencedTracksByRef: Thing.common.referenceList(Track),
    artTagsByRef: Thing.common.referenceList(ArtTag),

    hasCoverArt: {
        flags: {update: true, expose: true},

        update: {validate: isBoolean},

        expose: {
            dependencies: ['albumData', 'coverArtistContribsByRef'],
            transform: (hasCoverArt, { albumData, coverArtistContribsByRef, [Track.instance]: track }) => (
                Track.hasCoverArt(track, albumData, coverArtistContribsByRef, hasCoverArt))
        }
    },

    coverArtFileExtension: {
        flags: {update: true, expose: true},

        update: {validate: isFileExtension},

        expose: {
            dependencies: ['albumData', 'coverArtistContribsByRef'],
            transform: (coverArtFileExtension, { albumData, coverArtistContribsByRef, hasCoverArt, [Track.instance]: track }) => (
                coverArtFileExtension ??
                (Track.hasCoverArt(track, albumData, coverArtistContribsByRef, hasCoverArt)
                    ? Track.findAlbum(track, albumData)?.trackCoverArtFileExtension
                    : Track.findAlbum(track, albumData)?.coverArtFileExtension) ??
                'jpg')
        }
    },

    // Previously known as: (track).aka
    originalReleaseTrackByRef: Thing.common.singleReference(Track),

    dataSourceAlbumByRef: Thing.common.singleReference(Album),

    commentary: Thing.common.commentary(),
    lyrics: Thing.common.simpleString(),
    additionalFiles: Thing.common.additionalFiles(),

    // Update only

    albumData: Thing.common.wikiData(Album),
    artistData: Thing.common.wikiData(Artist),
    artTagData: Thing.common.wikiData(ArtTag),
    flashData: Thing.common.wikiData(Flash),
    trackData: Thing.common.wikiData(Track),

    // Expose only

    commentatorArtists: Thing.common.commentatorArtists(),

    album: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData'],
            compute: ({ [Track.instance]: track, albumData }) => (
                albumData?.find(album => album.tracks.includes(track)) ?? null)
        }
    },

    // Note - this is an internal property used only to help identify a track.
    // It should not be assumed in general that the album and dataSourceAlbum match
    // (i.e. a track may dynamically be moved from one album to another, at
    // which point dataSourceAlbum refers to where it was originally from, and is
    // not generally relevant information). It's also not guaranteed that
    // dataSourceAlbum is available (depending on the Track creator to optionally
    // provide dataSourceAlbumByRef).
    dataSourceAlbum: Thing.common.dynamicThingFromSingleReference('dataSourceAlbumByRef', 'albumData', find.album),

    date: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData', 'dateFirstReleased'],
            compute: ({ albumData, dateFirstReleased, [Track.instance]: track }) => (
                dateFirstReleased ??
                Track.findAlbum(track, albumData)?.date ??
                null
            )
        }
    },

    color: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData'],

            compute: ({ albumData, [Track.instance]: track }) => (
                (Track.findAlbum(track, albumData)?.trackGroups
                    .find(tg => tg.tracks.includes(track))?.color)
                ?? null
            )
        }
    },

    coverArtDate: {
        flags: {update: true, expose: true},

        update: {validate: isDate},

        expose: {
            dependencies: ['albumData', 'dateFirstReleased'],
            transform: (coverArtDate, { albumData, dateFirstReleased, [Track.instance]: track }) => (
                coverArtDate ??
                dateFirstReleased ??
                Track.findAlbum(track, albumData)?.trackArtDate ??
                Track.findAlbum(track, albumData)?.date ??
                null
            )
        }
    },

    originalReleaseTrack: Thing.common.dynamicThingFromSingleReference('originalReleaseTrackByRef', 'trackData', find.track),

    otherReleases: {
        flags: {expose: true},

        expose: {
            dependencies: ['originalReleaseTrackByRef', 'trackData'],

            compute: ({ originalReleaseTrackByRef: t1origRef, trackData, [Track.instance]: t1 }) => {
                if (!trackData) {
                    return [];
                }

                const t1orig = find.track(t1origRef, trackData);

                return [
                    t1orig,
                    ...trackData.filter(t2 => {
                        const { originalReleaseTrack: t2orig } = t2;
                        return (
                            t2 !== t1 &&
                            t2orig &&
                            (t2orig === t1orig || t2orig === t1)
                        );
                    })
                ].filter(Boolean);
            }
        }
    },

    // Previously known as: (track).artists
    artistContribs: Thing.common.dynamicInheritContribs('artistContribsByRef', 'artistContribsByRef', 'albumData', Track.findAlbum),

    // Previously known as: (track).contributors
    contributorContribs: Thing.common.dynamicContribs('contributorContribsByRef'),

    // Previously known as: (track).coverArtists
    coverArtistContribs: Thing.common.dynamicInheritContribs('coverArtistContribsByRef', 'trackCoverArtistContribsByRef', 'albumData', Track.findAlbum),

    // Previously known as: (track).references
    referencedTracks: Thing.common.dynamicThingsFromReferenceList('referencedTracksByRef', 'trackData', find.track),

    // Previously known as: (track).referencedBy
    referencedByTracks: Thing.common.reverseReferenceList('trackData', 'referencedTracks'),

    // Previously known as: (track).flashes
    featuredInFlashes: Thing.common.reverseReferenceList('flashData', 'featuredTracks'),

    artTags: Thing.common.dynamicThingsFromReferenceList('artTagsByRef', 'artTagData', find.artTag),
};

Track.prototype[inspect.custom] = function() {
    const base = Thing.prototype[inspect.custom].apply(this);

    const { album, dataSourceAlbum } = this;
    const albumName = (album ? album.name : dataSourceAlbum?.name);
    const albumIndex = albumName && (album ? album.tracks.indexOf(this) : dataSourceAlbum.tracks.indexOf(this));
    const trackNum = (albumIndex === -1 ? '#?' : `#${albumIndex + 1}`);

    return (albumName
        ? base + ` (${color.yellow(trackNum)} in ${color.green(albumName)})`
        : base);
};

// -> Artist

Artist.filterByContrib = (thingDataProperty, contribsProperty) => ({
    flags: {expose: true},

    expose: {
        dependencies: [thingDataProperty],

        compute: ({ [thingDataProperty]: thingData, [Artist.instance]: artist }) => (
            thingData?.filter(({ [contribsProperty]: contribs }) => (
                contribs?.some(contrib => contrib.who === artist))))
    }
});

Artist.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Artist'),
    directory: Thing.common.directory(),
    urls: Thing.common.urls(),
    contextNotes: Thing.common.simpleString(),

    hasAvatar: Thing.common.flag(false),
    avatarFileExtension: Thing.common.fileExtension('jpg'),

    aliasNames: {
        flags: {update: true, expose: true},
        update: {
            validate: validateArrayItems(isName)
        }
    },

    isAlias: Thing.common.flag(),
    aliasedArtistRef: Thing.common.singleReference(Artist),

    // Update only

    albumData: Thing.common.wikiData(Album),
    artistData: Thing.common.wikiData(Artist),
    flashData: Thing.common.wikiData(Flash),
    trackData: Thing.common.wikiData(Track),

    // Expose only

    aliasedArtist: {
        flags: {expose: true},

        expose: {
            dependencies: ['artistData', 'aliasedArtistRef'],
            compute: ({ artistData, aliasedArtistRef }) => (
                (aliasedArtistRef && artistData
                    ? find.artist(aliasedArtistRef, artistData, {mode: 'quiet'})
                    : null)
            )
        }
    },

    tracksAsArtist: Artist.filterByContrib('trackData', 'artistContribs'),
    tracksAsContributor: Artist.filterByContrib('trackData', 'contributorContribs'),
    tracksAsCoverArtist: Artist.filterByContrib('trackData', 'coverArtistContribs'),

    tracksAsAny: {
        flags: {expose: true},

        expose: {
            dependencies: ['trackData'],

            compute: ({ trackData, [Artist.instance]: artist }) => (
                trackData?.filter(track => (
                    [
                        ...track.artistContribs,
                        ...track.contributorContribs,
                        ...track.coverArtistContribs
                    ].some(({ who }) => who === artist))))
        }
    },

    tracksAsCommentator: {
        flags: {expose: true},

        expose: {
            dependencies: ['trackData'],

            compute: ({ trackData, [Artist.instance]: artist }) => (
                trackData.filter(({ commentatorArtists }) => commentatorArtists?.includes(artist)))
        }
    },

    albumsAsAlbumArtist: Artist.filterByContrib('albumData', 'artistContribs'),
    albumsAsCoverArtist: Artist.filterByContrib('albumData', 'coverArtistContribs'),
    albumsAsWallpaperArtist: Artist.filterByContrib('albumData', 'wallpaperArtistContribs'),
    albumsAsBannerArtist: Artist.filterByContrib('albumData', 'bannerArtistContribs'),

    albumsAsCommentator: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData'],

            compute: ({ albumData, [Artist.instance]: artist }) => (
                albumData.filter(({ commentatorArtists }) => commentatorArtists?.includes(artist)))
        }
    },

    flashesAsContributor: Artist.filterByContrib('flashData', 'contributorContribs'),
};

Artist[S.serializeDescriptors] = {
    name: S.id,
    directory: S.id,
    urls: S.id,
    contextNotes: S.id,

    hasAvatar: S.id,
    avatarFileExtension: S.id,

    aliasNames: S.id,

    tracksAsArtist: S.toRefs,
    tracksAsContributor: S.toRefs,
    tracksAsCoverArtist: S.toRefs,
    tracksAsCommentator: S.toRefs,

    albumsAsAlbumArtist: S.toRefs,
    albumsAsCoverArtist: S.toRefs,
    albumsAsWallpaperArtist: S.toRefs,
    albumsAsBannerArtist: S.toRefs,
    albumsAsCommentator: S.toRefs,

    flashesAsContributor: S.toRefs,
};

// -> Group

Group.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Group'),
    directory: Thing.common.directory(),

    description: Thing.common.simpleString(),

    urls: Thing.common.urls(),

    // Update only

    albumData: Thing.common.wikiData(Album),
    groupCategoryData: Thing.common.wikiData(GroupCategory),

    // Expose only

    descriptionShort: {
        flags: {expose: true},

        expose: {
            dependencies: ['description'],
            compute: ({ description }) => description.split('<hr class="split">')[0]
        }
    },

    albums: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData'],
            compute: ({ albumData, [Group.instance]: group }) => (
                albumData?.filter(album => album.groups.includes(group)) ?? [])
        }
    },

    color: {
        flags: {expose: true},

        expose: {
            dependencies: ['groupCategoryData'],

            compute: ({ groupCategoryData, [Group.instance]: group }) => (
                groupCategoryData.find(category => category.groups.includes(group))?.color ?? null)
        }
    },

    category: {
        flags: {expose: true},

        expose: {
            dependencies: ['groupCategoryData'],
            compute: ({ groupCategoryData, [Group.instance]: group }) => (
                groupCategoryData.find(category => category.groups.includes(group)) ?? null)
        }
    },
};

GroupCategory.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Group Category'),
    color: Thing.common.color(),

    groupsByRef: Thing.common.referenceList(Group),

    // Update only

    groupData: Thing.common.wikiData(Group),

    // Expose only

    groups: Thing.common.dynamicThingsFromReferenceList('groupsByRef', 'groupData', find.group),
};

// -> ArtTag

ArtTag.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Art Tag'),
    directory: Thing.common.directory(),
    color: Thing.common.color(),
    isContentWarning: Thing.common.flag(false),

    // Update only

    albumData: Thing.common.wikiData(Album),
    trackData: Thing.common.wikiData(Track),

    // Expose only

    // Previously known as: (tag).things
    taggedInThings: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData', 'trackData'],
            compute: ({ albumData, trackData, [ArtTag.instance]: artTag }) => (
                sortByArtDate([...albumData, ...trackData]
                    .filter(thing => thing.artTags?.includes(artTag))))
        }
    }
};

// -> NewsEntry

NewsEntry.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed News Entry'),
    directory: Thing.common.directory(),
    date: Thing.common.simpleDate(),

    content: Thing.common.simpleString(),

    // Expose only

    contentShort: {
        flags: {expose: true},

        expose: {
            dependencies: ['content'],

            compute: ({ content }) => content.split('<hr class="split">')[0]
        }
    },
};

// -> StaticPage

StaticPage.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Static Page'),

    nameShort: {
        flags: {update: true, expose: true},
        update: {validate: isName},

        expose: {
            dependencies: ['name'],
            transform: (value, { name }) => value ?? name
        }
    },

    directory: Thing.common.directory(),
    content: Thing.common.simpleString(),
    stylesheet: Thing.common.simpleString(),
    showInNavigationBar: Thing.common.flag(true),
};

// -> HomepageLayout

HomepageLayout.propertyDescriptors = {
    // Update & expose

    sidebarContent: Thing.common.simpleString(),

    rows: {
        flags: {update: true, expose: true},

        update: {
            validate: validateArrayItems(validateInstanceOf(HomepageLayoutRow))
        }
    },
};

HomepageLayoutRow.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Homepage Row'),

    type: {
        flags: {update: true, expose: true},

        update: {
            validate(value) {
                throw new Error(`'type' property validator must be overridden`);
            }
        }
    },

    color: Thing.common.color(),

    // Update only

    // These aren't necessarily used by every HomepageLayoutRow subclass, but
    // for convenience of providing this data, every row accepts all wiki data
    // arrays depended upon by any subclass's behavior.
    albumData: Thing.common.wikiData(Album),
    groupData: Thing.common.wikiData(Group),
};

HomepageLayoutAlbumsRow.propertyDescriptors = {
    ...HomepageLayoutRow.propertyDescriptors,

    // Update & expose

    type: {
        flags: {update: true, expose: true},
        update: {
            validate(value) {
                if (value !== 'albums') {
                    throw new TypeError(`Expected 'albums'`);
                }

                return true;
            }
        }
    },

    sourceGroupByRef: Thing.common.singleReference(Group),
    sourceAlbumsByRef: Thing.common.referenceList(Album),

    countAlbumsFromGroup: {
        flags: {update: true, expose: true},
        update: {validate: isCountingNumber}
    },

    actionLinks: {
        flags: {update: true, expose: true},
        update: {validate: validateArrayItems(isString)}
    },

    // Expose only

    sourceGroup: Thing.common.dynamicThingFromSingleReference('sourceGroupByRef', 'groupData', find.group),
    sourceAlbums: Thing.common.dynamicThingsFromReferenceList('sourceAlbumsByRef', 'albumData', find.album),
};

// -> Flash

Flash.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Flash'),

    directory: {
        flags: {update: true, expose: true},
        update: {validate: isDirectory},

        // Flashes expose directory differently from other Things! Their
        // default directory is dependent on the page number (or ID), not
        // the name.
        expose: {
            dependencies: ['page'],
            transform(directory, { page }) {
                if (directory === null && page === null)
                    return null;
                else if (directory === null)
                    return page;
                else
                    return directory;
            }
        }
    },

    page: {
        flags: {update: true, expose: true},
        update: {validate: oneOf(isString, isNumber)},

        expose: {
            transform: value => (value === null ? null : value.toString())
        }
    },

    date: Thing.common.simpleDate(),

    coverArtFileExtension: Thing.common.fileExtension('jpg'),

    contributorContribsByRef: Thing.common.contribsByRef(),

    featuredTracksByRef: Thing.common.referenceList(Track),

    urls: Thing.common.urls(),

    // Update only

    artistData: Thing.common.wikiData(Artist),
    trackData: Thing.common.wikiData(Track),
    flashActData: Thing.common.wikiData(FlashAct),

    // Expose only

    contributorContribs: Thing.common.dynamicContribs('contributorContribsByRef'),

    featuredTracks: Thing.common.dynamicThingsFromReferenceList('featuredTracksByRef', 'trackData', find.track),

    act: {
        flags: {expose: true},

        expose: {
            dependencies: ['flashActData'],

            compute: ({ flashActData, [Flash.instance]: flash }) => (
                flashActData.find(act => act.flashes.includes(flash)) ?? null)
        }
    },

    color: {
        flags: {expose: true},

        expose: {
            dependencies: ['flashActData'],

            compute: ({ flashActData, [Flash.instance]: flash }) => (
                flashActData.find(act => act.flashes.includes(flash))?.color ?? null)
        }
    },
};

Flash[S.serializeDescriptors] = {
    name: S.id,
    page: S.id,
    directory: S.id,
    date: S.id,
    contributors: S.toContribRefs,
    tracks: S.toRefs,
    urls: S.id,
    color: S.id,
};

FlashAct.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Flash Act'),
    color: Thing.common.color(),
    anchor: Thing.common.simpleString(),
    jump: Thing.common.simpleString(),
    jumpColor: Thing.common.color(),

    flashesByRef: Thing.common.referenceList(Flash),

    // Update only

    flashData: Thing.common.wikiData(Flash),

    // Expose only

    flashes: Thing.common.dynamicThingsFromReferenceList('flashesByRef', 'flashData', find.flash),
};

// -> WikiInfo

WikiInfo.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Wiki'),

    // Displayed in nav bar.
    nameShort: {
        flags: {update: true, expose: true},
        update: {validate: isName},

        expose: {
            dependencies: ['name'],
            transform: (value, { name }) => value ?? name
        }
    },

    color: Thing.common.color(),

    // One-line description used for <meta rel="description"> tag.
    description: Thing.common.simpleString(),

    footerContent: Thing.common.simpleString(),

    defaultLanguage: {
        flags: {update: true, expose: true},
        update: {validate: isLanguageCode}
    },

    canonicalBase: {
        flags: {update: true, expose: true},
        update: {validate: isURL}
    },

    // Feature toggles

    enableFlashesAndGames: Thing.common.flag(false),
    enableListings: Thing.common.flag(false),
    enableNews: Thing.common.flag(false),
    enableArtTagUI: Thing.common.flag(false),
    enableGroupUI: Thing.common.flag(false),
};

// -> Language

const intlHelper = (constructor, opts) => ({
    flags: {expose: true},
    expose: {
        dependencies: ['code', 'intlCode'],
        compute: ({ code, intlCode }) => {
            const constructCode = intlCode ?? code;
            if (!constructCode) return null;
            return Reflect.construct(constructor, [constructCode, opts]);
        }
    }
});

Language.propertyDescriptors = {
    // Update & expose

    // General language code. This is used to identify the language distinctly
    // from other languages (similar to how "Directory" operates in many data
    // objects).
    code: {
        flags: {update: true, expose: true},
        update: {validate: isLanguageCode}
    },

    // Human-readable name. This should be the language's own native name, not
    // localized to any other language.
    name: Thing.common.simpleString(),

    // Language code specific to JavaScript's Internationalization (Intl) API.
    // Usually this will be the same as the language's general code, but it
    // may be overridden to provide Intl constructors an alternative value.
    intlCode: {
        flags: {update: true, expose: true},
        update: {validate: isLanguageCode},
        expose: {
            dependencies: ['code'],
            transform: (intlCode, { code }) => intlCode ?? code
        }
    },

    // Mapping of translation keys to values (strings). Generally, don't
    // access this object directly - use methods instead.
    strings: {
        flags: {update: true, expose: true},
        update: {validate: t => typeof t === 'object'},
        expose: {
            dependencies: ['inheritedStrings'],
            transform(strings, { inheritedStrings }) {
                if (strings || inheritedStrings) {
                    return {...inheritedStrings ?? {}, ...strings ?? {}};
                } else {
                    return null;
                }
            }
        }
    },

    // May be provided to specify "default" strings, generally (but not
    // necessarily) inherited from another Language object.
    inheritedStrings: {
        flags: {update: true, expose: true},
        update: {validate: t => typeof t === 'object'}
    },

    // Update only

    escapeHTML: Thing.common.externalFunction(),

    // Expose only

    intl_date: intlHelper(Intl.DateTimeFormat, {full: true}),
    intl_number: intlHelper(Intl.NumberFormat),
    intl_listConjunction: intlHelper(Intl.ListFormat, {type: 'conjunction'}),
    intl_listDisjunction: intlHelper(Intl.ListFormat, {type: 'disjunction'}),
    intl_listUnit: intlHelper(Intl.ListFormat, {type: 'unit'}),
    intl_pluralCardinal: intlHelper(Intl.PluralRules, {type: 'cardinal'}),
    intl_pluralOrdinal: intlHelper(Intl.PluralRules, {type: 'ordinal'}),

    validKeys: {
        flags: {expose: true},

        expose: {
            dependencies: ['strings', 'inheritedStrings'],
            compute: ({ strings, inheritedStrings }) => Array.from(new Set([
                ...Object.keys(inheritedStrings ?? {}),
                ...Object.keys(strings ?? {})
            ]))
        }
    },

    strings_htmlEscaped: {
        flags: {expose: true},
        expose: {
            dependencies: ['strings', 'inheritedStrings', 'escapeHTML'],
            compute({ strings, inheritedStrings, escapeHTML }) {
                if (!(strings || inheritedStrings) || !escapeHTML) return null;
                const allStrings = {...inheritedStrings ?? {}, ...strings ?? {}};
                return Object.fromEntries(Object.entries(allStrings)
                    .map(([ k, v ]) => [k, escapeHTML(v)]));
            }
        }
    },
};

const countHelper = (stringKey, argName = stringKey) => function(value, {unit = false} = {}) {
    return this.$(
        (unit
            ? `count.${stringKey}.withUnit.` + this.getUnitForm(value)
            : `count.${stringKey}`),
        {[argName]: this.formatNumber(value)});
};

Object.assign(Language.prototype, {
    $(key, args = {}) {
        return this.formatString(key, args);
    },

    assertIntlAvailable(property) {
        if (!this[property]) {
            throw new Error(`Intl API ${property} unavailable`);
        }
    },

    getUnitForm(value) {
        this.assertIntlAvailable('intl_pluralCardinal');
        return this.intl_pluralCardinal.select(value);
    },

    formatString(key, args = {}) {
        if (this.strings && !this.strings_htmlEscaped) {
            throw new Error(`HTML-escaped strings unavailable - please ensure escapeHTML function is provided`);
        }

        return this.formatStringHelper(this.strings_htmlEscaped, key, args);
    },

    formatStringNoHTMLEscape(key, args = {}) {
        return this.formatStringHelper(this.strings, key, args);
    },

    formatStringHelper(strings, key, args = {}) {
        if (!strings) {
            throw new Error(`Strings unavailable`);
        }

        if (!this.validKeys.includes(key)) {
            throw new Error(`Invalid key ${key} accessed`);
        }

        const template = strings[key];

        // Convert the keys on the args dict from camelCase to CONSTANT_CASE.
        // (This isn't an OUTRAGEOUSLY versatile algorithm for doing that, 8ut
        // like, who cares, dude?) Also, this is an array, 8ecause it's handy
        // for the iterating we're a8out to do.
        const processedArgs = Object.entries(args)
            .map(([ k, v ]) => [k.replace(/[A-Z]/g, '_$&').toUpperCase(), v]);

        // Replacement time! Woot. Reduce comes in handy here!
        const output = processedArgs.reduce(
            (x, [ k, v ]) => x.replaceAll(`{${k}}`, v),
            template);

        // Post-processing: if any expected arguments *weren't* replaced, that
        // is almost definitely an error.
        if (output.match(/\{[A-Z_]+\}/)) {
            throw new Error(`Args in ${key} were missing - output: ${output}`);
        }

        return output;
    },

    formatDate(date) {
        this.assertIntlAvailable('intl_date');
        return this.intl_date.format(date);
    },

    formatDateRange(startDate, endDate) {
        this.assertIntlAvailable('intl_date');
        return this.intl_date.formatRange(startDate, endDate);
    },

    formatDuration(secTotal, {approximate = false, unit = false} = {}) {
        if (secTotal === 0) {
            return this.formatString('count.duration.missing');
        }

        const hour = Math.floor(secTotal / 3600);
        const min = Math.floor((secTotal - hour * 3600) / 60);
        const sec = Math.floor(secTotal - hour * 3600 - min * 60);

        const pad = val => val.toString().padStart(2, '0');

        const stringSubkey = unit ? '.withUnit' : '';

        const duration = (hour > 0
            ? this.formatString('count.duration.hours' + stringSubkey, {
                hours: hour,
                minutes: pad(min),
                seconds: pad(sec)
            })
            : this.formatString('count.duration.minutes' + stringSubkey, {
                minutes: min,
                seconds: pad(sec)
            }));

        return (approximate
            ? this.formatString('count.duration.approximate', {duration})
            : duration);
    },

    formatIndex(value) {
        this.assertIntlAvailable('intl_pluralOrdinal');
        return this.formatString('count.index.' + this.intl_pluralOrdinal.select(value), {index: value});
    },

    formatNumber(value) {
        this.assertIntlAvailable('intl_number');
        return this.intl_number.format(value);
    },

    formatWordCount(value) {
        const num = this.formatNumber(value > 1000
            ? Math.floor(value / 100) / 10
            : value);

        const words = (value > 1000
            ? this.formatString('count.words.thousand', {words: num})
            : this.formatString('count.words', {words: num}));

        return this.formatString('count.words.withUnit.' + this.getUnitForm(value), {words});
    },

    // Conjunction list: A, B, and C
    formatConjunctionList(array) {
        this.assertIntlAvailable('intl_listConjunction');
        return this.intl_listConjunction.format(array);
    },

    // Disjunction lists: A, B, or C
    formatDisjunctionList(array) {
        this.assertIntlAvailable('intl_listDisjunction');
        return this.intl_listDisjunction.format(array);
    },

    // Unit lists: A, B, C
    formatUnitList(array) {
        this.assertIntlAvailable('intl_listUnit');
        return this.intl_listUnit.format(array);
    },

    // File sizes: 42.5 kB, 127.2 MB, 4.13 GB, 998.82 TB
    formatFileSize(bytes) {
        if (!bytes) return '';

        bytes = parseInt(bytes);
        if (isNaN(bytes)) return '';

        const round = exp => Math.round(bytes / 10 ** (exp - 1)) / 10;

        if (bytes >= 10 ** 12) {
            return this.formatString('count.fileSize.terabytes', {terabytes: round(12)});
        } else if (bytes >= 10 ** 9) {
            return this.formatString('count.fileSize.gigabytes', {gigabytes: round(9)});
        } else if (bytes >= 10 ** 6) {
            return this.formatString('count.fileSize.megabytes', {megabytes: round(6)});
        } else if (bytes >= 10 ** 3) {
            return this.formatString('count.fileSize.kilobytes', {kilobytes: round(3)});
        } else {
            return this.formatString('count.fileSize.bytes', {bytes});
        }
    },

    // TODO: These are hard-coded. Is there a better way?
    countAlbums: countHelper('albums'),
    countCommentaryEntries: countHelper('commentaryEntries', 'entries'),
    countContributions: countHelper('contributions'),
    countCoverArts: countHelper('coverArts'),
    countTimesReferenced: countHelper('timesReferenced'),
    countTimesUsed: countHelper('timesUsed'),
    countTracks: countHelper('tracks'),
});