diff options
Diffstat (limited to 'src/data')
140 files changed, 7525 insertions, 5832 deletions
diff --git a/src/data/cacheable-object.js b/src/data/cacheable-object.js index 010d967a..9c655823 100644 --- a/src/data/cacheable-object.js +++ b/src/data/cacheable-object.js @@ -1,79 +1,3 @@ -// Generally extendable class for caching properties and handling dependencies, -// with a few key properties: -// -// 1) The behavior of every property is defined by its descriptor, which is a -// static value stored on the subclass (all instances share the same property -// descriptors). -// -// 1a) Additional properties may not be added past the time of object -// construction, and attempts to do so (including externally setting a -// property name which has no corresponding descriptor) will throw a -// TypeError. (This is done via an Object.seal(this) call after a newly -// created instance defines its own properties according to the descriptor -// on its constructor class.) -// -// 2) Properties may have two flags set: update and expose. Properties which -// update are provided values from the external. Properties which expose -// provide values to the external, generally dependent on other update -// properties (within the same object). -// -// 2a) Properties may be flagged as both updating and exposing. This is so -// that the same name may be used for both "output" and "input". -// -// 3) Exposed properties have values which are computations dependent on other -// properties, as described by a `compute` function on the descriptor. -// Depended-upon properties are explicitly listed on the descriptor next to -// this function, and are only provided as arguments to the function once -// listed. -// -// 3a) An exposed property may depend only upon updating properties, not other -// exposed properties (within the same object). This is to force the -// general complexity of a single object to be fairly simple: inputs -// directly determine outputs, with the only in-between step being the -// `compute` function, no multiple-layer dependencies. Note that this is -// only true within a given object - externally, values provided to one -// object's `update` may be (and regularly are) the exposed values of -// another object. -// -// 3b) If a property both updates and exposes, it is automatically regarded as -// a dependancy. (That is, its exposed value will depend on the value it is -// updated with.) Rather than a required `compute` function, these have an -// optional `transform` function, which takes the update value as its first -// argument and then the usual key-value dependencies as its second. If no -// `transform` function is provided, the expose value is the same as the -// update value. -// -// 4) Exposed properties are cached; that is, if no depended-upon properties are -// updated, the value of an exposed property is not recomputed. -// -// 4a) The cache for an exposed property is invalidated as soon as any of its -// dependencies are updated, but the cache itself is lazy: the exposed -// value will not be recomputed until it is again accessed. (Likewise, an -// exposed value won't be computed for the first time until it is first -// accessed.) -// -// 5) Updating a property may optionally apply validation checks before passing, -// declared by a `validate` function on the `update` block. This function -// should either throw an error (e.g. TypeError) or return false if the value -// is invalid. -// -// 6) Objects do not expect all updating properties to be provided at once. -// Incomplete objects are deliberately supported and enabled. -// -// 6a) The default value for every updating property is null; undefined is not -// accepted as a property value under any circumstances (it always errors). -// However, this default may be overridden by specifying a `default` value -// on a property's `update` block. (This value will be checked against -// the property's validate function.) Note that a property may always be -// updated to null, even if the default is non-null. (Null always bypasses -// the validate check.) -// -// 6b) It's required by the external consumer of an object to determine whether -// or not the object is ready for use (within the larger program). This is -// convenienced by the static CacheableObject.listAccessibleProperties() -// function, which provides a mapping of exposed property names to whether -// or not their dependencies are yet met. - import {inspect as nodeInspect} from 'node:util'; import {colors, ENABLE_COLOR} from '#cli'; @@ -84,245 +8,165 @@ function inspect(value) { export default class CacheableObject { static propertyDescriptors = Symbol.for('CacheableObject.propertyDescriptors'); + static constructorFinalized = Symbol.for('CacheableObject.constructorFinalized'); + static propertyDependants = Symbol.for('CacheableObject.propertyDependants'); - #propertyUpdateValues = Object.create(null); - #propertyUpdateCacheInvalidators = Object.create(null); - - // Note the constructor doesn't take an initial data source. Due to a quirk - // of JavaScript, private members can't be accessed before the superclass's - // constructor is finished processing - so if we call the overridden - // update() function from inside this constructor, it will error when - // writing to private members. Pretty bad! - // - // That means initial data must be provided by following up with update() - // after constructing the new instance of the Thing (sub)class. - - constructor() { - this.#defineProperties(); - this.#initializeUpdatingPropertyValues(); - - if (CacheableObject.DEBUG_SLOW_TRACK_INVALID_PROPERTIES) { - return new Proxy(this, { - get: (obj, key) => { - if (!Object.hasOwn(obj, key)) { - if (key !== 'constructor') { - CacheableObject._invalidAccesses.add(`(${obj.constructor.name}).${key}`); - } - } - return obj[key]; - }, - }); + static cacheValid = Symbol.for('CacheableObject.cacheValid'); + static cachedValue = Symbol.for('CacheableObject.cachedValue'); + static updateValue = Symbol.for('CacheableObject.updateValues'); + + constructor({seal = true} = {}) { + this[CacheableObject.cachedValue] = Object.create(null); + this[CacheableObject.cacheValid] = Object.create(null); + + this[CacheableObject.updateValue] = + Object.create(this[CacheableObject.updateValue]); + + if (seal) { + Object.seal(this); } } - #withEachPropertyDescriptor(callback) { - const {[CacheableObject.propertyDescriptors]: propertyDescriptors} = - this.constructor; + static finalizeCacheableObjectPrototype() { + if (Object.hasOwn(this, CacheableObject.constructorFinalized)) { + throw new Error(`Constructor ${this.name} already finalized`); + } - for (const property of Reflect.ownKeys(propertyDescriptors)) { - callback(property, propertyDescriptors[property]); + if (!this[CacheableObject.propertyDescriptors]) { + throw new Error(`Expected constructor ${this.name} to provide CacheableObject.propertyDescriptors`); } - } - #initializeUpdatingPropertyValues() { - this.#withEachPropertyDescriptor((property, descriptor) => { - const {flags, update} = descriptor; + const propertyDescriptors = this[CacheableObject.propertyDescriptors]; - if (!flags.update) { - return; - } + // Finalize prototype update value + + this.prototype[CacheableObject.updateValue] = + Object.create( + Object.getPrototypeOf(this.prototype)[CacheableObject.updateValue] ?? + null); + + for (const property of Reflect.ownKeys(propertyDescriptors)) { + const {flags, update} = propertyDescriptors[property]; + if (!flags.update) continue; - if ( - typeof update === 'object' && - update !== null && - 'default' in update - ) { - this[property] = update?.default; + if (typeof update === 'object' && update !== null && 'default' in update) { + validatePropertyValue(property, null, update.default, update); + this.prototype[CacheableObject.updateValue][property] = update.default; } else { - this[property] = null; + this.prototype[CacheableObject.updateValue][property] = null; } - }); - } - - #defineProperties() { - if (!this.constructor[CacheableObject.propertyDescriptors]) { - throw new Error(`Expected constructor ${this.constructor.name} to provide CacheableObject.propertyDescriptors`); } - this.#withEachPropertyDescriptor((property, descriptor) => { - const {flags} = descriptor; + // Finalize prototype property descriptors + + this[CacheableObject.propertyDependants] = Object.create(null); + + for (const property of Reflect.ownKeys(propertyDescriptors)) { + const {flags, update, expose} = propertyDescriptors[property]; const definition = { configurable: false, enumerable: flags.expose, }; - if (flags.update) { - definition.set = this.#getUpdateObjectDefinitionSetterFunction(property); - } - - if (flags.expose) { - definition.get = this.#getExposeObjectDefinitionGetterFunction(property); - } - - Object.defineProperty(this, property, definition); - }); - - Object.seal(this); - } + if (flags.update) setSetter: { + definition.set = function(newValue) { + if (newValue === undefined) { + throw new TypeError(`Properties cannot be set to undefined`); + } - #getUpdateObjectDefinitionSetterFunction(property) { - const {update} = this.#getPropertyDescriptor(property); - const validate = update?.validate; + const oldValue = this[CacheableObject.updateValue][property]; - return (newValue) => { - const oldValue = this.#propertyUpdateValues[property]; + if (newValue === oldValue) { + return; + } - if (newValue === undefined) { - throw new TypeError(`Properties cannot be set to undefined`); - } + if (newValue !== null && update?.validate) { + validatePropertyValue(property, oldValue, newValue, update); + } - if (newValue === oldValue) { - return; - } + this[CacheableObject.updateValue][property] = newValue; - if (newValue !== null && validate) { - try { - const result = validate(newValue); - if (result === undefined) { - throw new TypeError(`Validate function returned undefined`); - } else if (result !== true) { - throw new TypeError(`Validation failed for value ${newValue}`); + const dependants = this.constructor[CacheableObject.propertyDependants][property]; + if (dependants) { + for (const dependant of dependants) { + this[CacheableObject.cacheValid][dependant] = false; + } } - } catch (caughtError) { - throw new CacheableObjectPropertyValueError( - property, oldValue, newValue, {cause: caughtError}); - } + }; } - this.#propertyUpdateValues[property] = newValue; - this.#invalidateCachesDependentUpon(property); - }; - } + if (flags.expose) setGetter: { + if (flags.update && !expose?.transform) { + definition.get = function() { + return this[CacheableObject.updateValue][property]; + }; - #getPropertyDescriptor(property) { - return this.constructor[CacheableObject.propertyDescriptors][property]; - } - - #invalidateCachesDependentUpon(property) { - const invalidators = this.#propertyUpdateCacheInvalidators[property]; - if (!invalidators) { - return; - } - - for (const invalidate of invalidators) { - invalidate(); - } - } + break setGetter; + } - #getExposeObjectDefinitionGetterFunction(property) { - const {flags} = this.#getPropertyDescriptor(property); - const compute = this.#getExposeComputeFunction(property); - - if (compute) { - let cachedValue; - const checkCacheValid = this.#getExposeCheckCacheValidFunction(property); - return () => { - if (checkCacheValid()) { - return cachedValue; - } else { - return (cachedValue = compute()); + if (flags.update && expose?.compute) { + throw new Error(`Updating property ${property} has compute function, should be formatted as transform`); } - }; - } else if (!flags.update && !compute) { - throw new Error(`Exposed property ${property} does not update and is missing compute function`); - } else { - return () => this.#propertyUpdateValues[property]; - } - } - #getExposeComputeFunction(property) { - const {flags, expose} = this.#getPropertyDescriptor(property); + if (!flags.update && !expose?.compute) { + throw new Error(`Exposed property ${property} does not update and is missing compute function`); + } - const compute = expose?.compute; - const transform = expose?.transform; + definition.get = function() { + if (this[CacheableObject.cacheValid][property]) { + return this[CacheableObject.cachedValue][property]; + } - if (flags.update && !transform) { - return null; - } else if (flags.update && compute) { - throw new Error(`Updating property ${property} has compute function, should be formatted as transform`); - } else if (!flags.update && !compute) { - throw new Error(`Exposed property ${property} does not update and is missing compute function`); - } + const dependencies = Object.create(null); + for (const key of expose.dependencies ?? []) { + if (key === 'this') { + dependencies.this = this; + } else if (key === 'thisProperty') { + dependencies.thisProperty = property; + } else if (key.startsWith('_')) { + dependencies[key] = this[CacheableObject.updateValue][key.slice(1)]; + } else { + dependencies[key] = this[key]; + } + } - let getAllDependencies; + const value = + (flags.update + ? expose.transform(this[CacheableObject.updateValue][property], dependencies) + : expose.compute(dependencies)); - if (expose.dependencies?.length > 0) { - const dependencyKeys = expose.dependencies.slice(); - const shouldReflectObject = dependencyKeys.includes('this'); - const shouldReflectProperty = dependencyKeys.includes('thisProperty'); + this[CacheableObject.cachedValue][property] = value; + this[CacheableObject.cacheValid][property] = true; - getAllDependencies = () => { - const dependencies = Object.create(null); + return value; + }; + } - for (const key of dependencyKeys) { - dependencies[key] = this.#propertyUpdateValues[key]; - } + if (flags.expose) recordAsDependant: { + const dependantsMap = this[CacheableObject.propertyDependants]; - if (shouldReflectObject) { - dependencies.this = this; - } - - if (shouldReflectProperty) { - dependencies.thisProperty = property; + for (const dependency of dependenciesOf(property, propertyDescriptors)) { + if (dependantsMap[dependency]) { + dependantsMap[dependency].push(property); + } else { + dependantsMap[dependency] = [property]; + } } + } - return dependencies; - }; - } else { - const dependencies = Object.create(null); - Object.freeze(dependencies); - getAllDependencies = () => dependencies; + Object.defineProperty(this.prototype, property, definition); } - if (flags.update) { - return () => transform(this.#propertyUpdateValues[property], getAllDependencies()); - } else { - return () => compute(getAllDependencies()); - } + this[CacheableObject.constructorFinalized] = true; } - #getExposeCheckCacheValidFunction(property) { - const {flags, expose} = this.#getPropertyDescriptor(property); - - let valid = false; - - const invalidate = () => { - valid = false; - }; - - const dependencyKeys = new Set(expose?.dependencies); - - if (flags.update) { - dependencyKeys.add(property); - } - - for (const key of dependencyKeys) { - if (this.#propertyUpdateCacheInvalidators[key]) { - this.#propertyUpdateCacheInvalidators[key].push(invalidate); - } else { - this.#propertyUpdateCacheInvalidators[key] = [invalidate]; - } - } + static getPropertyDescriptor(property) { + return this[CacheableObject.propertyDescriptors][property]; + } - return () => { - if (!valid) { - valid = true; - return false; - } else { - return true; - } - }; + static hasPropertyDescriptor(property) { + return property in this[CacheableObject.propertyDescriptors]; } static cacheAllExposedProperties(obj) { @@ -349,30 +193,12 @@ export default class CacheableObject { } } - static DEBUG_SLOW_TRACK_INVALID_PROPERTIES = false; - static _invalidAccesses = new Set(); - - static showInvalidAccesses() { - if (!this.DEBUG_SLOW_TRACK_INVALID_PROPERTIES) { - return; - } - - if (!this._invalidAccesses.size) { - return; - } - - console.log(`${this._invalidAccesses.size} unique invalid accesses:`); - for (const line of this._invalidAccesses) { - console.log(` - ${line}`); - } - } - static getUpdateValue(object, key) { - if (!Object.hasOwn(object, key)) { + if (!object.constructor.hasPropertyDescriptor(key)) { return undefined; } - return object.#propertyUpdateValues[key] ?? null; + return object[CacheableObject.updateValue][key] ?? null; } static clone(object) { @@ -384,7 +210,7 @@ export default class CacheableObject { } static copyUpdateValuesOnto(source, target) { - Object.assign(target, source.#propertyUpdateValues); + Object.assign(target, source[CacheableObject.updateValue]); } } @@ -392,10 +218,81 @@ export class CacheableObjectPropertyValueError extends Error { [Symbol.for('hsmusic.aggregate.translucent')] = true; constructor(property, oldValue, newValue, options) { + let inspectOldValue, inspectNewValue; + + try { + inspectOldValue = inspect(oldValue); + } catch { + inspectOldValue = colors.red(`(couldn't inspect)`); + } + + try { + inspectNewValue = inspect(newValue); + } catch { + inspectNewValue = colors.red(`(couldn't inspect)`); + } + super( - `Error setting ${colors.green(property)} (${inspect(oldValue)} -> ${inspect(newValue)})`, + `Error setting ${colors.green(property)} (${inspectOldValue} -> ${inspectNewValue})`, options); this.property = property; } } + +// good ol' module-scope utility functions + +function validatePropertyValue(property, oldValue, newValue, update) { + try { + const result = update.validate(newValue); + if (result === undefined) { + throw new TypeError(`Validate function returned undefined`); + } else if (result !== true) { + throw new TypeError(`Validation failed for value ${newValue}`); + } + } catch (caughtError) { + throw new CacheableObjectPropertyValueError( + property, oldValue, newValue, {cause: caughtError}); + } +} + +function* dependenciesOf(property, propertyDescriptors, cycle = []) { + const descriptor = propertyDescriptors[property]; + + if (descriptor?.flags?.update && descriptor?.expose?.transform) { + yield property; + } + + const dependencies = descriptor?.expose?.dependencies; + if (!dependencies) return; + + for (const dependency of dependencies) { + if (dependency === 'this') continue; + if (dependency === 'thisProperty') continue; + + if (dependency.startsWith('_')) { + yield dependency.slice(1); + continue; + } + + if (dependency === property) { + throw new Error( + `property ${dependency} directly depends on its own computed value`); + } + + if (cycle.includes(dependency)) { + const subcycle = cycle.slice(cycle.indexOf(dependency)); + const supercycle = cycle.slice(0, cycle.indexOf(dependency)); + throw new Error( + `property ${dependency} indirectly depends on its own computed value\n` + + ` via: ` + subcycle.map(p => p + ' -> ').join('') + property + ' -> ' + dependency + + (supercycle.length + ? '\n in: ' + supercycle.join(' -> ') + : '')); + } + + cycle.push(property); + yield* dependenciesOf(dependency, propertyDescriptors, cycle); + cycle.pop(); + } +} diff --git a/src/data/checks.js b/src/data/checks.js index 8f9f0305..ac1b6257 100644 --- a/src/data/checks.js +++ b/src/data/checks.js @@ -4,14 +4,14 @@ import {inspect as nodeInspect} from 'node:util'; import {colors, ENABLE_COLOR} from '#cli'; import CacheableObject from '#cacheable-object'; -import {replacerSpec, parseInput} from '#replacer'; +import {replacerSpec, parseContentNodes} from '#replacer'; import {compareArrays, cut, cutStart, empty, getNestedProp, iterateMultiline} from '#sugar'; import Thing from '#thing'; import thingConstructors from '#things'; -import {combineWikiDataArrays, commentaryRegexCaseSensitive} from '#wiki-data'; import { + annotateError, annotateErrorWithIndex, conditionallySuppressError, decorateErrorWithIndex, @@ -50,7 +50,7 @@ export function reportDirectoryErrors(wikiData, { if (!thingData) continue; for (const thing of thingData) { - if (findSpec.include && !findSpec.include(thing)) { + if (findSpec.include && !findSpec.include(thing, thingConstructors)) { continue; } @@ -60,7 +60,7 @@ export function reportDirectoryErrors(wikiData, { : [thing.directory]); for (const directory of directories) { - if (directory === null || directory === undefined) { + if (directory === '' || directory === null || directory === undefined) { missingDirectoryThings.add(thing); continue; } @@ -166,6 +166,69 @@ function getFieldPropertyMessage(yamlDocumentSpec, property) { return fieldPropertyMessage; } +function decoAnnotateFindErrors(findFn) { + function annotateMultipleNameMatchesIncludingUnfortunatelyUnsecondary(error) { + const matches = error[Symbol.for('hsmusic.find.multipleNameMatches')]; + if (!matches) return; + + const notSoSecondary = + matches + .map(match => match.thing ?? match) + .filter(match => + match.isTrack && + match.isMainRelease && + CacheableObject.getUpdateValue(match, 'mainRelease')); + + if (empty(notSoSecondary)) return; + + let {message} = error; + message += (message.includes('\n') ? '\n\n' : '\n'); + message += colors.bright(colors.yellow('<!>')) + ' '; + message += colors.yellow(`Some of these tracks are meant to be secondary releases,`) + '\n'; + message += ' '.repeat(4); + message += colors.yellow(`but another error is keeping that from processing correctly!`) + '\n'; + message += ' '.repeat(4); + message += colors.yellow(`Probably look for an error to do with "Main Release", first.`); + Object.assign(error, {message}); + } + + return (...args) => { + try { + return findFn(...args); + } catch (caughtError) { + throw annotateError(caughtError, ...[ + annotateMultipleNameMatchesIncludingUnfortunatelyUnsecondary, + ]); + } + }; +} + +function decoSuppressFindErrors(findFn, {property}) { + void property; + + return conditionallySuppressError(_error => { + // We're not suppressing any errors at the moment. + // An old suppression is kept below for reference. + + /* + if (property === 'sampledTracks') { + // Suppress "didn't match anything" errors in particular, just for samples. + // In hsmusic-data we have a lot of "stub" sample data which don't have + // corresponding tracks yet, so it won't be useful to report such reference + // errors until we take the time to address that. But other errors, like + // malformed reference strings or miscapitalized existing tracks, should + // still be reported, as samples of existing tracks *do* display on the + // website! + if (error.message.includes(`Didn't match anything`)) { + return true; + } + } + */ + + return false; + }, findFn); +} + // Warn about references across data which don't match anything. This involves // using the find() functions on all references, setting it to 'error' mode, and // collecting everything in a structured logged (which gets logged if there are @@ -185,18 +248,34 @@ export function filterReferenceErrors(wikiData, { groups: 'group', artTags: '_artTag', referencedArtworks: '_artwork', - commentary: '_commentary', + commentary: '_content', + creditingSources: '_content', + }], + + ['artTagData', { + directDescendantArtTags: 'artTag', + }], + + ['artworkData', { + referencedArtworks: '_artwork', }], ['flashData', { - commentary: '_commentary', + commentary: '_content', + creditingSources: '_content', }], ['groupCategoryData', { groups: 'group', }], - ['homepageLayout.rows', { + ['homepageLayout.sections.rows', { + _include: row => row.type === 'album carousel', + albums: 'album', + }], + + ['homepageLayout.sections.rows', { + _include: row => row.type === 'album grid', sourceGroup: '_homepageSourceGroup', sourceAlbums: 'album', }], @@ -206,24 +285,24 @@ export function filterReferenceErrors(wikiData, { featuredTracks: 'track', }], - ['flashActData', { - flashes: 'flash', - }], - - ['groupData', { - serieses: '_serieses', + ['seriesData', { + albums: 'album', }], ['trackData', { artistContribs: '_contrib', contributorContribs: '_contrib', coverArtistContribs: '_contrib', - referencedTracks: '_trackNotRerelease', - sampledTracks: '_trackNotRerelease', + previousProductionTracks: '_trackMainReleasesOnly', + referencedTracks: '_trackMainReleasesOnly', + sampledTracks: '_trackMainReleasesOnly', artTags: '_artTag', referencedArtworks: '_artwork', - originalReleaseTrack: '_trackNotRerelease', - commentary: '_commentary', + mainRelease: '_mainRelease', + commentary: '_content', + creditingSources: '_content', + referencingSources: '_content', + lyrics: '_content', }], ['wikiInfo', { @@ -237,21 +316,33 @@ export function filterReferenceErrors(wikiData, { const aggregate = openAggregate({message: `Errors validating between-thing references in data`}); for (const [thingDataProp, propSpec] of referenceSpec) { const thingData = getNestedProp(wikiData, thingDataProp); - const things = Array.isArray(thingData) ? thingData : [thingData]; + const things = + (Array.isArray(thingData) + ? thingData.flat(Infinity) + : [thingData]); + aggregate.nest({message: `Reference errors in ${colors.green('wikiData.' + thingDataProp)}`}, ({nest}) => { for (const thing of things) { + if (propSpec._include && !propSpec._include(thing)) { + continue; + } + nest({message: `Reference errors in ${inspect(thing)}`}, ({nest, push, filter}) => { for (const [property, findFnKey] of Object.entries(propSpec)) { + if (property === '_include') { + continue; + } + let value = CacheableObject.getUpdateValue(thing, property); let writeProperty = true; switch (findFnKey) { - case '_commentary': + case '_content': if (value) { value = - Array.from(value.matchAll(commentaryRegexCaseSensitive)) - .map(({groups}) => groups.artistReferences) - .map(text => text.split(',').map(text => text.trim())); + value.map(entry => + CacheableObject.getUpdateValue(entry, 'artists') ?? + []); } writeProperty = false; @@ -265,15 +356,6 @@ export function filterReferenceErrors(wikiData, { // need writing, humm...) writeProperty = false; break; - - case '_serieses': - if (value) { - // Doesn't report on which series has the error, but... - value = value.flatMap(series => series.albums); - } - - writeProperty = false; - break; } if (value === undefined) { @@ -291,15 +373,12 @@ export function filterReferenceErrors(wikiData, { case '_artwork': { const mixed = find.mixed({ - album: find.albumWithArtwork, - track: find.trackWithArtwork, + album: find.albumPrimaryArtwork, + track: find.trackPrimaryArtwork, }); const data = - combineWikiDataArrays([ - wikiData.albumData, - wikiData.trackData, - ]); + wikiData.artworkData; findFn = ref => mixed(ref.reference, data, {mode: 'error'}); @@ -310,7 +389,7 @@ export function filterReferenceErrors(wikiData, { findFn = boundFind.artTag; break; - case '_commentary': + case '_content': findFn = findArtistOrAlias; break; @@ -328,37 +407,129 @@ export function filterReferenceErrors(wikiData, { }; break; - case '_serieses': - findFn = boundFind.album; + case '_mainRelease': + findFn = ref => { + // Mocking what's going on in `withMainRelease`. + + if (ref === 'same name single') { + // Accessing the current thing here. + try { + return boundFind.albumSinglesOnly(thing.name, { + fuzz: { + capitalization: true, + kebab: true, + }, + }); + } catch (caughtError) { + throw new Error( + `Didn't match a single with the same name`, + {cause: caughtError}); + } + } + + let track, trackError; + let album, albumError; + + try { + track = boundFind.trackMainReleasesOnly(ref); + } catch (caughtError) { + trackError = new Error( + `Didn't match a track`, {cause: caughtError}); + } + + try { + album = boundFind.album(ref); + } catch (caughtError) { + albumError = new Error( + `Didn't match an album`, {cause: caughtError}); + } + + if (track && album) { + if (album.tracks.includes(track)) { + return track; + } else { + throw new Error( + `Unrelated album and track matched for reference "${ref}". Please resolve:\n` + + `- ${inspect(track)}\n` + + `- ${inspect(album)}\n` + + `Returning null for this reference.`); + } + } + + if (track) { + return track; + } + + if (album) { + // At this point verification depends on the thing itself, + // which is currently in lexical scope, but if this code + // gets refactored, there might be trouble here... + + if (thing.mainReleaseTrack === null) { + if (album === thing.album) { + throw new Error( + `Matched album for reference "${ref}":\n` + + `- ` + inspect(album) + `\n` + + `...but this is the album that includes this secondary release, itself.\n` + + `Please resolve by pointing to aonther album here, or by removing this\n` + + `Main Release field, if this track is meant to be the main release.`); + } else { + throw new Error( + `Matched album for reference "${ref}":\n` + + `- ` + inspect(album) + `\n` + + `...but none of its tracks automatically match this secondary release.\n` + + `Please resolve by specifying the track here, instead of the album.`); + } + } else { + return album; + } + } + + const aggregateCause = + new AggregateError([albumError, trackError]); + + aggregateCause[Symbol.for('hsmusic.aggregate.translucent')] = true; + + throw new Error(`Trouble matching "${ref}"`, { + cause: aggregateCause, + }); + } + break; case '_trackArtwork': findFn = ref => boundFind.track(ref.reference); break; - case '_trackNotRerelease': + case '_trackMainReleasesOnly': findFn = trackRef => { - const track = boundFind.track(trackRef); - const originalRef = track && CacheableObject.getUpdateValue(track, 'originalReleaseTrack'); + let track = boundFind.trackMainReleasesOnly(trackRef, {mode: 'quiet'}); + if (track) { + return track; + } + + // Will error normally, if this can't unambiguously resolve + // or doesn't match any track. + track = boundFind.track(trackRef); - if (originalRef) { - // It's possible for the original to not actually exist, in this case. - // It should still be reported since the 'Originally Released As' field - // was present. - const original = boundFind.track(originalRef, {mode: 'quiet'}); + const mainRef = CacheableObject.getUpdateValue(track, 'mainRelease'); + if (mainRef) { + // It's possible for the main release to not actually exist, in this case. + // It should still be reported since the 'Main Release' field was present. + const main = boundFind.track(mainRef, {mode: 'quiet'}); // Prefer references by name, but only if it's unambiguous. - const originalByName = - (original - ? boundFind.track(original.name, {mode: 'quiet'}) + const mainByName = + (main + ? boundFind.track(main.name, {mode: 'quiet'}) : null); const shouldBeMessage = - (originalByName - ? colors.green(original.name) - : original - ? colors.green('track:' + original.directory) - : colors.green(originalRef)); + (mainByName + ? colors.green(main.name) + : main + ? colors.green('track:' + main.directory) + : colors.green(mainRef)); throw new Error(`Reference ${colors.red(trackRef)} is to a rerelease, should be ${shouldBeMessage}`); } @@ -372,22 +543,8 @@ export function filterReferenceErrors(wikiData, { break; } - const suppress = fn => conditionallySuppressError(error => { - if (property === 'sampledTracks') { - // Suppress "didn't match anything" errors in particular, just for samples. - // In hsmusic-data we have a lot of "stub" sample data which don't have - // corresponding tracks yet, so it won't be useful to report such reference - // errors until we take the time to address that. But other errors, like - // malformed reference strings or miscapitalized existing tracks, should - // still be reported, as samples of existing tracks *do* display on the - // website! - if (error.message.includes(`Didn't match anything`)) { - return true; - } - } - - return false; - }, fn); + findFn = decoSuppressFindErrors(findFn, {property}); + findFn = decoAnnotateFindErrors(findFn); const fieldPropertyMessage = getFieldPropertyMessage( @@ -438,15 +595,15 @@ export function filterReferenceErrors(wikiData, { } } - if (findFnKey === '_commentary') { + if (findFnKey === '_content') { filter( value, {message: errorMessage}, decorateErrorWithIndex(refs => (refs.length === 1 - ? suppress(findFn)(refs[0]) + ? findFn(refs[0]) : filterAggregate( refs, {message: `Errors in entry's artist references`}, - decorateErrorWithIndex(suppress(findFn))) + decorateErrorWithIndex(findFn)) .aggregate .close()))); @@ -458,19 +615,18 @@ export function filterReferenceErrors(wikiData, { if (Array.isArray(value)) { newPropertyValue = filter( value, {message: errorMessage}, - decorateErrorWithIndex(suppress(findFn))); + decorateErrorWithIndex(findFn)); break determineNewPropertyValue; } - nest({message: errorMessage}, - suppress(({call}) => { - try { - call(findFn, value); - } catch (error) { - newPropertyValue = null; - throw error; - } - })); + nest({message: errorMessage}, ({call}) => { + try { + call(findFn, value); + } catch (error) { + newPropertyValue = null; + throw error; + } + }); } if (writeProperty) { @@ -494,7 +650,11 @@ export class ContentNodeError extends Error { message, }) { const headingLine = - `(${where}) ${message}`; + (message.includes('\n\n') + ? `(${where})\n\n` + message + '\n' + : message.includes('\n') + ? `(${where})\n` + message + : `(${where}) ${message}`); const textUpToNode = containingLine.slice(0, columnNumber); @@ -539,16 +699,33 @@ export function reportContentTextErrors(wikiData, { description: 'description', }; + const artworkShape = { + source: 'artwork source', + originDetails: 'artwork origin details', + }; + const commentaryShape = { body: 'commentary body', - artistDisplayText: 'commentary artist display text', + artistText: 'commentary artist text', annotation: 'commentary annotation', }; + const lyricsShape = { + body: 'lyrics body', + artistText: 'lyrics artist text', + annotation: 'lyrics annotation', + }; + const contentTextSpec = [ ['albumData', { additionalFiles: additionalFileShape, commentary: commentaryShape, + creditingSources: commentaryShape, + coverArtworks: artworkShape, + }], + + ['artTagData', { + description: '_content', }], ['artistData', { @@ -557,6 +734,8 @@ export function reportContentTextErrors(wikiData, { ['flashData', { commentary: commentaryShape, + creditingSources: commentaryShape, + coverArtwork: artworkShape, }], ['flashActData', { @@ -586,10 +765,12 @@ export function reportContentTextErrors(wikiData, { ['trackData', { additionalFiles: additionalFileShape, commentary: commentaryShape, - creditSources: commentaryShape, - lyrics: '_content', + creditingSources: commentaryShape, + referencingSources: commentaryShape, + lyrics: lyricsShape, midiProjectFiles: additionalFileShape, sheetMusicFiles: additionalFileShape, + trackArtworks: artworkShape, }], ['wikiInfo', { @@ -598,11 +779,19 @@ export function reportContentTextErrors(wikiData, { }], ]; - const boundFind = bindFind(wikiData, {mode: 'error'}); + const boundFind = + bindFind(wikiData, { + mode: 'error', + fuzz: { + capitalization: true, + kebab: true, + }, + }); + const findArtistOrAlias = bindFindArtistOrAlias(boundFind); function* processContent(input) { - const nodes = parseInput(input); + const nodes = parseContentNodes(input); for (const node of nodes) { const index = node.i; @@ -639,6 +828,9 @@ export function reportContentTextErrors(wikiData, { break; } + findFn = decoSuppressFindErrors(findFn, {property: null}); + findFn = decoAnnotateFindErrors(findFn); + const findRef = (replacerKeyImplied ? replacerValue @@ -659,7 +851,7 @@ export function reportContentTextErrors(wikiData, { } else if (node.type === 'external-link') { try { new URL(node.data.href); - } catch (error) { + } catch { yield { index, length, message: @@ -710,8 +902,8 @@ export function reportContentTextErrors(wikiData, { for (const thing of things) { nest({message: `Content text errors in ${inspect(thing)}`}, ({nest, push}) => { - for (const [property, shape] of Object.entries(propSpec)) { - const value = thing[property]; + for (let [property, shape] of Object.entries(propSpec)) { + let value = thing[property]; if (value === undefined) { push(new TypeError(`Property ${colors.red(property)} isn't valid for ${colors.green(thing.constructor.name)}`)); @@ -730,6 +922,31 @@ export function reportContentTextErrors(wikiData, { const topMessage = `Content text errors` + fieldPropertyMessage; + const checkShapeEntries = (entry, callProcessContentOpts) => { + for (const [key, annotation] of Object.entries(shape)) { + const value = entry[key]; + + // TODO: This should be an undefined/null check, like above, + // but it's not, because sometimes the stuff we're checking + // here isn't actually coded as a Thing - so the properties + // might really be undefined instead of null. Terrifying and + // awful. And most of all, citation needed. + if (!value) continue; + + callProcessContent({ + ...callProcessContentOpts, + + // TODO: `nest` isn't provided by `callProcessContentOpts` + //`but `push` is - this is to match the old code, but + // what's the deal here? + nest, + + value, + message: `Error in ${colors.green(annotation)}`, + }); + } + }; + if (shape === '_content') { callProcessContent({ nest, @@ -737,26 +954,18 @@ export function reportContentTextErrors(wikiData, { value, message: topMessage, }); - } else { + } else if (Array.isArray(value)) { nest({message: topMessage}, ({push}) => { for (const [index, entry] of value.entries()) { - for (const [key, annotation] of Object.entries(shape)) { - const value = entry[key]; - - // TODO: Should this check undefined/null similar to above? - if (!value) continue; - - callProcessContent({ - nest, - push, - value, - message: `Error in ${colors.green(annotation)}`, - annotateError: error => - annotateErrorWithIndex(error, index), - }); - } + checkShapeEntries(entry, { + push, + annotateError: error => + annotateErrorWithIndex(error, index), + }); } }); + } else { + checkShapeEntries(value, {push}); } } }); @@ -765,3 +974,49 @@ export function reportContentTextErrors(wikiData, { } }); } + +export function reportOrphanedArtworks(wikiData) { + const aggregate = + openAggregate({message: `Artwork objects are orphaned`}); + + const assess = ({ + message, + filterThing, + filterContribs, + link, + }) => { + aggregate.nest({message: `Orphaned ${message}`}, ({push}) => { + const ostensibleArtworks = + wikiData.artworkData + .filter(artwork => + artwork.thing instanceof filterThing && + artwork.artistContribsFromThingProperty === filterContribs); + + const orphanedArtworks = + ostensibleArtworks + .filter(artwork => !artwork.thing[link].includes(artwork)); + + for (const artwork of orphanedArtworks) { + push(new Error(`Orphaned: ${inspect(artwork)}`)); + } + }); + }; + + const {Album, Track} = thingConstructors; + + assess({ + message: `album cover artworks`, + filterThing: Album, + filterContribs: 'coverArtistContribs', + link: 'coverArtworks', + }); + + assess({ + message: `track artworks`, + filterThing: Track, + filterContribs: 'coverArtistContribs', + link: 'trackArtworks', + }); + + aggregate.close(); +} diff --git a/src/data/composite.js b/src/data/composite.js index f31c4069..8ac906c7 100644 --- a/src/data/composite.js +++ b/src/data/composite.js @@ -17,7 +17,7 @@ const _valueIntoToken = shape => : typeof value === 'string' ? Symbol.for(`hsmusic.composite.${shape}:${value}`) : { - symbol: Symbol.for(`hsmusic.composite.input`), + symbol: Symbol.for(`hsmusic.composite.${shape.split('.')[0]}`), shape, value, }); @@ -36,6 +36,10 @@ input.updateValue = _valueIntoToken('input.updateValue'); input.staticDependency = _valueIntoToken('input.staticDependency'); input.staticValue = _valueIntoToken('input.staticValue'); +// Only valid in positional inputs. This is replaced with +// equivalent input.value() token in prepared inputs. +export const V = _valueIntoToken('V'); + function isInputToken(token) { if (token === null) { return false; @@ -48,27 +52,39 @@ function isInputToken(token) { } } +function isConciseInputToken(token) { + if (token === null) { + return false; + } else if (typeof token === 'object') { + return token.symbol === Symbol.for('hsmusic.composite.V'); + } else if (typeof token === 'symbol') { + return token.description.startsWith('hsmusic.composite.V'); + } else { + return false; + } +} + function getInputTokenShape(token) { - if (!isInputToken(token)) { + if (!isInputToken(token) && !isConciseInputToken(token)) { throw new TypeError(`Expected an input token, got ${typeAppearance(token)}`); } if (typeof token === 'object') { return token.shape; } else { - return token.description.match(/hsmusic\.composite\.(input.*?)(:|$)/)[1]; + return token.description.match(/hsmusic\.composite\.(input.*?|V)(:|$)/)[1]; } } function getInputTokenValue(token) { - if (!isInputToken(token)) { + if (!isInputToken(token) && !isConciseInputToken(token)) { throw new TypeError(`Expected an input token, got ${typeAppearance(token)}`); } if (typeof token === 'object') { return token.value; } else { - return token.description.match(/hsmusic\.composite\.input.*?:(.*)/)?.[1] ?? null; + return token.description.match(/hsmusic\.composite\.(?:input.*?|V):(.*)/)?.[1] ?? null; } } @@ -214,76 +230,161 @@ export function templateCompositeFrom(description) { ? Object.keys(description.inputs) : []); - const instantiate = (inputOptions = {}) => { + const optionalInputNames = + expectedInputNames.filter(name => { + const inputDescription = getInputTokenValue(description.inputs[name]); + if (!inputDescription) return false; + if ('defaultValue' in inputDescription) return true; + if ('defaultDependency' in inputDescription) return true; + return false; + }); + + const instantiate = (...args) => { + const preparedInputs = {}; + withAggregate({message: `Errors in input options passed to ${compositionName}`}, ({push}) => { - const providedInputNames = Object.keys(inputOptions); + const [positionalInputs, namedInputs] = + (typeof args.at(-1) === 'object' && + !isInputToken(args.at(-1)) && + !isConciseInputToken(args.at(-1)) + ? [args.slice(0, -1), args.at(-1)] + : [args, {}]); - const misplacedInputNames = - providedInputNames - .filter(name => !expectedInputNames.includes(name)); + const expresslyProvidedInputNames = Object.keys(namedInputs); + const positionallyProvidedInputNames = []; + const remainingInputNames = expectedInputNames.slice(); - const missingInputNames = - expectedInputNames - .filter(name => !providedInputNames.includes(name)) - .filter(name => { - const inputDescription = getInputTokenValue(description.inputs[name]); - if (!inputDescription) return true; - if ('defaultValue' in inputDescription) return false; - if ('defaultDependency' in inputDescription) return false; - return true; - }); + const apparentInputRoutes = {}; - const wrongTypeInputNames = []; + const wrongTypeInputPositions = []; + const namedAndPositionalConflictInputPositions = []; - const expectedStaticValueInputNames = []; - const expectedStaticDependencyInputNames = []; - const expectedValueProvidingTokenInputNames = []; + const maximumPositionalInputs = expectedInputNames.length; + const lastPossiblePositionalIndex = maximumPositionalInputs - 1; - const validateFailedErrors = []; + for (const [index, value] of positionalInputs.entries()) { + if (!isInputToken(value) && !isConciseInputToken(value)) { + if (typeof value === 'object' && value !== null) { + wrongTypeInputPositions.push(index); + continue; + } else if (typeof value !== 'string') { + wrongTypeInputPositions.push(index); + continue; + } + } + + if (index > lastPossiblePositionalIndex) { + continue; + } + + const correspondingName = remainingInputNames.shift(); + if (expresslyProvidedInputNames.includes(correspondingName)) { + namedAndPositionalConflictInputPositions.push(index); + continue; + } + + preparedInputs[correspondingName] = + (isConciseInputToken(value) + ? input.value(getInputTokenValue(value)) + : value); + + apparentInputRoutes[correspondingName] = `${correspondingName} (i = ${index})`; + positionallyProvidedInputNames.push(correspondingName); + } - for (const [name, value] of Object.entries(inputOptions)) { + const misplacedInputNames = + expresslyProvidedInputNames + .filter(name => !expectedInputNames.includes(name)); + + const wrongTypeInputNames = []; + const skippedInputNames = []; + const passedInputNames = []; + const nameProvidedInputNames = []; + + for (const [name, value] of Object.entries(namedInputs)) { if (misplacedInputNames.includes(name)) { continue; } + // Concise input tokens, V(...), end up here too. if (typeof value !== 'string' && !isInputToken(value)) { wrongTypeInputNames.push(name); continue; } + const index = remainingInputNames.indexOf(name); + if (index === 0) { + passedInputNames.push(remainingInputNames.shift()); + } else if (index === -1) { + // This input isn't misplaced, so it's an expected name, + // and SHOULD be in the list of remaining input names. + // But it isn't if it itself has already been skipped! + // And if so, that's already been tracked. + } else { + const til = remainingInputNames.splice(0, index); + passedInputNames.push(...til); + + const skipped = + til.filter(name => + !optionalInputNames.includes(name) || + expresslyProvidedInputNames.includes(name)); + + if (!empty(skipped)) { + skippedInputNames.push({skipped, before: name}); + } + + passedInputNames.push(remainingInputNames.shift()); + } + + preparedInputs[name] = value; + apparentInputRoutes[name] = name; + nameProvidedInputNames.push(name); + } + + const totalProvidedInputNames = + unique([ + ...expresslyProvidedInputNames, + ...positionallyProvidedInputNames, + ]); + + const missingInputNames = + expectedInputNames + .filter(name => !totalProvidedInputNames.includes(name)) + .filter(name => !optionalInputNames.includes(name)); + + const expectedStaticValueInputNames = []; + const expectedStaticDependencyInputNames = []; + const expectedValueProvidingTokenInputNames = []; + const validateFailedErrors = []; + + for (const [name, value] of Object.entries(preparedInputs)) { const descriptionShape = getInputTokenShape(description.inputs[name]); const tokenShape = (isInputToken(value) ? getInputTokenShape(value) : null); const tokenValue = (isInputToken(value) ? getInputTokenValue(value) : null); - switch (descriptionShape) { - case'input.staticValue': - if (tokenShape !== 'input.value') { - expectedStaticValueInputNames.push(name); - continue; - } - break; - - case 'input.staticDependency': - if (typeof value !== 'string' && tokenShape !== 'input.dependency') { - expectedStaticDependencyInputNames.push(name); - continue; - } - break; - - case 'input': - if (typeof value !== 'string' && ![ - 'input', - 'input.value', - 'input.dependency', - 'input.myself', - 'input.thisProperty', - 'input.updateValue', - ].includes(tokenShape)) { - expectedValueProvidingTokenInputNames.push(name); - continue; - } - break; + if (descriptionShape === 'input.staticValue') { + if (tokenShape !== 'input.value') { + expectedStaticValueInputNames.push(name); + continue; + } + } else if (descriptionShape === 'input.staticDependency') { + if (typeof value !== 'string' && tokenShape !== 'input.dependency') { + expectedStaticDependencyInputNames.push(name); + continue; + } + } else { + if (typeof value !== 'string' && ![ + 'input', + 'input.value', + 'input.dependency', + 'input.myself', + 'input.thisProperty', + 'input.updateValue', + ].includes(tokenShape)) { + expectedValueProvidingTokenInputNames.push(name); + continue; + } } if (tokenShape === 'input.value') { @@ -296,6 +397,11 @@ export function templateCompositeFrom(description) { } } + const inputAppearance = name => + (isInputToken(preparedInputs[name]) + ? `${getInputTokenShape(preparedInputs[name])}() call` + : `dependency name`); + if (!empty(misplacedInputNames)) { push(new Error(`Unexpected input names: ${misplacedInputNames.join(', ')}`)); } @@ -304,29 +410,53 @@ export function templateCompositeFrom(description) { push(new Error(`Required these inputs: ${missingInputNames.join(', ')}`)); } - const inputAppearance = name => - (isInputToken(inputOptions[name]) - ? `${getInputTokenShape(inputOptions[name])}() call` - : `dependency name`); + if (positionalInputs.length > maximumPositionalInputs) { + push(new Error(`Too many positional inputs provided (${positionalInputs.length} > ${maximumPositionalInputs}`)); + } + + for (const index of namedAndPositionalConflictInputPositions) { + const conflictingName = positionalInputNames[index]; + push(new Error(`${name}: Provided as both named and positional (i = ${index}) input`)); + } + + for (const {skipped, before} of skippedInputNames) { + push(new Error(`Expected ${skipped.join(', ')} before ${before}`)); + } for (const name of expectedStaticDependencyInputNames) { - const appearance = inputAppearance(name); - push(new Error(`${name}: Expected dependency name, got ${appearance}`)); + const appearance = inputAppearance(preparedInputs[name]); + const route = apparentInputRoutes[name]; + push(new Error(`${route}: Expected dependency name, got ${appearance}`)); } for (const name of expectedStaticValueInputNames) { - const appearance = inputAppearance(name) - push(new Error(`${name}: Expected input.value() call, got ${appearance}`)); + const appearance = inputAppearance(preparedInputs[name]); + const route = apparentInputRoutes[name]; + push(new Error(`${route}: Expected input.value() call, got ${appearance}`)); } for (const name of expectedValueProvidingTokenInputNames) { - const appearance = getInputTokenShape(inputOptions[name]); - push(new Error(`${name}: Expected dependency name or value-providing input() call, got ${appearance}`)); + const appearance = getInputTokenShape(preparedInputs[name]); + const route = apparentInputRoutes[name]; + push(new Error(`${route}: Expected dependency name or value-providing input() call, got ${appearance}`)); } for (const name of wrongTypeInputNames) { - const type = typeAppearance(inputOptions[name]); - push(new Error(`${name}: Expected dependency name or input() call, got ${type}`)); + if (isConciseInputToken(namedInputs[name])) { + push(new Error(`${name}: Use input.value() instead of V() for named inputs`)); + } else { + const type = typeAppearance(namedInputs[name]); + push(new Error(`${name}: Expected dependency name or input() call, got ${type}`)); + } + } + + for (const index of wrongTypeInputPositions) { + const type = typeAppearance(positionalInputs[index]); + if (type === 'object') { + push(new Error(`i = ${index}: Got object - all named dependencies must be passed together, in last argument`)); + } else { + push(new Error(`i = ${index}: Expected dependency name or input() call, got ${type}`)); + } } for (const error of validateFailedErrors) { @@ -338,13 +468,13 @@ export function templateCompositeFrom(description) { if ('inputs' in description) { for (const [name, token] of Object.entries(description.inputs)) { const tokenValue = getInputTokenValue(token); - if (name in inputOptions) { - if (typeof inputOptions[name] === 'string') { - inputMapping[name] = input.dependency(inputOptions[name]); + if (name in preparedInputs) { + if (typeof preparedInputs[name] === 'string') { + inputMapping[name] = input.dependency(preparedInputs[name]); } else { // This is always an input token, since only a string or // an input token is a valid input option (asserted above). - inputMapping[name] = inputOptions[name]; + inputMapping[name] = preparedInputs[name]; } } else if (tokenValue.defaultValue) { inputMapping[name] = input.value(tokenValue.defaultValue); @@ -713,8 +843,9 @@ export function compositeFrom(description) { stepExposeDescriptions .flatMap(expose => expose?.dependencies ?? []) .map(dependency => { - if (typeof dependency === 'string') + if (typeof dependency === 'string') { return (dependency.startsWith('#') ? null : dependency); + } const tokenShape = getInputTokenShape(dependency); const tokenValue = getInputTokenValue(dependency); @@ -886,7 +1017,7 @@ export function compositeFrom(description) { } }); - withAggregate({message: `Errors in input values provided to ${compositionName}`}, ({push}) => { + withAggregate({message: `Errors validating input values provided to ${compositionName}`}, ({push}) => { for (const {dynamic, name, value, description} of stitchArrays({ dynamic: inputsMayBeDynamicValue, name: inputNames, @@ -896,9 +1027,10 @@ export function compositeFrom(description) { if (!dynamic) continue; try { validateInputValue(value, description); - } catch (error) { - error.message = `${name}: ${error.message}`; - push(error); + } catch (caughtError) { + push(new Error( + `Error validating input ${name}: ` + inspect(value, {compact: true}), + {cause: caughtError})); } } }); @@ -1416,7 +1548,7 @@ export function compositeFrom(description) { export function displayCompositeCacheAnalysis() { const showTimes = (cache, key) => { - const times = cache.times[key].slice().sort(); + const times = cache.times[key].toSorted(); const all = times; const worst10pc = times.slice(-times.length / 10); diff --git a/src/data/composite/control-flow/exitWithoutDependency.js b/src/data/composite/control-flow/exitWithoutDependency.js index c660a7ef..598f2ec2 100644 --- a/src/data/composite/control-flow/exitWithoutDependency.js +++ b/src/data/composite/control-flow/exitWithoutDependency.js @@ -11,8 +11,8 @@ export default templateCompositeFrom({ inputs: { dependency: input({acceptsNull: true}), - mode: inputAvailabilityCheckMode(), value: input({defaultValue: null}), + mode: inputAvailabilityCheckMode(), }, steps: () => [ diff --git a/src/data/composite/control-flow/exitWithoutUpdateValue.js b/src/data/composite/control-flow/exitWithoutUpdateValue.js index 244b3233..5104a8c0 100644 --- a/src/data/composite/control-flow/exitWithoutUpdateValue.js +++ b/src/data/composite/control-flow/exitWithoutUpdateValue.js @@ -10,15 +10,27 @@ export default templateCompositeFrom({ annotation: `exitWithoutUpdateValue`, inputs: { - mode: inputAvailabilityCheckMode(), value: input({defaultValue: null}), + mode: inputAvailabilityCheckMode(), + + validate: input({ + type: 'function', + defaultValue: null, + }), }, + update: ({ + [input.staticValue('validate')]: validate, + }) => + (validate + ? {validate} + : {}), + steps: () => [ exitWithoutDependency({ dependency: input.updateValue(), - mode: input('mode'), value: input('value'), + mode: input('mode'), }), ], }); diff --git a/src/data/composite/control-flow/flipFilter.js b/src/data/composite/control-flow/flipFilter.js new file mode 100644 index 00000000..995bacad --- /dev/null +++ b/src/data/composite/control-flow/flipFilter.js @@ -0,0 +1,36 @@ +// Flips a filter, so that each true item becomes false, and vice versa. +// Overwrites the provided dependency. +// +// See also: +// - withAvailabilityFilter + +import {input, templateCompositeFrom} from '#composite'; + +export default templateCompositeFrom({ + annotation: `flipFilter`, + + inputs: { + filter: input({type: 'array'}), + }, + + outputs: ({ + [input.staticDependency('filter')]: filterDependency, + }) => [filterDependency ?? '#flippedFilter'], + + steps: () => [ + { + dependencies: [ + input('filter'), + input.staticDependency('filter'), + ], + + compute: (continuation, { + [input('filter')]: filter, + [input.staticDependency('filter')]: filterDependency, + }) => continuation({ + [filterDependency ?? '#flippedFilter']: + filter.map(item => !item), + }), + }, + ], +}); diff --git a/src/data/composite/control-flow/index.js b/src/data/composite/control-flow/index.js index 7e137a14..61bfa08e 100644 --- a/src/data/composite/control-flow/index.js +++ b/src/data/composite/control-flow/index.js @@ -10,6 +10,8 @@ export {default as exposeDependency} from './exposeDependency.js'; export {default as exposeDependencyOrContinue} from './exposeDependencyOrContinue.js'; export {default as exposeUpdateValueOrContinue} from './exposeUpdateValueOrContinue.js'; export {default as exposeWhetherDependencyAvailable} from './exposeWhetherDependencyAvailable.js'; +export {default as flipFilter} from './flipFilter.js'; +export {default as inputAvailabilityCheckMode} from './inputAvailabilityCheckMode.js'; // A helper, technically... export {default as raiseOutputWithoutDependency} from './raiseOutputWithoutDependency.js'; export {default as raiseOutputWithoutUpdateValue} from './raiseOutputWithoutUpdateValue.js'; export {default as withAvailabilityFilter} from './withAvailabilityFilter.js'; diff --git a/src/data/composite/control-flow/withAvailabilityFilter.js b/src/data/composite/control-flow/withAvailabilityFilter.js index cfea998e..fd93af71 100644 --- a/src/data/composite/control-flow/withAvailabilityFilter.js +++ b/src/data/composite/control-flow/withAvailabilityFilter.js @@ -4,6 +4,7 @@ // Accepts the same mode options as withResultOfAvailabilityCheck. // // See also: +// - flipFilter // - withFilteredList // - withResultOfAvailabilityCheck // diff --git a/src/data/composite/data/helpers/property-from-helpers.js b/src/data/composite/data/helpers/property-from-helpers.js new file mode 100644 index 00000000..00251f3b --- /dev/null +++ b/src/data/composite/data/helpers/property-from-helpers.js @@ -0,0 +1,14 @@ +export function getOutputName({property, from, prefix = null}) { + if (property && prefix) { + return `${prefix}.${property}`; + } else if (property && from) { + if (from.startsWith('_')) { + return `${from.slice(1)}.${property}`; + } else { + return `${from}.${property}`; + } + } else { + if (!property) throw new Error(`guard property outside getOutputName(), c'mon`); + if (!from) throw new Error(`guard from in getOutputName(), c'mon`); + } +} \ No newline at end of file diff --git a/src/data/composite/data/index.js b/src/data/composite/data/index.js index 46a3dc81..05b59445 100644 --- a/src/data/composite/data/index.js +++ b/src/data/composite/data/index.js @@ -20,6 +20,7 @@ export {default as withMappedList} from './withMappedList.js'; export {default as withSortedList} from './withSortedList.js'; export {default as withStretchedList} from './withStretchedList.js'; +export {default as withLengthOfList} from './withLengthOfList.js'; export {default as withPropertyFromList} from './withPropertyFromList.js'; export {default as withPropertiesFromList} from './withPropertiesFromList.js'; diff --git a/src/data/composite/data/withFilteredList.js b/src/data/composite/data/withFilteredList.js index 44c1661d..15ee3373 100644 --- a/src/data/composite/data/withFilteredList.js +++ b/src/data/composite/data/withFilteredList.js @@ -2,9 +2,6 @@ // corresponding items in a list. Items which correspond to a truthy value // are kept, and the rest are excluded from the output list. // -// If the flip option is set, only items corresponding with a *falsy* value in -// the filter are kept. -// // TODO: There should be two outputs - one for the items included according to // the filter, and one for the items excluded. // @@ -22,28 +19,19 @@ export default templateCompositeFrom({ inputs: { list: input({type: 'array'}), filter: input({type: 'array'}), - - flip: input({ - type: 'boolean', - defaultValue: false, - }), }, outputs: ['#filteredList'], steps: () => [ { - dependencies: [input('list'), input('filter'), input('flip')], + dependencies: [input('list'), input('filter')], compute: (continuation, { [input('list')]: list, [input('filter')]: filter, - [input('flip')]: flip, }) => continuation({ '#filteredList': - list.filter((_item, index) => - (flip - ? !filter[index] - : filter[index])), + list.filter((_item, index) => filter[index]), }), }, ], diff --git a/src/data/composite/data/withLengthOfList.js b/src/data/composite/data/withLengthOfList.js new file mode 100644 index 00000000..7e8fd17f --- /dev/null +++ b/src/data/composite/data/withLengthOfList.js @@ -0,0 +1,56 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {getOutputName} from './helpers/property-from-helpers.js'; + +export default templateCompositeFrom({ + annotation: `withMappedList`, + + inputs: { + list: input({type: 'array'}), + }, + + outputs: ({ + [input.staticDependency('list')]: list, + }) => [ + (list + ? getOutputName({property: 'length', from: list}) + : '#length'), + ], + + steps: () => [ + { + dependencies: [input.staticDependency('list')], + compute: (continuation, { + [input.staticDependency('list')]: list, + }) => continuation({ + '#output': + (list + ? getOutputName({property: 'length', from: list}) + : '#length'), + }), + }, + + { + dependencies: [input('list')], + compute: (continuation, { + [input('list')]: list, + }) => continuation({ + ['#value']: + (list === null + ? null + : list.length), + }), + }, + + { + dependencies: ['#output', '#value'], + + compute: (continuation, { + ['#output']: output, + ['#value']: value, + }) => continuation({ + [output]: value, + }), + }, + ], +}); diff --git a/src/data/composite/data/withMappedList.js b/src/data/composite/data/withMappedList.js index 0bc63a92..cd32058e 100644 --- a/src/data/composite/data/withMappedList.js +++ b/src/data/composite/data/withMappedList.js @@ -1,12 +1,16 @@ // Applies a map function to each item in a list, just like a normal JavaScript // map. // +// Pass a filter (e.g. from withAvailabilityFilter) to process only items +// kept by the filter. Other items will be left as-is. +// // See also: // - withFilteredList // - withSortedList // import {input, templateCompositeFrom} from '#composite'; +import {stitchArrays} from '#sugar'; export default templateCompositeFrom({ annotation: `withMappedList`, @@ -14,19 +18,31 @@ export default templateCompositeFrom({ inputs: { list: input({type: 'array'}), map: input({type: 'function'}), + + filter: input({ + type: 'array', + defaultValue: null, + }), }, outputs: ['#mappedList'], steps: () => [ { - dependencies: [input('list'), input('map')], + dependencies: [input('list'), input('map'), input('filter')], compute: (continuation, { [input('list')]: list, [input('map')]: mapFn, + [input('filter')]: filter, }) => continuation({ ['#mappedList']: - list.map(mapFn), + stitchArrays({ + item: list, + keep: filter ?? Array.from(list, () => true), + }).map(({item, keep}, index) => + (keep + ? mapFn(item, index, list) + : item)), }), }, ], diff --git a/src/data/composite/data/withNearbyItemFromList.js b/src/data/composite/data/withNearbyItemFromList.js index 83a8cc21..5e165219 100644 --- a/src/data/composite/data/withNearbyItemFromList.js +++ b/src/data/composite/data/withNearbyItemFromList.js @@ -9,6 +9,10 @@ // - If the 'valuePastEdge' input is provided, that value will be output // instead of null. // +// - If the 'filter' input is provided, corresponding items will be skipped, +// and only (repeating `offset`) the next included in the filter will be +// returned. +// // Both the list and item must be provided. // // See also: @@ -16,7 +20,6 @@ // import {input, templateCompositeFrom} from '#composite'; -import {atOffset} from '#sugar'; import {raiseOutputWithoutDependency} from '#composite/control-flow'; @@ -28,9 +31,12 @@ export default templateCompositeFrom({ inputs: { list: input({acceptsNull: false, type: 'array'}), item: input({acceptsNull: false}), - offset: input({type: 'number'}), + wrap: input({type: 'boolean', defaultValue: false}), + valuePastEdge: input({defaultValue: null}), + + filter: input({defaultValue: null, type: 'array'}), }, outputs: ['#nearbyItem'], @@ -45,29 +51,55 @@ export default templateCompositeFrom({ dependency: '#index', mode: input.value('index'), - output: input.value({ - ['#nearbyItem']: - null, - }), + output: input.value({'#nearbyItem': null}), }), { dependencies: [ input('list'), input('offset'), + input('wrap'), + input('valuePastEdge'), + + input('filter'), + '#index', ], compute: (continuation, { [input('list')]: list, [input('offset')]: offset, + [input('wrap')]: wrap, + [input('valuePastEdge')]: valuePastEdge, + + [input('filter')]: filter, + ['#index']: index, - }) => continuation({ - ['#nearbyItem']: - atOffset(list, index, offset, {wrap}), - }), + }) => { + const startIndex = index; + + do { + index += offset; + + if (wrap) { + index = index % list.length; + } else if (index < 0) { + return continuation({'#nearbyItem': valuePastEdge}); + } else if (index >= list.length) { + return continuation({'#nearbyItem': valuePastEdge}); + } + + if (filter && !filter[index]) { + continue; + } + + return continuation({'#nearbyItem': list[index]}); + } while (index !== startIndex); + + return continuation({'#nearbyItem': null}); + }, }, ], }); diff --git a/src/data/composite/data/withPropertiesFromList.js b/src/data/composite/data/withPropertiesFromList.js index fb4134bc..791165b3 100644 --- a/src/data/composite/data/withPropertiesFromList.js +++ b/src/data/composite/data/withPropertiesFromList.js @@ -12,6 +12,8 @@ import {input, templateCompositeFrom} from '#composite'; import {isString, validateArrayItems} from '#validators'; +import {getOutputName} from './helpers/property-from-helpers.js'; + export default templateCompositeFrom({ annotation: `withPropertiesFromList`, @@ -32,11 +34,7 @@ export default templateCompositeFrom({ }) => (properties ? properties.map(property => - (prefix - ? `${prefix}.${property}` - : list - ? `${list}.${property}` - : `#list.${property}`)) + getOutputName({property, from: list || '#list', prefix})) : ['#lists']), steps: () => [ @@ -73,11 +71,7 @@ export default templateCompositeFrom({ ? continuation( Object.fromEntries( properties.map(property => [ - (prefix - ? `${prefix}.${property}` - : list - ? `${list}.${property}` - : `#list.${property}`), + getOutputName({property, from: list || '#list', prefix}), lists[property], ]))) : continuation({'#lists': lists})), diff --git a/src/data/composite/data/withPropertiesFromObject.js b/src/data/composite/data/withPropertiesFromObject.js index 21726b58..f600df0d 100644 --- a/src/data/composite/data/withPropertiesFromObject.js +++ b/src/data/composite/data/withPropertiesFromObject.js @@ -11,6 +11,8 @@ import {input, templateCompositeFrom} from '#composite'; import {isString, validateArrayItems} from '#validators'; +import {getOutputName} from './helpers/property-from-helpers.js'; + export default templateCompositeFrom({ annotation: `withPropertiesFromObject`, @@ -32,11 +34,7 @@ export default templateCompositeFrom({ }) => (properties ? properties.map(property => - (prefix - ? `${prefix}.${property}` - : object - ? `${object}.${property}` - : `#object.${property}`)) + getOutputName({property, from: object || '#object', prefix})) : ['#object']), steps: () => [ @@ -71,11 +69,7 @@ export default templateCompositeFrom({ ? continuation( Object.fromEntries( entries.map(([property, value]) => [ - (prefix - ? `${prefix}.${property}` - : object - ? `${object}.${property}` - : `#object.${property}`), + getOutputName({property, from: object || '#object', prefix}), value ?? null, ]))) : continuation({ diff --git a/src/data/composite/data/withPropertyFromList.js b/src/data/composite/data/withPropertyFromList.js index 65ebf77b..485dd197 100644 --- a/src/data/composite/data/withPropertyFromList.js +++ b/src/data/composite/data/withPropertyFromList.js @@ -5,19 +5,18 @@ // original list are kept null here. Objects which don't have the specified // property are retained in-place as null. // +// If the `internal` input is true, this reads the CacheableObject update value +// of each object rather than its exposed value. +// // See also: // - withPropertiesFromList // - withPropertyFromObject // +import CacheableObject from '#cacheable-object'; import {input, templateCompositeFrom} from '#composite'; -function getOutputName({list, property, prefix}) { - if (!property) return `#values`; - if (prefix) return `${prefix}.${property}`; - if (list) return `${list}.${property}`; - return `#list.${property}`; -} +import {getOutputName} from './helpers/property-from-helpers.js'; export default templateCompositeFrom({ annotation: `withPropertyFromList`, @@ -26,24 +25,41 @@ export default templateCompositeFrom({ list: input({type: 'array'}), property: input({type: 'string'}), prefix: input.staticValue({type: 'string', defaultValue: null}), + internal: input({type: 'boolean', defaultValue: false}), }, outputs: ({ [input.staticDependency('list')]: list, [input.staticValue('property')]: property, [input.staticValue('prefix')]: prefix, - }) => - [getOutputName({list, property, prefix})], + }) => [ + (property + ? getOutputName({property, from: list || '#list', prefix}) + : '#values'), + ], steps: () => [ { - dependencies: [input('list'), input('property')], + dependencies: [ + input('list'), + input('property'), + input('internal'), + ], + compute: (continuation, { [input('list')]: list, [input('property')]: property, + [input('internal')]: internal, }) => continuation({ ['#values']: - list.map(item => item[property] ?? null), + list.map(item => + (item === null + ? null + : internal + ? CacheableObject.getUpdateValue(item, property) + ?? null + : item[property] + ?? null)), }), }, @@ -60,7 +76,9 @@ export default templateCompositeFrom({ [input.staticValue('prefix')]: prefix, }) => continuation({ ['#outputName']: - getOutputName({list, property, prefix}), + (property + ? getOutputName({property, from: list || '#list', prefix}) + : '#values'), }), }, diff --git a/src/data/composite/data/withPropertyFromObject.js b/src/data/composite/data/withPropertyFromObject.js index 4f240506..7f8c4449 100644 --- a/src/data/composite/data/withPropertyFromObject.js +++ b/src/data/composite/data/withPropertyFromObject.js @@ -13,6 +13,8 @@ import CacheableObject from '#cacheable-object'; import {input, templateCompositeFrom} from '#composite'; +import {getOutputName} from './helpers/property-from-helpers.js'; + export default templateCompositeFrom({ annotation: `withPropertyFromObject`, @@ -25,12 +27,11 @@ export default templateCompositeFrom({ outputs: ({ [input.staticDependency('object')]: object, [input.staticValue('property')]: property, - }) => - (object && property - ? (object.startsWith('#') - ? [`${object}.${property}`] - : [`#${object}.${property}`]) - : ['#value']), + }) => [ + (property + ? getOutputName({property, from: object || '#object'}) + : '#value'), + ], steps: () => [ { @@ -44,10 +45,8 @@ export default templateCompositeFrom({ [input.staticValue('property')]: property, }) => continuation({ '#output': - (object && property - ? (object.startsWith('#') - ? `${object}.${property}` - : `#${object}.${property}`) + (property + ? getOutputName({property, from: object || '#object'}) : '#value'), }), }, diff --git a/src/data/composite/things/album/index.js b/src/data/composite/things/album/index.js deleted file mode 100644 index 8b5098f0..00000000 --- a/src/data/composite/things/album/index.js +++ /dev/null @@ -1 +0,0 @@ -export {default as withTracks} from './withTracks.js'; diff --git a/src/data/composite/things/album/withTracks.js b/src/data/composite/things/album/withTracks.js deleted file mode 100644 index 348220e7..00000000 --- a/src/data/composite/things/album/withTracks.js +++ /dev/null @@ -1,30 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {withFlattenedList, withPropertyFromList} from '#composite/data'; -import {withResolvedReferenceList} from '#composite/wiki-data'; - -import {raiseOutputWithoutDependency} from '#composite/control-flow'; - -export default templateCompositeFrom({ - annotation: `withTracks`, - - outputs: ['#tracks'], - - steps: () => [ - raiseOutputWithoutDependency({ - dependency: 'trackSections', - output: input.value({'#tracks': []}), - }), - - withPropertyFromList({ - list: 'trackSections', - property: input.value('tracks'), - }), - - withFlattenedList({ - list: '#trackSections.tracks', - }).outputs({ - ['#flattenedList']: '#tracks', - }), - ], -}); diff --git a/src/data/composite/things/artist/artistTotalDuration.js b/src/data/composite/things/artist/artistTotalDuration.js deleted file mode 100644 index ff709f28..00000000 --- a/src/data/composite/things/artist/artistTotalDuration.js +++ /dev/null @@ -1,70 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exposeDependency} from '#composite/control-flow'; -import {withFilteredList, withPropertyFromList} from '#composite/data'; -import {withContributionListSums, withReverseContributionList} - from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `artistTotalDuration`, - - compose: false, - - steps: () => [ - withReverseContributionList({ - data: 'trackData', - list: input.value('artistContribs'), - }).outputs({ - '#reverseContributionList': '#contributionsAsArtist', - }), - - withReverseContributionList({ - data: 'trackData', - list: input.value('contributorContribs'), - }).outputs({ - '#reverseContributionList': '#contributionsAsContributor', - }), - - { - dependencies: [ - '#contributionsAsArtist', - '#contributionsAsContributor', - ], - - compute: (continuation, { - ['#contributionsAsArtist']: artistContribs, - ['#contributionsAsContributor']: contributorContribs, - }) => continuation({ - ['#allContributions']: [ - ...artistContribs, - ...contributorContribs, - ], - }), - }, - - withPropertyFromList({ - list: '#allContributions', - property: input.value('thing'), - }), - - withPropertyFromList({ - list: '#allContributions.thing', - property: input.value('isOriginalRelease'), - }), - - withFilteredList({ - list: '#allContributions', - filter: '#allContributions.thing.isOriginalRelease', - }).outputs({ - '#filteredList': '#originalContributions', - }), - - withContributionListSums({ - list: '#originalContributions', - }), - - exposeDependency({ - dependency: '#contributionListDuration', - }), - ], -}); diff --git a/src/data/composite/things/artist/index.js b/src/data/composite/things/artist/index.js deleted file mode 100644 index 55514c71..00000000 --- a/src/data/composite/things/artist/index.js +++ /dev/null @@ -1 +0,0 @@ -export {default as artistTotalDuration} from './artistTotalDuration.js'; diff --git a/src/data/composite/things/artwork/index.js b/src/data/composite/things/artwork/index.js new file mode 100644 index 00000000..2cd3c388 --- /dev/null +++ b/src/data/composite/things/artwork/index.js @@ -0,0 +1 @@ +export {default as withContainingArtworkList} from './withContainingArtworkList.js'; diff --git a/src/data/composite/things/artwork/withContainingArtworkList.js b/src/data/composite/things/artwork/withContainingArtworkList.js new file mode 100644 index 00000000..9c928ffd --- /dev/null +++ b/src/data/composite/things/artwork/withContainingArtworkList.js @@ -0,0 +1,46 @@ +// Gets the list of artworks which contains this one, which is functionally +// equivalent to `this.thing[this.thingProperty]`. If the exposed value is not +// a list at all (i.e. the property holds a single artwork), this composition +// outputs null. + +import {input, templateCompositeFrom} from '#composite'; + +import {raiseOutputWithoutDependency} from '#composite/control-flow'; +import {withPropertyFromObject} from '#composite/data'; + +export default templateCompositeFrom({ + annotation: `withContainingArtworkList`, + + outputs: ['#containingArtworkList'], + + steps: () => [ + raiseOutputWithoutDependency({ + dependency: 'thing', + output: input.value({'#containingArtworkList': null}), + }), + + raiseOutputWithoutDependency({ + dependency: 'thingProperty', + output: input.value({'#containingArtworkList': null}), + }), + + withPropertyFromObject({ + object: 'thing', + property: 'thingProperty', + }).outputs({ + '#value': '#containingValue', + }), + + { + dependencies: ['#containingValue'], + compute: (continuation, { + ['#containingValue']: containingValue, + }) => continuation({ + ['#containingArtworkList']: + (Array.isArray(containingValue) + ? containingValue + : null), + }), + }, + ], +}); diff --git a/src/data/composite/things/content/hasAnnotationPart.js b/src/data/composite/things/content/hasAnnotationPart.js new file mode 100644 index 00000000..93aaf5e5 --- /dev/null +++ b/src/data/composite/things/content/hasAnnotationPart.js @@ -0,0 +1,25 @@ +import {input, templateCompositeFrom} from '#composite'; + +export default templateCompositeFrom({ + annotation: `hasAnnotationPart`, + + compose: false, + + inputs: { + part: input({type: 'string'}), + }, + + steps: () => [ + { + dependencies: [input('part'), 'annotationParts'], + + compute: ({ + [input('part')]: search, + ['annotationParts']: parts, + }) => + parts.some(part => + part.toLowerCase() === + search.toLowerCase()), + }, + ], +}); diff --git a/src/data/composite/things/content/index.js b/src/data/composite/things/content/index.js new file mode 100644 index 00000000..27bf7c53 --- /dev/null +++ b/src/data/composite/things/content/index.js @@ -0,0 +1,4 @@ +export {default as hasAnnotationPart} from './hasAnnotationPart.js'; +export {default as withAnnotationPartNodeLists} from './withAnnotationPartNodeLists.js'; +export {default as withExpressedOrImplicitArtistReferences} from './withExpressedOrImplicitArtistReferences.js'; +export {default as withWebArchiveDate} from './withWebArchiveDate.js'; diff --git a/src/data/composite/things/content/withAnnotationPartNodeLists.js b/src/data/composite/things/content/withAnnotationPartNodeLists.js new file mode 100644 index 00000000..fc304594 --- /dev/null +++ b/src/data/composite/things/content/withAnnotationPartNodeLists.js @@ -0,0 +1,28 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {raiseOutputWithoutDependency} from '#composite/control-flow'; +import {splitContentNodesAround, withContentNodes} from '#composite/wiki-data'; + +export default templateCompositeFrom({ + annotation: `withAnnotationPartNodeLists`, + + outputs: ['#annotationPartNodeLists'], + + steps: () => [ + raiseOutputWithoutDependency({ + dependency: 'annotation', + output: input.value({'#annotationPartNodeLists': []}), + }), + + withContentNodes({ + from: 'annotation', + }), + + splitContentNodesAround({ + nodes: '#contentNodes', + around: input.value(/, */g), + }).outputs({ + '#contentNodeLists': '#annotationPartNodeLists', + }), + ], +}); diff --git a/src/data/composite/things/content/withExpressedOrImplicitArtistReferences.js b/src/data/composite/things/content/withExpressedOrImplicitArtistReferences.js new file mode 100644 index 00000000..69da8c75 --- /dev/null +++ b/src/data/composite/things/content/withExpressedOrImplicitArtistReferences.js @@ -0,0 +1,61 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {raiseOutputWithoutDependency} from '#composite/control-flow'; +import {withFilteredList, withMappedList} from '#composite/data'; +import {withContentNodes} from '#composite/wiki-data'; + +export default templateCompositeFrom({ + annotation: `withExpressedOrImplicitArtistReferences`, + + inputs: { + from: input({type: 'array', acceptsNull: true}), + }, + + outputs: ['#artistReferences'], + + steps: () => [ + { + dependencies: [input('from')], + compute: (continuation, { + [input('from')]: expressedArtistReferences, + }) => + (expressedArtistReferences + ? continuation.raiseOutput({'#artistReferences': expressedArtistReferences}) + : continuation()), + }, + + raiseOutputWithoutDependency({ + dependency: 'artistText', + output: input.value({'#artistReferences': null}), + }), + + withContentNodes({ + from: 'artistText', + }), + + withMappedList({ + list: '#contentNodes', + map: input.value(node => + node.type === 'tag' && + node.data.replacerKey?.data === 'artist'), + }).outputs({ + '#mappedList': '#artistTagFilter', + }), + + withFilteredList({ + list: '#contentNodes', + filter: '#artistTagFilter', + }).outputs({ + '#filteredList': '#artistTags', + }), + + withMappedList({ + list: '#artistTags', + map: input.value(node => + 'artist:' + + node.data.replacerValue[0].data), + }).outputs({ + '#mappedList': '#artistReferences', + }), + ], +}); diff --git a/src/data/composite/things/content/withWebArchiveDate.js b/src/data/composite/things/content/withWebArchiveDate.js new file mode 100644 index 00000000..3aaa4f64 --- /dev/null +++ b/src/data/composite/things/content/withWebArchiveDate.js @@ -0,0 +1,41 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {raiseOutputWithoutDependency} from '#composite/control-flow'; + +export default templateCompositeFrom({ + annotation: `withWebArchiveDate`, + + outputs: ['#webArchiveDate'], + + steps: () => [ + { + dependencies: ['annotation'], + + compute: (continuation, {annotation}) => + continuation({ + ['#dateText']: + annotation + ?.match(/https?:\/\/web.archive.org\/web\/([0-9]{8,8})[0-9]*\//) + ?.[1] ?? + null, + }), + }, + + raiseOutputWithoutDependency({ + dependency: '#dateText', + output: input.value({['#webArchiveDate']: null}), + }), + + { + dependencies: ['#dateText'], + compute: (continuation, {['#dateText']: dateText}) => + continuation({ + ['#webArchiveDate']: + new Date( + dateText.slice(0, 4) + '/' + + dateText.slice(4, 6) + '/' + + dateText.slice(6, 8)), + }), + }, + ], +}); diff --git a/src/data/composite/things/contribution/index.js b/src/data/composite/things/contribution/index.js index 9b22be2e..2bbf994d 100644 --- a/src/data/composite/things/contribution/index.js +++ b/src/data/composite/things/contribution/index.js @@ -1,7 +1,3 @@ export {default as inheritFromContributionPresets} from './inheritFromContributionPresets.js'; -export {default as thingPropertyMatches} from './thingPropertyMatches.js'; -export {default as thingReferenceTypeMatches} from './thingReferenceTypeMatches.js'; export {default as withContainingReverseContributionList} from './withContainingReverseContributionList.js'; -export {default as withContributionArtist} from './withContributionArtist.js'; export {default as withContributionContext} from './withContributionContext.js'; -export {default as withMatchingContributionPresets} from './withMatchingContributionPresets.js'; diff --git a/src/data/composite/things/contribution/inheritFromContributionPresets.js b/src/data/composite/things/contribution/inheritFromContributionPresets.js index 82425b9c..17387404 100644 --- a/src/data/composite/things/contribution/inheritFromContributionPresets.js +++ b/src/data/composite/things/contribution/inheritFromContributionPresets.js @@ -1,31 +1,20 @@ import {input, templateCompositeFrom} from '#composite'; import {raiseOutputWithoutDependency} from '#composite/control-flow'; -import {withPropertyFromList, withPropertyFromObject} from '#composite/data'; - -import withMatchingContributionPresets - from './withMatchingContributionPresets.js'; +import {withPropertyFromList} from '#composite/data'; export default templateCompositeFrom({ annotation: `inheritFromContributionPresets`, - inputs: { - property: input({type: 'string'}), - }, - steps: () => [ - withMatchingContributionPresets().outputs({ - '#matchingContributionPresets': '#presets', - }), - raiseOutputWithoutDependency({ - dependency: '#presets', + dependency: 'matchingPresets', mode: input.value('empty'), }), withPropertyFromList({ - list: '#presets', - property: input('property'), + list: 'matchingPresets', + property: input.thisProperty(), }), { diff --git a/src/data/composite/things/contribution/thingPropertyMatches.js b/src/data/composite/things/contribution/thingPropertyMatches.js deleted file mode 100644 index 4a37f2cf..00000000 --- a/src/data/composite/things/contribution/thingPropertyMatches.js +++ /dev/null @@ -1,33 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exitWithoutDependency} from '#composite/control-flow'; - -export default templateCompositeFrom({ - annotation: `thingPropertyMatches`, - - compose: false, - - inputs: { - value: input({type: 'string'}), - }, - - steps: () => [ - exitWithoutDependency({ - dependency: 'thingProperty', - value: input.value(false), - }), - - { - dependencies: [ - 'thingProperty', - input('value'), - ], - - compute: ({ - ['thingProperty']: thingProperty, - [input('value')]: value, - }) => - thingProperty === value, - }, - ], -}); diff --git a/src/data/composite/things/contribution/thingReferenceTypeMatches.js b/src/data/composite/things/contribution/thingReferenceTypeMatches.js deleted file mode 100644 index 2ee811af..00000000 --- a/src/data/composite/things/contribution/thingReferenceTypeMatches.js +++ /dev/null @@ -1,39 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exitWithoutDependency} from '#composite/control-flow'; -import {withPropertyFromObject} from '#composite/data'; - -export default templateCompositeFrom({ - annotation: `thingReferenceTypeMatches`, - - compose: false, - - inputs: { - value: input({type: 'string'}), - }, - - steps: () => [ - exitWithoutDependency({ - dependency: 'thing', - value: input.value(false), - }), - - withPropertyFromObject({ - object: 'thing', - property: input.value('constructor'), - }), - - { - dependencies: [ - '#thing.constructor', - input('value'), - ], - - compute: ({ - ['#thing.constructor']: constructor, - [input('value')]: value, - }) => - constructor[Symbol.for('Thing.referenceType')] === value, - }, - ], -}); diff --git a/src/data/composite/things/contribution/withContainingReverseContributionList.js b/src/data/composite/things/contribution/withContainingReverseContributionList.js index 56704c8b..a9ba31c9 100644 --- a/src/data/composite/things/contribution/withContainingReverseContributionList.js +++ b/src/data/composite/things/contribution/withContainingReverseContributionList.js @@ -1,18 +1,20 @@ -// Get the artist's contribution list containing this property. +// Get the artist's contribution list containing this property. Although that +// list literally includes both dated and dateless contributions, here, if the +// current contribution is dateless, the list is filtered to only include +// dateless contributions from the same immediately nearby context. import {input, templateCompositeFrom} from '#composite'; -import {raiseOutputWithoutDependency} from '#composite/control-flow'; +import {raiseOutputWithoutDependency, withResultOfAvailabilityCheck} + from '#composite/control-flow'; import {withPropertyFromObject} from '#composite/data'; -import withContributionArtist from './withContributionArtist.js'; - export default templateCompositeFrom({ annotation: `withContainingReverseContributionList`, inputs: { artistProperty: input({ - defaultDependency: 'artistProperty', + defaultDependency: '_artistProperty', acceptsNull: true, }), }, @@ -28,13 +30,47 @@ export default templateCompositeFrom({ }), }), - withContributionArtist(), - withPropertyFromObject({ - object: '#artist', + object: 'artist', property: input('artistProperty'), }).outputs({ - ['#value']: '#containingReverseContributionList', + ['#value']: '#list', + }), + + withResultOfAvailabilityCheck({ + from: 'date', + }).outputs({ + ['#availability']: '#hasDate', }), + + { + dependencies: ['#hasDate', '#list'], + compute: (continuation, { + ['#hasDate']: hasDate, + ['#list']: list, + }) => + (hasDate + ? continuation.raiseOutput({ + ['#containingReverseContributionList']: + list.filter(contrib => contrib.date), + }) + : continuation({ + ['#list']: + list.filter(contrib => !contrib.date), + })), + }, + + { + dependencies: ['#list', 'thing'], + compute: (continuation, { + ['#list']: list, + ['thing']: thing, + }) => continuation({ + ['#containingReverseContributionList']: + (thing.album + ? list.filter(contrib => contrib.thing.album === thing.album) + : list), + }), + }, ], }); diff --git a/src/data/composite/things/contribution/withContributionArtist.js b/src/data/composite/things/contribution/withContributionArtist.js deleted file mode 100644 index 5a611c1a..00000000 --- a/src/data/composite/things/contribution/withContributionArtist.js +++ /dev/null @@ -1,34 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; -import find from '#find'; - -import {withPropertyFromObject} from '#composite/data'; -import {withResolvedReference} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withContributionArtist`, - - inputs: { - ref: input({ - type: 'string', - defaultDependency: 'artist', - }), - }, - - outputs: ['#artist'], - - steps: () => [ - withPropertyFromObject({ - object: 'thing', - property: input.value('artistData'), - internal: input.value(true), - }), - - withResolvedReference({ - ref: input('ref'), - data: '#thing.artistData', - find: input.value(find.artist), - }).outputs({ - '#resolvedReference': '#artist', - }), - ], -}); diff --git a/src/data/composite/things/contribution/withMatchingContributionPresets.js b/src/data/composite/things/contribution/withMatchingContributionPresets.js deleted file mode 100644 index 09454164..00000000 --- a/src/data/composite/things/contribution/withMatchingContributionPresets.js +++ /dev/null @@ -1,70 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {raiseOutputWithoutDependency} from '#composite/control-flow'; -import {withPropertyFromObject} from '#composite/data'; - -import withContributionContext from './withContributionContext.js'; - -export default templateCompositeFrom({ - annotation: `withMatchingContributionPresets`, - - outputs: ['#matchingContributionPresets'], - - steps: () => [ - withPropertyFromObject({ - object: 'thing', - property: input.value('wikiInfo'), - internal: input.value(true), - }), - - raiseOutputWithoutDependency({ - dependency: '#thing.wikiInfo', - output: input.value({ - '#matchingContributionPresets': null, - }), - }), - - withPropertyFromObject({ - object: '#thing.wikiInfo', - property: input.value('contributionPresets'), - }).outputs({ - '#thing.wikiInfo.contributionPresets': '#contributionPresets', - }), - - raiseOutputWithoutDependency({ - dependency: '#contributionPresets', - mode: input.value('empty'), - output: input.value({ - '#matchingContributionPresets': [], - }), - }), - - withContributionContext(), - - { - dependencies: [ - '#contributionPresets', - '#contributionTarget', - '#contributionProperty', - 'annotation', - ], - - compute: (continuation, { - ['#contributionPresets']: presets, - ['#contributionTarget']: target, - ['#contributionProperty']: property, - ['annotation']: annotation, - }) => continuation({ - ['#matchingContributionPresets']: - presets - .filter(preset => - preset.context[0] === target && - preset.context.slice(1).includes(property) && - // For now, only match if the annotation is a complete match. - // Partial matches (e.g. because the contribution includes "two" - // annotations, separated by commas) don't count. - preset.annotation === annotation), - }) - }, - ], -}); diff --git a/src/data/composite/things/flash-act/index.js b/src/data/composite/things/flash-act/index.js deleted file mode 100644 index 40fecd2f..00000000 --- a/src/data/composite/things/flash-act/index.js +++ /dev/null @@ -1 +0,0 @@ -export {default as withFlashSide} from './withFlashSide.js'; diff --git a/src/data/composite/things/flash-act/withFlashSide.js b/src/data/composite/things/flash-act/withFlashSide.js deleted file mode 100644 index 64daa1fb..00000000 --- a/src/data/composite/things/flash-act/withFlashSide.js +++ /dev/null @@ -1,22 +0,0 @@ -// Gets the flash act's side. This will early exit if flashSideData is missing. -// If there's no side whose list of flash acts includes this act, the output -// dependency will be null. - -import {input, templateCompositeFrom} from '#composite'; - -import {withUniqueReferencingThing} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withFlashSide`, - - outputs: ['#flashSide'], - - steps: () => [ - withUniqueReferencingThing({ - data: 'flashSideData', - list: input.value('acts'), - }).outputs({ - ['#uniqueReferencingThing']: '#flashSide', - }), - ], -}); diff --git a/src/data/composite/things/flash/index.js b/src/data/composite/things/flash/index.js deleted file mode 100644 index 63ac13da..00000000 --- a/src/data/composite/things/flash/index.js +++ /dev/null @@ -1 +0,0 @@ -export {default as withFlashAct} from './withFlashAct.js'; diff --git a/src/data/composite/things/flash/withFlashAct.js b/src/data/composite/things/flash/withFlashAct.js deleted file mode 100644 index 652b8bfb..00000000 --- a/src/data/composite/things/flash/withFlashAct.js +++ /dev/null @@ -1,22 +0,0 @@ -// Gets the flash's act. This will early exit if flashActData is missing. -// If there's no flash whose list of flashes includes this flash, the output -// dependency will be null. - -import {input, templateCompositeFrom} from '#composite'; - -import {withUniqueReferencingThing} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withFlashAct`, - - outputs: ['#flashAct'], - - steps: () => [ - withUniqueReferencingThing({ - data: 'flashActData', - list: input.value('flashes'), - }).outputs({ - ['#uniqueReferencingThing']: '#flashAct', - }), - ], -}); diff --git a/src/data/composite/things/track-section/index.js b/src/data/composite/things/track-section/index.js deleted file mode 100644 index 3202ed49..00000000 --- a/src/data/composite/things/track-section/index.js +++ /dev/null @@ -1 +0,0 @@ -export {default as withAlbum} from './withAlbum.js'; diff --git a/src/data/composite/things/track-section/withAlbum.js b/src/data/composite/things/track-section/withAlbum.js deleted file mode 100644 index a4dfff0d..00000000 --- a/src/data/composite/things/track-section/withAlbum.js +++ /dev/null @@ -1,20 +0,0 @@ -// Gets the track section's album. - -import {input, templateCompositeFrom} from '#composite'; - -import {withUniqueReferencingThing} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withAlbum`, - - outputs: ['#album'], - - steps: () => [ - withUniqueReferencingThing({ - data: 'albumData', - list: input.value('trackSections'), - }).outputs({ - ['#uniqueReferencingThing']: '#album', - }), - ], -}); diff --git a/src/data/composite/things/track/exitWithoutUniqueCoverArt.js b/src/data/composite/things/track/exitWithoutUniqueCoverArt.js deleted file mode 100644 index f47086d9..00000000 --- a/src/data/composite/things/track/exitWithoutUniqueCoverArt.js +++ /dev/null @@ -1,26 +0,0 @@ -// Shorthand for checking if the track has unique cover art and exposing a -// fallback value if it isn't. - -import {input, templateCompositeFrom} from '#composite'; - -import {exitWithoutDependency} from '#composite/control-flow'; - -import withHasUniqueCoverArt from './withHasUniqueCoverArt.js'; - -export default templateCompositeFrom({ - annotation: `exitWithoutUniqueCoverArt`, - - inputs: { - value: input({defaultValue: null}), - }, - - steps: () => [ - withHasUniqueCoverArt(), - - exitWithoutDependency({ - dependency: '#hasUniqueCoverArt', - mode: input.value('falsy'), - value: input('value'), - }), - ], -}); diff --git a/src/data/composite/things/track/index.js b/src/data/composite/things/track/index.js index 05ccaaba..c200df19 100644 --- a/src/data/composite/things/track/index.js +++ b/src/data/composite/things/track/index.js @@ -1,16 +1,2 @@ -export {default as exitWithoutUniqueCoverArt} from './exitWithoutUniqueCoverArt.js'; -export {default as inheritContributionListFromOriginalRelease} from './inheritContributionListFromOriginalRelease.js'; -export {default as inheritFromOriginalRelease} from './inheritFromOriginalRelease.js'; -export {default as trackReverseReferenceList} from './trackReverseReferenceList.js'; -export {default as withAlbum} from './withAlbum.js'; -export {default as withAlwaysReferenceByDirectory} from './withAlwaysReferenceByDirectory.js'; -export {default as withContainingTrackSection} from './withContainingTrackSection.js'; -export {default as withDate} from './withDate.js'; -export {default as withDirectorySuffix} from './withDirectorySuffix.js'; -export {default as withHasUniqueCoverArt} from './withHasUniqueCoverArt.js'; -export {default as withOriginalRelease} from './withOriginalRelease.js'; -export {default as withOtherReleases} from './withOtherReleases.js'; -export {default as withPropertyFromAlbum} from './withPropertyFromAlbum.js'; -export {default as withPropertyFromOriginalRelease} from './withPropertyFromOriginalRelease.js'; -export {default as withSuffixDirectoryFromAlbum} from './withSuffixDirectoryFromAlbum.js'; -export {default as withTrackArtDate} from './withTrackArtDate.js'; +export {default as inheritContributionListFromMainRelease} from './inheritContributionListFromMainRelease.js'; +export {default as inheritFromMainRelease} from './inheritFromMainRelease.js'; diff --git a/src/data/composite/things/track/inheritContributionListFromOriginalRelease.js b/src/data/composite/things/track/inheritContributionListFromMainRelease.js index f4ae3ddb..8db50060 100644 --- a/src/data/composite/things/track/inheritContributionListFromOriginalRelease.js +++ b/src/data/composite/things/track/inheritContributionListFromMainRelease.js @@ -1,44 +1,41 @@ -// Like inheritFromOriginalRelease, but tuned for contributions. -// Recontextualized contributions for this track. +// Like inheritFromMainRelease, but tuned for contributions. +// Recontextualizes contributions for this track. import {input, templateCompositeFrom} from '#composite'; import {exposeDependency, raiseOutputWithoutDependency} from '#composite/control-flow'; +import {withPropertyFromObject} from '#composite/data'; import {withRecontextualizedContributionList, withRedatedContributionList} from '#composite/wiki-data'; -import withDate from './withDate.js'; -import withPropertyFromOriginalRelease - from './withPropertyFromOriginalRelease.js'; - export default templateCompositeFrom({ - annotation: `inheritContributionListFromOriginalRelease`, + annotation: `inheritContributionListFromMainRelease`, steps: () => [ - withPropertyFromOriginalRelease({ - property: input.thisProperty(), - notFoundValue: input.value([]), - }), - raiseOutputWithoutDependency({ - dependency: '#isRerelease', + dependency: 'isSecondaryRelease', mode: input.value('falsy'), }), - withRecontextualizedContributionList({ - list: '#originalValue', + withPropertyFromObject({ + object: 'mainReleaseTrack', + property: input.thisProperty(), + }).outputs({ + '#value': '#contributions', }), - withDate(), + withRecontextualizedContributionList({ + list: '#contributions', + }), withRedatedContributionList({ - list: '#originalValue', - date: '#date', + list: '#contributions', + date: 'date', }), exposeDependency({ - dependency: '#originalValue', + dependency: '#contributions', }), ], }); diff --git a/src/data/composite/things/track/inheritFromMainRelease.js b/src/data/composite/things/track/inheritFromMainRelease.js new file mode 100644 index 00000000..ca532bc7 --- /dev/null +++ b/src/data/composite/things/track/inheritFromMainRelease.js @@ -0,0 +1,29 @@ +// Early exits with the value for the same property as specified on the +// main release, if this track is a secondary release, and otherwise continues +// without providing any further dependencies. + +import {input, templateCompositeFrom} from '#composite'; + +import {exposeDependency, raiseOutputWithoutDependency} + from '#composite/control-flow'; +import {withPropertyFromObject} from '#composite/data'; + +export default templateCompositeFrom({ + annotation: `inheritFromMainRelease`, + + steps: () => [ + raiseOutputWithoutDependency({ + dependency: 'isSecondaryRelease', + mode: input.value('falsy'), + }), + + withPropertyFromObject({ + object: 'mainReleaseTrack', + property: input.thisProperty(), + }), + + exposeDependency({ + dependency: '#value', + }), + ], +}); diff --git a/src/data/composite/things/track/inheritFromOriginalRelease.js b/src/data/composite/things/track/inheritFromOriginalRelease.js deleted file mode 100644 index 38ab06be..00000000 --- a/src/data/composite/things/track/inheritFromOriginalRelease.js +++ /dev/null @@ -1,41 +0,0 @@ -// Early exits with the value for the same property as specified on the -// original release, if this track is a rerelease, and otherwise continues -// without providing any further dependencies. -// -// Like withOriginalRelease, this will early exit (with notFoundValue) if the -// original release is specified by reference and that reference doesn't -// resolve to anything. - -import {input, templateCompositeFrom} from '#composite'; - -import {exposeDependency, raiseOutputWithoutDependency} - from '#composite/control-flow'; - -import withPropertyFromOriginalRelease - from './withPropertyFromOriginalRelease.js'; - -export default templateCompositeFrom({ - annotation: `inheritFromOriginalRelease`, - - inputs: { - notFoundValue: input({ - defaultValue: null, - }), - }, - - steps: () => [ - withPropertyFromOriginalRelease({ - property: input.thisProperty(), - notFoundValue: input('notFoundValue'), - }), - - raiseOutputWithoutDependency({ - dependency: '#isRerelease', - mode: input.value('falsy'), - }), - - exposeDependency({ - dependency: '#originalValue', - }), - ], -}); diff --git a/src/data/composite/things/track/trackAdditionalNameList.js b/src/data/composite/things/track/trackAdditionalNameList.js deleted file mode 100644 index 65a2263d..00000000 --- a/src/data/composite/things/track/trackAdditionalNameList.js +++ /dev/null @@ -1,38 +0,0 @@ -// Compiles additional names from various sources. - -import {input, templateCompositeFrom} from '#composite'; -import {isAdditionalNameList} from '#validators'; - -import withInferredAdditionalNames from './withInferredAdditionalNames.js'; -import withSharedAdditionalNames from './withSharedAdditionalNames.js'; - -export default templateCompositeFrom({ - annotation: `trackAdditionalNameList`, - - compose: false, - - update: {validate: isAdditionalNameList}, - - steps: () => [ - withInferredAdditionalNames(), - withSharedAdditionalNames(), - - { - dependencies: [ - '#inferredAdditionalNames', - '#sharedAdditionalNames', - input.updateValue(), - ], - - compute: ({ - ['#inferredAdditionalNames']: inferredAdditionalNames, - ['#sharedAdditionalNames']: sharedAdditionalNames, - [input.updateValue()]: providedAdditionalNames, - }) => [ - ...providedAdditionalNames ?? [], - ...sharedAdditionalNames, - ...inferredAdditionalNames, - ], - }, - ], -}); diff --git a/src/data/composite/things/track/trackReverseReferenceList.js b/src/data/composite/things/track/trackReverseReferenceList.js deleted file mode 100644 index 44940ae7..00000000 --- a/src/data/composite/things/track/trackReverseReferenceList.js +++ /dev/null @@ -1,38 +0,0 @@ -// Like a normal reverse reference list ("objects which reference this object -// under a specified property"), only excluding rereleases from the possible -// outputs. While it's useful to travel from a rerelease to the tracks it -// references, rereleases aren't generally relevant from the perspective of -// the tracks *being* referenced. Apart from hiding rereleases from lists on -// the site, it also excludes keeps them from relational data processing, such -// as on the "Tracks - by Times Referenced" listing page. - -import {input, templateCompositeFrom} from '#composite'; -import {withReverseReferenceList} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `trackReverseReferenceList`, - - compose: false, - - inputs: { - list: input({type: 'string'}), - }, - - steps: () => [ - withReverseReferenceList({ - data: 'trackData', - list: input('list'), - }), - - { - flags: {expose: true}, - expose: { - dependencies: ['#reverseReferenceList'], - compute: ({ - ['#reverseReferenceList']: reverseReferenceList, - }) => - reverseReferenceList.filter(track => !track.originalReleaseTrack), - }, - }, - ], -}); diff --git a/src/data/composite/things/track/withAlbum.js b/src/data/composite/things/track/withAlbum.js deleted file mode 100644 index 03b840d4..00000000 --- a/src/data/composite/things/track/withAlbum.js +++ /dev/null @@ -1,22 +0,0 @@ -// Gets the track's album. This will early exit if albumData is missing. -// If there's no album whose list of tracks includes this track, the output -// dependency will be null. - -import {input, templateCompositeFrom} from '#composite'; - -import {withUniqueReferencingThing} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withAlbum`, - - outputs: ['#album'], - - steps: () => [ - withUniqueReferencingThing({ - data: 'albumData', - list: input.value('tracks'), - }).outputs({ - ['#uniqueReferencingThing']: '#album', - }), - ], -}); diff --git a/src/data/composite/things/track/withAlwaysReferenceByDirectory.js b/src/data/composite/things/track/withAlwaysReferenceByDirectory.js deleted file mode 100644 index e01720b4..00000000 --- a/src/data/composite/things/track/withAlwaysReferenceByDirectory.js +++ /dev/null @@ -1,105 +0,0 @@ -// Controls how find.track works - it'll never be matched by a reference -// just to the track's name, which means you don't have to always reference -// some *other* (much more commonly referenced) track by directory instead -// of more naturally by name. - -import {input, templateCompositeFrom} from '#composite'; -import find from '#find'; -import {isBoolean} from '#validators'; - -import {withPropertyFromObject} from '#composite/data'; -import {withResolvedReference} from '#composite/wiki-data'; - -import { - exitWithoutDependency, - exposeDependencyOrContinue, - exposeUpdateValueOrContinue, -} from '#composite/control-flow'; - -export default templateCompositeFrom({ - annotation: `withAlwaysReferenceByDirectory`, - - outputs: ['#alwaysReferenceByDirectory'], - - steps: () => [ - exposeUpdateValueOrContinue({ - validate: input.value(isBoolean), - }), - - // withAlwaysReferenceByDirectory is sort of a fragile area - we can't - // find the track's album the normal way because albums' track lists - // recurse back into alwaysReferenceByDirectory! - withResolvedReference({ - ref: 'dataSourceAlbum', - data: 'albumData', - find: input.value(find.album), - }).outputs({ - '#resolvedReference': '#album', - }), - - withPropertyFromObject({ - object: '#album', - property: input.value('alwaysReferenceTracksByDirectory'), - }), - - // Falsy mode means this exposes true if the album's property is true, - // but continues if the property is false (which is also the default). - exposeDependencyOrContinue({ - dependency: '#album.alwaysReferenceTracksByDirectory', - mode: input.value('falsy'), - }), - - // Remaining code is for defaulting to true if this track is a rerelease of - // another with the same name, so everything further depends on access to - // trackData as well as originalReleaseTrack. - - exitWithoutDependency({ - dependency: 'trackData', - mode: input.value('empty'), - value: input.value(false), - }), - - exitWithoutDependency({ - dependency: 'originalReleaseTrack', - value: input.value(false), - }), - - // It's necessary to use the custom trackOriginalReleasesOnly find function - // here, so as to avoid recursion issues - the find.track() function depends - // on accessing each track's alwaysReferenceByDirectory, which means it'll - // hit *this track* - and thus this step - and end up recursing infinitely. - // By definition, find.trackOriginalReleasesOnly excludes tracks which have - // an originalReleaseTrack update value set, which means even though it does - // still access each of tracks' `alwaysReferenceByDirectory` property, it - // won't access that of *this* track - it will never proceed past the - // `exitWithoutDependency` step directly above, so there's no opportunity - // for recursion. - withResolvedReference({ - ref: 'originalReleaseTrack', - data: 'trackData', - find: input.value(find.trackOriginalReleasesOnly), - }).outputs({ - '#resolvedReference': '#originalRelease', - }), - - exitWithoutDependency({ - dependency: '#originalRelease', - value: input.value(false), - }), - - withPropertyFromObject({ - object: '#originalRelease', - property: input.value('name'), - }), - - { - dependencies: ['name', '#originalRelease.name'], - compute: (continuation, { - name, - ['#originalRelease.name']: originalName, - }) => continuation({ - ['#alwaysReferenceByDirectory']: name === originalName, - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withContainingTrackSection.js b/src/data/composite/things/track/withContainingTrackSection.js deleted file mode 100644 index 9bbd9bd5..00000000 --- a/src/data/composite/things/track/withContainingTrackSection.js +++ /dev/null @@ -1,20 +0,0 @@ -// Gets the track section containing this track from its album's track list. - -import {input, templateCompositeFrom} from '#composite'; - -import {withUniqueReferencingThing} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withContainingTrackSection`, - - outputs: ['#trackSection'], - - steps: () => [ - withUniqueReferencingThing({ - data: 'trackSectionData', - list: input.value('tracks'), - }).outputs({ - ['#uniqueReferencingThing']: '#trackSection', - }), - ], -}); diff --git a/src/data/composite/things/track/withDate.js b/src/data/composite/things/track/withDate.js deleted file mode 100644 index b5a770e9..00000000 --- a/src/data/composite/things/track/withDate.js +++ /dev/null @@ -1,34 +0,0 @@ -// Gets the track's own date. This is either its dateFirstReleased property -// or, if unset, the album's date. - -import {input, templateCompositeFrom} from '#composite'; - -import withPropertyFromAlbum from './withPropertyFromAlbum.js'; - -export default templateCompositeFrom({ - annotation: `withDate`, - - outputs: ['#date'], - - steps: () => [ - { - dependencies: ['dateFirstReleased'], - compute: (continuation, {dateFirstReleased}) => - (dateFirstReleased - ? continuation.raiseOutput({'#date': dateFirstReleased}) - : continuation()), - }, - - withPropertyFromAlbum({ - property: input.value('date'), - }), - - { - dependencies: ['#album.date'], - compute: (continuation, {['#album.date']: albumDate}) => - (albumDate - ? continuation.raiseOutput({'#date': albumDate}) - : continuation.raiseOutput({'#date': null})), - }, - ], -}) diff --git a/src/data/composite/things/track/withDirectorySuffix.js b/src/data/composite/things/track/withDirectorySuffix.js deleted file mode 100644 index c063e158..00000000 --- a/src/data/composite/things/track/withDirectorySuffix.js +++ /dev/null @@ -1,36 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {raiseOutputWithoutDependency} from '#composite/control-flow'; - -import withPropertyFromAlbum from './withPropertyFromAlbum.js'; -import withSuffixDirectoryFromAlbum from './withSuffixDirectoryFromAlbum.js'; - -export default templateCompositeFrom({ - annotation: `withDirectorySuffix`, - - outputs: ['#directorySuffix'], - - steps: () => [ - withSuffixDirectoryFromAlbum(), - - raiseOutputWithoutDependency({ - dependency: '#suffixDirectoryFromAlbum', - mode: input.value('falsy'), - output: input.value({['#directorySuffix']: null}), - }), - - withPropertyFromAlbum({ - property: input.value('directorySuffix'), - }), - - { - dependencies: ['#album.directorySuffix'], - compute: (continuation, { - ['#album.directorySuffix']: directorySuffix, - }) => continuation({ - ['#directorySuffix']: - directorySuffix, - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withHasUniqueCoverArt.js b/src/data/composite/things/track/withHasUniqueCoverArt.js deleted file mode 100644 index f7e65f25..00000000 --- a/src/data/composite/things/track/withHasUniqueCoverArt.js +++ /dev/null @@ -1,64 +0,0 @@ -// Whether or not the track has "unique" cover artwork - a cover which is -// specifically associated with this track in particular, rather than with -// the track's album as a whole. This is typically used to select between -// displaying the track artwork and a fallback, such as the album artwork -// or a placeholder. (This property is named hasUniqueCoverArt instead of -// the usual hasCoverArt to emphasize that it does not inherit from the -// album.) - -import {input, templateCompositeFrom} from '#composite'; -import {empty} from '#sugar'; - -import {withResolvedContribs} from '#composite/wiki-data'; - -import withPropertyFromAlbum from './withPropertyFromAlbum.js'; - -export default templateCompositeFrom({ - annotation: 'withHasUniqueCoverArt', - - outputs: ['#hasUniqueCoverArt'], - - steps: () => [ - { - dependencies: ['disableUniqueCoverArt'], - compute: (continuation, {disableUniqueCoverArt}) => - (disableUniqueCoverArt - ? continuation.raiseOutput({ - ['#hasUniqueCoverArt']: false, - }) - : continuation()), - }, - - withResolvedContribs({ - from: 'coverArtistContribs', - date: input.value(null), - }), - - { - dependencies: ['#resolvedContribs'], - compute: (continuation, { - ['#resolvedContribs']: contribsFromTrack, - }) => - (empty(contribsFromTrack) - ? continuation() - : continuation.raiseOutput({ - ['#hasUniqueCoverArt']: true, - })), - }, - - withPropertyFromAlbum({ - property: input.value('trackCoverArtistContribs'), - }), - - { - dependencies: ['#album.trackCoverArtistContribs'], - compute: (continuation, { - ['#album.trackCoverArtistContribs']: contribsFromAlbum, - }) => - continuation.raiseOutput({ - ['#hasUniqueCoverArt']: - !empty(contribsFromAlbum), - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withOriginalRelease.js b/src/data/composite/things/track/withOriginalRelease.js deleted file mode 100644 index c7f49657..00000000 --- a/src/data/composite/things/track/withOriginalRelease.js +++ /dev/null @@ -1,78 +0,0 @@ -// Just includes the original release of this track as a dependency. -// If this track isn't a rerelease, then it'll provide null, unless the -// {selfIfOriginal} option is set, in which case it'll provide this track -// itself. This will early exit (with notFoundValue) if the original release -// is specified by reference and that reference doesn't resolve to anything. - -import {input, templateCompositeFrom} from '#composite'; -import find from '#find'; -import {validateWikiData} from '#validators'; - -import {exitWithoutDependency, withResultOfAvailabilityCheck} - from '#composite/control-flow'; -import {withResolvedReference} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `withOriginalRelease`, - - inputs: { - selfIfOriginal: input({type: 'boolean', defaultValue: false}), - - data: input({ - validate: validateWikiData({referenceType: 'track'}), - defaultDependency: 'trackData', - }), - - notFoundValue: input({defaultValue: null}), - }, - - outputs: ['#originalRelease'], - - steps: () => [ - withResultOfAvailabilityCheck({ - from: 'originalReleaseTrack', - }), - - { - dependencies: [ - input.myself(), - input('selfIfOriginal'), - '#availability', - ], - - compute: (continuation, { - [input.myself()]: track, - [input('selfIfOriginal')]: selfIfOriginal, - '#availability': availability, - }) => - (availability - ? continuation() - : continuation.raiseOutput({ - ['#originalRelease']: - (selfIfOriginal ? track : null), - })), - }, - - withResolvedReference({ - ref: 'originalReleaseTrack', - data: input('data'), - find: input.value(find.track), - }), - - exitWithoutDependency({ - dependency: '#resolvedReference', - value: input('notFoundValue'), - }), - - { - dependencies: ['#resolvedReference'], - - compute: (continuation, { - ['#resolvedReference']: resolvedReference, - }) => - continuation({ - ['#originalRelease']: resolvedReference, - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withOtherReleases.js b/src/data/composite/things/track/withOtherReleases.js deleted file mode 100644 index f8c1c3f0..00000000 --- a/src/data/composite/things/track/withOtherReleases.js +++ /dev/null @@ -1,41 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exitWithoutDependency} from '#composite/control-flow'; - -import withOriginalRelease from './withOriginalRelease.js'; - -export default templateCompositeFrom({ - annotation: `withOtherReleases`, - - outputs: ['#otherReleases'], - - steps: () => [ - exitWithoutDependency({ - dependency: 'trackData', - mode: input.value('empty'), - }), - - withOriginalRelease({ - selfIfOriginal: input.value(true), - notFoundValue: input.value([]), - }), - - { - dependencies: [input.myself(), '#originalRelease', 'trackData'], - compute: (continuation, { - [input.myself()]: thisTrack, - ['#originalRelease']: originalRelease, - trackData, - }) => continuation({ - ['#otherReleases']: - (originalRelease === thisTrack - ? [] - : [originalRelease]) - .concat(trackData.filter(track => - track !== originalRelease && - track !== thisTrack && - track.originalReleaseTrack === originalRelease)), - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withPropertyFromAlbum.js b/src/data/composite/things/track/withPropertyFromAlbum.js deleted file mode 100644 index d41390fa..00000000 --- a/src/data/composite/things/track/withPropertyFromAlbum.js +++ /dev/null @@ -1,40 +0,0 @@ -// Gets a single property from this track's album, providing it as the same -// property name prefixed with '#album.' (by default). - -import {input, templateCompositeFrom} from '#composite'; -import {is} from '#validators'; - -import {withPropertyFromObject} from '#composite/data'; - -import withAlbum from './withAlbum.js'; - -export default templateCompositeFrom({ - annotation: `withPropertyFromAlbum`, - - inputs: { - property: input.staticValue({type: 'string'}), - }, - - outputs: ({ - [input.staticValue('property')]: property, - }) => ['#album.' + property], - - steps: () => [ - withAlbum(), - - withPropertyFromObject({ - object: '#album', - property: input('property'), - }), - - { - dependencies: ['#value', input.staticValue('property')], - compute: (continuation, { - ['#value']: value, - [input.staticValue('property')]: property, - }) => continuation({ - ['#album.' + property]: value, - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withPropertyFromOriginalRelease.js b/src/data/composite/things/track/withPropertyFromOriginalRelease.js deleted file mode 100644 index fd37f6de..00000000 --- a/src/data/composite/things/track/withPropertyFromOriginalRelease.js +++ /dev/null @@ -1,86 +0,0 @@ -// Provides a value inherited from the original release, if applicable, and a -// flag indicating if this track is a rerelase or not. -// -// Like withOriginalRelease, this will early exit (with notFoundValue) if the -// original release is specified by reference and that reference doesn't -// resolve to anything. - -import {input, templateCompositeFrom} from '#composite'; - -import {withResultOfAvailabilityCheck} from '#composite/control-flow'; -import {withPropertyFromObject} from '#composite/data'; - -import withOriginalRelease from './withOriginalRelease.js'; - -export default templateCompositeFrom({ - annotation: `inheritFromOriginalRelease`, - - inputs: { - property: input({type: 'string'}), - - notFoundValue: input({ - defaultValue: null, - }), - }, - - outputs: ({ - [input.staticValue('property')]: property, - }) => - ['#isRerelease'].concat( - (property - ? ['#original.' + property] - : ['#originalValue'])), - - steps: () => [ - withOriginalRelease({ - notFoundValue: input('notFoundValue'), - }), - - withResultOfAvailabilityCheck({ - from: '#originalRelease', - }), - - { - dependencies: [ - '#availability', - input.staticValue('property'), - ], - - compute: (continuation, { - ['#availability']: availability, - [input.staticValue('property')]: property, - }) => - (availability - ? continuation() - : continuation.raiseOutput( - Object.assign( - {'#isRerelease': false}, - (property - ? {['#original.' + property]: null} - : {'#originalValue': null})))), - }, - - withPropertyFromObject({ - object: '#originalRelease', - property: input('property'), - }), - - { - dependencies: [ - '#value', - input.staticValue('property'), - ], - - compute: (continuation, { - ['#value']: value, - [input.staticValue('property')]: property, - }) => - continuation.raiseOutput( - Object.assign( - {'#isRerelease': true}, - (property - ? {['#original.' + property]: value} - : {'#originalValue': value}))), - }, - ], -}); diff --git a/src/data/composite/things/track/withSuffixDirectoryFromAlbum.js b/src/data/composite/things/track/withSuffixDirectoryFromAlbum.js deleted file mode 100644 index 7159a3f4..00000000 --- a/src/data/composite/things/track/withSuffixDirectoryFromAlbum.js +++ /dev/null @@ -1,53 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {withResultOfAvailabilityCheck} from '#composite/control-flow'; - -import withPropertyFromAlbum from './withPropertyFromAlbum.js'; - -export default templateCompositeFrom({ - annotation: `withSuffixDirectoryFromAlbum`, - - inputs: { - flagValue: input({ - defaultDependency: 'suffixDirectoryFromAlbum', - acceptsNull: true, - }), - }, - - outputs: ['#suffixDirectoryFromAlbum'], - - steps: () => [ - withResultOfAvailabilityCheck({ - from: 'suffixDirectoryFromAlbum', - }), - - { - dependencies: [ - '#availability', - 'suffixDirectoryFromAlbum' - ], - - compute: (continuation, { - ['#availability']: availability, - ['suffixDirectoryFromAlbum']: flagValue, - }) => - (availability - ? continuation.raiseOutput({['#suffixDirectoryFromAlbum']: flagValue}) - : continuation()), - }, - - withPropertyFromAlbum({ - property: input.value('suffixTrackDirectories'), - }), - - { - dependencies: ['#album.suffixTrackDirectories'], - compute: (continuation, { - ['#album.suffixTrackDirectories']: suffixTrackDirectories, - }) => continuation({ - ['#suffixDirectoryFromAlbum']: - suffixTrackDirectories, - }), - }, - ], -}); diff --git a/src/data/composite/things/track/withTrackArtDate.js b/src/data/composite/things/track/withTrackArtDate.js deleted file mode 100644 index e2c4d8bc..00000000 --- a/src/data/composite/things/track/withTrackArtDate.js +++ /dev/null @@ -1,80 +0,0 @@ -// Gets the date of cover art release. This represents only the track's own -// unique cover artwork, if any. -// -// If the 'fallback' option is false (the default), this will only output -// the track's own coverArtDate or its album's trackArtDate. If 'fallback' -// is set, and neither of these is available, it'll output the track's own -// date instead. - -import {input, templateCompositeFrom} from '#composite'; -import {isDate} from '#validators'; - -import {raiseOutputWithoutDependency} from '#composite/control-flow'; - -import withDate from './withDate.js'; -import withHasUniqueCoverArt from './withHasUniqueCoverArt.js'; -import withPropertyFromAlbum from './withPropertyFromAlbum.js'; - -export default templateCompositeFrom({ - annotation: `withTrackArtDate`, - - inputs: { - from: input({ - validate: isDate, - defaultDependency: 'coverArtDate', - acceptsNull: true, - }), - - fallback: input({ - type: 'boolean', - defaultValue: false, - }), - }, - - outputs: ['#trackArtDate'], - - steps: () => [ - withHasUniqueCoverArt(), - - raiseOutputWithoutDependency({ - dependency: '#hasUniqueCoverArt', - mode: input.value('falsy'), - output: input.value({'#trackArtDate': null}), - }), - - { - dependencies: [input('from')], - compute: (continuation, { - [input('from')]: from, - }) => - (from - ? continuation.raiseOutput({'#trackArtDate': from}) - : continuation()), - }, - - withPropertyFromAlbum({ - property: input.value('trackArtDate'), - }), - - { - dependencies: [ - '#album.trackArtDate', - input('fallback'), - ], - - compute: (continuation, { - ['#album.trackArtDate']: albumTrackArtDate, - [input('fallback')]: fallback, - }) => - (albumTrackArtDate - ? continuation.raiseOutput({'#trackArtDate': albumTrackArtDate}) - : fallback - ? continuation() - : continuation.raiseOutput({'#trackArtDate': null})), - }, - - withDate().outputs({ - '#date': '#trackArtDate', - }), - ], -}); diff --git a/src/data/composite/wiki-data/constituteFrom.js b/src/data/composite/wiki-data/constituteFrom.js new file mode 100644 index 00000000..b919d5cd --- /dev/null +++ b/src/data/composite/wiki-data/constituteFrom.js @@ -0,0 +1,31 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {inputAvailabilityCheckMode,} from '#composite/control-flow'; + +import constituteOrContinue from './constituteOrContinue.js'; + +export default templateCompositeFrom({ + annotation: `constituteFrom`, + + inputs: { + object: input({type: 'object', acceptsNull: true}), + property: input({type: 'string', acceptsNull: true}), + else: input({defaultValue: null}), + mode: inputAvailabilityCheckMode(), + }, + + compose: false, + + steps: () => [ + constituteOrContinue({ + object: input('object'), + property: input('property'), + mode: input('mode'), + }), + + { + dependencies: [input('else')], + compute: ({[input('else')]: fallback}) => fallback, + }, + ], +}); diff --git a/src/data/composite/wiki-data/constituteOrContinue.js b/src/data/composite/wiki-data/constituteOrContinue.js new file mode 100644 index 00000000..92b941ba --- /dev/null +++ b/src/data/composite/wiki-data/constituteOrContinue.js @@ -0,0 +1,34 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {withPropertyFromObject} from '#composite/data'; + +import { + exposeDependencyOrContinue, + inputAvailabilityCheckMode, + raiseOutputWithoutDependency, +} from '#composite/control-flow'; + +export default templateCompositeFrom({ + annotation: `constituteFrom`, + + inputs: { + object: input({type: 'object', acceptsNull: true}), + property: input({type: 'string', acceptsNull: true}), + mode: inputAvailabilityCheckMode(), + }, + + steps: () => [ + raiseOutputWithoutDependency({ + dependency: input('property'), + }), + + withPropertyFromObject({ + object: input('object'), + property: input('property'), + }), + + exposeDependencyOrContinue({ + dependency: '#value', + }), + ], +}); diff --git a/src/data/composite/wiki-data/gobbleSoupyFind.js b/src/data/composite/wiki-data/gobbleSoupyFind.js new file mode 100644 index 00000000..98d5f5c9 --- /dev/null +++ b/src/data/composite/wiki-data/gobbleSoupyFind.js @@ -0,0 +1,39 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {withPropertyFromObject} from '#composite/data'; + +import inputSoupyFind, {getSoupyFindInputKey} from './inputSoupyFind.js'; + +export default templateCompositeFrom({ + annotation: `gobbleSoupyFind`, + + inputs: { + find: inputSoupyFind(), + }, + + outputs: ['#find'], + + steps: () => [ + { + dependencies: [input('find')], + compute: (continuation, { + [input('find')]: find, + }) => + (typeof find === 'function' + ? continuation.raiseOutput({ + ['#find']: find, + }) + : continuation({ + ['#key']: + getSoupyFindInputKey(find), + })), + }, + + withPropertyFromObject({ + object: '_find', + property: '#key', + }).outputs({ + '#value': '#find', + }), + ], +}); diff --git a/src/data/composite/wiki-data/gobbleSoupyReverse.js b/src/data/composite/wiki-data/gobbleSoupyReverse.js new file mode 100644 index 00000000..26052f28 --- /dev/null +++ b/src/data/composite/wiki-data/gobbleSoupyReverse.js @@ -0,0 +1,39 @@ +import {input, templateCompositeFrom} from '#composite'; + +import {withPropertyFromObject} from '#composite/data'; + +import inputSoupyReverse, {getSoupyReverseInputKey} from './inputSoupyReverse.js'; + +export default templateCompositeFrom({ + annotation: `gobbleSoupyReverse`, + + inputs: { + reverse: inputSoupyReverse(), + }, + + outputs: ['#reverse'], + + steps: () => [ + { + dependencies: [input('reverse')], + compute: (continuation, { + [input('reverse')]: reverse, + }) => + (typeof reverse === 'function' + ? continuation.raiseOutput({ + ['#reverse']: reverse, + }) + : continuation({ + ['#key']: + getSoupyReverseInputKey(reverse), + })), + }, + + withPropertyFromObject({ + object: '_reverse', + property: '#key', + }).outputs({ + '#value': '#reverse', + }), + ], +}); diff --git a/src/data/composite/wiki-data/helpers/withResolvedReverse.js b/src/data/composite/wiki-data/helpers/withResolvedReverse.js new file mode 100644 index 00000000..818f60b7 --- /dev/null +++ b/src/data/composite/wiki-data/helpers/withResolvedReverse.js @@ -0,0 +1,40 @@ +// Actually execute a reverse function. + +import {input, templateCompositeFrom} from '#composite'; + +import inputWikiData from '../inputWikiData.js'; + +export default templateCompositeFrom({ + annotation: `withReverseReferenceList`, + + inputs: { + data: inputWikiData({allowMixedTypes: true}), + reverse: input({type: 'function'}), + options: input({type: 'object', defaultValue: null}), + }, + + outputs: ['#resolvedReverse'], + + steps: () => [ + { + dependencies: [ + input.myself(), + input('data'), + input('reverse'), + input('options'), + ], + + compute: (continuation, { + [input.myself()]: myself, + [input('data')]: data, + [input('reverse')]: reverseFunction, + [input('options')]: opts, + }) => continuation({ + ['#resolvedReverse']: + (data + ? reverseFunction(myself, data, opts) + : reverseFunction(myself, opts)), + }), + }, + ], +}); diff --git a/src/data/composite/wiki-data/helpers/withReverseList-template.js b/src/data/composite/wiki-data/helpers/withReverseList-template.js deleted file mode 100644 index 6ffd5d70..00000000 --- a/src/data/composite/wiki-data/helpers/withReverseList-template.js +++ /dev/null @@ -1,193 +0,0 @@ -// Baseline implementation shared by or underlying reverse lists. -// -// This is a very rudimentary "these compositions have basically the same -// shape but slightly different guts midway through" kind of solution, -// and should use compositional subroutines instead, once those are ready. -// -// But, until then, this has the same effect of avoiding code duplication -// and clearly identifying differences. -// -// --- -// -// This implementation uses a global cache (via WeakMap) to attempt to speed -// up subsequent similar accesses. -// -// This has absolutely not been rigorously tested with altering properties of -// data objects in a wiki data array which is reused. If a new wiki data array -// is used, a fresh cache will always be created. -// - -import {input, templateCompositeFrom} from '#composite'; -import {sortByDate} from '#sort'; -import {stitchArrays} from '#sugar'; - -import {exitWithoutDependency, raiseOutputWithoutDependency} - from '#composite/control-flow'; -import {withFlattenedList, withMappedList} from '#composite/data'; - -import inputWikiData from '../inputWikiData.js'; - -export default function withReverseList_template({ - annotation, - - propertyInputName, - outputName, - - additionalInputs = {}, - - customCompositionSteps, -}) { - // Mapping of reference list property to WeakMap. - // Each WeakMap maps a wiki data array to another weak map, - // which in turn maps each referenced thing to an array of - // things referencing it. - const caches = new Map(); - - return templateCompositeFrom({ - annotation, - - inputs: { - data: inputWikiData({ - allowMixedTypes: true, - }), - - [propertyInputName]: input({ - type: 'string', - }), - - ...additionalInputs, - }, - - outputs: [outputName], - - steps: () => [ - // Early exit with an empty array if the data list isn't available. - exitWithoutDependency({ - dependency: input('data'), - value: input.value([]), - }), - - // Raise an empty array (don't early exit) if the data list is empty. - raiseOutputWithoutDependency({ - dependency: input('data'), - mode: input.value('empty'), - output: input.value({[outputName]: []}), - }), - - // Check for an existing cache record which corresponds to this - // property input and input('data'). If it exists, query it for the - // current thing, and raise that; if it doesn't, create it, put it - // where it needs to be, and provide it so the next steps can fill - // it in. - { - dependencies: [input(propertyInputName), input('data'), input.myself()], - - compute: (continuation, { - [input(propertyInputName)]: property, - [input('data')]: data, - [input.myself()]: myself, - }) => { - if (!caches.has(property)) { - const cache = new WeakMap(); - caches.set(property, cache); - - const cacheRecord = new WeakMap(); - cache.set(data, cacheRecord); - - return continuation({ - ['#cacheRecord']: cacheRecord, - }); - } - - const cache = caches.get(property); - - if (!cache.has(data)) { - const cacheRecord = new WeakMap(); - cache.set(data, cacheRecord); - - return continuation({ - ['#cacheRecord']: cacheRecord, - }); - } - - return continuation.raiseOutput({ - [outputName]: - cache.get(data).get(myself) ?? [], - }); - }, - }, - - ...customCompositionSteps(), - - // Actually fill in the cache record. Since we're building up a *reverse* - // reference list, track connections in terms of the referenced thing. - // Although we gather all referenced things into a set and provide that - // for sorting purposes in the next step, we *don't* reprovide the cache - // record, because we're mutating that in-place - we'll just reuse its - // existing '#cacheRecord' dependency. - { - dependencies: ['#cacheRecord', '#referencingThings', '#referencedThings'], - compute: (continuation, { - ['#cacheRecord']: cacheRecord, - ['#referencingThings']: referencingThings, - ['#referencedThings']: referencedThings, - }) => { - const allReferencedThings = new Set(); - - stitchArrays({ - referencingThing: referencingThings, - referencedThings: referencedThings, - }).forEach(({referencingThing, referencedThings}) => { - for (const referencedThing of referencedThings) { - if (cacheRecord.has(referencedThing)) { - cacheRecord.get(referencedThing).push(referencingThing); - } else { - cacheRecord.set(referencedThing, [referencingThing]); - allReferencedThings.add(referencedThing); - } - } - }); - - return continuation({ - ['#allReferencedThings']: - allReferencedThings, - }); - }, - }, - - // Sort the entries in the cache records, too, just by date - the rest of - // sorting should be handled outside of this composition, either preceding - // (changing the 'data' input) or following (sorting the output). - // Again we're mutating in place, so no need to reprovide '#cacheRecord' - // here. - { - dependencies: ['#cacheRecord', '#allReferencedThings'], - compute: (continuation, { - ['#cacheRecord']: cacheRecord, - ['#allReferencedThings']: allReferencedThings, - }) => { - for (const referencedThing of allReferencedThings) { - if (cacheRecord.has(referencedThing)) { - const referencingThings = cacheRecord.get(referencedThing); - sortByDate(referencingThings); - } - } - - return continuation(); - }, - }, - - // Then just pluck out the current object from the now-filled cache record! - { - dependencies: ['#cacheRecord', input.myself()], - compute: (continuation, { - ['#cacheRecord']: cacheRecord, - [input.myself()]: myself, - }) => continuation({ - [outputName]: - cacheRecord.get(myself) ?? [], - }), - }, - ], - }); -} diff --git a/src/data/composite/wiki-data/helpers/withSimpleDirectory.js b/src/data/composite/wiki-data/helpers/withSimpleDirectory.js index 08ca3bfc..0b225847 100644 --- a/src/data/composite/wiki-data/helpers/withSimpleDirectory.js +++ b/src/data/composite/wiki-data/helpers/withSimpleDirectory.js @@ -15,7 +15,7 @@ export default templateCompositeFrom({ inputs: { directory: input({ validate: isDirectory, - defaultDependency: 'directory', + defaultDependency: '_directory', acceptsNull: true, }), diff --git a/src/data/composite/wiki-data/index.js b/src/data/composite/wiki-data/index.js index 51d07384..41f34d21 100644 --- a/src/data/composite/wiki-data/index.js +++ b/src/data/composite/wiki-data/index.js @@ -4,24 +4,28 @@ // #composite/data. // +export {default as constituteFrom} from './constituteFrom.js'; +export {default as constituteOrContinue} from './constituteOrContinue.js'; export {default as exitWithoutContribs} from './exitWithoutContribs.js'; +export {default as gobbleSoupyFind} from './gobbleSoupyFind.js'; +export {default as gobbleSoupyReverse} from './gobbleSoupyReverse.js'; +export {default as inputFindOptions} from './inputFindOptions.js'; export {default as inputNotFoundMode} from './inputNotFoundMode.js'; +export {default as inputSoupyFind} from './inputSoupyFind.js'; +export {default as inputSoupyReverse} from './inputSoupyReverse.js'; export {default as inputWikiData} from './inputWikiData.js'; +export {default as splitContentNodesAround} from './splitContentNodesAround.js'; export {default as withClonedThings} from './withClonedThings.js'; +export {default as withConstitutedArtwork} from './withConstitutedArtwork.js'; +export {default as withContentNodes} from './withContentNodes.js'; export {default as withContributionListSums} from './withContributionListSums.js'; -export {default as withCoverArtDate} from './withCoverArtDate.js'; export {default as withDirectory} from './withDirectory.js'; -export {default as withParsedCommentaryEntries} from './withParsedCommentaryEntries.js'; export {default as withRecontextualizedContributionList} from './withRecontextualizedContributionList.js'; export {default as withRedatedContributionList} from './withRedatedContributionList.js'; export {default as withResolvedAnnotatedReferenceList} from './withResolvedAnnotatedReferenceList.js'; export {default as withResolvedContribs} from './withResolvedContribs.js'; export {default as withResolvedReference} from './withResolvedReference.js'; export {default as withResolvedReferenceList} from './withResolvedReferenceList.js'; -export {default as withResolvedSeriesList} from './withResolvedSeriesList.js'; -export {default as withReverseAnnotatedReferenceList} from './withReverseAnnotatedReferenceList.js'; -export {default as withReverseContributionList} from './withReverseContributionList.js'; export {default as withReverseReferenceList} from './withReverseReferenceList.js'; -export {default as withReverseSingleReferenceList} from './withReverseSingleReferenceList.js'; export {default as withThingsSortedAlphabetically} from './withThingsSortedAlphabetically.js'; export {default as withUniqueReferencingThing} from './withUniqueReferencingThing.js'; diff --git a/src/data/composite/wiki-data/inputFindOptions.js b/src/data/composite/wiki-data/inputFindOptions.js new file mode 100644 index 00000000..07ed4bce --- /dev/null +++ b/src/data/composite/wiki-data/inputFindOptions.js @@ -0,0 +1,5 @@ +import {input} from '#composite'; + +export default function inputFindOptions() { + return input({type: 'object', defaultValue: null}); +} diff --git a/src/data/composite/wiki-data/inputSoupyFind.js b/src/data/composite/wiki-data/inputSoupyFind.js new file mode 100644 index 00000000..020f4990 --- /dev/null +++ b/src/data/composite/wiki-data/inputSoupyFind.js @@ -0,0 +1,28 @@ +import {input} from '#composite'; +import {anyOf, isFunction, isString} from '#validators'; + +function inputSoupyFind() { + return input({ + validate: + anyOf( + isFunction, + val => { + isString(val); + + if (!val.startsWith('_soupyFind:')) { + throw new Error(`Expected soupyFind.input() token`); + } + + return true; + }), + }); +} + +inputSoupyFind.input = key => + input.value('_soupyFind:' + key); + +export default inputSoupyFind; + +export function getSoupyFindInputKey(value) { + return value.slice('_soupyFind:'.length); +} diff --git a/src/data/composite/wiki-data/inputSoupyReverse.js b/src/data/composite/wiki-data/inputSoupyReverse.js new file mode 100644 index 00000000..0b0a23fe --- /dev/null +++ b/src/data/composite/wiki-data/inputSoupyReverse.js @@ -0,0 +1,32 @@ +import {input} from '#composite'; +import {anyOf, isFunction, isString} from '#validators'; + +function inputSoupyReverse() { + return input({ + validate: + anyOf( + isFunction, + val => { + isString(val); + + if (!val.startsWith('_soupyReverse:')) { + throw new Error(`Expected soupyReverse.input() token`); + } + + return true; + }), + }); +} + +inputSoupyReverse.input = key => + input.value('_soupyReverse:' + key); + +export default inputSoupyReverse; + +export function getSoupyReverseInputKey(value) { + return value.slice('_soupyReverse:'.length).replace(/\.unique$/, ''); +} + +export function doesSoupyReverseInputWantUnique(value) { + return value.endsWith('.unique'); +} diff --git a/src/data/composite/wiki-data/inputWikiData.js b/src/data/composite/wiki-data/inputWikiData.js index cf7a7c2c..b9021986 100644 --- a/src/data/composite/wiki-data/inputWikiData.js +++ b/src/data/composite/wiki-data/inputWikiData.js @@ -12,6 +12,6 @@ export default function inputWikiData({ } = {}) { return input({ validate: validateWikiData({referenceType, allowMixedTypes}), - acceptsNull: true, + defaultValue: null, }); } diff --git a/src/data/composite/wiki-data/splitContentNodesAround.js b/src/data/composite/wiki-data/splitContentNodesAround.js new file mode 100644 index 00000000..f12bd8fc --- /dev/null +++ b/src/data/composite/wiki-data/splitContentNodesAround.js @@ -0,0 +1,100 @@ +import {input, templateCompositeFrom} from '#composite'; +import {splitContentNodesAround} from '#replacer'; +import {anyOf, isFunction, validateInstanceOf} from '#validators'; + +import {withAvailabilityFilter} from '#composite/control-flow'; +import {withFilteredList, withMappedList, withUnflattenedList} + from '#composite/data'; + +export default templateCompositeFrom({ + annotation: `splitContentNodesAround`, + + inputs: { + nodes: input({type: 'array'}), + + around: input({ + validate: + anyOf(isFunction, validateInstanceOf(RegExp)), + }), + }, + + outputs: ['#contentNodeLists'], + + steps: () => [ + { + dependencies: [input('nodes'), input('around')], + + compute: (continuation, { + [input('nodes')]: nodes, + [input('around')]: splitter, + }) => continuation({ + ['#nodes']: + Array.from(splitContentNodesAround(nodes, splitter)), + }), + }, + + withMappedList({ + list: '#nodes', + map: input.value(node => node.type === 'separator'), + }).outputs({ + '#mappedList': '#separatorFilter', + }), + + withMappedList({ + list: '#separatorFilter', + map: input.value((_node, index) => index), + filter: '#separatorFilter', + }), + + withFilteredList({ + list: '#mappedList', + filter: '#separatorFilter', + }).outputs({ + '#filteredList': '#separatorIndices', + }), + + { + dependencies: ['#nodes', '#separatorFilter'], + + compute: (continuation, { + ['#nodes']: nodes, + ['#separatorFilter']: separatorFilter, + }) => continuation({ + ['#nodes']: + nodes.map((node, index) => + (separatorFilter[index] + ? null + : node)), + }), + }, + + { + dependencies: ['#separatorIndices'], + compute: (continuation, { + ['#separatorIndices']: separatorIndices, + }) => continuation({ + ['#unflattenIndices']: + [0, ...separatorIndices], + }), + }, + + withUnflattenedList({ + list: '#nodes', + indices: '#unflattenIndices', + }).outputs({ + '#unflattenedList': '#contentNodeLists', + }), + + withAvailabilityFilter({ + from: '#contentNodeLists', + mode: input.value('empty'), + }), + + withFilteredList({ + list: '#contentNodeLists', + filter: '#availabilityFilter', + }).outputs({ + '#filteredList': '#contentNodeLists', + }), + ], +}); diff --git a/src/data/composite/wiki-data/withConstitutedArtwork.js b/src/data/composite/wiki-data/withConstitutedArtwork.js new file mode 100644 index 00000000..28d719e2 --- /dev/null +++ b/src/data/composite/wiki-data/withConstitutedArtwork.js @@ -0,0 +1,60 @@ +import {input, templateCompositeFrom} from '#composite'; +import thingConstructors from '#things'; + +export default templateCompositeFrom({ + annotation: `withConstitutedArtwork`, + + inputs: { + thingProperty: input({type: 'string', acceptsNull: true}), + dimensionsFromThingProperty: input({type: 'string', acceptsNull: true}), + fileExtensionFromThingProperty: input({type: 'string', acceptsNull: true}), + dateFromThingProperty: input({type: 'string', acceptsNull: true}), + artistContribsFromThingProperty: input({type: 'string', acceptsNull: true}), + artistContribsArtistProperty: input({type: 'string', acceptsNull: true}), + artTagsFromThingProperty: input({type: 'string', acceptsNull: true}), + referencedArtworksFromThingProperty: input({type: 'string', acceptsNull: true}), + }, + + outputs: ['#constitutedArtwork'], + + steps: () => [ + { + dependencies: [ + input.myself(), + input('thingProperty'), + input('dimensionsFromThingProperty'), + input('fileExtensionFromThingProperty'), + input('dateFromThingProperty'), + input('artistContribsFromThingProperty'), + input('artistContribsArtistProperty'), + input('artTagsFromThingProperty'), + input('referencedArtworksFromThingProperty'), + ], + + compute: (continuation, { + [input.myself()]: myself, + [input('thingProperty')]: thingProperty, + [input('dimensionsFromThingProperty')]: dimensionsFromThingProperty, + [input('fileExtensionFromThingProperty')]: fileExtensionFromThingProperty, + [input('dateFromThingProperty')]: dateFromThingProperty, + [input('artistContribsFromThingProperty')]: artistContribsFromThingProperty, + [input('artistContribsArtistProperty')]: artistContribsArtistProperty, + [input('artTagsFromThingProperty')]: artTagsFromThingProperty, + [input('referencedArtworksFromThingProperty')]: referencedArtworksFromThingProperty, + }) => continuation({ + ['#constitutedArtwork']: + Object.assign(new thingConstructors.Artwork, { + thing: myself, + thingProperty, + dimensionsFromThingProperty, + fileExtensionFromThingProperty, + artistContribsFromThingProperty, + artistContribsArtistProperty, + artTagsFromThingProperty, + dateFromThingProperty, + referencedArtworksFromThingProperty, + }), + }), + }, + ], +}); diff --git a/src/data/composite/wiki-data/withContentNodes.js b/src/data/composite/wiki-data/withContentNodes.js new file mode 100644 index 00000000..d014d43b --- /dev/null +++ b/src/data/composite/wiki-data/withContentNodes.js @@ -0,0 +1,25 @@ +import {input, templateCompositeFrom} from '#composite'; +import {parseContentNodes} from '#replacer'; + +export default templateCompositeFrom({ + annotation: `withContentNodes`, + + inputs: { + from: input({type: 'string', acceptsNull: false}), + }, + + outputs: ['#contentNodes'], + + steps: () => [ + { + dependencies: [input('from')], + + compute: (continuation, { + [input('from')]: string, + }) => continuation({ + ['#contentNodes']: + parseContentNodes(string), + }), + }, + ], +}); diff --git a/src/data/composite/wiki-data/withCoverArtDate.js b/src/data/composite/wiki-data/withCoverArtDate.js deleted file mode 100644 index 0c644c77..00000000 --- a/src/data/composite/wiki-data/withCoverArtDate.js +++ /dev/null @@ -1,70 +0,0 @@ -// Gets the current thing's coverArtDate, or, if the 'fallback' option is set, -// the thing's date. This is always null if the thing doesn't actually have -// any coverArtistContribs. - -import {input, templateCompositeFrom} from '#composite'; -import {isDate} from '#validators'; - -import {raiseOutputWithoutDependency} from '#composite/control-flow'; - -import withResolvedContribs from './withResolvedContribs.js'; - -export default templateCompositeFrom({ - annotation: `withCoverArtDate`, - - inputs: { - from: input({ - validate: isDate, - defaultDependency: 'coverArtDate', - acceptsNull: true, - }), - - fallback: input({ - type: 'boolean', - defaultValue: false, - }), - }, - - outputs: ['#coverArtDate'], - - steps: () => [ - withResolvedContribs({ - from: 'coverArtistContribs', - date: input.value(null), - }), - - raiseOutputWithoutDependency({ - dependency: '#resolvedContribs', - mode: input.value('empty'), - output: input.value({'#coverArtDate': null}), - }), - - { - dependencies: [input('from')], - compute: (continuation, { - [input('from')]: from, - }) => - (from - ? continuation.raiseOutput({'#coverArtDate': from}) - : continuation()), - }, - - { - dependencies: [input('fallback')], - compute: (continuation, { - [input('fallback')]: fallback, - }) => - (fallback - ? continuation() - : continuation.raiseOutput({'#coverArtDate': null})), - }, - - { - dependencies: ['date'], - compute: (continuation, {date}) => - (date - ? continuation.raiseOutput({'#coverArtDate': date}) - : continuation.raiseOutput({'#coverArtDate': null})), - }, - ], -}); diff --git a/src/data/composite/wiki-data/withDirectory.js b/src/data/composite/wiki-data/withDirectory.js index f3bedf2e..e7c3960e 100644 --- a/src/data/composite/wiki-data/withDirectory.js +++ b/src/data/composite/wiki-data/withDirectory.js @@ -17,13 +17,13 @@ export default templateCompositeFrom({ inputs: { directory: input({ validate: isDirectory, - defaultDependency: 'directory', + defaultDependency: '_directory', acceptsNull: true, }), name: input({ validate: isName, - defaultDependency: 'name', + defaultDependency: '_name', acceptsNull: true, }), diff --git a/src/data/composite/wiki-data/withParsedCommentaryEntries.js b/src/data/composite/wiki-data/withParsedCommentaryEntries.js deleted file mode 100644 index 144781a8..00000000 --- a/src/data/composite/wiki-data/withParsedCommentaryEntries.js +++ /dev/null @@ -1,261 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; -import find from '#find'; -import {stitchArrays} from '#sugar'; -import {isCommentary} from '#validators'; -import {commentaryRegexCaseSensitive} from '#wiki-data'; - -import { - fillMissingListItems, - withFlattenedList, - withPropertiesFromList, - withUnflattenedList, -} from '#composite/data'; - -import withResolvedReferenceList from './withResolvedReferenceList.js'; - -export default templateCompositeFrom({ - annotation: `withParsedCommentaryEntries`, - - inputs: { - from: input({validate: isCommentary}), - }, - - outputs: ['#parsedCommentaryEntries'], - - steps: () => [ - { - dependencies: [input('from')], - - compute: (continuation, { - [input('from')]: commentaryText, - }) => continuation({ - ['#rawMatches']: - Array.from(commentaryText.matchAll(commentaryRegexCaseSensitive)), - }), - }, - - withPropertiesFromList({ - list: '#rawMatches', - properties: input.value([ - '0', // The entire match as a string. - 'groups', - 'index', - ]), - }).outputs({ - '#rawMatches.0': '#rawMatches.text', - '#rawMatches.groups': '#rawMatches.groups', - '#rawMatches.index': '#rawMatches.startIndex', - }), - - { - dependencies: [ - '#rawMatches.text', - '#rawMatches.startIndex', - ], - - compute: (continuation, { - ['#rawMatches.text']: text, - ['#rawMatches.startIndex']: startIndex, - }) => continuation({ - ['#rawMatches.endIndex']: - stitchArrays({text, startIndex}) - .map(({text, startIndex}) => startIndex + text.length), - }), - }, - - { - dependencies: [ - input('from'), - '#rawMatches.startIndex', - '#rawMatches.endIndex', - ], - - compute: (continuation, { - [input('from')]: commentaryText, - ['#rawMatches.startIndex']: startIndex, - ['#rawMatches.endIndex']: endIndex, - }) => continuation({ - ['#entries.body']: - stitchArrays({startIndex, endIndex}) - .map(({endIndex}, index, stitched) => - (index === stitched.length - 1 - ? commentaryText.slice(endIndex) - : commentaryText.slice( - endIndex, - stitched[index + 1].startIndex))) - .map(body => body.trim()), - }), - }, - - withPropertiesFromList({ - list: '#rawMatches.groups', - prefix: input.value('#entries'), - properties: input.value([ - 'artistReferences', - 'artistDisplayText', - 'annotation', - 'date', - 'secondDate', - 'dateKind', - 'accessDate', - 'accessKind', - ]), - }), - - // The artistReferences group will always have a value, since it's required - // for the line to match in the first place. - - { - dependencies: ['#entries.artistReferences'], - compute: (continuation, { - ['#entries.artistReferences']: artistReferenceTexts, - }) => continuation({ - ['#entries.artistReferences']: - artistReferenceTexts - .map(text => text.split(',').map(ref => ref.trim())), - }), - }, - - withFlattenedList({ - list: '#entries.artistReferences', - }), - - withResolvedReferenceList({ - list: '#flattenedList', - data: 'artistData', - find: input.value(find.artist), - notFoundMode: input.value('null'), - }), - - withUnflattenedList({ - list: '#resolvedReferenceList', - }).outputs({ - '#unflattenedList': '#entries.artists', - }), - - fillMissingListItems({ - list: '#entries.artistDisplayText', - fill: input.value(null), - }), - - fillMissingListItems({ - list: '#entries.annotation', - fill: input.value(null), - }), - - { - dependencies: ['#entries.annotation'], - compute: (continuation, { - ['#entries.annotation']: annotation, - }) => continuation({ - ['#entries.webArchiveDate']: - annotation - .map(text => text?.match(/https?:\/\/web.archive.org\/web\/([0-9]{8,8})[0-9]*\//)) - .map(match => match?.[1]) - .map(dateText => - (dateText - ? dateText.slice(0, 4) + '/' + - dateText.slice(4, 6) + '/' + - dateText.slice(6, 8) - : null)), - }), - }, - - { - dependencies: ['#entries.date'], - compute: (continuation, { - ['#entries.date']: date, - }) => continuation({ - ['#entries.date']: - date - .map(date => date ? new Date(date) : null), - }), - }, - - { - dependencies: ['#entries.secondDate'], - compute: (continuation, { - ['#entries.secondDate']: secondDate, - }) => continuation({ - ['#entries.secondDate']: - secondDate - .map(date => date ? new Date(date) : null), - }), - }, - - fillMissingListItems({ - list: '#entries.dateKind', - fill: input.value(null), - }), - - { - dependencies: ['#entries.accessDate', '#entries.webArchiveDate'], - compute: (continuation, { - ['#entries.accessDate']: accessDate, - ['#entries.webArchiveDate']: webArchiveDate, - }) => continuation({ - ['#entries.accessDate']: - stitchArrays({accessDate, webArchiveDate}) - .map(({accessDate, webArchiveDate}) => - accessDate ?? - webArchiveDate ?? - null) - .map(date => date ? new Date(date) : date), - }), - }, - - { - dependencies: ['#entries.accessKind', '#entries.webArchiveDate'], - compute: (continuation, { - ['#entries.accessKind']: accessKind, - ['#entries.webArchiveDate']: webArchiveDate, - }) => continuation({ - ['#entries.accessKind']: - stitchArrays({accessKind, webArchiveDate}) - .map(({accessKind, webArchiveDate}) => - accessKind ?? - (webArchiveDate && 'captured') ?? - null), - }), - }, - - { - dependencies: [ - '#entries.artists', - '#entries.artistDisplayText', - '#entries.annotation', - '#entries.date', - '#entries.secondDate', - '#entries.dateKind', - '#entries.accessDate', - '#entries.accessKind', - '#entries.body', - ], - - compute: (continuation, { - ['#entries.artists']: artists, - ['#entries.artistDisplayText']: artistDisplayText, - ['#entries.annotation']: annotation, - ['#entries.date']: date, - ['#entries.secondDate']: secondDate, - ['#entries.dateKind']: dateKind, - ['#entries.accessDate']: accessDate, - ['#entries.accessKind']: accessKind, - ['#entries.body']: body, - }) => continuation({ - ['#parsedCommentaryEntries']: - stitchArrays({ - artists, - artistDisplayText, - annotation, - date, - secondDate, - dateKind, - accessDate, - accessKind, - body, - }), - }), - }, - ], -}); diff --git a/src/data/composite/wiki-data/withRecontextualizedContributionList.js b/src/data/composite/wiki-data/withRecontextualizedContributionList.js index d2401eac..bcc6e486 100644 --- a/src/data/composite/wiki-data/withRecontextualizedContributionList.js +++ b/src/data/composite/wiki-data/withRecontextualizedContributionList.js @@ -10,7 +10,6 @@ import {input, templateCompositeFrom} from '#composite'; import {isStringNonEmpty} from '#validators'; -import {raiseOutputWithoutDependency} from '#composite/control-flow'; import {withClonedThings} from '#composite/wiki-data'; export default templateCompositeFrom({ diff --git a/src/data/composite/wiki-data/withResolvedAnnotatedReferenceList.js b/src/data/composite/wiki-data/withResolvedAnnotatedReferenceList.js index 789a8844..71bc56ac 100644 --- a/src/data/composite/wiki-data/withResolvedAnnotatedReferenceList.js +++ b/src/data/composite/wiki-data/withResolvedAnnotatedReferenceList.js @@ -1,15 +1,14 @@ import {input, templateCompositeFrom} from '#composite'; import {stitchArrays} from '#sugar'; -import {isDate, isObject, validateArrayItems} from '#validators'; +import {isObject, validateArrayItems} from '#validators'; import {withPropertyFromList} from '#composite/data'; -import { - exitWithoutDependency, - raiseOutputWithoutDependency, - withAvailabilityFilter, -} from '#composite/control-flow'; +import {raiseOutputWithoutDependency, withAvailabilityFilter} + from '#composite/control-flow'; +import inputFindOptions from './inputFindOptions.js'; +import inputSoupyFind from './inputSoupyFind.js'; import inputNotFoundMode from './inputNotFoundMode.js'; import inputWikiData from './inputWikiData.js'; import raiseResolvedReferenceList from './raiseResolvedReferenceList.js'; @@ -24,29 +23,20 @@ export default templateCompositeFrom({ acceptsNull: true, }), - date: input({ - validate: isDate, - acceptsNull: true, - }), + data: inputWikiData({allowMixedTypes: true}), + find: inputSoupyFind(), + findOptions: inputFindOptions(), reference: input({type: 'string', defaultValue: 'reference'}), annotation: input({type: 'string', defaultValue: 'annotation'}), thing: input({type: 'string', defaultValue: 'thing'}), - data: inputWikiData({allowMixedTypes: true}), - find: input({type: 'function'}), - notFoundMode: inputNotFoundMode(), }, outputs: ['#resolvedAnnotatedReferenceList'], steps: () => [ - exitWithoutDependency({ - dependency: input('data'), - value: input.value([]), - }), - raiseOutputWithoutDependency({ dependency: input('list'), mode: input.value('empty'), @@ -73,6 +63,7 @@ export default templateCompositeFrom({ list: '#references', data: input('data'), find: input('find'), + findOptions: input('findOptions'), notFoundMode: input.value('null'), }), @@ -98,17 +89,6 @@ export default templateCompositeFrom({ }), }, - { - dependencies: ['#matches', input('date')], - compute: (continuation, { - ['#matches']: matches, - [input('date')]: date, - }) => continuation({ - ['#matches']: - matches.map(match => ({...match, date})), - }), - }, - withAvailabilityFilter({ from: '#resolvedReferenceList', }), diff --git a/src/data/composite/wiki-data/withResolvedContribs.js b/src/data/composite/wiki-data/withResolvedContribs.js index b4119604..7729d5b6 100644 --- a/src/data/composite/wiki-data/withResolvedContribs.js +++ b/src/data/composite/wiki-data/withResolvedContribs.js @@ -28,6 +28,7 @@ export default templateCompositeFrom({ date: input({ validate: isDate, acceptsNull: true, + defaultDependency: 'date', }), notFoundMode: inputNotFoundMode(), @@ -110,6 +111,7 @@ export default templateCompositeFrom({ '#thingProperty', input('artistProperty'), input.myself(), + '_find', ], compute: (continuation, { @@ -117,6 +119,7 @@ export default templateCompositeFrom({ ['#thingProperty']: thingProperty, [input('artistProperty')]: artistProperty, [input.myself()]: myself, + ['_find']: find, }) => continuation({ ['#contributions']: details.map(details => { @@ -127,6 +130,7 @@ export default templateCompositeFrom({ thing: myself, thingProperty: thingProperty, artistProperty: artistProperty, + find: find, }); return contrib; @@ -136,11 +140,11 @@ export default templateCompositeFrom({ withPropertyFromList({ list: '#contributions', - property: input.value('thing'), + property: input.value('artist'), }), withAvailabilityFilter({ - from: '#contributions.thing', + from: '#contributions.artist', }), raiseResolvedReferenceList({ diff --git a/src/data/composite/wiki-data/withResolvedReference.js b/src/data/composite/wiki-data/withResolvedReference.js index ea71707e..d9a05367 100644 --- a/src/data/composite/wiki-data/withResolvedReference.js +++ b/src/data/composite/wiki-data/withResolvedReference.js @@ -1,16 +1,15 @@ // 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. Otherwise, the data object is provided on the -// output dependency, or null, if the reference doesn't match anything or +// within the provided thingData dependency. 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. import {input, templateCompositeFrom} from '#composite'; -import { - exitWithoutDependency, - raiseOutputWithoutDependency, -} from '#composite/control-flow'; +import {raiseOutputWithoutDependency} from '#composite/control-flow'; +import gobbleSoupyFind from './gobbleSoupyFind.js'; +import inputFindOptions from './inputFindOptions.js'; +import inputSoupyFind from './inputSoupyFind.js'; import inputWikiData from './inputWikiData.js'; export default templateCompositeFrom({ @@ -19,8 +18,9 @@ export default templateCompositeFrom({ inputs: { ref: input({type: 'string', acceptsNull: true}), - data: inputWikiData({allowMixedTypes: false}), - find: input({type: 'function'}), + data: inputWikiData({allowMixedTypes: true}), + find: inputSoupyFind(), + findOptions: inputFindOptions(), }, outputs: ['#resolvedReference'], @@ -33,24 +33,40 @@ export default templateCompositeFrom({ }), }), - exitWithoutDependency({ - dependency: input('data'), + gobbleSoupyFind({ + find: input('find'), }), { + dependencies: [input('findOptions')], + compute: (continuation, { + [input('findOptions')]: findOptions, + }) => continuation({ + ['#findOptions']: + (findOptions + ? {...findOptions, mode: 'quiet'} + : {mode: 'quiet'}), + }), + }, + + { dependencies: [ input('ref'), input('data'), - input('find'), + '#find', + '#findOptions', ], compute: (continuation, { [input('ref')]: ref, [input('data')]: data, - [input('find')]: findFunction, + ['#find']: findFunction, + ['#findOptions']: findOptions, }) => continuation({ ['#resolvedReference']: - findFunction(ref, data, {mode: 'quiet'}) ?? null, + (data + ? findFunction(ref, data, findOptions) ?? null + : findFunction(ref, findOptions) ?? null), }), }, ], diff --git a/src/data/composite/wiki-data/withResolvedReferenceList.js b/src/data/composite/wiki-data/withResolvedReferenceList.js index 790a962f..14ce6919 100644 --- a/src/data/composite/wiki-data/withResolvedReferenceList.js +++ b/src/data/composite/wiki-data/withResolvedReferenceList.js @@ -1,19 +1,19 @@ // 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'). +// data in the same way as withResolvedReference. 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'). import {input, templateCompositeFrom} from '#composite'; import {isString, validateArrayItems} from '#validators'; -import { - exitWithoutDependency, - raiseOutputWithoutDependency, - withAvailabilityFilter, -} from '#composite/control-flow'; +import {raiseOutputWithoutDependency, withAvailabilityFilter} + from '#composite/control-flow'; +import {withMappedList} from '#composite/data'; +import gobbleSoupyFind from './gobbleSoupyFind.js'; +import inputFindOptions from './inputFindOptions.js'; import inputNotFoundMode from './inputNotFoundMode.js'; +import inputSoupyFind from './inputSoupyFind.js'; import inputWikiData from './inputWikiData.js'; import raiseResolvedReferenceList from './raiseResolvedReferenceList.js'; @@ -27,7 +27,8 @@ export default templateCompositeFrom({ }), data: inputWikiData({allowMixedTypes: true}), - find: input({type: 'function'}), + find: inputSoupyFind(), + findOptions: inputFindOptions(), notFoundMode: inputNotFoundMode(), }, @@ -35,11 +36,6 @@ export default templateCompositeFrom({ outputs: ['#resolvedReferenceList'], steps: () => [ - exitWithoutDependency({ - dependency: input('data'), - value: input.value([]), - }), - raiseOutputWithoutDependency({ dependency: input('list'), mode: input.value('empty'), @@ -48,18 +44,43 @@ export default templateCompositeFrom({ }), }), + gobbleSoupyFind({ + find: input('find'), + }), + + { + dependencies: [input('findOptions')], + compute: (continuation, { + [input('findOptions')]: findOptions, + }) => continuation({ + ['#findOptions']: + (findOptions + ? {...findOptions, mode: 'quiet'} + : {mode: 'quiet'}), + }), + }, + { - dependencies: [input('list'), input('data'), input('find')], + dependencies: [input('data'), '#find', '#findOptions'], compute: (continuation, { - [input('list')]: list, [input('data')]: data, - [input('find')]: findFunction, - }) => - continuation({ - '#matches': list.map(ref => findFunction(ref, data, {mode: 'quiet'})), - }), + ['#find']: findFunction, + ['#findOptions']: findOptions, + }) => continuation({ + ['#map']: + (data + ? ref => findFunction(ref, data, findOptions) + : ref => findFunction(ref, findOptions)), + }), }, + withMappedList({ + list: input('list'), + map: '#map', + }).outputs({ + '#mappedList': '#matches', + }), + withAvailabilityFilter({ from: '#matches', }), diff --git a/src/data/composite/wiki-data/withResolvedSeriesList.js b/src/data/composite/wiki-data/withResolvedSeriesList.js deleted file mode 100644 index 4ac74cc3..00000000 --- a/src/data/composite/wiki-data/withResolvedSeriesList.js +++ /dev/null @@ -1,131 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; -import find from '#find'; -import {stitchArrays} from '#sugar'; -import {isSeriesList, validateThing} from '#validators'; - -import {raiseOutputWithoutDependency} from '#composite/control-flow'; - -import { - fillMissingListItems, - withFlattenedList, - withUnflattenedList, - withPropertiesFromList, -} from '#composite/data'; - -import withResolvedReferenceList from './withResolvedReferenceList.js'; - -export default templateCompositeFrom({ - annotation: `withResolvedSeriesList`, - - inputs: { - group: input({ - validate: validateThing({referenceType: 'group'}), - }), - - list: input({ - validate: isSeriesList, - acceptsNull: true, - }), - }, - - outputs: ['#resolvedSeriesList'], - - steps: () => [ - raiseOutputWithoutDependency({ - dependency: input('list'), - mode: input.value('empty'), - output: input.value({ - ['#resolvedSeriesList']: [], - }), - }), - - withPropertiesFromList({ - list: input('list'), - prefix: input.value('#serieses'), - properties: input.value([ - 'name', - 'description', - 'albums', - - 'showAlbumArtists', - ]), - }), - - fillMissingListItems({ - list: '#serieses.albums', - fill: input.value([]), - }), - - withFlattenedList({ - list: '#serieses.albums', - }), - - withResolvedReferenceList({ - list: '#flattenedList', - data: 'albumData', - find: input.value(find.album), - notFoundMode: input.value('null'), - }), - - withUnflattenedList({ - list: '#resolvedReferenceList', - }).outputs({ - '#unflattenedList': '#serieses.albums', - }), - - fillMissingListItems({ - list: '#serieses.description', - fill: input.value(null), - }), - - fillMissingListItems({ - list: '#serieses.showAlbumArtists', - fill: input.value(null), - }), - - { - dependencies: [ - '#serieses.name', - '#serieses.description', - '#serieses.albums', - - '#serieses.showAlbumArtists', - ], - - compute: (continuation, { - ['#serieses.name']: name, - ['#serieses.description']: description, - ['#serieses.albums']: albums, - - ['#serieses.showAlbumArtists']: showAlbumArtists, - }) => continuation({ - ['#seriesProperties']: - stitchArrays({ - name, - description, - albums, - - showAlbumArtists, - }).map(properties => ({ - ...properties, - group: input - })) - }), - }, - - { - dependencies: ['#seriesProperties', input('group')], - compute: (continuation, { - ['#seriesProperties']: seriesProperties, - [input('group')]: group, - }) => continuation({ - ['#resolvedSeriesList']: - seriesProperties - .map(properties => ({ - ...properties, - group, - })), - }), - }, - ], -}); diff --git a/src/data/composite/wiki-data/withReverseAnnotatedReferenceList.js b/src/data/composite/wiki-data/withReverseAnnotatedReferenceList.js deleted file mode 100644 index feae9ccb..00000000 --- a/src/data/composite/wiki-data/withReverseAnnotatedReferenceList.js +++ /dev/null @@ -1,116 +0,0 @@ -// Analogous implementation for withReverseReferenceList, for annotated -// references. -// -// Unlike withReverseContributionList, this composition is responsible for -// "flipping" the directionality of references: in a forward reference list, -// `thing` points to the thing being referenced, while here, it points to the -// referencing thing. -// -// This behavior can be customized to respect reference lists which are shaped -// differently than the default and/or to customize the reversed property and -// provide a less generic label than just "thing". - -import withReverseList_template from './helpers/withReverseList-template.js'; - -import {input} from '#composite'; -import {stitchArrays} from '#sugar'; - -import { - withFlattenedList, - withMappedList, - withPropertyFromList, - withStretchedList, -} from '#composite/data'; - -export default withReverseList_template({ - annotation: `withReverseAnnotatedReferenceList`, - - propertyInputName: 'list', - outputName: '#reverseAnnotatedReferenceList', - - additionalInputs: { - forward: input({type: 'string', defaultValue: 'thing'}), - backward: input({type: 'string', defaultValue: 'thing'}), - annotation: input({type: 'string', defaultValue: 'annotation'}), - }, - - customCompositionSteps: () => [ - withPropertyFromList({ - list: input('data'), - property: input('list'), - }).outputs({ - '#values': '#referenceLists', - }), - - withPropertyFromList({ - list: '#referenceLists', - property: input.value('length'), - }), - - withFlattenedList({ - list: '#referenceLists', - }).outputs({ - '#flattenedList': '#references', - }), - - withStretchedList({ - list: input('data'), - lengths: '#referenceLists.length', - }).outputs({ - '#stretchedList': '#things', - }), - - withPropertyFromList({ - list: '#references', - property: input('annotation'), - }).outputs({ - '#values': '#annotations', - }), - - withPropertyFromList({ - list: '#references', - property: input.value('date'), - }).outputs({ - '#references.date': '#dates', - }), - - { - dependencies: [ - input('backward'), - input('annotation'), - '#things', - '#annotations', - '#dates', - ], - - compute: (continuation, { - [input('backward')]: thingProperty, - [input('annotation')]: annotationProperty, - ['#things']: things, - ['#annotations']: annotations, - ['#dates']: dates, - }) => continuation({ - '#referencingThings': - stitchArrays({ - [thingProperty]: things, - [annotationProperty]: annotations, - date: dates, - }), - }), - }, - - withPropertyFromList({ - list: '#references', - property: input('forward'), - }).outputs({ - '#values': '#individualReferencedThings', - }), - - withMappedList({ - list: '#individualReferencedThings', - map: input.value(thing => [thing]), - }).outputs({ - '#mappedList': '#referencedThings', - }), - ], -}); diff --git a/src/data/composite/wiki-data/withReverseContributionList.js b/src/data/composite/wiki-data/withReverseContributionList.js deleted file mode 100644 index 2396c3b4..00000000 --- a/src/data/composite/wiki-data/withReverseContributionList.js +++ /dev/null @@ -1,37 +0,0 @@ -// Analogous implementation for withReverseReferenceList, for contributions. - -import withReverseList_template from './helpers/withReverseList-template.js'; - -import {input} from '#composite'; - -import {withFlattenedList, withMappedList, withPropertyFromList} - from '#composite/data'; - -export default withReverseList_template({ - annotation: `withReverseContributionList`, - - propertyInputName: 'list', - outputName: '#reverseContributionList', - - customCompositionSteps: () => [ - withPropertyFromList({ - list: input('data'), - property: input('list'), - }).outputs({ - '#values': '#contributionLists', - }), - - withFlattenedList({ - list: '#contributionLists', - }).outputs({ - '#flattenedList': '#referencingThings', - }), - - withMappedList({ - list: '#referencingThings', - map: input.value(contrib => [contrib.artist]), - }).outputs({ - '#mappedList': '#referencedThings', - }), - ], -}); diff --git a/src/data/composite/wiki-data/withReverseReferenceList.js b/src/data/composite/wiki-data/withReverseReferenceList.js index 70d9a58d..906f5bc5 100644 --- a/src/data/composite/wiki-data/withReverseReferenceList.js +++ b/src/data/composite/wiki-data/withReverseReferenceList.js @@ -1,44 +1,36 @@ // Check out the info on reverseReferenceList! // This is its composable form. -import withReverseList_template from './helpers/withReverseList-template.js'; +import {input, templateCompositeFrom} from '#composite'; -import {input} from '#composite'; +import gobbleSoupyReverse from './gobbleSoupyReverse.js'; +import inputSoupyReverse from './inputSoupyReverse.js'; +import inputWikiData from './inputWikiData.js'; -import {withMappedList} from '#composite/data'; +import withResolvedReverse from './helpers/withResolvedReverse.js'; -export default withReverseList_template({ +export default templateCompositeFrom({ annotation: `withReverseReferenceList`, - propertyInputName: 'list', - outputName: '#reverseReferenceList', - - customCompositionSteps: () => [ - { - dependencies: [input('list')], - compute: (continuation, { - [input('list')]: list, - }) => continuation({ - ['#referenceMap']: - thing => thing[list], - }), - }, - - withMappedList({ - list: input('data'), - map: '#referenceMap', - }).outputs({ - '#mappedList': '#referencedThings', + inputs: { + data: inputWikiData({allowMixedTypes: true}), + reverse: inputSoupyReverse(), + }, + + outputs: ['#reverseReferenceList'], + + steps: () => [ + gobbleSoupyReverse({ + reverse: input('reverse'), }), - { - dependencies: [input('data')], - compute: (continuation, { - [input('data')]: data, - }) => continuation({ - ['#referencingThings']: - data, - }), - }, + // TODO: Check that the reverse spec returns a list. + + withResolvedReverse({ + data: input('data'), + reverse: '#reverse', + }).outputs({ + '#resolvedReverse': '#reverseReferenceList', + }), ], }); diff --git a/src/data/composite/wiki-data/withReverseSingleReferenceList.js b/src/data/composite/wiki-data/withReverseSingleReferenceList.js deleted file mode 100644 index dd97dc66..00000000 --- a/src/data/composite/wiki-data/withReverseSingleReferenceList.js +++ /dev/null @@ -1,50 +0,0 @@ -// Like withReverseReferenceList, but for finding all things which reference -// the current thing by a property that contains a single reference, rather -// than within a reference list. - -import withReverseList_template from './helpers/withReverseList-template.js'; - -import {input} from '#composite'; - -import {withMappedList} from '#composite/data'; - -export default withReverseList_template({ - annotation: `withReverseSingleReferenceList`, - - propertyInputName: 'ref', - outputName: '#reverseSingleReferenceList', - - customCompositionSteps: () => [ - { - dependencies: [input('data')], - compute: (continuation, { - [input('data')]: data, - }) => continuation({ - ['#referencingThings']: - data, - }), - }, - - // This map wraps each referenced thing in a single-item array. - // Each referencing thing references exactly one thing, if any. - { - dependencies: [input('ref')], - compute: (continuation, { - [input('ref')]: ref, - }) => continuation({ - ['#singleReferenceMap']: - thing => - (thing[ref] - ? [thing[ref]] - : []), - }), - }, - - withMappedList({ - list: '#referencingThings', - map: '#singleReferenceMap', - }).outputs({ - '#mappedList': '#referencedThings', - }), - ], -}); diff --git a/src/data/composite/wiki-data/withUniqueReferencingThing.js b/src/data/composite/wiki-data/withUniqueReferencingThing.js index 61c10618..7c267038 100644 --- a/src/data/composite/wiki-data/withUniqueReferencingThing.js +++ b/src/data/composite/wiki-data/withUniqueReferencingThing.js @@ -4,48 +4,33 @@ import {input, templateCompositeFrom} from '#composite'; -import {exitWithoutDependency, raiseOutputWithoutDependency} - from '#composite/control-flow'; - +import gobbleSoupyReverse from './gobbleSoupyReverse.js'; +import inputSoupyReverse from './inputSoupyReverse.js'; import inputWikiData from './inputWikiData.js'; -import withReverseReferenceList from './withReverseReferenceList.js'; + +import withResolvedReverse from './helpers/withResolvedReverse.js'; export default templateCompositeFrom({ annotation: `withUniqueReferencingThing`, inputs: { - data: inputWikiData({allowMixedTypes: false}), - list: input({type: 'string'}), + data: inputWikiData({allowMixedTypes: true}), + reverse: inputSoupyReverse(), }, outputs: ['#uniqueReferencingThing'], steps: () => [ - // Early exit with null (not an empty array) if the data list - // isn't available. - exitWithoutDependency({ - dependency: input('data'), + gobbleSoupyReverse({ + reverse: input('reverse'), }), - withReverseReferenceList({ + withResolvedReverse({ data: input('data'), - list: input('list'), + reverse: '#reverse', + options: input.value({unique: true}), + }).outputs({ + '#resolvedReverse': '#uniqueReferencingThing', }), - - raiseOutputWithoutDependency({ - dependency: '#reverseReferenceList', - mode: input.value('empty'), - output: input.value({'#uniqueReferencingThing': null}), - }), - - { - dependencies: ['#reverseReferenceList'], - compute: (continuation, { - ['#reverseReferenceList']: reverseReferenceList, - }) => continuation({ - ['#uniqueReferencingThing']: - reverseReferenceList[0], - }), - }, ], }); diff --git a/src/data/composite/wiki-properties/additionalFiles.js b/src/data/composite/wiki-properties/additionalFiles.js deleted file mode 100644 index 6760527a..00000000 --- a/src/data/composite/wiki-properties/additionalFiles.js +++ /dev/null @@ -1,30 +0,0 @@ -// 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: [...]}, -// ... -// ] -// - -import {isAdditionalFileList} from '#validators'; - -// TODO: Not templateCompositeFrom. - -export default function() { - return { - flags: {update: true, expose: true}, - update: {validate: isAdditionalFileList}, - expose: { - transform: (additionalFiles) => - additionalFiles ?? [], - }, - }; -} diff --git a/src/data/composite/wiki-properties/additionalNameList.js b/src/data/composite/wiki-properties/additionalNameList.js deleted file mode 100644 index c5971d4a..00000000 --- a/src/data/composite/wiki-properties/additionalNameList.js +++ /dev/null @@ -1,14 +0,0 @@ -// A list of additional names! These can be used for a variety of purposes, -// e.g. providing extra searchable titles, localizations, romanizations or -// original titles, and so on. Each item has a name and, optionally, a -// descriptive annotation. - -import {isAdditionalNameList} from '#validators'; - -export default function() { - return { - flags: {update: true, expose: true}, - update: {validate: isAdditionalNameList}, - expose: {transform: value => value ?? []}, - }; -} diff --git a/src/data/composite/wiki-properties/annotatedReferenceList.js b/src/data/composite/wiki-properties/annotatedReferenceList.js index d6364475..918f8567 100644 --- a/src/data/composite/wiki-properties/annotatedReferenceList.js +++ b/src/data/composite/wiki-properties/annotatedReferenceList.js @@ -1,10 +1,7 @@ import {input, templateCompositeFrom} from '#composite'; -import find from '#find'; -import {combineWikiDataArrays} from '#wiki-data'; import { isContentString, - isDate, optional, validateArrayItems, validateProperties, @@ -12,8 +9,13 @@ import { } from '#validators'; import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withResolvedAnnotatedReferenceList} - from '#composite/wiki-data'; + +import { + inputFindOptions, + inputSoupyFind, + inputWikiData, + withResolvedAnnotatedReferenceList, +} from '#composite/wiki-data'; import {referenceListInputDescriptions, referenceListUpdateDescription} from './helpers/reference-list-helpers.js'; @@ -27,12 +29,8 @@ export default templateCompositeFrom({ ...referenceListInputDescriptions(), data: inputWikiData({allowMixedTypes: true}), - find: input({type: 'function'}), - - date: input({ - validate: isDate, - acceptsNull: true, - }), + find: inputSoupyFind(), + findOptions: inputFindOptions(), reference: input.staticValue({type: 'string', defaultValue: 'reference'}), annotation: input.staticValue({type: 'string', defaultValue: 'annotation'}), @@ -59,14 +57,13 @@ export default templateCompositeFrom({ withResolvedAnnotatedReferenceList({ list: input.updateValue(), - date: input('date'), + data: input('data'), + find: input('find'), + findOptions: input('findOptions'), reference: input('reference'), annotation: input('annotation'), thing: input('thing'), - - data: input('data'), - find: input('find'), }), exposeDependency({dependency: '#resolvedAnnotatedReferenceList'}), diff --git a/src/data/composite/wiki-properties/canonicalBase.js b/src/data/composite/wiki-properties/canonicalBase.js new file mode 100644 index 00000000..81740d6c --- /dev/null +++ b/src/data/composite/wiki-properties/canonicalBase.js @@ -0,0 +1,16 @@ +import {isURL} from '#validators'; + +export default function() { + return { + flags: {update: true, expose: true}, + update: {validate: isURL}, + expose: { + transform: (value) => + (value === null + ? null + : value.endsWith('/') + ? value + : value + '/'), + }, + }; +} diff --git a/src/data/composite/wiki-properties/color.js b/src/data/composite/wiki-properties/color.js index 1bc9888b..e7fe472a 100644 --- a/src/data/composite/wiki-properties/color.js +++ b/src/data/composite/wiki-properties/color.js @@ -1,12 +1,26 @@ // A color! This'll be some CSS-ready value. +import {input, templateCompositeFrom} from '#composite'; import {isColor} from '#validators'; -// TODO: Not templateCompositeFrom. +export default templateCompositeFrom({ + annotation: 'color', -export default function() { - return { - flags: {update: true, expose: true}, - update: {validate: isColor}, - }; -} + compose: false, + + inputs: { + default: input({validate: isColor, defaultValue: null}), + }, + + update: { + validate: isColor, + }, + + steps: () => [ + { + dependencies: [input('default')], + transform: (value, {[input('default')]: defaultValue}) => + value ?? defaultValue, + }, + ], +}); \ No newline at end of file diff --git a/src/data/composite/wiki-properties/commentary.js b/src/data/composite/wiki-properties/commentary.js deleted file mode 100644 index cd6b7ac4..00000000 --- a/src/data/composite/wiki-properties/commentary.js +++ /dev/null @@ -1,30 +0,0 @@ -// Artist commentary! Generally present on tracks and albums. - -import {input, templateCompositeFrom} from '#composite'; -import {isCommentary} from '#validators'; - -import {exitWithoutDependency, exposeDependency} - from '#composite/control-flow'; -import {withParsedCommentaryEntries} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `commentary`, - - compose: false, - - steps: () => [ - exitWithoutDependency({ - dependency: input.updateValue({validate: isCommentary}), - mode: input.value('falsy'), - value: input.value(null), - }), - - withParsedCommentaryEntries({ - from: input.updateValue(), - }), - - exposeDependency({ - dependency: '#parsedCommentaryEntries', - }), - ], -}); diff --git a/src/data/composite/wiki-properties/commentatorArtists.js b/src/data/composite/wiki-properties/commentatorArtists.js index c5c14769..44dee028 100644 --- a/src/data/composite/wiki-properties/commentatorArtists.js +++ b/src/data/composite/wiki-properties/commentatorArtists.js @@ -7,7 +7,6 @@ import {exitWithoutDependency, exposeDependency} from '#composite/control-flow'; import {withFlattenedList, withPropertyFromList, withUniqueItemsOnly} from '#composite/data'; -import {withParsedCommentaryEntries} from '#composite/wiki-data'; export default templateCompositeFrom({ annotation: `commentatorArtists`, @@ -15,25 +14,18 @@ export default templateCompositeFrom({ compose: false, steps: () => [ - exitWithoutDependency({ - dependency: 'commentary', - mode: input.value('falsy'), + exitWithoutDependency('commentary', { value: input.value([]), - }), - - withParsedCommentaryEntries({ - from: 'commentary', + mode: input.value('falsy'), }), withPropertyFromList({ - list: '#parsedCommentaryEntries', + list: 'commentary', property: input.value('artists'), - }).outputs({ - '#parsedCommentaryEntries.artists': '#artistLists', }), withFlattenedList({ - list: '#artistLists', + list: '#commentary.artists', }).outputs({ '#flattenedList': '#artists', }), diff --git a/src/data/composite/wiki-properties/constitutibleArtwork.js b/src/data/composite/wiki-properties/constitutibleArtwork.js new file mode 100644 index 00000000..48f4211a --- /dev/null +++ b/src/data/composite/wiki-properties/constitutibleArtwork.js @@ -0,0 +1,70 @@ +// This composition does not actually inspect the values of any properties +// specified, so it's not responsible for determining whether a constituted +// artwork should exist at all. + +import {input, templateCompositeFrom} from '#composite'; +import {withEntries} from '#sugar'; +import Thing from '#thing'; +import {validateThing} from '#validators'; + +import {exposeDependency, exposeUpdateValueOrContinue} + from '#composite/control-flow'; +import {withConstitutedArtwork} from '#composite/wiki-data'; + +const template = templateCompositeFrom({ + annotation: `constitutibleArtwork`, + + compose: false, + + inputs: { + thingProperty: input({type: 'string', acceptsNull: true}), + dimensionsFromThingProperty: input({type: 'string', acceptsNull: true}), + fileExtensionFromThingProperty: input({type: 'string', acceptsNull: true}), + dateFromThingProperty: input({type: 'string', acceptsNull: true}), + artistContribsFromThingProperty: input({type: 'string', acceptsNull: true}), + artistContribsArtistProperty: input({type: 'string', acceptsNull: true}), + artTagsFromThingProperty: input({type: 'string', acceptsNull: true}), + referencedArtworksFromThingProperty: input({type: 'string', acceptsNull: true}), + }, + + steps: () => [ + exposeUpdateValueOrContinue({ + validate: input.value( + validateThing({ + referenceType: 'artwork', + })), + }), + + withConstitutedArtwork({ + thingProperty: input('thingProperty'), + dimensionsFromThingProperty: input('dimensionsFromThingProperty'), + fileExtensionFromThingProperty: input('fileExtensionFromThingProperty'), + dateFromThingProperty: input('dateFromThingProperty'), + artistContribsFromThingProperty: input('artistContribsFromThingProperty'), + artistContribsArtistProperty: input('artistContribsArtistProperty'), + artTagsFromThingProperty: input('artTagsFromThingProperty'), + referencedArtworksFromThingProperty: input('referencedArtworksFromThingProperty'), + }), + + exposeDependency({ + dependency: '#constitutedArtwork', + }), + ], +}); + +template.fromYAMLFieldSpec = function(field) { + const {[Thing.yamlDocumentSpec]: documentSpec} = this; + + const {provide} = documentSpec.fields[field].transform; + + const inputs = + withEntries(provide, entries => + entries.map(([property, value]) => [ + property, + input.value(value), + ])); + + return template(inputs); +}; + +export default template; diff --git a/src/data/composite/wiki-properties/constitutibleArtworkList.js b/src/data/composite/wiki-properties/constitutibleArtworkList.js new file mode 100644 index 00000000..dad3a957 --- /dev/null +++ b/src/data/composite/wiki-properties/constitutibleArtworkList.js @@ -0,0 +1,72 @@ +// This composition does not actually inspect the values of any properties +// specified, so it's not responsible for determining whether a constituted +// artwork should exist at all. + +import {input, templateCompositeFrom} from '#composite'; +import {withEntries} from '#sugar'; +import Thing from '#thing'; +import {validateWikiData} from '#validators'; + +import {exposeUpdateValueOrContinue} from '#composite/control-flow'; +import {withConstitutedArtwork} from '#composite/wiki-data'; + +const template = templateCompositeFrom({ + annotation: `constitutibleArtworkList`, + + compose: false, + + inputs: { + thingProperty: input({type: 'string', acceptsNull: true}), + dimensionsFromThingProperty: input({type: 'string', acceptsNull: true}), + fileExtensionFromThingProperty: input({type: 'string', acceptsNull: true}), + dateFromThingProperty: input({type: 'string', acceptsNull: true}), + artistContribsFromThingProperty: input({type: 'string', acceptsNull: true}), + artistContribsArtistProperty: input({type: 'string', acceptsNull: true}), + artTagsFromThingProperty: input({type: 'string', acceptsNull: true}), + referencedArtworksFromThingProperty: input({type: 'string', acceptsNull: true}), + }, + + steps: () => [ + exposeUpdateValueOrContinue({ + validate: input.value( + validateWikiData({ + referenceType: 'artwork', + })), + }), + + withConstitutedArtwork({ + thingProperty: input('thingProperty'), + dimensionsFromThingProperty: input('dimensionsFromThingProperty'), + fileExtensionFromThingProperty: input('fileExtensionFromThingProperty'), + dateFromThingProperty: input('dateFromThingProperty'), + artistContribsFromThingProperty: input('artistContribsFromThingProperty'), + artistContribsArtistProperty: input('artistContribsArtistProperty'), + artTagsFromThingProperty: input('artTagsFromThingProperty'), + referencedArtworksFromThingProperty: input('referencedArtworksFromThingProperty'), + }), + + { + dependencies: ['#constitutedArtwork'], + compute: ({ + ['#constitutedArtwork']: constitutedArtwork, + }) => [constitutedArtwork], + }, + ], +}); + +template.fromYAMLFieldSpec = function(field) { + const {[Thing.yamlDocumentSpec]: documentSpec} = this; + + const {provide} = documentSpec.fields[field].transform; + + const inputs = + withEntries(provide, entries => + entries.map(([property, value]) => [ + property, + input.value(value), + ])); + + return template(inputs); +}; + +export default template; diff --git a/src/data/composite/wiki-properties/contribsPresent.js b/src/data/composite/wiki-properties/contribsPresent.js deleted file mode 100644 index 24f302a5..00000000 --- a/src/data/composite/wiki-properties/contribsPresent.js +++ /dev/null @@ -1,30 +0,0 @@ -// Nice 'n simple shorthand for an exposed-only flag which is true when any -// contributions are present in the specified property. - -import {input, templateCompositeFrom} from '#composite'; -import {isContributionList} from '#validators'; - -import {exposeDependency, withResultOfAvailabilityCheck} - from '#composite/control-flow'; - -export default templateCompositeFrom({ - annotation: `contribsPresent`, - - compose: false, - - inputs: { - contribs: input.staticDependency({ - validate: isContributionList, - acceptsNull: true, - }), - }, - - steps: () => [ - withResultOfAvailabilityCheck({ - from: input('contribs'), - mode: input.value('empty'), - }), - - exposeDependency({dependency: '#availability'}), - ], -}); diff --git a/src/data/composite/wiki-properties/contributionList.js b/src/data/composite/wiki-properties/contributionList.js index d9a6b417..04f93b52 100644 --- a/src/data/composite/wiki-properties/contributionList.js +++ b/src/data/composite/wiki-properties/contributionList.js @@ -29,6 +29,7 @@ export default templateCompositeFrom({ date: input({ validate: isDate, acceptsNull: true, + defaultDependency: 'date', }), artistProperty: input({ @@ -42,9 +43,9 @@ export default templateCompositeFrom({ steps: () => [ withResolvedContribs({ from: input.updateValue(), + date: input('date'), thingProperty: input.thisProperty(), artistProperty: input('artistProperty'), - date: input('date'), }), exposeDependencyOrContinue({ diff --git a/src/data/composite/wiki-properties/directory.js b/src/data/composite/wiki-properties/directory.js index 9ca2a204..1756a8e5 100644 --- a/src/data/composite/wiki-properties/directory.js +++ b/src/data/composite/wiki-properties/directory.js @@ -18,6 +18,7 @@ export default templateCompositeFrom({ name: input({ validate: isName, defaultDependency: 'name', + acceptsNull: true, }), suffix: input({ diff --git a/src/data/composite/wiki-properties/fileExtension.js b/src/data/composite/wiki-properties/fileExtension.js index c926fa8b..fa933f56 100644 --- a/src/data/composite/wiki-properties/fileExtension.js +++ b/src/data/composite/wiki-properties/fileExtension.js @@ -1,13 +1,26 @@ // A file extension! Or the default, if provided when calling this. +import {input, templateCompositeFrom} from '#composite'; import {isFileExtension} from '#validators'; -// TODO: Not templateCompositeFrom. +export default templateCompositeFrom({ + annotation: 'name', -export default function(defaultFileExtension = null) { - return { - flags: {update: true, expose: true}, - update: {validate: isFileExtension}, - expose: {transform: (value) => value ?? defaultFileExtension}, - }; -} + compose: false, + + inputs: { + default: input({validate: isFileExtension, acceptsNull: true}), + }, + + update: { + validate: isFileExtension, + }, + + steps: () => [ + { + dependencies: [input('default')], + transform: (value, {[input('default')]: defaultValue}) => + value ?? defaultValue, + }, + ], +}); \ No newline at end of file diff --git a/src/data/composite/wiki-properties/flag.js b/src/data/composite/wiki-properties/flag.js index 076e663f..fa787f92 100644 --- a/src/data/composite/wiki-properties/flag.js +++ b/src/data/composite/wiki-properties/flag.js @@ -1,19 +1,27 @@ // Straightforward flag descriptor for a variety of property purposes. // Provide a default value, true or false! +import {input, templateCompositeFrom} from '#composite'; import {isBoolean} from '#validators'; -// TODO: Not templateCompositeFrom. +export default templateCompositeFrom({ + annotation: 'flag', -// TODO: The description is a lie. This defaults to false. Bad. + compose: false, -export default function(defaultValue = false) { - if (typeof defaultValue !== 'boolean') { - throw new TypeError(`Always set explicit defaults for flags!`); - } + inputs: { + default: input({type: 'boolean'}), + }, - return { - flags: {update: true, expose: true}, - update: {validate: isBoolean, default: defaultValue}, - }; -} + update: { + validate: isBoolean, + }, + + steps: () => [ + { + dependencies: [input('default')], + transform: (value, {[input('default')]: defaultValue}) => + value ?? defaultValue, + }, + ], +}); \ No newline at end of file diff --git a/src/data/composite/wiki-properties/hasArtwork.js b/src/data/composite/wiki-properties/hasArtwork.js new file mode 100644 index 00000000..e403a7e2 --- /dev/null +++ b/src/data/composite/wiki-properties/hasArtwork.js @@ -0,0 +1,90 @@ +import {input, templateCompositeFrom, V} from '#composite'; +import {isContributionList, isThing, strictArrayOf} from '#validators'; + +import {fillMissingListItems, withFlattenedList, withPropertyFromList} + from '#composite/data'; + +import { + exitWithoutDependency, + exposeWhetherDependencyAvailable, + withResultOfAvailabilityCheck, +} from '#composite/control-flow'; + +export default templateCompositeFrom({ + annotation: 'hasArtwork', + + inputs: { + contribs: input({ + validate: isContributionList, + defaultValue: null, + }), + + artwork: input({ + validate: isThing, + defaultValue: null, + }), + + artworks: input({ + validate: strictArrayOf(isThing), + defaultValue: null, + }), + }, + + compose: false, + + steps: () => [ + withResultOfAvailabilityCheck({ + from: input('contribs'), + mode: input.value('empty'), + }), + + { + dependencies: ['#availability'], + compute: (continuation, { + ['#availability']: availability, + }) => + (availability + ? true + : continuation()), + }, + + { + dependencies: [input('artwork'), input('artworks')], + compute: (continuation, { + [input('artwork')]: artwork, + [input('artworks')]: artworks, + }) => + continuation({ + ['#artworks']: + (artwork && artworks + ? [artwork, ...artworks] + : artwork + ? [artwork] + : artworks + ? artworks + : []), + }), + }, + + exitWithoutDependency('#artworks', { + value: input.value(false), + mode: input.value('empty'), + }), + + withPropertyFromList('#artworks', { + property: input.value('artistContribs'), + internal: input.value(true), + }), + + // Since we're getting the update value for each artwork's artistContribs, + // it may not be set at all, and in that case won't be exposing as []. + fillMissingListItems('#artworks.artistContribs', V([])), + + withFlattenedList('#artworks.artistContribs'), + + exposeWhetherDependencyAvailable({ + dependency: '#flattenedList', + mode: input.value('empty'), + }), + ], +}); \ No newline at end of file diff --git a/src/data/composite/wiki-properties/index.js b/src/data/composite/wiki-properties/index.js index b55616c0..9ef7ccc4 100644 --- a/src/data/composite/wiki-properties/index.js +++ b/src/data/composite/wiki-properties/index.js @@ -3,14 +3,13 @@ // Entries here may depend on entries in #composite/control-flow, // #composite/data, and #composite/wiki-data. -export {default as additionalFiles} from './additionalFiles.js'; -export {default as additionalNameList} from './additionalNameList.js'; export {default as annotatedReferenceList} from './annotatedReferenceList.js'; +export {default as canonicalBase} from './canonicalBase.js'; export {default as color} from './color.js'; -export {default as commentary} from './commentary.js'; export {default as commentatorArtists} from './commentatorArtists.js'; +export {default as constitutibleArtwork} from './constitutibleArtwork.js'; +export {default as constitutibleArtworkList} from './constitutibleArtworkList.js'; export {default as contentString} from './contentString.js'; -export {default as contribsPresent} from './contribsPresent.js'; export {default as contributionList} from './contributionList.js'; export {default as dimensions} from './dimensions.js'; export {default as directory} from './directory.js'; @@ -18,18 +17,16 @@ export {default as duration} from './duration.js'; export {default as externalFunction} from './externalFunction.js'; export {default as fileExtension} from './fileExtension.js'; export {default as flag} from './flag.js'; +export {default as hasArtwork} from './hasArtwork.js'; export {default as name} from './name.js'; export {default as referenceList} from './referenceList.js'; export {default as referencedArtworkList} from './referencedArtworkList.js'; -export {default as reverseAnnotatedReferenceList} from './reverseAnnotatedReferenceList.js'; -export {default as reverseContributionList} from './reverseContributionList.js'; export {default as reverseReferenceList} from './reverseReferenceList.js'; -export {default as reverseReferencedArtworkList} from './reverseReferencedArtworkList.js'; -export {default as reverseSingleReferenceList} from './reverseSingleReferenceList.js'; -export {default as seriesList} from './seriesList.js'; export {default as simpleDate} from './simpleDate.js'; export {default as simpleString} from './simpleString.js'; export {default as singleReference} from './singleReference.js'; +export {default as soupyFind} from './soupyFind.js'; +export {default as soupyReverse} from './soupyReverse.js'; export {default as thing} from './thing.js'; export {default as thingList} from './thingList.js'; export {default as urls} from './urls.js'; diff --git a/src/data/composite/wiki-properties/name.js b/src/data/composite/wiki-properties/name.js index 5146488b..e4a28860 100644 --- a/src/data/composite/wiki-properties/name.js +++ b/src/data/composite/wiki-properties/name.js @@ -1,11 +1,27 @@ // A wiki data object's name! Its directory (i.e. unique identifier) will be // computed based on this value if not otherwise specified. +import {input, templateCompositeFrom} from '#composite'; import {isName} from '#validators'; -export default function(defaultName) { - return { - flags: {update: true, expose: true}, - update: {validate: isName, default: defaultName}, - }; -} +export default templateCompositeFrom({ + annotation: 'name', + + compose: false, + + inputs: { + default: input({type: 'string'}), + }, + + update: { + validate: isName, + }, + + steps: () => [ + { + dependencies: [input('default')], + transform: (value, {[input('default')]: defaultValue}) => + value ?? defaultValue, + }, + ], +}); \ No newline at end of file diff --git a/src/data/composite/wiki-properties/referenceList.js b/src/data/composite/wiki-properties/referenceList.js index 4d4cb106..663349ee 100644 --- a/src/data/composite/wiki-properties/referenceList.js +++ b/src/data/composite/wiki-properties/referenceList.js @@ -11,7 +11,13 @@ import {input, templateCompositeFrom} from '#composite'; import {validateReferenceList} from '#validators'; import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withResolvedReferenceList} from '#composite/wiki-data'; + +import { + inputFindOptions, + inputSoupyFind, + inputWikiData, + withResolvedReferenceList, +} from '#composite/wiki-data'; import {referenceListInputDescriptions, referenceListUpdateDescription} from './helpers/reference-list-helpers.js'; @@ -25,7 +31,8 @@ export default templateCompositeFrom({ ...referenceListInputDescriptions(), data: inputWikiData({allowMixedTypes: true}), - find: input({type: 'function'}), + find: inputSoupyFind(), + findOptions: inputFindOptions(), }, update: @@ -38,6 +45,7 @@ export default templateCompositeFrom({ list: input.updateValue(), data: input('data'), find: input('find'), + findOptions: input('findOptions'), }), exposeDependency({dependency: '#resolvedReferenceList'}), diff --git a/src/data/composite/wiki-properties/referencedArtworkList.js b/src/data/composite/wiki-properties/referencedArtworkList.js index 819b2f43..278f063d 100644 --- a/src/data/composite/wiki-properties/referencedArtworkList.js +++ b/src/data/composite/wiki-properties/referencedArtworkList.js @@ -1,7 +1,5 @@ import {input, templateCompositeFrom} from '#composite'; import find from '#find'; -import {isDate} from '#validators'; -import {combineWikiDataArrays} from '#wiki-data'; import annotatedReferenceList from './annotatedReferenceList.js'; @@ -10,47 +8,24 @@ export default templateCompositeFrom({ compose: false, - inputs: { - date: input({ - validate: isDate, - acceptsNull: true, - }), - }, - steps: () => [ { - dependencies: [ - 'albumData', - 'trackData', - ], - - compute: (continuation, { - albumData, - trackData, - }) => continuation({ - ['#data']: - combineWikiDataArrays([ - albumData, - trackData, - ]), - }), - }, - - { compute: (continuation) => continuation({ ['#find']: find.mixed({ - track: find.trackWithArtwork, - album: find.albumWithArtwork, + track: find.trackPrimaryArtwork, + album: find.albumPrimaryArtwork, }), }), }, annotatedReferenceList({ referenceType: input.value(['album', 'track']), - data: '#data', + + data: '_artworkData', find: '#find', - date: input('date'), + + thing: input.value('artwork'), }), ], }); diff --git a/src/data/composite/wiki-properties/reverseAnnotatedReferenceList.js b/src/data/composite/wiki-properties/reverseAnnotatedReferenceList.js deleted file mode 100644 index ba7166b9..00000000 --- a/src/data/composite/wiki-properties/reverseAnnotatedReferenceList.js +++ /dev/null @@ -1,33 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withReverseAnnotatedReferenceList} - from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `reverseAnnotatedReferenceList`, - - compose: false, - - inputs: { - data: inputWikiData({allowMixedTypes: false}), - list: input({type: 'string'}), - - forward: input({type: 'string', defaultValue: 'thing'}), - backward: input({type: 'string', defaultValue: 'thing'}), - annotation: input({type: 'string', defaultValue: 'annotation'}), - }, - - steps: () => [ - withReverseAnnotatedReferenceList({ - data: input('data'), - list: input('list'), - - forward: input('forward'), - backward: input('backward'), - annotation: input('annotation'), - }), - - exposeDependency({dependency: '#reverseAnnotatedReferenceList'}), - ], -}); diff --git a/src/data/composite/wiki-properties/reverseContributionList.js b/src/data/composite/wiki-properties/reverseContributionList.js deleted file mode 100644 index 7f3f9c81..00000000 --- a/src/data/composite/wiki-properties/reverseContributionList.js +++ /dev/null @@ -1,24 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withReverseContributionList} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `reverseContributionList`, - - compose: false, - - inputs: { - data: inputWikiData({allowMixedTypes: false}), - list: input({type: 'string'}), - }, - - steps: () => [ - withReverseContributionList({ - data: input('data'), - list: input('list'), - }), - - exposeDependency({dependency: '#reverseContributionList'}), - ], -}); diff --git a/src/data/composite/wiki-properties/reverseReferenceList.js b/src/data/composite/wiki-properties/reverseReferenceList.js index 84ba67df..6d590a67 100644 --- a/src/data/composite/wiki-properties/reverseReferenceList.js +++ b/src/data/composite/wiki-properties/reverseReferenceList.js @@ -1,13 +1,13 @@ // 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. +// property. import {input, templateCompositeFrom} from '#composite'; import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withReverseReferenceList} from '#composite/wiki-data'; +import {inputSoupyReverse, inputWikiData, withReverseReferenceList} + from '#composite/wiki-data'; export default templateCompositeFrom({ annotation: `reverseReferenceList`, @@ -15,14 +15,14 @@ export default templateCompositeFrom({ compose: false, inputs: { - data: inputWikiData({allowMixedTypes: false}), - list: input({type: 'string'}), + data: inputWikiData({allowMixedTypes: true}), + reverse: inputSoupyReverse(), }, steps: () => [ withReverseReferenceList({ data: input('data'), - list: input('list'), + reverse: input('reverse'), }), exposeDependency({dependency: '#reverseReferenceList'}), diff --git a/src/data/composite/wiki-properties/reverseReferencedArtworkList.js b/src/data/composite/wiki-properties/reverseReferencedArtworkList.js deleted file mode 100644 index 2950bdb9..00000000 --- a/src/data/composite/wiki-properties/reverseReferencedArtworkList.js +++ /dev/null @@ -1,39 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; -import {combineWikiDataArrays} from '#wiki-data'; - -import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withReverseAnnotatedReferenceList} - from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `reverseReferencedArtworkList`, - - compose: false, - - steps: () => [ - { - dependencies: [ - 'albumData', - 'trackData', - ], - - compute: (continuation, { - albumData, - trackData, - }) => continuation({ - ['#data']: - combineWikiDataArrays([ - albumData, - trackData, - ]), - }), - }, - - withReverseAnnotatedReferenceList({ - data: '#data', - list: input.value('referencedArtworks'), - }), - - exposeDependency({dependency: '#reverseAnnotatedReferenceList'}), - ], -}); diff --git a/src/data/composite/wiki-properties/reverseSingleReferenceList.js b/src/data/composite/wiki-properties/reverseSingleReferenceList.js deleted file mode 100644 index d180b12d..00000000 --- a/src/data/composite/wiki-properties/reverseSingleReferenceList.js +++ /dev/null @@ -1,24 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; - -import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withReverseSingleReferenceList} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `reverseSingleReferenceList`, - - compose: false, - - inputs: { - data: inputWikiData({allowMixedTypes: false}), - ref: input({type: 'string'}), - }, - - steps: () => [ - withReverseSingleReferenceList({ - data: input('data'), - ref: input('ref'), - }), - - exposeDependency({dependency: '#reverseSingleReferenceList'}), - ], -}); diff --git a/src/data/composite/wiki-properties/seriesList.js b/src/data/composite/wiki-properties/seriesList.js deleted file mode 100644 index 2a101b45..00000000 --- a/src/data/composite/wiki-properties/seriesList.js +++ /dev/null @@ -1,31 +0,0 @@ -import {input, templateCompositeFrom} from '#composite'; -import {isSeriesList, validateThing} from '#validators'; - -import {exposeDependency} from '#composite/control-flow'; -import {withResolvedSeriesList} from '#composite/wiki-data'; - -export default templateCompositeFrom({ - annotation: `seriesList`, - - compose: false, - - inputs: { - group: input({ - validate: validateThing({referenceType: 'group'}), - }), - }, - - steps: () => [ - withResolvedSeriesList({ - group: input('group'), - - list: input.updateValue({ - validate: isSeriesList, - }), - }), - - exposeDependency({ - dependency: '#resolvedSeriesList', - }), - ], -}); diff --git a/src/data/composite/wiki-properties/singleReference.js b/src/data/composite/wiki-properties/singleReference.js index db4fc9f9..25b97907 100644 --- a/src/data/composite/wiki-properties/singleReference.js +++ b/src/data/composite/wiki-properties/singleReference.js @@ -8,10 +8,19 @@ // import {input, templateCompositeFrom} from '#composite'; -import {isThingClass, validateReference} from '#validators'; +import {validateReference} from '#validators'; import {exposeDependency} from '#composite/control-flow'; -import {inputWikiData, withResolvedReference} from '#composite/wiki-data'; + +import { + inputFindOptions, + inputSoupyFind, + inputWikiData, + withResolvedReference, +} from '#composite/wiki-data'; + +import {referenceListInputDescriptions, referenceListUpdateDescription} + from './helpers/reference-list-helpers.js'; export default templateCompositeFrom({ annotation: `singleReference`, @@ -19,26 +28,24 @@ export default templateCompositeFrom({ compose: false, inputs: { - class: input.staticValue({validate: isThingClass}), + ...referenceListInputDescriptions(), - find: input({type: 'function'}), - - data: inputWikiData({allowMixedTypes: false}), + data: inputWikiData({allowMixedTypes: true}), + find: inputSoupyFind(), + findOptions: inputFindOptions(), }, - update: ({ - [input.staticValue('class')]: thingClass, - }) => ({ - validate: - validateReference( - thingClass[Symbol.for('Thing.referenceType')]), - }), + update: + referenceListUpdateDescription({ + validateReferenceList: validateReference, + }), steps: () => [ withResolvedReference({ ref: input.updateValue(), data: input('data'), find: input('find'), + findOptions: input('findOptions'), }), exposeDependency({dependency: '#resolvedReference'}), diff --git a/src/data/composite/wiki-properties/soupyFind.js b/src/data/composite/wiki-properties/soupyFind.js new file mode 100644 index 00000000..0f9a17e3 --- /dev/null +++ b/src/data/composite/wiki-properties/soupyFind.js @@ -0,0 +1,14 @@ +import {isObject} from '#validators'; + +import {inputSoupyFind} from '#composite/wiki-data'; + +function soupyFind() { + return { + flags: {update: true}, + update: {validate: isObject}, + }; +} + +soupyFind.input = inputSoupyFind.input; + +export default soupyFind; diff --git a/src/data/composite/wiki-properties/soupyReverse.js b/src/data/composite/wiki-properties/soupyReverse.js new file mode 100644 index 00000000..784a66b4 --- /dev/null +++ b/src/data/composite/wiki-properties/soupyReverse.js @@ -0,0 +1,37 @@ +import {isObject} from '#validators'; + +import {inputSoupyReverse} from '#composite/wiki-data'; + +function soupyReverse() { + return { + flags: {update: true}, + update: {validate: isObject}, + }; +} + +soupyReverse.input = inputSoupyReverse.input; + +soupyReverse.contributionsBy = + (bindTo, contributionsProperty) => ({ + bindTo, + + referencing: thing => thing[contributionsProperty], + referenced: contrib => [contrib.artist], + }); + +soupyReverse.artworkContributionsBy = + (bindTo, artworkProperty, {single = false} = {}) => ({ + bindTo, + + referencing: thing => + (single + ? (thing[artworkProperty] + ? thing[artworkProperty].artistContribs + : []) + : thing[artworkProperty] + .flatMap(artwork => artwork.artistContribs)), + + referenced: contrib => [contrib.artist], + }); + +export default soupyReverse; diff --git a/src/data/language.js b/src/data/language.js index 3edf7e51..e97267c0 100644 --- a/src/data/language.js +++ b/src/data/language.js @@ -4,12 +4,10 @@ import path from 'node:path'; import {fileURLToPath} from 'node:url'; import chokidar from 'chokidar'; -import he from 'he'; // It stands for "HTML Entities", apparently. Cursed. import yaml from 'js-yaml'; import {annotateError, annotateErrorWithFile, showAggregate, withAggregate} from '#aggregate'; -import {externalLinkSpec} from '#external-links'; import {colors, logWarn} from '#cli'; import {empty, splitKeys, withEntries} from '#sugar'; import T from '#things'; @@ -248,19 +246,8 @@ async function processLanguageSpecFromFile(file, processLanguageSpecOpts) { } } -export function initializeLanguageObject() { - const language = new Language(); - - language.escapeHTML = string => - he.encode(string, {useNamedReferences: true}); - - language.externalLinkSpec = externalLinkSpec; - - return language; -} - export async function processLanguageFile(file) { - const language = initializeLanguageObject(); + const language = new Language() const properties = await processLanguageSpecFromFile(file); return Object.assign(language, properties); } @@ -271,7 +258,7 @@ export function watchLanguageFile(file, { const basename = path.basename(file); const events = new EventEmitter(); - const language = initializeLanguageObject(); + const language = new Language(); let emittedReady = false; let successfullyAppliedLanguage = false; diff --git a/src/data/thing.js b/src/data/thing.js index 78ad3642..32eff4d1 100644 --- a/src/data/thing.js +++ b/src/data/thing.js @@ -10,15 +10,29 @@ export default class Thing extends CacheableObject { static referenceType = Symbol.for('Thing.referenceType'); static friendlyName = Symbol.for('Thing.friendlyName'); + static wikiData = Symbol.for('Thing.wikiData'); + static oneInstancePerWiki = Symbol.for('Thing.oneThingPerWiki'); + static constitutibleProperties = Symbol.for('Thing.constitutibleProperties'); + static getPropertyDescriptors = Symbol.for('Thing.getPropertyDescriptors'); static getSerializeDescriptors = Symbol.for('Thing.getSerializeDescriptors'); static findSpecs = Symbol.for('Thing.findSpecs'); static findThisThingOnly = Symbol.for('Thing.findThisThingOnly'); + static reverseSpecs = Symbol.for('Thing.reverseSpecs'); + static yamlDocumentSpec = Symbol.for('Thing.yamlDocumentSpec'); static getYamlLoadingSpec = Symbol.for('Thing.getYamlLoadingSpec'); + static yamlSourceFilename = Symbol.for('Thing.yamlSourceFilename'); + static yamlSourceDocument = Symbol.for('Thing.yamlSourceDocument'); + static yamlSourceDocumentPlacement = Symbol.for('Thing.yamlSourceDocumentPlacement'); + + [Symbol.for('Thing.yamlSourceFilename')] = null; + [Symbol.for('Thing.yamlSourceDocument')] = null; + [Symbol.for('Thing.yamlSourceDocumentPlacement')] = null; + static isThingConstructor = Symbol.for('Thing.isThingConstructor'); static isThing = Symbol.for('Thing.isThing'); @@ -26,14 +40,15 @@ export default class Thing extends CacheableObject { // Symbol.for('Thing.isThingConstructor') in constructor static [Symbol.for('Thing.isThingConstructor')] = NaN; - static [CacheableObject.propertyDescriptors] = { + constructor() { + super({seal: false}); + // To detect: // Object.hasOwn(object, Symbol.for('Thing.isThing')) - [Symbol.for('Thing.isThing')]: { - flags: {expose: true}, - expose: {compute: () => NaN}, - }, - }; + this[Symbol.for('Thing.isThing')] = NaN; + + Object.seal(this); + } static [Symbol.for('Thing.selectAll')] = _wikiData => []; @@ -49,7 +64,7 @@ export default class Thing extends CacheableObject { if (this.name) { name = colors.green(`"${this.name}"`); } - } catch (error) { + } catch { name = colors.yellow(`couldn't get name`); } @@ -58,7 +73,7 @@ export default class Thing extends CacheableObject { if (this.directory) { reference = colors.blue(Thing.getReference(this)); } - } catch (error) { + } catch { reference = colors.yellow(`couldn't get reference`); } @@ -73,7 +88,13 @@ export default class Thing extends CacheableObject { } if (!thing.directory) { - throw TypeError(`Passed ${thing.constructor.name} is missing its directory`); + if (thing.name) { + throw TypeError( + `Passed ${thing.constructor.name} (named ${inspect(thing.name)}) ` + + `is missing its directory`); + } else { + throw TypeError(`Passed ${thing.constructor.name} is missing its directory`); + } } return `${thing.constructor[Thing.referenceType]}:${thing.directory}`; diff --git a/src/data/things/additional-file.js b/src/data/things/additional-file.js new file mode 100644 index 00000000..b15f62e0 --- /dev/null +++ b/src/data/things/additional-file.js @@ -0,0 +1,54 @@ +import {input} from '#composite'; +import Thing from '#thing'; +import {isString, validateArrayItems} from '#validators'; + +import {exposeConstant, exposeUpdateValueOrContinue} + from '#composite/control-flow'; +import {contentString, simpleString, thing} from '#composite/wiki-properties'; + +export class AdditionalFile extends Thing { + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + thing: thing(), + + title: simpleString(), + + description: contentString(), + + filenames: [ + exposeUpdateValueOrContinue({ + validate: input.value(validateArrayItems(isString)), + }), + + exposeConstant({ + value: input.value([]), + }), + ], + + // Expose only + + isAdditionalFile: [ + exposeConstant({ + value: input.value(true), + }), + ], + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Title': {property: 'title'}, + 'Description': {property: 'description'}, + 'Files': {property: 'filenames'}, + }, + }; + + get paths() { + if (!this.thing) return null; + if (!this.thing.getOwnAdditionalFilePath) return null; + + return ( + this.filenames.map(filename => + this.thing.getOwnAdditionalFilePath(this, filename))); + } +} diff --git a/src/data/things/additional-name.js b/src/data/things/additional-name.js new file mode 100644 index 00000000..99f3ee46 --- /dev/null +++ b/src/data/things/additional-name.js @@ -0,0 +1,31 @@ +import {input} from '#composite'; +import Thing from '#thing'; + +import {exposeConstant} from '#composite/control-flow'; +import {contentString, thing} from '#composite/wiki-properties'; + +export class AdditionalName extends Thing { + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + thing: thing(), + + name: contentString(), + annotation: contentString(), + + // Expose only + + isAdditionalName: [ + exposeConstant({ + value: input.value(true), + }), + ], + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Name': {property: 'name'}, + 'Annotation': {property: 'annotation'}, + }, + }; +} diff --git a/src/data/things/album.js b/src/data/things/album.js index bd54a356..31d94ef1 100644 --- a/src/data/things/album.js +++ b/src/data/things/album.js @@ -3,57 +3,74 @@ export const DATA_ALBUM_DIRECTORY = 'album'; import * as path from 'node:path'; import {inspect} from 'node:util'; -import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; -import find from '#find'; +import {input, V} from '#composite'; import {traverse} from '#node-utils'; import {sortAlbumsTracksChronologically, sortChronologically} from '#sort'; -import {accumulateSum, empty} from '#sugar'; +import {empty} from '#sugar'; import Thing from '#thing'; -import {isColor, isDate, isDirectory, validateWikiData} from '#validators'; + +import { + is, + isBoolean, + isColor, + isContributionList, + isDate, + isDirectory, + isNumber, +} from '#validators'; import { parseAdditionalFiles, parseAdditionalNames, parseAnnotatedReferences, + parseArtwork, + parseCommentary, parseContributors, + parseCreditingSources, parseDate, parseDimensions, parseWallpaperParts, } from '#yaml'; -import {exitWithoutDependency, exposeDependency, exposeUpdateValueOrContinue} - from '#composite/control-flow'; -import {withPropertyFromObject} from '#composite/data'; +import {withRecontextualizedContributionList, withResolvedContribs} + from '#composite/wiki-data'; + +import { + exitWithoutDependency, + exposeConstant, + exposeDependency, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; import { - exitWithoutContribs, - withDirectory, - withResolvedReference, - withCoverArtDate, -} from '#composite/wiki-data'; + withFlattenedList, + withLengthOfList, + withNearbyItemFromList, + withPropertyFromList, + withPropertyFromObject, +} from '#composite/data'; import { - additionalFiles, - additionalNameList, - commentary, color, commentatorArtists, + constitutibleArtwork, + constitutibleArtworkList, contentString, - contribsPresent, contributionList, dimensions, directory, fileExtension, flag, + hasArtwork, name, referencedArtworkList, referenceList, - reverseReferencedArtworkList, simpleDate, simpleString, - singleReference, + soupyFind, + soupyReverse, thing, thingList, urls, @@ -61,23 +78,34 @@ import { wikiData, } from '#composite/wiki-properties'; -import {withTracks} from '#composite/things/album'; -import {withAlbum} from '#composite/things/track-section'; - export class Album extends Thing { static [Thing.referenceType] = 'album'; + static [Thing.wikiData] = 'albumData'; + + static [Thing.constitutibleProperties] = [ + 'coverArtworks', + 'wallpaperArtwork', + 'bannerArtwork', + ]; static [Thing.getPropertyDescriptors] = ({ + AdditionalFile, + AdditionalName, ArtTag, - Artist, + Artwork, + CommentaryEntry, + CreditingSourcesEntry, Group, - Track, TrackSection, WikiInfo, }) => ({ - // Update & expose + // > Update & expose - Internal relationships + + trackSections: thingList(V(TrackSection)), + + // > Update & expose - Identifying metadata - name: name('Unnamed Album'), + name: name(V('Unnamed Album')), directory: directory(), directorySuffix: [ @@ -85,114 +113,143 @@ export class Album extends Thing { validate: input.value(isDirectory), }), - withDirectory(), - - exposeDependency({ - dependency: '#directory', - }), + exposeDependency('directory'), ], - alwaysReferenceTracksByDirectory: flag(false), - suffixTrackDirectories: flag(false), + alwaysReferenceByDirectory: flag(V(false)), + alwaysReferenceTracksByDirectory: flag(V(false)), + suffixTrackDirectories: flag(V(false)), - color: color(), - urls: urls(), + style: [ + exposeUpdateValueOrContinue({ + validate: input.value(is(...[ + 'album', + 'single', + ])), + }), - additionalNames: additionalNameList(), + exposeConstant(V('album')), + ], bandcampAlbumIdentifier: simpleString(), bandcampArtworkIdentifier: simpleString(), + additionalNames: thingList(V(AdditionalName)), + date: simpleDate(), - trackArtDate: simpleDate(), dateAddedToWiki: simpleDate(), - coverArtDate: [ - // ~~TODO: Why does this fall back, but Track.coverArtDate doesn't?~~ - // TODO: OK so it's because tracks don't *store* dates just like that. - // Really instead of fallback being a flag, it should be a date value, - // if this option is worth existing at all. - withCoverArtDate({ - from: input.updateValue({ - validate: isDate, - }), + // > Update & expose - Credits and contributors + + artistContribs: contributionList({ + artistProperty: input.value('albumArtistContributions'), + }), + + trackArtistText: contentString(), - fallback: input.value(true), + trackArtistContribs: [ + withResolvedContribs({ + from: input.updateValue({validate: isContributionList}), + thingProperty: input.thisProperty(), + artistProperty: input.value('albumTrackArtistContributions'), + }).outputs({ + '#resolvedContribs': '#trackArtistContribs', }), - exposeDependency({dependency: '#coverArtDate'}), - ], + exposeDependencyOrContinue('#trackArtistContribs', V('empty')), - coverArtFileExtension: [ - exitWithoutContribs({contribs: 'coverArtistContribs'}), - fileExtension('jpg'), + withRecontextualizedContributionList('artistContribs', { + artistProperty: input.value('albumTrackArtistContributions'), + }), + + exposeDependency('#artistContribs'), ], - trackCoverArtFileExtension: fileExtension('jpg'), + // > Update & expose - General configuration - wallpaperFileExtension: [ - exitWithoutContribs({contribs: 'wallpaperArtistContribs'}), - fileExtension('jpg'), - ], + countTracksInArtistTotals: flag(V(true)), - bannerFileExtension: [ - exitWithoutContribs({contribs: 'bannerArtistContribs'}), - fileExtension('jpg'), - ], + showAlbumInTracksWithoutArtists: flag(V(false)), - wallpaperStyle: [ - exitWithoutContribs({contribs: 'wallpaperArtistContribs'}), - simpleString(), - ], + hasTrackNumbers: flag(V(true)), + isListedOnHomepage: flag(V(true)), + isListedInGalleries: flag(V(true)), - wallpaperParts: [ - exitWithoutContribs({contribs: 'wallpaperArtistContribs'}), - wallpaperParts(), - ], + hideDuration: flag(V(false)), - bannerStyle: [ - exitWithoutContribs({contribs: 'bannerArtistContribs'}), - simpleString(), - ], + // > Update & expose - General metadata - coverArtDimensions: [ - exitWithoutContribs({contribs: 'coverArtistContribs'}), - dimensions(), + color: color(), + + urls: urls(), + + // > Update & expose - Artworks + + coverArtworks: [ + exitWithoutDependency('hasCoverArt', { + value: input.value([]), + mode: input.value('falsy'), + }), + + constitutibleArtworkList.fromYAMLFieldSpec + .call(this, 'Cover Artwork'), ], - trackDimensions: dimensions(), + coverArtistContribs: contributionList({ + date: 'coverArtDate', + artistProperty: input.value('albumCoverArtistContributions'), + }), - bannerDimensions: [ - exitWithoutContribs({contribs: 'bannerArtistContribs'}), - dimensions(), + coverArtDate: [ + exitWithoutDependency('hasCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + exposeUpdateValueOrContinue({ + validate: input.value(isDate), + }), + + exposeDependency('date'), ], - hasTrackNumbers: flag(true), - isListedOnHomepage: flag(true), - isListedInGalleries: flag(true), + coverArtFileExtension: [ + exitWithoutDependency('hasCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), - commentary: commentary(), - creditSources: commentary(), - additionalFiles: additionalFiles(), + fileExtension(V('jpg')), + ], - trackSections: thingList({ - class: input.value(TrackSection), - }), + coverArtDimensions: [ + exitWithoutDependency('hasCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), - artistContribs: contributionList({ - date: 'date', - artistProperty: input.value('albumArtistContributions'), - }), + dimensions(), + ], + + artTags: [ + exitWithoutDependency('hasCoverArt', { + value: input.value([]), + mode: input.value('falsy'), + }), - coverArtistContribs: [ - withCoverArtDate({ - fallback: input.value(true), + referenceList({ + class: input.value(ArtTag), + find: soupyFind.input('artTag'), }), + ], - contributionList({ - date: '#coverArtDate', - artistProperty: input.value('albumCoverArtistContributions'), + referencedArtworks: [ + exitWithoutDependency('hasCoverArt', { + value: input.value([]), + mode: input.value('falsy'), }), + + referencedArtworkList(), ], trackCoverArtistContribs: contributionList({ @@ -205,115 +262,150 @@ export class Album extends Thing { artistProperty: input.value('trackCoverArtistContributions'), }), - wallpaperArtistContribs: [ - withCoverArtDate({ - fallback: input.value(true), + trackArtDate: simpleDate(), + + trackCoverArtFileExtension: fileExtension(V('jpg')), + + trackDimensions: dimensions(), + + wallpaperArtwork: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value(null), + mode: input.value('falsy'), }), - contributionList({ - date: '#coverArtDate', - artistProperty: input.value('albumWallpaperArtistContributions'), + constitutibleArtwork.fromYAMLFieldSpec + .call(this, 'Wallpaper Artwork'), + ], + + wallpaperArtistContribs: contributionList({ + date: 'coverArtDate', + artistProperty: input.value('albumWallpaperArtistContributions'), + }), + + wallpaperFileExtension: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value(null), + mode: input.value('falsy'), }), + + fileExtension(V('jpg')), ], - bannerArtistContribs: [ - withCoverArtDate({ - fallback: input.value(true), + wallpaperStyle: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value(null), + mode: input.value('falsy'), }), - contributionList({ - date: '#coverArtDate', - artistProperty: input.value('albumBannerArtistContributions'), + simpleString(), + ], + + wallpaperParts: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value([]), + mode: input.value('falsy'), + }), + + wallpaperParts(), + ], + + bannerArtwork: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), }), + + constitutibleArtwork.fromYAMLFieldSpec + .call(this, 'Banner Artwork'), ], - groups: referenceList({ - class: input.value(Group), - find: input.value(find.group), - data: 'groupData', + bannerArtistContribs: contributionList({ + date: 'coverArtDate', + artistProperty: input.value('albumBannerArtistContributions'), }), - artTags: [ - exitWithoutContribs({ - contribs: 'coverArtistContribs', - value: input.value([]), + bannerFileExtension: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), }), - referenceList({ - class: input.value(ArtTag), - find: input.value(find.artTag), - data: 'artTagData', - }), + fileExtension(V('jpg')), ], - referencedArtworks: [ - exitWithoutContribs({ - contribs: 'coverArtistContribs', - value: input.value([]), + bannerDimensions: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), }), - { - dependencies: ['coverArtDate', 'date'], - compute: (continuation, { - coverArtDate, - date, - }) => continuation({ - ['#date']: - coverArtDate ?? date, - }), - }, + dimensions(), + ], - referencedArtworkList({ - date: '#date', + bannerStyle: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), }), + + simpleString(), ], - // Update only + // > Update & expose - Groups - albumData: wikiData({ - class: input.value(Album), + groups: referenceList({ + class: input.value(Group), + find: soupyFind.input('group'), }), - artistData: wikiData({ - class: input.value(Artist), - }), + // > Update & expose - Content entries - artTagData: wikiData({ - class: input.value(ArtTag), - }), + commentary: thingList(V(CommentaryEntry)), + creditingSources: thingList(V(CreditingSourcesEntry)), - groupData: wikiData({ - class: input.value(Group), - }), + // > Update & expose - Additional files - trackData: wikiData({ - class: input.value(Track), - }), + additionalFiles: thingList(V(AdditionalFile)), - wikiInfo: thing({ - class: input.value(WikiInfo), - }), + // > Update only - // Expose only + find: soupyFind(), + reverse: soupyReverse(), + + // used for referencedArtworkList (mixedFind) + artworkData: wikiData(V(Artwork)), + + // used for withMatchingContributionPresets (indirectly by Contribution) + wikiInfo: thing(V(WikiInfo)), + + // > Expose only + + isAlbum: exposeConstant(V(true)), commentatorArtists: commentatorArtists(), - hasCoverArt: contribsPresent({contribs: 'coverArtistContribs'}), - hasWallpaperArt: contribsPresent({contribs: 'wallpaperArtistContribs'}), - hasBannerArt: contribsPresent({contribs: 'bannerArtistContribs'}), + hasCoverArt: hasArtwork({ + contribs: '_coverArtistContribs', + artworks: '_coverArtworks', + }), - tracks: [ - withTracks(), - exposeDependency({dependency: '#tracks'}), - ], + hasWallpaperArt: hasArtwork({ + contribs: '_wallpaperArtistContribs', + artwork: '_wallpaperArtwork', + }), - referencedByArtworks: [ - exitWithoutContribs({ - contribs: 'coverArtistContribs', - value: input.value([]), - }), + hasBannerArt: hasArtwork({ + contribs: '_bannerArtistContribs', + artwork: '_bannerArtwork', + }), + + tracks: [ + exitWithoutDependency('trackSections', V([])), - reverseReferencedArtworkList(), + withPropertyFromList('trackSections', V('tracks')), + withFlattenedList('#trackSections.tracks'), + exposeDependency('#flattenedList'), ], }); @@ -359,35 +451,127 @@ export class Album extends Thing { static [Thing.findSpecs] = { album: { - referenceTypes: ['album', 'album-commentary', 'album-gallery'], + referenceTypes: [ + 'album', + 'album-commentary', + 'album-gallery', + ], + + bindTo: 'albumData', + + getMatchableNames: album => + (album.alwaysReferenceByDirectory + ? [] + : [album.name]), + }, + + albumSinglesOnly: { + referencing: ['album'], + bindTo: 'albumData', + + incldue: album => + album.style === 'single', + + getMatchableNames: album => + (album.alwaysReferenceByDirectory + ? [] + : [album.name]), }, albumWithArtwork: { - referenceTypes: ['album'], + referenceTypes: [ + 'album', + 'album-referencing-artworks', + 'album-referenced-artworks', + ], + bindTo: 'albumData', include: album => album.hasCoverArt, + + getMatchableNames: album => + (album.alwaysReferenceByDirectory + ? [] + : [album.name]), + }, + + albumPrimaryArtwork: { + [Thing.findThisThingOnly]: false, + + referenceTypes: [ + 'album', + 'album-referencing-artworks', + 'album-referenced-artworks', + ], + + bindTo: 'artworkData', + + include: (artwork, {Artwork, Album}) => + artwork instanceof Artwork && + artwork.thing instanceof Album && + artwork === artwork.thing.coverArtworks[0], + + getMatchableNames: ({thing: album}) => + (album.alwaysReferenceByDirectory + ? [] + : [album.name]), + + getMatchableDirectories: ({thing: album}) => + [album.directory], + }, + }; + + static [Thing.reverseSpecs] = { + albumsWhoseArtworksFeature: { + bindTo: 'albumData', + + referencing: album => [album], + referenced: album => album.artTags, + }, + + albumsWhoseGroupsInclude: { + bindTo: 'albumData', + + referencing: album => [album], + referenced: album => album.groups, + }, + + albumArtistContributionsBy: + soupyReverse.contributionsBy('albumData', 'artistContribs'), + + albumTrackArtistContributionsBy: + soupyReverse.contributionsBy('albumData', 'trackArtistContribs'), + + albumCoverArtistContributionsBy: + soupyReverse.artworkContributionsBy('albumData', 'coverArtworks'), + + albumWallpaperArtistContributionsBy: + soupyReverse.artworkContributionsBy('albumData', 'wallpaperArtwork', {single: true}), + + albumBannerArtistContributionsBy: + soupyReverse.artworkContributionsBy('albumData', 'bannerArtwork', {single: true}), + + albumsWithCommentaryBy: { + bindTo: 'albumData', + + referencing: album => [album], + referenced: album => album.commentatorArtists, }, }; static [Thing.yamlDocumentSpec] = { fields: { - 'Album': {property: 'name'}, + // Identifying metadata + 'Album': {property: 'name'}, 'Directory': {property: 'directory'}, 'Directory Suffix': {property: 'directorySuffix'}, 'Suffix Track Directories': {property: 'suffixTrackDirectories'}, - - 'Always Reference Tracks By Directory': { - property: 'alwaysReferenceTracksByDirectory', - }, - - 'Additional Names': { - property: 'additionalNames', - transform: parseAdditionalNames, - }, + 'Always Reference By Directory': {property: 'alwaysReferenceByDirectory'}, + 'Always Reference Tracks By Directory': {property: 'alwaysReferenceTracksByDirectory'}, + 'Style': {property: 'style'}, 'Bandcamp Album ID': { property: 'bandcampAlbumIdentifier', @@ -399,41 +583,129 @@ export class Album extends Thing { transform: String, }, + 'Additional Names': { + property: 'additionalNames', + transform: parseAdditionalNames, + }, + 'Date': { property: 'date', transform: parseDate, }, - 'Color': {property: 'color'}, - 'URLs': {property: 'urls'}, + 'Date Added': { + property: 'dateAddedToWiki', + transform: parseDate, + }, + + // Credits and contributors + + 'Artists': { + property: 'artistContribs', + transform: parseContributors, + }, + + 'Track Artist Text': { + property: 'trackArtistText', + }, + + 'Track Artists': { + property: 'trackArtistContribs', + transform: parseContributors, + }, + + // General configuration + + 'Count Tracks In Artist Totals': {property: 'countTracksInArtistTotals'}, + + 'Show Album In Tracks Without Artists': { + property: 'showAlbumInTracksWithoutArtists', + }, 'Has Track Numbers': {property: 'hasTrackNumbers'}, 'Listed on Homepage': {property: 'isListedOnHomepage'}, 'Listed in Galleries': {property: 'isListedInGalleries'}, - 'Cover Art Date': { - property: 'coverArtDate', - transform: parseDate, + 'Hide Duration': {property: 'hideDuration'}, + + // General metadata + + 'Color': {property: 'color'}, + + 'URLs': {property: 'urls'}, + + // Artworks + // (Note - this YAML section is deliberately ordered differently + // than the corresponding property descriptors.) + + 'Cover Artwork': { + property: 'coverArtworks', + transform: + parseArtwork({ + thingProperty: 'coverArtworks', + dimensionsFromThingProperty: 'coverArtDimensions', + fileExtensionFromThingProperty: 'coverArtFileExtension', + dateFromThingProperty: 'coverArtDate', + artistContribsFromThingProperty: 'coverArtistContribs', + artistContribsArtistProperty: 'albumCoverArtistContributions', + artTagsFromThingProperty: 'artTags', + referencedArtworksFromThingProperty: 'referencedArtworks', + }), }, - 'Default Track Cover Art Date': { - property: 'trackArtDate', - transform: parseDate, + 'Banner Artwork': { + property: 'bannerArtwork', + transform: + parseArtwork({ + single: true, + thingProperty: 'bannerArtwork', + dimensionsFromThingProperty: 'bannerDimensions', + fileExtensionFromThingProperty: 'bannerFileExtension', + dateFromThingProperty: 'date', + artistContribsFromThingProperty: 'bannerArtistContribs', + artistContribsArtistProperty: 'albumBannerArtistContributions', + }), }, - 'Date Added': { - property: 'dateAddedToWiki', - transform: parseDate, + 'Wallpaper Artwork': { + property: 'wallpaperArtwork', + transform: + parseArtwork({ + single: true, + thingProperty: 'wallpaperArtwork', + dimensionsFromThingProperty: null, + fileExtensionFromThingProperty: 'wallpaperFileExtension', + dateFromThingProperty: 'date', + artistContribsFromThingProperty: 'wallpaperArtistContribs', + artistContribsArtistProperty: 'albumWallpaperArtistContributions', + }), }, - 'Cover Art File Extension': {property: 'coverArtFileExtension'}, - 'Track Art File Extension': {property: 'trackCoverArtFileExtension'}, + 'Cover Artists': { + property: 'coverArtistContribs', + transform: parseContributors, + }, + + 'Cover Art Date': { + property: 'coverArtDate', + transform: parseDate, + }, 'Cover Art Dimensions': { property: 'coverArtDimensions', transform: parseDimensions, }, + 'Default Track Cover Artists': { + property: 'trackCoverArtistContribs', + transform: parseContributors, + }, + + 'Default Track Cover Art Date': { + property: 'trackArtDate', + transform: parseDate, + }, + 'Default Track Dimensions': { property: 'trackDimensions', transform: parseDimensions, @@ -445,7 +717,6 @@ export class Album extends Thing { }, 'Wallpaper Style': {property: 'wallpaperStyle'}, - 'Wallpaper File Extension': {property: 'wallpaperFileExtension'}, 'Wallpaper Parts': { property: 'wallpaperParts', @@ -457,51 +728,70 @@ export class Album extends Thing { transform: parseContributors, }, - 'Banner Style': {property: 'bannerStyle'}, - 'Banner File Extension': {property: 'bannerFileExtension'}, - 'Banner Dimensions': { property: 'bannerDimensions', transform: parseDimensions, }, - 'Commentary': {property: 'commentary'}, - 'Credit Sources': {property: 'creditSources'}, + 'Banner Style': {property: 'bannerStyle'}, - 'Additional Files': { - property: 'additionalFiles', - transform: parseAdditionalFiles, - }, + 'Cover Art File Extension': {property: 'coverArtFileExtension'}, + 'Track Art File Extension': {property: 'trackCoverArtFileExtension'}, + 'Wallpaper File Extension': {property: 'wallpaperFileExtension'}, + 'Banner File Extension': {property: 'bannerFileExtension'}, + + 'Art Tags': {property: 'artTags'}, 'Referenced Artworks': { property: 'referencedArtworks', transform: parseAnnotatedReferences, }, - 'Franchises': {ignore: true}, + // Groups - 'Artists': { - property: 'artistContribs', - transform: parseContributors, + 'Groups': {property: 'groups'}, + + // Content entries + + 'Commentary': { + property: 'commentary', + transform: parseCommentary, }, - 'Cover Artists': { - property: 'coverArtistContribs', - transform: parseContributors, + 'Crediting Sources': { + property: 'creditingSources', + transform: parseCreditingSources, }, - 'Default Track Cover Artists': { - property: 'trackCoverArtistContribs', - transform: parseContributors, + // Additional files + + 'Additional Files': { + property: 'additionalFiles', + transform: parseAdditionalFiles, }, - 'Groups': {property: 'groups'}, - 'Art Tags': {property: 'artTags'}, + // Shenanigans + 'Franchises': {ignore: true}, 'Review Points': {ignore: true}, }, invalidFieldCombinations: [ + {message: `Move commentary on singles to the track`, fields: [ + ['Style', 'single'], + 'Commentary', + ]}, + + {message: `Move crediting sources on singles to the track`, fields: [ + ['Style', 'single'], + 'Crediting Sources', + ]}, + + {message: `Move additional names on singles to the track`, fields: [ + ['Style', 'single'], + 'Additional Names', + ]}, + {message: `Specify one wallpaper style or multiple wallpaper parts, not both`, fields: [ 'Wallpaper Parts', 'Wallpaper Style', @@ -516,7 +806,7 @@ export class Album extends Thing { static [Thing.getYamlLoadingSpec] = ({ documentModes: {headerAndEntries}, - thingConstructors: {Album, Track, TrackSectionHelper}, + thingConstructors: {Album, Track}, }) => ({ title: `Process album files`, @@ -533,61 +823,48 @@ export class Album extends Thing { ? TrackSection : Track), - save(results) { - const albumData = []; - const trackSectionData = []; - const trackData = []; - - for (const {header: album, entries} of results) { - const trackSections = []; - - let currentTrackSection = new TrackSection(); - let currentTrackSectionTracks = []; - - Object.assign(currentTrackSection, { - name: `Default Track Section`, - isDefaultTrackSection: true, - }); - - const albumRef = Thing.getReference(album); + connect({header: album, entries}) { + const trackSections = []; - const closeCurrentTrackSection = () => { - if ( - currentTrackSection.isDefaultTrackSection && - empty(currentTrackSectionTracks) - ) { - return; - } + let currentTrackSection = new TrackSection(); + let currentTrackSectionTracks = []; - currentTrackSection.tracks = - currentTrackSectionTracks; + Object.assign(currentTrackSection, { + name: `Default Track Section`, + isDefaultTrackSection: true, + }); - trackSections.push(currentTrackSection); - trackSectionData.push(currentTrackSection); - }; + const closeCurrentTrackSection = () => { + if ( + currentTrackSection.isDefaultTrackSection && + empty(currentTrackSectionTracks) + ) { + return; + } - for (const entry of entries) { - if (entry instanceof TrackSection) { - closeCurrentTrackSection(); - currentTrackSection = entry; - currentTrackSectionTracks = []; - continue; - } + currentTrackSection.tracks = currentTrackSectionTracks; + currentTrackSection.album = album; - currentTrackSectionTracks.push(entry); - trackData.push(entry); + trackSections.push(currentTrackSection); + }; - entry.dataSourceAlbum = albumRef; + for (const entry of entries) { + if (entry instanceof TrackSection) { + closeCurrentTrackSection(); + currentTrackSection = entry; + currentTrackSectionTracks = []; + continue; } - closeCurrentTrackSection(); - - albumData.push(album); + entry.album = album; + entry.trackSection = currentTrackSection; - album.trackSections = trackSections; + currentTrackSectionTracks.push(entry); } - return {albumData, trackSectionData, trackData}; + closeCurrentTrackSection(); + + album.trackSections = trackSections; }, sort({albumData, trackData}) { @@ -595,120 +872,217 @@ export class Album extends Thing { sortAlbumsTracksChronologically(trackData); }, }); + + getOwnAdditionalFilePath(_file, filename) { + return [ + 'media.albumAdditionalFile', + this.directory, + filename, + ]; + } + + getOwnArtworkPath(artwork) { + if (artwork === this.bannerArtwork) { + return [ + 'media.albumBanner', + this.directory, + artwork.fileExtension, + ]; + } + + if (artwork === this.wallpaperArtwork) { + if (!empty(this.wallpaperParts)) { + return null; + } + + return [ + 'media.albumWallpaper', + this.directory, + artwork.fileExtension, + ]; + } + + // TODO: using trackCover here is obviously, badly wrong + // but we ought to refactor banners and wallpapers similarly + // (i.e. depend on those intrinsic artwork paths rather than + // accessing media.{albumBanner,albumWallpaper} from content + // or other code directly) + return [ + 'media.trackCover', + this.directory, + + (artwork.unqualifiedDirectory + ? 'cover-' + artwork.unqualifiedDirectory + : 'cover'), + + artwork.fileExtension, + ]; + } + + // As of writing, albums don't even have a `duration` property... + // so this function will never be called... but the message stands... + countOwnContributionInDurationTotals(_contrib) { + return false; + } } export class TrackSection extends Thing { static [Thing.friendlyName] = `Track Section`; static [Thing.referenceType] = `track-section`; + static [Thing.wikiData] = 'trackSectionData'; - static [Thing.getPropertyDescriptors] = ({Album, Track}) => ({ + static [Thing.getPropertyDescriptors] = ({Track}) => ({ // Update & expose - name: name('Unnamed Track Section'), + album: thing(V(Album)), + + name: name(V('Unnamed Track Section')), unqualifiedDirectory: directory(), + directorySuffix: [ + exposeUpdateValueOrContinue({ + validate: input.value(isDirectory), + }), + + withPropertyFromObject({ + object: 'album', + property: input.value('directorySuffix'), + }), + + exposeDependency({dependency: '#album.directorySuffix'}), + ], + + suffixTrackDirectories: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withPropertyFromObject({ + object: 'album', + property: input.value('suffixTrackDirectories'), + }), + + exposeDependency({dependency: '#album.suffixTrackDirectories'}), + ], + color: [ exposeUpdateValueOrContinue({ validate: input.value(isColor), }), - withAlbum(), - withPropertyFromObject({ - object: '#album', + object: 'album', property: input.value('color'), }), exposeDependency({dependency: '#album.color'}), ], + hasTrackNumbers: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withPropertyFromObject('album', V('hasTrackNumbers')), + exposeDependency('#album.hasTrackNumbers'), + ], + + startCountingFrom: [ + exposeUpdateValueOrContinue({ + validate: input.value(isNumber), + }), + + withPropertyFromObject('album', V('hasTrackNumbers')), + exitWithoutDependency('#album.hasTrackNumbers', V(1), V('falsy')), + + withPropertyFromObject('album', V('trackSections')), + + withNearbyItemFromList({ + list: '#album.trackSections', + item: input.myself(), + offset: input.value(-1), + }).outputs({ + '#nearbyItem': '#previousTrackSection', + }), + + exitWithoutDependency('#previousTrackSection', V(1)), + + withPropertyFromObject('#previousTrackSection', V('continueCountingFrom')), + exposeDependency('#previousTrackSection.continueCountingFrom'), + ], + dateOriginallyReleased: simpleDate(), - isDefaultTrackSection: flag(false), + countTracksInArtistTotals: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), - description: contentString(), + withPropertyFromObject({ + object: 'album', + property: input.value('countTracksInArtistTotals'), + }), - album: [ - withAlbum(), - exposeDependency({dependency: '#album'}), + exposeDependency({dependency: '#album.countTracksInArtistTotals'}), ], - tracks: thingList({ - class: input.value(Track), - }), + isDefaultTrackSection: flag(V(false)), + + description: contentString(), + + tracks: thingList(V(Track)), // Update only - albumData: wikiData({ - class: input.value(Album), - }), + reverse: soupyReverse(), // Expose only - directory: [ - withAlbum(), + isTrackSection: [ + exposeConstant({ + value: input.value(true), + }), + ], + directory: [ exitWithoutDependency({ - dependency: '#album', + dependency: 'album', }), withPropertyFromObject({ - object: '#album', + object: 'album', property: input.value('directory'), }), - withDirectory({ - directory: 'unqualifiedDirectory', - }).outputs({ - '#directory': '#unqualifiedDirectory', - }), - { - dependencies: ['#album.directory', '#unqualifiedDirectory'], + dependencies: ['#album.directory', 'unqualifiedDirectory'], compute: ({ ['#album.directory']: albumDirectory, - ['#unqualifiedDirectory']: unqualifiedDirectory, + ['unqualifiedDirectory']: unqualifiedDirectory, }) => albumDirectory + '/' + unqualifiedDirectory, }, ], - startIndex: [ - withAlbum(), - - withPropertyFromObject({ - object: '#album', - property: input.value('trackSections'), - }), + continueCountingFrom: [ + withPropertyFromObject('album', V('hasTrackNumbers')), + exitWithoutDependency('#album.hasTrackNumbers', V(null), V('falsy')), { - dependencies: ['#album.trackSections', input.myself()], - compute: (continuation, { - ['#album.trackSections']: trackSections, - [input.myself()]: myself, - }) => continuation({ - ['#index']: - trackSections.indexOf(myself), - }), + dependencies: ['hasTrackNumbers', 'startCountingFrom'], + compute: (continuation, {hasTrackNumbers, startCountingFrom}) => + (hasTrackNumbers + ? continuation() + : continuation.exit(startCountingFrom)), }, - exitWithoutDependency({ - dependency: '#index', - mode: input.value('index'), - value: input.value(0), - }), + withLengthOfList('tracks'), { - dependencies: ['#album.trackSections', '#index'], - compute: ({ - ['#album.trackSections']: trackSections, - ['#index']: index, - }) => - accumulateSum( - trackSections - .slice(0, index) - .map(section => section.tracks.length)), + dependencies: ['startCountingFrom', '#tracks.length'], + compute: ({startCountingFrom, '#tracks.length': tracks}) => + startCountingFrom + tracks, }, ], }); @@ -730,13 +1104,20 @@ export class TrackSection extends Thing { static [Thing.yamlDocumentSpec] = { fields: { 'Section': {property: 'name'}, + 'Directory Suffix': {property: 'directorySuffix'}, + 'Suffix Track Directories': {property: 'suffixTrackDirectories'}, + 'Color': {property: 'color'}, + 'Has Track Numbers': {property: 'hasTrackNumbers'}, + 'Start Counting From': {property: 'startCountingFrom'}, 'Date Originally Released': { property: 'dateOriginallyReleased', transform: parseDate, }, + 'Count Tracks In Artist Totals': {property: 'countTracksInArtistTotals'}, + 'Description': {property: 'description'}, }, }; @@ -746,38 +1127,38 @@ export class TrackSection extends Thing { parts.push(Thing.prototype[inspect.custom].apply(this)); - if (depth >= 0) { + if (depth >= 0) showAlbum: { let album = null; try { album = this.album; - } catch {} + } catch { + break showAlbum; + } let first = null; try { - first = this.startIndex; + first = this.tracks.at(0).trackNumber; } catch {} - let length = null; + let last = null; try { - length = this.tracks.length; + last = this.tracks.at(-1).trackNumber; } catch {} - if (album) { - const albumName = album.name; - const albumIndex = album.trackSections.indexOf(this); + const albumName = album.name; + const albumIndex = album.trackSections.indexOf(this); - const num = - (albumIndex === -1 - ? 'indeterminate position' - : `#${albumIndex + 1}`); + const num = + (albumIndex === -1 + ? 'indeterminate position' + : `#${albumIndex + 1}`); - const range = - (albumIndex >= 0 && first !== null && length !== null - ? `: ${first + 1}-${first + length + 1}` - : ''); + const range = + (albumIndex >= 0 && first !== null && last !== null + ? `: ${first}-${last}` + : ''); - parts.push(` (${colors.yellow(num + range)} in ${colors.green(albumName)})`); - } + parts.push(` (${colors.yellow(num + range)} in ${colors.green(`"${albumName}"`)})`); } return parts.join(''); diff --git a/src/data/things/art-tag.js b/src/data/things/art-tag.js index 3149b310..f4fedf49 100644 --- a/src/data/things/art-tag.js +++ b/src/data/things/art-tag.js @@ -1,31 +1,51 @@ +export const DATA_ART_TAGS_DIRECTORY = 'art-tags'; export const ART_TAG_DATA_FILE = 'tags.yaml'; -import {input} from '#composite'; -import {sortAlphabetically, sortAlbumsTracksChronologically} from '#sort'; +import {readFile} from 'node:fs/promises'; +import * as path from 'node:path'; + +import {input, V} from '#composite'; +import {traverse} from '#node-utils'; +import {sortAlphabetically} from '#sort'; import Thing from '#thing'; +import {unique} from '#sugar'; import {isName} from '#validators'; +import {parseAdditionalNames, parseAnnotatedReferences} from '#yaml'; -import {exposeUpdateValueOrContinue} from '#composite/control-flow'; +import { + exitWithoutDependency, + exposeConstant, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; import { + annotatedReferenceList, color, + contentString, directory, flag, + referenceList, + reverseReferenceList, name, - wikiData, + soupyFind, + soupyReverse, + thingList, + urls, } from '#composite/wiki-properties'; export class ArtTag extends Thing { static [Thing.referenceType] = 'tag'; static [Thing.friendlyName] = `Art Tag`; + static [Thing.wikiData] = 'artTagData'; - static [Thing.getPropertyDescriptors] = ({Album, Track}) => ({ + static [Thing.getPropertyDescriptors] = ({AdditionalName}) => ({ // Update & expose - name: name('Unnamed Art Tag'), + name: name(V('Unnamed Art Tag')), directory: directory(), color: color(), - isContentWarning: flag(false), + isContentWarning: flag(V(false)), + extraReadingURLs: urls(), nameShort: [ exposeUpdateValueOrContinue({ @@ -39,30 +59,96 @@ export class ArtTag extends Thing { }, ], - // Update only + additionalNames: thingList(V(AdditionalName)), - albumData: wikiData({ - class: input.value(Album), + description: contentString(), + + directDescendantArtTags: referenceList({ + class: input.value(ArtTag), + find: soupyFind.input('artTag'), }), - trackData: wikiData({ - class: input.value(Track), + relatedArtTags: annotatedReferenceList({ + class: input.value(ArtTag), + find: soupyFind.input('artTag'), + + reference: input.value('artTag'), + thing: input.value('artTag'), }), + // Update only + + find: soupyFind(), + reverse: soupyReverse(), + // Expose only - taggedInThings: { - flags: {expose: true}, + isArtTag: exposeConstant(V(true)), - expose: { - dependencies: ['this', 'albumData', 'trackData'], - compute: ({this: artTag, albumData, trackData}) => - sortAlbumsTracksChronologically( - [...albumData, ...trackData] - .filter(({artTags}) => artTags.includes(artTag)), - {getDate: thing => thing.coverArtDate ?? thing.date}), + descriptionShort: [ + exitWithoutDependency('description', { + value: input.value(null), + mode: input.value('falsy'), + }), + + { + dependencies: ['description'], + compute: ({description}) => + description.split('<hr class="split">')[0], }, - }, + ], + + directlyFeaturedInArtworks: reverseReferenceList({ + reverse: soupyReverse.input('artworksWhichFeature'), + }), + + indirectlyFeaturedInArtworks: [ + { + dependencies: ['allDescendantArtTags'], + compute: ({allDescendantArtTags}) => + unique( + allDescendantArtTags + .flatMap(artTag => artTag.directlyFeaturedInArtworks)), + }, + ], + + // All the art tags which descend from this one - that means its own direct + // descendants, plus all the direct and indirect descendants of each of those! + // The results aren't specially sorted, but they won't contain any duplicates + // (for example if two descendant tags both route deeper to end up including + // some of the same tags). + allDescendantArtTags: [ + { + dependencies: ['directDescendantArtTags'], + compute: ({directDescendantArtTags}) => + unique([ + ...directDescendantArtTags, + ...directDescendantArtTags.flatMap(artTag => artTag.allDescendantArtTags), + ]), + }, + ], + + directAncestorArtTags: reverseReferenceList({ + reverse: soupyReverse.input('artTagsWhichDirectlyAncestor'), + }), + + // All the art tags which are ancestors of this one as a "baobab tree" - + // what you'd typically think of as roots are all up in the air! Since this + // really is backwards from the way that the art tag tree is written in data, + // chances are pretty good that there will be many of the exact same "leaf" + // nodes - art tags which don't themselves have any ancestors. In the actual + // data structure, each node is a Map, with keys for each ancestor and values + // for each ancestor's own baobab (thus a branching structure, just like normal + // trees in this regard). + ancestorArtTagBaobabTree: [ + { + dependencies: ['directAncestorArtTags'], + compute: ({directAncestorArtTags}) => + new Map( + directAncestorArtTags + .map(artTag => [artTag, artTag.ancestorArtTagBaobabTree])), + }, + ], }); static [Thing.findSpecs] = { @@ -70,10 +156,19 @@ export class ArtTag extends Thing { referenceTypes: ['tag'], bindTo: 'artTagData', - getMatchableNames: tag => - (tag.isContentWarning - ? [`cw: ${tag.name}`] - : [tag.name]), + getMatchableNames: artTag => + (artTag.isContentWarning + ? [`cw: ${artTag.name}`] + : [artTag.name]), + }, + }; + + static [Thing.reverseSpecs] = { + artTagsWhichDirectlyAncestor: { + bindTo: 'artTagData', + + referencing: artTag => [artTag], + referenced: artTag => artTag.directDescendantArtTags, }, }; @@ -82,23 +177,51 @@ export class ArtTag extends Thing { 'Tag': {property: 'name'}, 'Short Name': {property: 'nameShort'}, 'Directory': {property: 'directory'}, + 'Description': {property: 'description'}, + 'Extra Reading URLs': {property: 'extraReadingURLs'}, + + 'Additional Names': { + property: 'additionalNames', + transform: parseAdditionalNames, + }, 'Color': {property: 'color'}, 'Is CW': {property: 'isContentWarning'}, + + 'Direct Descendant Tags': {property: 'directDescendantArtTags'}, + + 'Related Tags': { + property: 'relatedArtTags', + transform: entries => + parseAnnotatedReferences(entries, { + referenceField: 'Tag', + referenceProperty: 'artTag', + }), + }, }, }; static [Thing.getYamlLoadingSpec] = ({ - documentModes: {allInOne}, + documentModes: {allTogether}, thingConstructors: {ArtTag}, }) => ({ title: `Process art tags file`, - file: ART_TAG_DATA_FILE, - documentMode: allInOne, - documentThing: ArtTag, + files: dataPath => + Promise.allSettled([ + readFile(path.join(dataPath, ART_TAG_DATA_FILE)) + .then(() => [ART_TAG_DATA_FILE]), - save: (results) => ({artTagData: results}), + traverse(path.join(dataPath, DATA_ART_TAGS_DIRECTORY), { + filterFile: name => path.extname(name) === '.yaml', + prefixPath: DATA_ART_TAGS_DIRECTORY, + }), + ]).then(results => results + .filter(({status}) => status === 'fulfilled') + .flatMap(({value}) => value)), + + documentMode: allTogether, + documentThing: ArtTag, sort({artTagData}) { sortAlphabetically(artTagData); diff --git a/src/data/things/artist.js b/src/data/things/artist.js index 8fdb8a12..a2ed0b74 100644 --- a/src/data/things/artist.js +++ b/src/data/things/artist.js @@ -4,151 +4,202 @@ import {inspect} from 'node:util'; import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; -import find from '#find'; -import {sortAlphabetically} from '#sort'; -import {stitchArrays, unique} from '#sugar'; +import {input, V} from '#composite'; import Thing from '#thing'; -import {isName, validateArrayItems} from '#validators'; -import {getKebabCase} from '#wiki-data'; +import {parseArtistAliases, parseArtwork} from '#yaml'; -import {exposeDependency} from '#composite/control-flow'; -import {withReverseContributionList} from '#composite/wiki-data'; +import { + sortAlbumsTracksChronologically, + sortArtworksChronologically, + sortAlphabetically, + sortContributionsChronologically, +} from '#sort'; + +import {exitWithoutDependency, exposeConstant, exposeDependency} + from '#composite/control-flow'; +import {withFilteredList, withPropertyFromList} from '#composite/data'; +import {withContributionListSums} from '#composite/wiki-data'; import { + constitutibleArtwork, contentString, directory, fileExtension, flag, name, - reverseAnnotatedReferenceList, - reverseContributionList, reverseReferenceList, - singleReference, + soupyFind, + soupyReverse, + thing, + thingList, urls, - wikiData, } from '#composite/wiki-properties'; -import {artistTotalDuration} from '#composite/things/artist'; - export class Artist extends Thing { static [Thing.referenceType] = 'artist'; - static [Thing.wikiDataArray] = 'artistData'; + static [Thing.wikiData] = 'artistData'; - static [Thing.getPropertyDescriptors] = ({Album, Flash, Group, Track}) => ({ + static [Thing.constitutibleProperties] = [ + 'avatarArtwork', // from inline fields + ]; + + static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - name: name('Unnamed Artist'), + name: name(V('Unnamed Artist')), directory: directory(), urls: urls(), contextNotes: contentString(), - hasAvatar: flag(false), - avatarFileExtension: fileExtension('jpg'), + hasAvatar: flag(V(false)), + avatarFileExtension: fileExtension(V('jpg')), - aliasNames: { - flags: {update: true, expose: true}, - update: {validate: validateArrayItems(isName)}, - expose: {transform: (names) => names ?? []}, - }, + avatarArtwork: [ + exitWithoutDependency('hasAvatar', { + value: input.value(null), + mode: input.value('falsy'), + }), - isAlias: flag(), + constitutibleArtwork.fromYAMLFieldSpec + .call(this, 'Avatar Artwork'), + ], - aliasedArtist: singleReference({ - class: input.value(Artist), - find: input.value(find.artist), - data: 'artistData', - }), + isAlias: flag(V(false)), + artistAliases: thingList(V(Artist)), + aliasedArtist: thing(V(Artist)), // Update only - albumData: wikiData({ - class: input.value(Album), - }), + find: soupyFind(), + reverse: soupyReverse(), - artistData: wikiData({ - class: input.value(Artist), - }), - - flashData: wikiData({ - class: input.value(Flash), - }), + // Expose only - groupData: wikiData({ - class: input.value(Group), - }), + isArtist: exposeConstant(V(true)), - trackData: wikiData({ - class: input.value(Track), + trackArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('trackArtistContributionsBy'), }), - // Expose only - - trackArtistContributions: reverseContributionList({ - data: 'trackData', - list: input.value('artistContribs'), + trackContributorContributions: reverseReferenceList({ + reverse: soupyReverse.input('trackContributorContributionsBy'), }), - trackContributorContributions: reverseContributionList({ - data: 'trackData', - list: input.value('contributorContribs'), + trackCoverArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('trackCoverArtistContributionsBy'), }), - trackCoverArtistContributions: reverseContributionList({ - data: 'trackData', - list: input.value('coverArtistContribs'), + tracksAsCommentator: reverseReferenceList({ + reverse: soupyReverse.input('tracksWithCommentaryBy'), }), - tracksAsCommentator: reverseReferenceList({ - data: 'trackData', - list: input.value('commentatorArtists'), + albumArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('albumArtistContributionsBy'), }), - albumArtistContributions: reverseContributionList({ - data: 'albumData', - list: input.value('artistContribs'), + albumTrackArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('albumTrackArtistContributionsBy'), }), - albumCoverArtistContributions: reverseContributionList({ - data: 'albumData', - list: input.value('coverArtistContribs'), + albumCoverArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('albumCoverArtistContributionsBy'), }), - albumWallpaperArtistContributions: reverseContributionList({ - data: 'albumData', - list: input.value('wallpaperArtistContribs'), + albumWallpaperArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('albumWallpaperArtistContributionsBy'), }), - albumBannerArtistContributions: reverseContributionList({ - data: 'albumData', - list: input.value('bannerArtistContribs'), + albumBannerArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('albumBannerArtistContributionsBy'), }), albumsAsCommentator: reverseReferenceList({ - data: 'albumData', - list: input.value('commentatorArtists'), + reverse: soupyReverse.input('albumsWithCommentaryBy'), }), - flashContributorContributions: reverseContributionList({ - data: 'flashData', - list: input.value('contributorContribs'), + flashContributorContributions: reverseReferenceList({ + reverse: soupyReverse.input('flashContributorContributionsBy'), }), flashesAsCommentator: reverseReferenceList({ - data: 'flashData', - list: input.value('commentatorArtists'), + reverse: soupyReverse.input('flashesWithCommentaryBy'), }), - closelyLinkedGroups: reverseAnnotatedReferenceList({ - data: 'groupData', - list: input.value('closelyLinkedArtists'), - - forward: input.value('artist'), - backward: input.value('group'), + closelyLinkedGroups: reverseReferenceList({ + reverse: soupyReverse.input('groupsCloselyLinkedTo'), }), - totalDuration: artistTotalDuration(), + musicContributions: [ + { + dependencies: [ + 'trackArtistContributions', + 'trackContributorContributions', + ], + + compute: (continuation, { + trackArtistContributions, + trackContributorContributions, + }) => continuation({ + ['#contributions']: [ + ...trackArtistContributions, + ...trackContributorContributions, + ], + }), + }, + + { + dependencies: ['#contributions'], + compute: ({'#contributions': contributions}) => + sortContributionsChronologically( + contributions, + sortAlbumsTracksChronologically), + }, + ], + + artworkContributions: [ + { + dependencies: [ + 'trackCoverArtistContributions', + 'albumCoverArtistContributions', + 'albumWallpaperArtistContributions', + 'albumBannerArtistContributions', + ], + + compute: (continuation, { + trackCoverArtistContributions, + albumCoverArtistContributions, + albumWallpaperArtistContributions, + albumBannerArtistContributions, + }) => continuation({ + ['#contributions']: [ + ...trackCoverArtistContributions, + ...albumCoverArtistContributions, + ...albumWallpaperArtistContributions, + ...albumBannerArtistContributions, + ], + }), + }, + + { + dependencies: ['#contributions'], + compute: ({'#contributions': contributions}) => + sortContributionsChronologically( + contributions, + sortArtworksChronologically), + }, + ], + + totalDuration: [ + withPropertyFromList('musicContributions', V('thing')), + withPropertyFromList('#musicContributions.thing', V('isMainRelease')), + + withFilteredList('musicContributions', '#musicContributions.thing.isMainRelease') + .outputs({'#filteredList': '#mainReleaseContributions'}), + + withContributionListSums('#mainReleaseContributions'), + exposeDependency('#contributionListDuration'), + ], }); static [Thing.getSerializeDescriptors] = ({ @@ -162,8 +213,6 @@ export class Artist extends Thing { hasAvatar: S.id, avatarFileExtension: S.id, - aliasNames: S.id, - tracksAsCommentator: S.toRefs, albumsAsCommentator: S.toRefs, }); @@ -194,17 +243,9 @@ export class Artist extends Thing { // in the original's alias list. This is honestly a bit awkward, but it // avoids artist aliases conflicting with each other when checking for // duplicate directories. - for (const aliasName of originalArtist.aliasNames) { - // These are trouble. We should be accessing aliases' directories - // directly, but artists currently don't expose a reverse reference - // list for aliases. (This is pending a cleanup of "reverse reference" - // behavior in general.) It doesn't actually cause problems *here* - // because alias directories are computed from their names 100% of the - // time, but that *is* an assumption this code makes. - if (aliasName === artist.name) continue; - if (artist.directory === getKebabCase(aliasName)) { - return []; - } + for (const alias of originalArtist.artistAliases) { + if (alias === artist) break; + if (alias.directory === artist.directory) return []; } // And, aliases never return just a blank string. This part is pretty @@ -230,10 +271,24 @@ export class Artist extends Thing { 'URLs': {property: 'urls'}, 'Context Notes': {property: 'contextNotes'}, + // note: doesn't really work as an independent field yet + 'Avatar Artwork': { + property: 'avatarArtwork', + transform: + parseArtwork({ + single: true, + thingProperty: 'avatarArtwork', + fileExtensionFromThingProperty: 'avatarFileExtension', + }), + }, + 'Has Avatar': {property: 'hasAvatar'}, 'Avatar File Extension': {property: 'avatarFileExtension'}, - 'Aliases': {property: 'aliasNames'}, + 'Aliases': { + property: 'artistAliases', + transform: parseArtistAliases, + }, 'Dead URLs': {ignore: true}, @@ -251,33 +306,6 @@ export class Artist extends Thing { documentMode: allInOne, documentThing: Artist, - save(results) { - const artists = results; - - const artistRefs = - artists.map(artist => Thing.getReference(artist)); - - const artistAliasNames = - artists.map(artist => artist.aliasNames); - - const artistAliases = - stitchArrays({ - originalArtistRef: artistRefs, - aliasNames: artistAliasNames, - }).flatMap(({originalArtistRef, aliasNames}) => - aliasNames.map(name => { - const alias = new Artist(); - alias.name = name; - alias.isAlias = true; - alias.aliasedArtist = originalArtistRef; - return alias; - })); - - const artistData = [...artists, ...artistAliases]; - - return {artistData}; - }, - sort({artistData}) { sortAlphabetically(artistData); }, @@ -294,7 +322,7 @@ export class Artist extends Thing { let aliasedArtist; try { aliasedArtist = this.aliasedArtist.name; - } catch (_error) { + } catch { aliasedArtist = CacheableObject.getUpdateValue(this, 'aliasedArtist'); } @@ -303,4 +331,12 @@ export class Artist extends Thing { return parts.join(''); } + + getOwnArtworkPath(artwork) { + return [ + 'media.artistAvatar', + this.directory, + artwork.fileExtension, + ]; + } } diff --git a/src/data/things/artwork.js b/src/data/things/artwork.js new file mode 100644 index 00000000..c1aafa8f --- /dev/null +++ b/src/data/things/artwork.js @@ -0,0 +1,422 @@ +import {inspect} from 'node:util'; + +import {colors} from '#cli'; +import {input, V} from '#composite'; +import find from '#find'; +import Thing from '#thing'; + +import { + isContentString, + isContributionList, + isDate, + isDimensions, + isFileExtension, + optional, + validateArrayItems, + validateProperties, + validateReference, + validateReferenceList, +} from '#validators'; + +import { + parseAnnotatedReferences, + parseContributors, + parseDate, + parseDimensions, +} from '#yaml'; + +import { + exitWithoutDependency, + exposeConstant, + exposeDependency, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, + flipFilter, +} from '#composite/control-flow'; + +import { + withFilteredList, + withNearbyItemFromList, + withPropertyFromList, + withPropertyFromObject, +} from '#composite/data'; + +import { + constituteFrom, + constituteOrContinue, + withRecontextualizedContributionList, + withResolvedAnnotatedReferenceList, + withResolvedContribs, + withResolvedReferenceList, +} from '#composite/wiki-data'; + +import { + contentString, + directory, + flag, + reverseReferenceList, + simpleString, + soupyFind, + soupyReverse, + thing, + wikiData, +} from '#composite/wiki-properties'; + +import {withContainingArtworkList} from '#composite/things/artwork'; + +export class Artwork extends Thing { + static [Thing.referenceType] = 'artwork'; + static [Thing.wikiData] = 'artworkData'; + + static [Thing.constitutibleProperties] = [ + // Contributions currently aren't being observed for constitution. + // 'artistContribs', // from attached artwork or thing + ]; + + static [Thing.getPropertyDescriptors] = ({ArtTag}) => ({ + // Update & expose + + unqualifiedDirectory: directory({ + name: input.value(null), + }), + + thing: thing(), + thingProperty: simpleString(), + + label: simpleString(), + source: contentString(), + originDetails: contentString(), + showFilename: simpleString(), + + dateFromThingProperty: simpleString(), + + date: [ + exposeUpdateValueOrContinue({ + validate: input.value(isDate), + }), + + constituteFrom('thing', 'dateFromThingProperty'), + ], + + fileExtensionFromThingProperty: simpleString(), + + fileExtension: [ + exposeUpdateValueOrContinue({ + validate: input.value(isFileExtension), + }), + + constituteFrom('thing', 'fileExtensionFromThingProperty', { + else: input.value('jpg'), + }), + ], + + dimensionsFromThingProperty: simpleString(), + + dimensions: [ + exposeUpdateValueOrContinue({ + validate: input.value(isDimensions), + }), + + constituteFrom('thing', 'dimensionsFromThingProperty'), + ], + + attachAbove: flag(V(false)), + + artistContribsFromThingProperty: simpleString(), + artistContribsArtistProperty: simpleString(), + + artistContribs: [ + withResolvedContribs({ + from: input.updateValue({validate: isContributionList}), + date: 'date', + thingProperty: input.thisProperty(), + artistProperty: 'artistContribsArtistProperty', + }), + + exposeDependencyOrContinue('#resolvedContribs', V('empty')), + + withPropertyFromObject('attachedArtwork', V('artistContribs')), + + withRecontextualizedContributionList('#attachedArtwork.artistContribs'), + exposeDependencyOrContinue('#attachedArtwork.artistContribs'), + + exitWithoutDependency('artistContribsFromThingProperty', V([])), + + withPropertyFromObject('thing', 'artistContribsFromThingProperty') + .outputs({'#value': '#artistContribsFromThing'}), + + withRecontextualizedContributionList('#artistContribsFromThing'), + exposeDependency('#artistContribsFromThing'), + ], + + style: simpleString(), + + artTagsFromThingProperty: simpleString(), + + artTags: [ + withResolvedReferenceList({ + list: input.updateValue({ + validate: + validateReferenceList(ArtTag[Thing.referenceType]), + }), + find: soupyFind.input('artTag'), + }), + + exposeDependencyOrContinue('#resolvedReferenceList', V('empty')), + + constituteOrContinue('attachedArtwork', V('artTags'), V('empty')), + + constituteFrom('thing', 'artTagsFromThingProperty', V([])), + ], + + referencedArtworksFromThingProperty: simpleString(), + + referencedArtworks: [ + { + compute: (continuation) => continuation({ + ['#find']: + find.mixed({ + track: find.trackPrimaryArtwork, + album: find.albumPrimaryArtwork, + }), + }), + }, + + withResolvedAnnotatedReferenceList({ + list: input.updateValue({ + validate: + // TODO: It's annoying to hardcode this when it's really the + // same behavior as through annotatedReferenceList and through + // referenceListUpdateDescription, the latter of which isn't + // available outside of #composite/wiki-data internals. + validateArrayItems( + validateProperties({ + reference: validateReference(['album', 'track']), + annotation: optional(isContentString), + })), + }), + + data: '_artworkData', + find: '#find', + + thing: input.value('artwork'), + }), + + exposeDependencyOrContinue('#resolvedAnnotatedReferenceList', V('empty')), + + constituteFrom('thing', 'referencedArtworksFromThingProperty', { + else: input.value([]), + }), + ], + + // Update only + + find: soupyFind(), + reverse: soupyReverse(), + + // used for referencedArtworks (mixedFind) + artworkData: wikiData(V(Artwork)), + + // Expose only + + isArtwork: exposeConstant(V(true)), + + referencedByArtworks: reverseReferenceList({ + reverse: soupyReverse.input('artworksWhichReference'), + }), + + isMainArtwork: [ + withContainingArtworkList(), + exitWithoutDependency('#containingArtworkList'), + + { + dependencies: [input.myself(), '#containingArtworkList'], + compute: ({ + [input.myself()]: myself, + ['#containingArtworkList']: list, + }) => + list[0] === myself, + }, + ], + + mainArtwork: [ + withContainingArtworkList(), + exitWithoutDependency('#containingArtworkList'), + + { + dependencies: ['#containingArtworkList'], + compute: ({'#containingArtworkList': list}) => + list[0], + }, + ], + + attachedArtwork: [ + exitWithoutDependency('attachAbove', { + value: input.value(null), + mode: input.value('falsy'), + }), + + withContainingArtworkList(), + + withPropertyFromList('#containingArtworkList', V('attachAbove')), + + flipFilter('#containingArtworkList.attachAbove') + .outputs({'#containingArtworkList.attachAbove': '#filterNotAttached'}), + + withNearbyItemFromList({ + list: '#containingArtworkList', + item: input.myself(), + offset: input.value(-1), + filter: '#filterNotAttached', + }), + + exposeDependency('#nearbyItem'), + ], + + attachingArtworks: reverseReferenceList({ + reverse: soupyReverse.input('artworksWhichAttach'), + }), + + groups: [ + withPropertyFromObject('thing', V('groups')), + exposeDependencyOrContinue('#thing.groups'), + + exposeConstant(V([])), + ], + + contentWarningArtTags: [ + withPropertyFromList('artTags', V('isContentWarning')), + withFilteredList('artTags', '#artTags.isContentWarning'), + exposeDependency('#filteredList'), + ], + + contentWarnings: [ + withPropertyFromList('contentWarningArtTags', V('name')), + exposeDependency('#contentWarningArtTags.name'), + ], + + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Directory': {property: 'unqualifiedDirectory'}, + 'File Extension': {property: 'fileExtension'}, + + 'Dimensions': { + property: 'dimensions', + transform: parseDimensions, + }, + + 'Label': {property: 'label'}, + 'Source': {property: 'source'}, + 'Origin Details': {property: 'originDetails'}, + 'Show Filename': {property: 'showFilename'}, + + 'Date': { + property: 'date', + transform: parseDate, + }, + + 'Attach Above': {property: 'attachAbove'}, + + 'Artists': { + property: 'artistContribs', + transform: parseContributors, + }, + + 'Style': {property: 'style'}, + + 'Tags': {property: 'artTags'}, + + 'Referenced Artworks': { + property: 'referencedArtworks', + transform: parseAnnotatedReferences, + }, + }, + }; + + static [Thing.reverseSpecs] = { + artworksWhichReference: { + bindTo: 'artworkData', + + referencing: referencingArtwork => + referencingArtwork.referencedArtworks + .map(({artwork: referencedArtwork, ...referenceDetails}) => ({ + referencingArtwork, + referencedArtwork, + referenceDetails, + })), + + referenced: ({referencedArtwork}) => [referencedArtwork], + + tidy: ({referencingArtwork, referenceDetails}) => ({ + artwork: referencingArtwork, + ...referenceDetails, + }), + + date: ({artwork}) => artwork.date, + }, + + artworksWhichAttach: { + bindTo: 'artworkData', + + referencing: referencingArtwork => + (referencingArtwork.attachAbove + ? [referencingArtwork] + : []), + + referenced: referencingArtwork => + [referencingArtwork.attachedArtwork], + }, + + artworksWhichFeature: { + bindTo: 'artworkData', + + referencing: artwork => [artwork], + referenced: artwork => artwork.artTags, + }, + }; + + get path() { + if (!this.thing) return null; + if (!this.thing.getOwnArtworkPath) return null; + + return this.thing.getOwnArtworkPath(this); + } + + countOwnContributionInContributionTotals(contrib) { + if (this.attachAbove) { + return false; + } + + if (contrib.annotation?.startsWith('edits for wiki')) { + return false; + } + + return true; + } + + [inspect.custom](depth, options, inspect) { + const parts = []; + + parts.push(Thing.prototype[inspect.custom].apply(this)); + + if (this.thing) { + if (depth >= 0) { + const newOptions = { + ...options, + depth: + (options.depth === null + ? null + : options.depth - 1), + }; + + parts.push(` for ${inspect(this.thing, newOptions)}`); + } else { + parts.push(` for ${colors.blue(Thing.getReference(this.thing))}`); + } + } + + return parts.join(''); + } +} diff --git a/src/data/things/content.js b/src/data/things/content.js new file mode 100644 index 00000000..64d03e69 --- /dev/null +++ b/src/data/things/content.js @@ -0,0 +1,319 @@ +import {input, V} from '#composite'; +import {transposeArrays} from '#sugar'; +import Thing from '#thing'; +import {is, isDate, validateReferenceList} from '#validators'; +import {parseDate} from '#yaml'; + +import {withFilteredList, withMappedList, withPropertyFromList} + from '#composite/data'; +import {withResolvedReferenceList} from '#composite/wiki-data'; +import {contentString, simpleDate, soupyFind, thing} + from '#composite/wiki-properties'; + +import { + exitWithoutDependency, + exposeConstant, + exposeDependency, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, + withResultOfAvailabilityCheck, +} from '#composite/control-flow'; + +import { + hasAnnotationPart, + withAnnotationPartNodeLists, + withExpressedOrImplicitArtistReferences, + withWebArchiveDate, +} from '#composite/things/content'; + +export class ContentEntry extends Thing { + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + thing: thing(), + + artists: [ + withExpressedOrImplicitArtistReferences({ + from: input.updateValue({ + validate: validateReferenceList('artist'), + }), + }), + + exitWithoutDependency('#artistReferences', V([])), + + withResolvedReferenceList({ + list: '#artistReferences', + find: soupyFind.input('artist'), + }), + + exposeDependency('#resolvedReferenceList'), + ], + + artistText: contentString(), + + annotation: contentString(), + + dateKind: { + flags: {update: true, expose: true}, + + update: { + validate: is(...[ + 'sometime', + 'throughout', + 'around', + ]), + }, + }, + + accessKind: [ + exitWithoutDependency('_accessDate'), + + exposeUpdateValueOrContinue({ + validate: input.value( + is(...[ + 'captured', + 'accessed', + ])), + }), + + withWebArchiveDate(), + + withResultOfAvailabilityCheck({from: '#webArchiveDate'}), + + { + dependencies: ['#availability'], + compute: (continuation, {['#availability']: availability}) => + (availability + ? continuation.exit('captured') + : continuation()), + }, + + exposeConstant(V('accessed')), + ], + + date: simpleDate(), + secondDate: simpleDate(), + + accessDate: [ + exposeUpdateValueOrContinue({ + validate: input.value(isDate), + }), + + withWebArchiveDate(), + + exposeDependencyOrContinue({ + dependency: '#webArchiveDate', + }), + + exposeConstant(V(null)), + ], + + body: contentString(), + + // Update only + + find: soupyFind(), + + // Expose only + + isContentEntry: exposeConstant(V(true)), + + annotationParts: [ + withAnnotationPartNodeLists(), + + { + dependencies: ['#annotationPartNodeLists'], + compute: (continuation, { + ['#annotationPartNodeLists']: nodeLists, + }) => continuation({ + ['#firstNodes']: + nodeLists.map(list => list.at(0)), + + ['#lastNodes']: + nodeLists.map(list => list.at(-1)), + }), + }, + + withPropertyFromList('#firstNodes', V('i')) + .outputs({'#firstNodes.i': '#startIndices'}), + + withPropertyFromList('#lastNodes', V('iEnd')) + .outputs({'#lastNodes.iEnd': '#endIndices'}), + + { + dependencies: [ + 'annotation', + '#startIndices', + '#endIndices', + ], + + compute: ({ + ['annotation']: annotation, + ['#startIndices']: startIndices, + ['#endIndices']: endIndices, + }) => + transposeArrays([startIndices, endIndices]) + .map(([start, end]) => + annotation.slice(start, end)), + }, + ], + + sourceText: [ + withAnnotationPartNodeLists(), + + { + dependencies: ['#annotationPartNodeLists'], + compute: (continuation, { + ['#annotationPartNodeLists']: nodeLists, + }) => continuation({ + ['#firstPartWithExternalLink']: + nodeLists + .find(nodes => nodes + .some(node => node.type === 'external-link')) ?? + null, + }), + }, + + exitWithoutDependency('#firstPartWithExternalLink'), + + { + dependencies: ['annotation', '#firstPartWithExternalLink'], + compute: ({ + ['annotation']: annotation, + ['#firstPartWithExternalLink']: nodes, + }) => + annotation.slice( + nodes.at(0).i, + nodes.at(-1).iEnd), + }, + ], + + sourceURLs: [ + withAnnotationPartNodeLists(), + + { + dependencies: ['#annotationPartNodeLists'], + compute: (continuation, { + ['#annotationPartNodeLists']: nodeLists, + }) => continuation({ + ['#firstPartWithExternalLink']: + nodeLists + .find(nodes => nodes + .some(node => node.type === 'external-link')) ?? + null, + }), + }, + + exitWithoutDependency('#firstPartWithExternalLink', V([])), + + withMappedList({ + list: '#firstPartWithExternalLink', + map: input.value(node => node.type === 'external-link'), + }).outputs({ + '#mappedList': '#externalLinkFilter', + }), + + withFilteredList({ + list: '#firstPartWithExternalLink', + filter: '#externalLinkFilter', + }), + + withMappedList({ + list: '#filteredList', + map: input.value(node => node.data.href), + }), + + exposeDependency('#mappedList'), + ], + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Artists': {property: 'artists'}, + 'Artist Text': {property: 'artistText'}, + + 'Annotation': {property: 'annotation'}, + + 'Date Kind': {property: 'dateKind'}, + 'Access Kind': {property: 'accessKind'}, + + 'Date': {property: 'date', transform: parseDate}, + 'Second Date': {property: 'secondDate', transform: parseDate}, + 'Access Date': {property: 'accessDate', transform: parseDate}, + + 'Body': {property: 'body'}, + }, + }; +} + +export class CommentaryEntry extends ContentEntry { + static [Thing.wikiData] = 'commentaryData'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Expose only + + isCommentaryEntry: [ + exposeConstant({ + value: input.value(true), + }), + ], + + isWikiEditorCommentary: hasAnnotationPart({ + part: input.value('wiki editor'), + }), + }); +} + +export class LyricsEntry extends ContentEntry { + static [Thing.wikiData] = 'lyricsData'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + originDetails: contentString(), + + // Expose only + + isLyricsEntry: exposeConstant(V(true)), + + isWikiLyrics: hasAnnotationPart(V('wiki lyrics')), + helpNeeded: hasAnnotationPart(V('help needed')), + + hasSquareBracketAnnotations: [ + exitWithoutDependency('isWikiLyrics', V(false), V('falsy')), + exitWithoutDependency('body', V(false)), + + { + dependencies: ['body'], + compute: ({body}) => + /\[.*\]/m.test(body), + }, + ], + }); + + static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(ContentEntry, { + fields: { + 'Origin Details': {property: 'originDetails'}, + }, + }); +} + +export class CreditingSourcesEntry extends ContentEntry { + static [Thing.wikiData] = 'creditingSourceData'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Expose only + + isCreditingSourcesEntry: exposeConstant(V(true)), + }); +} + +export class ReferencingSourcesEntry extends ContentEntry { + static [Thing.wikiData] = 'referencingSourceData'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Expose only + + isReferencingSourceEntry: exposeConstant(V(true)), + }); +} diff --git a/src/data/things/contribution.js b/src/data/things/contribution.js index 2712af70..393a60b4 100644 --- a/src/data/things/contribution.js +++ b/src/data/things/contribution.js @@ -2,14 +2,21 @@ import {inspect} from 'node:util'; import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; +import {input, V} from '#composite'; import {empty} from '#sugar'; import Thing from '#thing'; -import {isStringNonEmpty, isThing, validateReference} from '#validators'; +import {isBoolean, isStringNonEmpty, isThing} from '#validators'; -import {exitWithoutDependency, exposeDependency} from '#composite/control-flow'; -import {withResolvedReference} from '#composite/wiki-data'; -import {flag, simpleDate} from '#composite/wiki-properties'; +import {simpleDate, singleReference, soupyFind} + from '#composite/wiki-properties'; + +import { + exitWithoutDependency, + exposeConstant, + exposeDependency, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; import { withFilteredList, @@ -20,12 +27,8 @@ import { import { inheritFromContributionPresets, - thingPropertyMatches, - thingReferenceTypeMatches, withContainingReverseContributionList, - withContributionArtist, withContributionContext, - withMatchingContributionPresets, } from '#composite/things/contribution'; export class Contribution extends Thing { @@ -49,17 +52,9 @@ export class Contribution extends Thing { date: simpleDate(), - artist: [ - withContributionArtist({ - ref: input.updateValue({ - validate: validateReference('artist'), - }), - }), - - exposeDependency({ - dependency: '#artist', - }), - ], + artist: singleReference({ + find: soupyFind.input('artist'), + }), annotation: { flags: {update: true, expose: true}, @@ -67,23 +62,65 @@ export class Contribution extends Thing { }, countInContributionTotals: [ - inheritFromContributionPresets({ - property: input.thisProperty(), + inheritFromContributionPresets(), + + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - flag(true), + { + dependencies: ['thing', input.myself()], + compute: (continuation, { + ['thing']: thing, + [input.myself()]: contribution, + }) => + (thing.countOwnContributionInContributionTotals?.(contribution) + ? true + : thing.countOwnContributionInContributionTotals + ? false + : continuation()), + }, + + exposeConstant(V(true)), ], countInDurationTotals: [ - inheritFromContributionPresets({ - property: input.thisProperty(), + inheritFromContributionPresets(), + + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - flag(true), + withPropertyFromObject('thing', V('duration')), + exitWithoutDependency('#thing.duration', { + value: input.value(false), + mode: input.value('falsy'), + }), + + { + dependencies: ['thing', input.myself()], + compute: (continuation, { + ['thing']: thing, + [input.myself()]: contribution, + }) => + (thing.countOwnContributionInDurationTotals?.(contribution) + ? true + : thing.countOwnContributionInDurationTotals + ? false + : continuation()), + }, + + exposeConstant(V(true)), ], + // Update only + + find: soupyFind(), + // Expose only + isContribution: exposeConstant(V(true)), + context: [ withContributionContext(), @@ -104,11 +141,43 @@ export class Contribution extends Thing { ], matchingPresets: [ - withMatchingContributionPresets(), - - exposeDependency({ - dependency: '#matchingContributionPresets', + withPropertyFromObject('thing', { + property: input.value('wikiInfo'), + internal: input.value(true), }), + + exitWithoutDependency('#thing.wikiInfo', V([])), + + withPropertyFromObject('#thing.wikiInfo', V('contributionPresets')) + .outputs({'#thing.wikiInfo.contributionPresets': '#contributionPresets'}), + + exitWithoutDependency('#contributionPresets', V([]), V('empty')), + + withContributionContext(), + + // TODO: implementing this with compositional filters would be fun + { + dependencies: [ + '#contributionPresets', + '#contributionTarget', + '#contributionProperty', + 'annotation', + ], + + compute: ({ + ['#contributionPresets']: presets, + ['#contributionTarget']: target, + ['#contributionProperty']: property, + ['annotation']: annotation, + }) => + presets.filter(preset => + preset.context[0] === target && + preset.context.slice(1).includes(property) && + // For now, only match if the annotation is a complete match. + // Partial matches (e.g. because the contribution includes "two" + // annotations, separated by commas) don't count. + preset.annotation === annotation), + }, ], // All the contributions from the list which includes this contribution. @@ -116,27 +185,13 @@ export class Contribution extends Thing { // artist, but also this very contribution. It doesn't mix contributions // exposed on different properties. associatedContributions: [ - exitWithoutDependency({ - dependency: 'thing', - value: input.value([]), - }), - - exitWithoutDependency({ - dependency: 'thingProperty', - value: input.value([]), - }), + exitWithoutDependency('thing', V([])), + exitWithoutDependency('thingProperty', V([])), - withPropertyFromObject({ - object: 'thing', - property: 'thingProperty', - }).outputs({ - '#value': '#contributions', - }), + withPropertyFromObject('thing', 'thingProperty') + .outputs({'#value': '#contributions'}), - withPropertyFromList({ - list: '#contributions', - property: input.value('annotation'), - }), + withPropertyFromList('#contributions', V('annotation')), { dependencies: ['#contributions.annotation', 'annotation'], @@ -152,88 +207,37 @@ export class Contribution extends Thing { }), }, - withFilteredList({ - list: '#contributions', - filter: '#likeContributionsFilter', - }).outputs({ - '#filteredList': '#contributions', - }), + withFilteredList('#contributions', '#likeContributionsFilter') + .outputs({'#filteredList': '#contributions'}), - exposeDependency({ - dependency: '#contributions', - }), + exposeDependency('#contributions'), ], - isArtistContribution: thingPropertyMatches({ - value: input.value('artistContribs'), - }), - - isContributorContribution: thingPropertyMatches({ - value: input.value('contributorContribs'), - }), - - isCoverArtistContribution: thingPropertyMatches({ - value: input.value('coverArtistContribs'), - }), - - isBannerArtistContribution: thingPropertyMatches({ - value: input.value('bannerArtistContribs'), - }), - - isWallpaperArtistContribution: thingPropertyMatches({ - value: input.value('wallpaperArtistContribs'), - }), - - isForTrack: thingReferenceTypeMatches({ - value: input.value('track'), - }), - - isForAlbum: thingReferenceTypeMatches({ - value: input.value('album'), - }), - - isForFlash: thingReferenceTypeMatches({ - value: input.value('flash'), - }), - previousBySameArtist: [ - withContainingReverseContributionList().outputs({ - '#containingReverseContributionList': '#list', - }), - - exitWithoutDependency({ - dependency: '#list', - }), + withContainingReverseContributionList() + .outputs({'#containingReverseContributionList': '#list'}), - withNearbyItemFromList({ - list: '#list', - item: input.myself(), - offset: input.value(-1), - }), + exitWithoutDependency('#list'), - exposeDependency({ - dependency: '#nearbyItem', - }), + withNearbyItemFromList('#list', input.myself(), V(-1)), + exposeDependency('#nearbyItem'), ], nextBySameArtist: [ - withContainingReverseContributionList().outputs({ - '#containingReverseContributionList': '#list', - }), + withContainingReverseContributionList() + .outputs({'#containingReverseContributionList': '#list'}), - exitWithoutDependency({ - dependency: '#list', - }), + exitWithoutDependency('#list'), - withNearbyItemFromList({ - list: '#list', - item: input.myself(), - offset: input.value(+1), - }), + withNearbyItemFromList('#list', input.myself(), V(+1)), + exposeDependency('#nearbyItem'), + ], - exposeDependency({ - dependency: '#nearbyItem', - }), + groups: [ + withPropertyFromObject('thing', V('groups')), + exposeDependencyOrContinue('#thing.groups'), + + exposeConstant(V([])), ], }); @@ -256,7 +260,7 @@ export class Contribution extends Thing { let artist; try { artist = this.artist; - } catch (_error) { + } catch { // Computing artist might crash for any reason - don't distract from // other errors as a result of inspecting this contribution. } diff --git a/src/data/things/flash.js b/src/data/things/flash.js index aa6b9cd1..b595ec58 100644 --- a/src/data/things/flash.js +++ b/src/data/things/flash.js @@ -1,27 +1,33 @@ export const FLASH_DATA_FILE = 'flashes.yaml'; -import {input} from '#composite'; -import find from '#find'; -import {empty} from '#sugar'; +import {input, V} from '#composite'; import {sortFlashesChronologically} from '#sort'; import Thing from '#thing'; import {anyOf, isColor, isContentString, isDirectory, isNumber, isString} from '#validators'; -import {parseContributors, parseDate, parseDimensions} from '#yaml'; + +import { + parseArtwork, + parseAdditionalNames, + parseCommentary, + parseContributors, + parseCreditingSources, + parseDate, + parseDimensions, +} from '#yaml'; import {withPropertyFromObject} from '#composite/data'; import { exposeConstant, exposeDependency, - exposeDependencyOrContinue, exposeUpdateValueOrContinue, } from '#composite/control-flow'; import { color, - commentary, commentatorArtists, + constitutibleArtwork, contentString, contributionList, dimensions, @@ -30,26 +36,34 @@ import { name, referenceList, simpleDate, + soupyFind, + soupyReverse, thing, + thingList, urls, - wikiData, } from '#composite/wiki-properties'; -import {withFlashAct} from '#composite/things/flash'; -import {withFlashSide} from '#composite/things/flash-act'; - export class Flash extends Thing { static [Thing.referenceType] = 'flash'; + static [Thing.wikiData] = 'flashData'; + + static [Thing.constitutibleProperties] = [ + 'coverArtwork', // from inline fields + ]; static [Thing.getPropertyDescriptors] = ({ - Artist, - Track, + AdditionalName, + CommentaryEntry, + CreditingSourcesEntry, FlashAct, + Track, WikiInfo, }) => ({ // Update & expose - name: name('Unnamed Flash'), + act: thing(V(FlashAct)), + + name: name(V('Unnamed Flash')), directory: { flags: {update: true, expose: true}, @@ -82,74 +96,53 @@ export class Flash extends Thing { validate: input.value(isColor), }), - withFlashAct(), - - withPropertyFromObject({ - object: '#flashAct', - property: input.value('color'), - }), - - exposeDependency({dependency: '#flashAct.color'}), + withPropertyFromObject('act', V('color')), + exposeDependency('#act.color'), ], date: simpleDate(), - coverArtFileExtension: fileExtension('jpg'), + coverArtFileExtension: fileExtension(V('jpg')), coverArtDimensions: dimensions(), + coverArtwork: + constitutibleArtwork.fromYAMLFieldSpec + .call(this, 'Cover Artwork'), + contributorContribs: contributionList({ - date: 'date', artistProperty: input.value('flashContributorContributions'), }), featuredTracks: referenceList({ class: input.value(Track), - find: input.value(find.track), - data: 'trackData', + find: soupyFind.input('track'), }), urls: urls(), - commentary: commentary(), - creditSources: commentary(), + additionalNames: thingList(V(AdditionalName)), - // Update only + commentary: thingList(V(CommentaryEntry)), + creditingSources: thingList(V(CreditingSourcesEntry)), - artistData: wikiData({ - class: input.value(Artist), - }), + // Update only - trackData: wikiData({ - class: input.value(Track), - }), + find: soupyFind(), + reverse: soupyReverse(), - flashActData: wikiData({ - class: input.value(FlashAct), - }), - - wikiInfo: thing({ - class: input.value(WikiInfo), - }), + // used for withMatchingContributionPresets (indirectly by Contribution) + wikiInfo: thing(V(WikiInfo)), // Expose only - commentatorArtists: commentatorArtists(), + isFlash: exposeConstant(V(true)), - act: [ - withFlashAct(), - exposeDependency({dependency: '#flashAct'}), - ], + commentatorArtists: commentatorArtists(), side: [ - withFlashAct(), - - withPropertyFromObject({ - object: '#flashAct', - property: input.value('side'), - }), - - exposeDependency({dependency: '#flashAct.side'}), + withPropertyFromObject('act', V('side')), + exposeDependency('#act.side'), ], }); @@ -173,6 +166,25 @@ export class Flash extends Thing { }, }; + static [Thing.reverseSpecs] = { + flashesWhichFeature: { + bindTo: 'flashData', + + referencing: flash => [flash], + referenced: flash => flash.featuredTracks, + }, + + flashContributorContributionsBy: + soupyReverse.contributionsBy('flashData', 'contributorContribs'), + + flashesWithCommentaryBy: { + bindTo: 'flashData', + + referencing: flash => [flash], + referenced: flash => flash.commentatorArtists, + }, + }; + static [Thing.yamlDocumentSpec] = { fields: { 'Flash': {property: 'name'}, @@ -186,6 +198,22 @@ export class Flash extends Thing { transform: parseDate, }, + 'Additional Names': { + property: 'additionalNames', + transform: parseAdditionalNames, + }, + + 'Cover Artwork': { + property: 'coverArtwork', + transform: + parseArtwork({ + single: true, + thingProperty: 'coverArtwork', + fileExtensionFromThingProperty: 'coverArtFileExtension', + dimensionsFromThingProperty: 'coverArtDimensions', + }), + }, + 'Cover Art File Extension': {property: 'coverArtFileExtension'}, 'Cover Art Dimensions': { @@ -200,22 +228,40 @@ export class Flash extends Thing { transform: parseContributors, }, - 'Commentary': {property: 'commentary'}, - 'Credit Sources': {property: 'creditSources'}, + 'Commentary': { + property: 'commentary', + transform: parseCommentary, + }, + + 'Crediting Sources': { + property: 'creditingSources', + transform: parseCreditingSources, + }, 'Review Points': {ignore: true}, }, }; + + getOwnArtworkPath(artwork) { + return [ + 'media.flashArt', + this.directory, + artwork.fileExtension, + ]; + } } export class FlashAct extends Thing { static [Thing.referenceType] = 'flash-act'; static [Thing.friendlyName] = `Flash Act`; + static [Thing.wikiData] = 'flashActData'; - static [Thing.getPropertyDescriptors] = () => ({ + static [Thing.getPropertyDescriptors] = ({Flash, FlashSide}) => ({ // Update & expose - name: name('Unnamed Flash Act'), + side: thing(V(FlashSide)), + + name: name(V('Unnamed Flash Act')), directory: directory(), color: color(), @@ -224,44 +270,20 @@ export class FlashAct extends Thing { validate: input.value(isContentString), }), - withFlashSide(), - - withPropertyFromObject({ - object: '#flashSide', - property: input.value('listTerminology'), - }), - - exposeDependencyOrContinue({ - dependency: '#flashSide.listTerminology', - }), - - exposeConstant({ - value: input.value(null), - }), + withPropertyFromObject('side', V('listTerminology')), + exposeDependency('#side.listTerminology'), ], - flashes: referenceList({ - class: input.value(Flash), - find: input.value(find.flash), - data: 'flashData', - }), + flashes: thingList(V(Flash)), // Update only - flashData: wikiData({ - class: input.value(Flash), - }), - - flashSideData: wikiData({ - class: input.value(FlashSide), - }), + find: soupyFind(), + reverse: soupyReverse(), // Expose only - side: [ - withFlashSide(), - exposeDependency({dependency: '#flashSide'}), - ], + isFlashAct: exposeConstant(V(true)), }); static [Thing.findSpecs] = { @@ -271,6 +293,15 @@ export class FlashAct extends Thing { }, }; + static [Thing.reverseSpecs] = { + flashActsWhoseFlashesInclude: { + bindTo: 'flashActData', + + referencing: flashAct => [flashAct], + referenced: flashAct => flashAct.flashes, + }, + }; + static [Thing.yamlDocumentSpec] = { fields: { 'Act': {property: 'name'}, @@ -287,26 +318,25 @@ export class FlashAct extends Thing { export class FlashSide extends Thing { static [Thing.referenceType] = 'flash-side'; static [Thing.friendlyName] = `Flash Side`; + static [Thing.wikiData] = 'flashSideData'; - static [Thing.getPropertyDescriptors] = () => ({ + static [Thing.getPropertyDescriptors] = ({FlashAct}) => ({ // Update & expose - name: name('Unnamed Flash Side'), + name: name(V('Unnamed Flash Side')), directory: directory(), color: color(), listTerminology: contentString(), - acts: referenceList({ - class: input.value(FlashAct), - find: input.value(find.flashAct), - data: 'flashActData', - }), + acts: thingList(V(FlashAct)), // Update only - flashActData: wikiData({ - class: input.value(FlashAct), - }), + find: soupyFind(), + + // Expose only + + isFlashSide: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { @@ -325,6 +355,15 @@ export class FlashSide extends Thing { }, }; + static [Thing.reverseSpecs] = { + flashSidesWhoseActsInclude: { + bindTo: 'flashSideData', + + referencing: flashSide => [flashSide], + referenced: flashSide => flashSide.acts, + }, + }; + static [Thing.getYamlLoadingSpec] = ({ documentModes: {allInOne}, thingConstructors: {Flash, FlashAct}, @@ -340,50 +379,61 @@ export class FlashSide extends Thing { ? FlashAct : Flash), - save(results) { - // JavaScript likes you. + connect(results) { + let thing, i; - if (!empty(results) && !(results[0] instanceof FlashSide)) { - throw new Error(`Expected a side at top of flash data file`); - } + for (i = 0; thing = results[i]; i++) { + if (thing.isFlashSide) { + const side = thing; + const acts = []; - let index = 0; - let thing; - for (; thing = results[index]; index++) { - const flashSide = thing; - const flashActRefs = []; + for (i++; thing = results[i]; i++) { + if (thing.isFlashAct) { + const act = thing; + const flashes = []; - if (results[index + 1] instanceof Flash) { - throw new Error(`Expected an act to immediately follow a side`); - } + for (i++; thing = results[i]; i++) { + if (thing.isFlash) { + const flash = thing; + + flash.act = act; + flashes.push(flash); + + continue; + } - for ( - index++; - (thing = results[index]) && thing instanceof FlashAct; - index++ - ) { - const flashAct = thing; - const flashRefs = []; - for ( - index++; - (thing = results[index]) && thing instanceof Flash; - index++ - ) { - flashRefs.push(Thing.getReference(thing)); + i--; + break; + } + + act.side = side; + act.flashes = flashes; + acts.push(act); + + continue; + } + + if (thing.isFlash) { + throw new Error(`Flashes must be under an act`); + } + + i--; + break; } - index--; - flashAct.flashes = flashRefs; - flashActRefs.push(Thing.getReference(flashAct)); + + side.acts = acts; + + continue; } - index--; - flashSide.acts = flashActRefs; - } - const flashData = results.filter(x => x instanceof Flash); - const flashActData = results.filter(x => x instanceof FlashAct); - const flashSideData = results.filter(x => x instanceof FlashSide); + if (thing.isFlashAct) { + throw new Error(`Acts must be under a side`); + } - return {flashData, flashActData, flashSideData}; + if (thing.isFlash) { + throw new Error(`Flashes must be under a side and act`); + } + } }, sort({flashData}) { diff --git a/src/data/things/group.js b/src/data/things/group.js index 8418cb99..cc5f4cb8 100644 --- a/src/data/things/group.js +++ b/src/data/things/group.js @@ -1,41 +1,73 @@ export const GROUP_DATA_FILE = 'groups.yaml'; -import {input} from '#composite'; -import find from '#find'; +import {inspect} from 'node:util'; + +import {colors} from '#cli'; +import {input, V} from '#composite'; import Thing from '#thing'; +import {is, isBoolean} from '#validators'; import {parseAnnotatedReferences, parseSerieses} from '#yaml'; +import {withPropertyFromObject} from '#composite/data'; +import {withUniqueReferencingThing} from '#composite/wiki-data'; + +import { + exposeConstant, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; + import { annotatedReferenceList, color, contentString, directory, + flag, name, referenceList, - seriesList, + soupyFind, + soupyReverse, + thing, + thingList, urls, - wikiData, } from '#composite/wiki-properties'; export class Group extends Thing { static [Thing.referenceType] = 'group'; + static [Thing.wikiData] = 'groupData'; - static [Thing.getPropertyDescriptors] = ({Album, Artist}) => ({ + static [Thing.getPropertyDescriptors] = ({Album, Artist, Series}) => ({ // Update & expose - name: name('Unnamed Group'), + name: name(V('Unnamed Group')), directory: directory(), + excludeFromGalleryTabs: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withUniqueReferencingThing({ + reverse: soupyReverse.input('groupCategoriesWhichInclude'), + }).outputs({ + '#uniqueReferencingThing': '#category', + }), + + withPropertyFromObject('#category', V('excludeGroupsFromGalleryTabs')), + exposeDependencyOrContinue('#category.excludeGroupsFromGalleryTabs'), + + exposeConstant(V(false)), + ], + + divideAlbumsByStyle: flag(V(false)), + description: contentString(), urls: urls(), closelyLinkedArtists: annotatedReferenceList({ class: input.value(Artist), - find: input.value(find.artist), - data: 'artistData', - - date: input.value(null), + find: soupyFind.input('artist'), reference: input.value('artist'), thing: input.value('artist'), @@ -43,30 +75,20 @@ export class Group extends Thing { featuredAlbums: referenceList({ class: input.value(Album), - find: input.value(find.album), - data: 'albumData', + find: soupyFind.input('album'), }), - serieses: seriesList({ - group: input.myself(), - }), + serieses: thingList(V(Series)), // Update only - albumData: wikiData({ - class: input.value(Album), - }), - - artistData: wikiData({ - class: input.value(Artist), - }), - - groupCategoryData: wikiData({ - class: input.value(GroupCategory), - }), + find: soupyFind(), + reverse: soupyReverse(), // Expose only + isGroup: exposeConstant(V(true)), + descriptionShort: { flags: {expose: true}, @@ -83,9 +105,9 @@ export class Group extends Thing { flags: {expose: true}, expose: { - dependencies: ['this', 'albumData'], - compute: ({this: group, albumData}) => - albumData?.filter((album) => album.groups.includes(group)) ?? [], + dependencies: ['this', '_reverse'], + compute: ({this: group, _reverse: reverse}) => + reverse.albumsWhoseGroupsInclude(group), }, }, @@ -93,9 +115,9 @@ export class Group extends Thing { flags: {expose: true}, expose: { - dependencies: ['this', 'groupCategoryData'], - compute: ({this: group, groupCategoryData}) => - groupCategoryData.find((category) => category.groups.includes(group)) + dependencies: ['this', '_reverse'], + compute: ({this: group, _reverse: reverse}) => + reverse.groupCategoriesWhichInclude(group, {unique: true}) ?.color, }, }, @@ -104,9 +126,9 @@ export class Group extends Thing { flags: {expose: true}, expose: { - dependencies: ['this', 'groupCategoryData'], - compute: ({this: group, groupCategoryData}) => - groupCategoryData.find((category) => category.groups.includes(group)) ?? + dependencies: ['this', '_reverse'], + compute: ({this: group, _reverse: reverse}) => + reverse.groupCategoriesWhichInclude(group, {unique: true}) ?? null, }, }, @@ -119,10 +141,33 @@ export class Group extends Thing { }, }; + static [Thing.reverseSpecs] = { + groupsCloselyLinkedTo: { + bindTo: 'groupData', + + referencing: group => + group.closelyLinkedArtists + .map(({artist, ...referenceDetails}) => ({ + group, + artist, + referenceDetails, + })), + + referenced: ({artist}) => [artist], + + tidy: ({group, referenceDetails}) => + ({group, ...referenceDetails}), + }, + }; + static [Thing.yamlDocumentSpec] = { fields: { 'Group': {property: 'name'}, 'Directory': {property: 'directory'}, + + 'Exclude From Gallery Tabs': {property: 'excludeFromGalleryTabs'}, + 'Divide Albums By Style': {property: 'divideAlbumsByStyle'}, + 'Description': {property: 'description'}, 'URLs': {property: 'urls'}, @@ -159,7 +204,7 @@ export class Group extends Thing { ? GroupCategory : Group), - save(results) { + connect(results) { let groupCategory; let groupRefs = []; @@ -183,11 +228,6 @@ export class Group extends Thing { if (groupCategory) { Object.assign(groupCategory, {groups: groupRefs}); } - - const groupData = results.filter(x => x instanceof Group); - const groupCategoryData = results.filter(x => x instanceof GroupCategory); - - return {groupData, groupCategoryData}; }, // Groups aren't sorted at all, always preserving the order in the data @@ -199,32 +239,120 @@ export class Group extends Thing { export class GroupCategory extends Thing { static [Thing.referenceType] = 'group-category'; static [Thing.friendlyName] = `Group Category`; + static [Thing.wikiData] = 'groupCategoryData'; static [Thing.getPropertyDescriptors] = ({Group}) => ({ // Update & expose - name: name('Unnamed Group Category'), + name: name(V('Unnamed Group Category')), directory: directory(), + excludeGroupsFromGalleryTabs: flag(V(false)), + color: color(), groups: referenceList({ class: input.value(Group), - find: input.value(find.group), - data: 'groupData', + find: soupyFind.input('group'), }), // Update only - groupData: wikiData({ - class: input.value(Group), - }), + find: soupyFind(), + + // Expose only + + isGroupCategory: exposeConstant(V(true)), }); + static [Thing.reverseSpecs] = { + groupCategoriesWhichInclude: { + bindTo: 'groupCategoryData', + + referencing: groupCategory => [groupCategory], + referenced: groupCategory => groupCategory.groups, + }, + }; + static [Thing.yamlDocumentSpec] = { fields: { 'Category': {property: 'name'}, + 'Color': {property: 'color'}, + + 'Exclude Groups From Gallery Tabs': { + property: 'excludeGroupsFromGalleryTabs', + }, }, }; } + +export class Series extends Thing { + static [Thing.wikiData] = 'seriesData'; + + static [Thing.getPropertyDescriptors] = ({Album, Group}) => ({ + // Update & expose + + name: name(V('Unnamed Series')), + + showAlbumArtists: { + flags: {update: true, expose: true}, + update: { + validate: + is('all', 'differing', 'none'), + }, + }, + + description: contentString(), + + group: thing(V(Group)), + + albums: referenceList({ + class: input.value(Album), + find: soupyFind.input('album'), + }), + + // Update only + + find: soupyFind(), + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Name': {property: 'name'}, + + 'Description': {property: 'description'}, + + 'Show Album Artists': {property: 'showAlbumArtists'}, + + 'Albums': {property: 'albums'}, + }, + }; + + [inspect.custom](depth, options, inspect) { + const parts = []; + + parts.push(Thing.prototype[inspect.custom].apply(this)); + + if (depth >= 0) showGroup: { + let group = null; + try { + group = this.group; + } catch { + break showGroup; + } + + const groupName = group.name; + const groupIndex = group.serieses.indexOf(this); + + const num = + (groupIndex === -1 + ? 'indeterminate position' + : `#${groupIndex + 1}`); + + parts.push(` (${colors.yellow(num)} in ${colors.green(`"${groupName}"`)})`); + } + + return parts.join(''); + } +} diff --git a/src/data/things/homepage-layout.js b/src/data/things/homepage-layout.js index 00d6aef5..c4dc2812 100644 --- a/src/data/things/homepage-layout.js +++ b/src/data/things/homepage-layout.js @@ -1,8 +1,11 @@ export const HOMEPAGE_LAYOUT_DATA_FILE = 'homepage.yaml'; -import {input} from '#composite'; -import find from '#find'; +import {inspect} from 'node:util'; + +import {colors} from '#cli'; +import {input, V} from '#composite'; import Thing from '#thing'; +import {empty} from '#sugar'; import { anyOf, @@ -11,19 +14,28 @@ import { isString, isStringNonEmpty, validateArrayItems, - validateInstanceOf, validateReference, } from '#validators'; -import {exposeDependency} from '#composite/control-flow'; +import {exposeConstant, exposeDependency} from '#composite/control-flow'; import {withResolvedReference} from '#composite/wiki-data'; -import {color, contentString, name, referenceList, wikiData} - from '#composite/wiki-properties'; + +import { + color, + contentString, + name, + referenceList, + soupyFind, + thing, + thingList, +} from '#composite/wiki-properties'; export class HomepageLayout extends Thing { static [Thing.friendlyName] = `Homepage Layout`; + static [Thing.wikiData] = 'homepageLayout'; + static [Thing.oneInstancePerWiki] = true; - static [Thing.getPropertyDescriptors] = ({HomepageLayoutRow}) => ({ + static [Thing.getPropertyDescriptors] = ({HomepageLayoutSection}) => ({ // Update & expose sidebarContent: contentString(), @@ -31,15 +43,14 @@ export class HomepageLayout extends Thing { navbarLinks: { flags: {update: true, expose: true}, update: {validate: validateArrayItems(isStringNonEmpty)}, + expose: {transform: value => value ?? []}, }, - rows: { - flags: {update: true, expose: true}, + sections: thingList(V(HomepageLayoutSection)), - update: { - validate: validateArrayItems(validateInstanceOf(HomepageLayoutRow)), - }, - }, + // Expose only + + isHomepageLayout: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { @@ -50,85 +61,220 @@ export class HomepageLayout extends Thing { 'Navbar Links': {property: 'navbarLinks'}, }, }; + + static [Thing.getYamlLoadingSpec] = ({ + documentModes: {allInOne}, + thingConstructors: { + HomepageLayout, + HomepageLayoutSection, + }, + }) => ({ + title: `Process homepage layout file`, + file: HOMEPAGE_LAYOUT_DATA_FILE, + + documentMode: allInOne, + documentThing: document => { + if (document['Homepage']) { + return HomepageLayout; + } + + if (document['Section']) { + return HomepageLayoutSection; + } + + if (document['Row']) { + switch (document['Row']) { + case 'actions': + return HomepageLayoutActionsRow; + case 'album carousel': + return HomepageLayoutAlbumCarouselRow; + case 'album grid': + return HomepageLayoutAlbumGridRow; + default: + throw new TypeError(`Unrecognized row type ${document['Row']}`); + } + } + + return null; + }, + + connect(results) { + if (!empty(results) && !(results[0] instanceof HomepageLayout)) { + throw new Error(`Expected 'Homepage' document at top of homepage layout file`); + } + + const homepageLayout = results[0]; + const sections = []; + + let currentSection = null; + let currentSectionRows = []; + + const closeCurrentSection = () => { + if (currentSection) { + for (const row of currentSectionRows) { + row.section = currentSection; + } + + currentSection.rows = currentSectionRows; + sections.push(currentSection); + + currentSection = null; + currentSectionRows = []; + } + }; + + for (const entry of results.slice(1)) { + if (entry instanceof HomepageLayout) { + throw new Error(`Expected only one 'Homepage' document in total`); + } else if (entry instanceof HomepageLayoutSection) { + closeCurrentSection(); + currentSection = entry; + } else if (entry instanceof HomepageLayoutRow) { + if (currentSection) { + currentSectionRows.push(entry); + } else { + throw new Error(`Expected a 'Section' document to add following rows into`); + } + } + } + + closeCurrentSection(); + + homepageLayout.sections = sections; + }, + }); +} + +export class HomepageLayoutSection extends Thing { + static [Thing.friendlyName] = `Homepage Section`; + + static [Thing.getPropertyDescriptors] = ({HomepageLayoutRow}) => ({ + // Update & expose + + name: name(V(`Unnamed Homepage Section`)), + + color: color(), + + rows: thingList(V(HomepageLayoutRow)), + + // Expose only + + isHomepageLayoutSection: exposeConstant(V(true)), + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Section': {property: 'name'}, + 'Color': {property: 'color'}, + }, + }; } export class HomepageLayoutRow extends Thing { static [Thing.friendlyName] = `Homepage Row`; - static [Thing.getPropertyDescriptors] = ({Album, Group}) => ({ + static [Thing.getPropertyDescriptors] = ({HomepageLayoutSection}) => ({ // Update & expose - name: name('Unnamed Homepage Row'), + section: thing(V(HomepageLayoutSection)), + + // Update only + + find: soupyFind(), + + // Expose only + + isHomepageLayoutRow: exposeConstant(V(true)), type: { - flags: {update: true, expose: true}, + flags: {expose: true}, - update: { - validate() { + expose: { + compute() { throw new Error(`'type' property validator must be overridden`); }, }, }, + }); - color: color(), + static [Thing.yamlDocumentSpec] = { + fields: { + 'Row': {ignore: true}, + }, + }; - // Update only + [inspect.custom](depth) { + const parts = []; - // These wiki data arrays aren't necessarily used by every subclass, but - // to the convenience of providing these, the superclass accepts all wiki - // data arrays depended upon by any subclass. + parts.push(Thing.prototype[inspect.custom].apply(this)); - albumData: wikiData({ - class: input.value(Album), - }), + if (depth >= 0 && this.section) { + const sectionName = this.section.name; + const index = this.section.rows.indexOf(this); + const rowNum = + (index === -1 + ? 'indeterminate position' + : `#${index + 1}`); + parts.push(` (${colors.yellow(rowNum)} in ${colors.green(sectionName)})`); + } - groupData: wikiData({ - class: input.value(Group), - }), + return parts.join(''); + } +} + +export class HomepageLayoutActionsRow extends HomepageLayoutRow { + static [Thing.friendlyName] = `Homepage Actions Row`; + + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + actionLinks: { + flags: {update: true, expose: true}, + update: {validate: validateArrayItems(isString)}, + }, + + // Expose only + + isHomepageLayoutActionsRow: exposeConstant(V(true)), + type: exposeConstant(V('actions')), }); static [Thing.yamlDocumentSpec] = { fields: { - 'Row': {property: 'name'}, - 'Color': {property: 'color'}, - 'Type': {property: 'type'}, + 'Actions': {property: 'actionLinks'}, }, }; } -export class HomepageLayoutAlbumsRow extends HomepageLayoutRow { - static [Thing.friendlyName] = `Homepage Albums Row`; - - static [Thing.getPropertyDescriptors] = (opts, {Album, Group} = opts) => ({ - ...HomepageLayoutRow[Thing.getPropertyDescriptors](opts), +export class HomepageLayoutAlbumCarouselRow extends HomepageLayoutRow { + static [Thing.friendlyName] = `Homepage Album Carousel Row`; + static [Thing.getPropertyDescriptors] = (opts, {Album} = opts) => ({ // Update & expose - type: { - flags: {update: true, expose: true}, - update: { - validate(value) { - if (value !== 'albums') { - throw new TypeError(`Expected 'albums'`); - } - - return true; - }, - }, - }, + albums: referenceList({ + class: input.value(Album), + find: soupyFind.input('album'), + }), - displayStyle: { - flags: {update: true, expose: true}, + // Expose only - update: { - validate: is('grid', 'carousel'), - }, + isHomepageLayoutAlbumCarouselRow: exposeConstant(V(true)), + type: exposeConstant(V('album carousel')), + }); - expose: { - transform: (displayStyle) => - displayStyle ?? 'grid', - }, + static [Thing.yamlDocumentSpec] = { + fields: { + 'Albums': {property: 'albums'}, }, + }; +} + +export class HomepageLayoutAlbumGridRow extends HomepageLayoutRow { + static [Thing.friendlyName] = `Homepage Album Grid Row`; + + static [Thing.getPropertyDescriptors] = (opts, {Album, Group} = opts) => ({ + // Update & expose sourceGroup: [ { @@ -151,17 +297,15 @@ export class HomepageLayoutAlbumsRow extends HomepageLayoutRow { withResolvedReference({ ref: input.updateValue(), - data: 'groupData', - find: input.value(find.group), + find: soupyFind.input('group'), }), - exposeDependency({dependency: '#resolvedReference'}), + exposeDependency('#resolvedReference'), ], sourceAlbums: referenceList({ class: input.value(Album), - find: input.value(find.album), - data: 'albumData', + find: soupyFind.input('album'), }), countAlbumsFromGroup: { @@ -169,55 +313,17 @@ export class HomepageLayoutAlbumsRow extends HomepageLayoutRow { update: {validate: isCountingNumber}, }, - actionLinks: { - flags: {update: true, expose: true}, - update: {validate: validateArrayItems(isString)}, - }, + // Expose only + + isHomepageLayoutAlbumGridRow: exposeConstant(V(true)), + type: exposeConstant(V('album grid')), }); - static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(HomepageLayoutRow, { + static [Thing.yamlDocumentSpec] = { fields: { - 'Display Style': {property: 'displayStyle'}, 'Group': {property: 'sourceGroup'}, 'Count': {property: 'countAlbumsFromGroup'}, 'Albums': {property: 'sourceAlbums'}, - 'Actions': {property: 'actionLinks'}, }, - }); - - static [Thing.getYamlLoadingSpec] = ({ - documentModes: {headerAndEntries}, // Kludge, see below - thingConstructors: { - HomepageLayout, - HomepageLayoutAlbumsRow, - }, - }) => ({ - title: `Process homepage layout file`, - - // Kludge: This benefits from the same headerAndEntries style messaging as - // albums and tracks (for example), but that document mode is designed to - // support multiple files, and only one is actually getting processed here. - files: [HOMEPAGE_LAYOUT_DATA_FILE], - - documentMode: headerAndEntries, - headerDocumentThing: HomepageLayout, - entryDocumentThing: document => { - switch (document['Type']) { - case 'albums': - return HomepageLayoutAlbumsRow; - default: - throw new TypeError(`No processDocument function for row type ${document['Type']}!`); - } - }, - - save(results) { - if (!results[0]) { - return; - } - - const {header: homepageLayout, entries: rows} = results[0]; - Object.assign(homepageLayout, {rows}); - return {homepageLayout}; - }, - }); + }; } diff --git a/src/data/things/index.js b/src/data/things/index.js index f18e283a..09765fd2 100644 --- a/src/data/things/index.js +++ b/src/data/things/index.js @@ -6,31 +6,42 @@ import CacheableObject from '#cacheable-object'; import {logError} from '#cli'; import {compositeFrom} from '#composite'; import * as serialize from '#serialize'; +import {empty} from '#sugar'; import Thing from '#thing'; +import * as additionalFileClasses from './additional-file.js'; +import * as additionalNameClasses from './additional-name.js'; import * as albumClasses from './album.js'; import * as artTagClasses from './art-tag.js'; import * as artistClasses from './artist.js'; +import * as artworkClasses from './artwork.js'; +import * as contentClasses from './content.js'; import * as contributionClasses from './contribution.js'; import * as flashClasses from './flash.js'; import * as groupClasses from './group.js'; import * as homepageLayoutClasses from './homepage-layout.js'; import * as languageClasses from './language.js'; import * as newsEntryClasses from './news-entry.js'; +import * as sortingRuleClasses from './sorting-rule.js'; import * as staticPageClasses from './static-page.js'; import * as trackClasses from './track.js'; import * as wikiInfoClasses from './wiki-info.js'; const allClassLists = { + 'additional-file.js': additionalFileClasses, + 'additional-name.js': additionalNameClasses, 'album.js': albumClasses, 'art-tag.js': artTagClasses, 'artist.js': artistClasses, + 'artwork.js': artworkClasses, + 'content.js': contentClasses, 'contribution.js': contributionClasses, 'flash.js': flashClasses, 'group.js': groupClasses, 'homepage-layout.js': homepageLayoutClasses, 'language.js': languageClasses, 'news-entry.js': newsEntryClasses, + 'sorting-rule.js': sortingRuleClasses, 'static-page.js': staticPageClasses, 'track.js': trackClasses, 'wiki-info.js': wikiInfoClasses, @@ -47,6 +58,7 @@ const __dirname = path.dirname( function niceShowAggregate(error, ...opts) { showAggregate(error, { pathToFileURL: (f) => path.relative(__dirname, fileURLToPath(f)), + showClasses: false, ...opts, }); } @@ -79,13 +91,39 @@ function errorDuplicateClassNames() { } function flattenClassLists() { + let remaining = []; for (const classes of Object.values(allClassLists)) { - for (const [name, constructor] of Object.entries(classes)) { + for (const constructor of Object.values(classes)) { if (typeof constructor !== 'function') continue; if (!(constructor.prototype instanceof Thing)) continue; - allClasses[name] = constructor; + remaining.push(constructor); } } + + let sorted = []; + while (true) { + if (sorted[0]) { + const superclass = Object.getPrototypeOf(sorted[0]); + if (superclass !== Thing) { + if (sorted.includes(superclass)) { + sorted.unshift(...sorted.splice(sorted.indexOf(superclass), 1)); + } else { + sorted.unshift(superclass); + } + continue; + } + } + + if (!empty(remaining)) { + sorted.unshift(remaining.shift()); + } else { + break; + } + } + + for (const constructor of sorted) { + allClasses[constructor.name] = constructor; + } } function descriptorAggregateHelper({ @@ -115,6 +153,15 @@ function descriptorAggregateHelper({ } catch (error) { niceShowAggregate(error); showFailedClasses(failedClasses); + + /* + if (error.errors) { + for (const sub of error.errors) { + console.error(sub); + } + } + */ + return false; } } @@ -144,10 +191,10 @@ function evaluatePropertyDescriptors() { } } - constructor[CacheableObject.propertyDescriptors] = { - ...constructor[CacheableObject.propertyDescriptors] ?? {}, - ...results, - }; + constructor[CacheableObject.propertyDescriptors] = + Object.create(constructor[CacheableObject.propertyDescriptors] ?? null); + + Object.assign(constructor[CacheableObject.propertyDescriptors], results); }, showFailedClasses(failedClasses) { @@ -177,16 +224,49 @@ function evaluateSerializeDescriptors() { }); } -if (!errorDuplicateClassNames()) - process.exit(1); +function finalizeYamlDocumentSpecs() { + return descriptorAggregateHelper({ + message: `Errors finalizing Thing YAML document specs`, -flattenClassLists(); + op(constructor) { + const superclass = Object.getPrototypeOf(constructor); + if ( + constructor[Thing.yamlDocumentSpec] && + superclass[Thing.yamlDocumentSpec] + ) { + constructor[Thing.yamlDocumentSpec] = + Thing.extendDocumentSpec(superclass, constructor[Thing.yamlDocumentSpec]); + } + }, + + showFailedClasses(failedClasses) { + logError`Failed to finalize YAML document specs for classes: ${failedClasses.join(', ')}`; + }, + }); +} + +function finalizeCacheableObjectPrototypes() { + return descriptorAggregateHelper({ + message: `Errors finalizing Thing class prototypes`, + + op(constructor) { + constructor.finalizeCacheableObjectPrototype(); + }, -if (!evaluatePropertyDescriptors()) - process.exit(1); + showFailedClasses(failedClasses) { + logError`Failed to finalize cacheable object prototypes for classes: ${failedClasses.join(', ')}`; + }, + }); +} + +if (!errorDuplicateClassNames()) process.exit(1); + +flattenClassLists(); -if (!evaluateSerializeDescriptors()) - process.exit(1); +if (!evaluatePropertyDescriptors()) process.exit(1); +if (!evaluateSerializeDescriptors()) process.exit(1); +if (!finalizeYamlDocumentSpecs()) process.exit(1); +if (!finalizeCacheableObjectPrototypes()) process.exit(1); Object.assign(allClasses, {Thing}); diff --git a/src/data/things/language.js b/src/data/things/language.js index e9aa58be..7f3f43de 100644 --- a/src/data/things/language.js +++ b/src/data/things/language.js @@ -1,24 +1,25 @@ -import { Temporal, toTemporalInstant } from '@js-temporal/polyfill'; +import {Temporal, toTemporalInstant} from '@js-temporal/polyfill'; import {withAggregate} from '#aggregate'; -import CacheableObject from '#cacheable-object'; import {logWarn} from '#cli'; +import {input, V} from '#composite'; import * as html from '#html'; -import {empty} from '#sugar'; -import {isLanguageCode} from '#validators'; +import {accumulateSum, empty, withEntries} from '#sugar'; +import {isLanguageCode, isObject} from '#validators'; import Thing from '#thing'; +import {languageOptionRegex} from '#wiki-data'; import { + externalLinkSpec, getExternalLinkStringOfStyleFromDescriptors, getExternalLinkStringsFromDescriptors, isExternalLinkContext, - isExternalLinkSpec, isExternalLinkStyle, } from '#external-links'; -import {externalFunction, flag, name} from '#composite/wiki-properties'; - -export const languageOptionRegex = /{(?<name>[A-Z0-9_]+)}/g; +import {exitWithoutDependency, exposeConstant} + from '#composite/control-flow'; +import {flag, name} from '#composite/wiki-properties'; export class Language extends Thing { static [Thing.getPropertyDescriptors] = () => ({ @@ -34,7 +35,7 @@ export class Language extends Thing { // Human-readable name. This should be the language's own native name, not // localized to any other language. - name: name(`Unnamed Language`), + name: name(V(`Unnamed Language`)), // Language code specific to JavaScript's Internationalization (Intl) API. // Usually this will be the same as the language's general code, but it @@ -56,20 +57,29 @@ export class Language extends Thing { // with languages that are currently in development and not ready for // formal release, or which are just kept hidden as "experimental zones" // for wiki development or content testing. - hidden: flag(false), + hidden: flag(V(false)), // 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'}, + strings: [ + { + dependencies: [ + input.updateValue({validate: isObject}), + 'inheritedStrings', + ], + + compute: (continuation, { + [input.updateValue()]: strings, + ['inheritedStrings']: inheritedStrings, + }) => + (strings && inheritedStrings + ? continuation() + : strings ?? inheritedStrings), + }, - expose: { + { dependencies: ['inheritedStrings', 'code'], transform(strings, {inheritedStrings, code}) { - if (!strings && !inheritedStrings) return null; - if (!inheritedStrings) return strings; - const validStrings = { ...inheritedStrings, ...strings, @@ -98,6 +108,7 @@ export class Language extends Thing { logWarn`- Missing options: ${missingOptionNames.join(', ')}`; if (!empty(misplacedOptionNames)) logWarn`- Unexpected options: ${misplacedOptionNames.join(', ')}`; + validStrings[key] = inheritedStrings[key]; } } @@ -105,7 +116,7 @@ export class Language extends Thing { return validStrings; }, }, - }, + ], // May be provided to specify "default" strings, generally (but not // necessarily) inherited from another Language object. @@ -114,33 +125,22 @@ export class Language extends Thing { update: {validate: (t) => typeof t === 'object'}, }, - // List of descriptors for providing to external link utilities when using - // language.formatExternalLink - refer to util/external-links.js for info. - externalLinkSpec: { - flags: {update: true, expose: true}, - update: {validate: isExternalLinkSpec}, - }, - - // Update only - - escapeHTML: externalFunction(), - // Expose only - onlyIfOptions: { - flags: {expose: true}, - expose: { - compute: () => Symbol.for(`language.onlyIfOptions`), - }, - }, + isLanguage: exposeConstant(V(true)), + + onlyIfOptions: exposeConstant(V(Symbol.for(`language.onlyIfOptions`))), intl_date: this.#intlHelper(Intl.DateTimeFormat, {full: true}), + intl_dateYear: this.#intlHelper(Intl.DateTimeFormat, {year: 'numeric'}), + intl_dateMonthDay: this.#intlHelper(Intl.DateTimeFormat, {month: 'numeric', day: 'numeric'}), intl_number: this.#intlHelper(Intl.NumberFormat), intl_listConjunction: this.#intlHelper(Intl.ListFormat, {type: 'conjunction'}), intl_listDisjunction: this.#intlHelper(Intl.ListFormat, {type: 'disjunction'}), intl_listUnit: this.#intlHelper(Intl.ListFormat, {type: 'unit'}), intl_pluralCardinal: this.#intlHelper(Intl.PluralRules, {type: 'cardinal'}), intl_pluralOrdinal: this.#intlHelper(Intl.PluralRules, {type: 'ordinal'}), + intl_wordSegmenter: this.#intlHelper(Intl.Segmenter, {granularity: 'word'}), validKeys: { flags: {expose: true}, @@ -158,19 +158,16 @@ export class Language extends Thing { }, // TODO: This currently isn't used. Is it still needed? - 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)]) - ); - }, + strings_htmlEscaped: [ + exitWithoutDependency('strings'), + + { + dependencies: ['strings'], + compute: ({strings}) => + withEntries(strings, entries => entries + .map(([key, value]) => [key, html.escape(value)])), }, - }, + ], }); static #intlHelper (constructor, opts) { @@ -191,18 +188,35 @@ export class Language extends Thing { return this.formatString(...args); } + $order(...args) { + return this.orderStringOptions(...args); + } + assertIntlAvailable(property) { if (!this[property]) { throw new Error(`Intl API ${property} unavailable`); } } + countWords(text) { + this.assertIntlAvailable('intl_wordSegmenter'); + + const string = html.resolve(text, {normalize: 'plain'}); + const segments = this.intl_wordSegmenter.segment(string); + + return accumulateSum(segments, segment => segment.isWordLike ? 1 : 0); + } + getUnitForm(value) { this.assertIntlAvailable('intl_pluralCardinal'); return this.intl_pluralCardinal.select(value); } formatString(...args) { + if (typeof args.at(-1) === 'function') { + throw new Error(`Passed function - did you mean language.encapsulate() instead?`); + } + const hasOptions = typeof args.at(-1) === 'object' && args.at(-1) !== null; @@ -210,19 +224,14 @@ export class Language extends Thing { const key = this.#joinKeyParts(hasOptions ? args.slice(0, -1) : args); + const template = + this.#getStringTemplateFromFormedKey(key); + const options = (hasOptions ? args.at(-1) : {}); - if (!this.strings) { - throw new Error(`Strings unavailable`); - } - - if (!this.validKeys.includes(key)) { - throw new Error(`Invalid key ${key} accessed`); - } - const constantCasify = name => name .replace(/[A-Z]/g, '_$&') @@ -263,8 +272,7 @@ export class Language extends Thing { ])); const output = this.#iterateOverTemplate({ - template: this.strings[key], - + template, match: languageOptionRegex, insert: ({name: optionName}, canceledForming) => { @@ -309,7 +317,7 @@ export class Language extends Thing { return undefined; } - return optionValue; + return this.sanitize(optionValue); }, }); @@ -344,6 +352,46 @@ export class Language extends Thing { return output; } + orderStringOptions(...args) { + let slice = null, at = null, parts = null; + if (args.length >= 2 && typeof args.at(-1) === 'number') { + if (args.length >= 3 && typeof args.at(-2) === 'number') { + slice = [args.at(-2), args.at(-1)]; + parts = args.slice(0, -2); + } else { + at = args.at(-1); + parts = args.slice(0, -1); + } + } else { + parts = args; + } + + const template = this.getStringTemplate(...parts); + const matches = Array.from(template.matchAll(languageOptionRegex)); + const options = matches.map(({groups}) => groups.name); + + if (slice !== null) return options.slice(...slice); + if (at !== null) return options.at(at); + return options; + } + + getStringTemplate(...args) { + const key = this.#joinKeyParts(args); + return this.#getStringTemplateFromFormedKey(key); + } + + #getStringTemplateFromFormedKey(key) { + if (!this.strings) { + throw new Error(`Strings unavailable`); + } + + if (!this.validKeys.includes(key)) { + throw new Error(`Invalid key ${key} accessed`); + } + + return this.strings[key]; + } + #iterateOverTemplate({ template, match: regexp, @@ -374,26 +422,22 @@ export class Language extends Thing { partInProgress += template.slice(lastIndex, match.index); - // Sanitize string arguments in particular. These are taken to come from - // (raw) data and may include special characters that aren't meant to be - // rendered as HTML markup. - const sanitizedInsertion = - this.#sanitizeValueForInsertion(insertion); - - if (typeof sanitizedInsertion === 'string') { - // Join consecutive strings together. - partInProgress += sanitizedInsertion; - } else if ( - sanitizedInsertion instanceof html.Tag && - sanitizedInsertion.contentOnly - ) { - // Collapse string-only tag contents onto the current string part. - partInProgress += sanitizedInsertion.toString(); - } else { - // Push the string part in progress, then the insertion as-is. - outputParts.push(partInProgress); - outputParts.push(sanitizedInsertion); + const insertionItems = html.smush(insertion).content; + if (insertionItems.length === 1 && typeof insertionItems[0] !== 'string') { + // Push the insertion exactly as it is, rather than manipulating. + if (partInProgress) outputParts.push(partInProgress); + outputParts.push(insertion); partInProgress = ''; + } else for (const insertionItem of insertionItems) { + if (typeof insertionItem === 'string') { + // Join consecutive strings together. + partInProgress += insertionItem; + } else { + // Push the string part in progress, then the insertion as-is. + if (partInProgress) outputParts.push(partInProgress); + outputParts.push(insertionItem); + partInProgress = ''; + } } lastIndex = match.index + match[0].length; @@ -425,14 +469,9 @@ export class Language extends Thing { // html.Tag objects - gets left as-is, preserving the value exactly as it's // provided. #sanitizeValueForInsertion(value) { - const escapeHTML = CacheableObject.getUpdateValue(this, 'escapeHTML'); - if (!escapeHTML) { - throw new Error(`escapeHTML unavailable`); - } - switch (typeof value) { case 'string': - return escapeHTML(value); + return html.escape(value); case 'number': case 'boolean': @@ -488,22 +527,53 @@ export class Language extends Thing { // or both are undefined, that's just blank content. const hasStart = startDate !== null && startDate !== undefined; const hasEnd = endDate !== null && endDate !== undefined; - if (!hasStart || !hasEnd) { - if (startDate === endDate) { - return html.blank(); - } else if (hasStart) { - throw new Error(`Expected both start and end of date range, got only start`); - } else if (hasEnd) { - throw new Error(`Expected both start and end of date range, got only end`); - } else { - throw new Error(`Got mismatched ${startDate}/${endDate} for start and end`); - } + if (!hasStart && !hasEnd) { + return html.blank(); + } else if (hasStart && !hasEnd) { + throw new Error(`Expected both start and end of date range, got only start`); + } else if (!hasStart && hasEnd) { + throw new Error(`Expected both start and end of date range, got only end`); } this.assertIntlAvailable('intl_date'); return this.intl_date.formatRange(startDate, endDate); } + formatYear(date) { + if (date === null || date === undefined) { + return html.blank(); + } + + this.assertIntlAvailable('intl_dateYear'); + return this.intl_dateYear.format(date); + } + + formatMonthDay(date) { + if (date === null || date === undefined) { + return html.blank(); + } + + this.assertIntlAvailable('intl_dateMonthDay'); + return this.intl_dateMonthDay.format(date); + } + + formatYearRange(startDate, endDate) { + // formatYearRange expects both values to be present, but if both are null + // or both are undefined, that's just blank content. + const hasStart = startDate !== null && startDate !== undefined; + const hasEnd = endDate !== null && endDate !== undefined; + if (!hasStart && !hasEnd) { + return html.blank(); + } else if (hasStart && !hasEnd) { + throw new Error(`Expected both start and end of date range, got only start`); + } else if (!hasStart && hasEnd) { + throw new Error(`Expected both start and end of date range, got only end`); + } + + this.assertIntlAvailable('intl_dateYear'); + return this.intl_dateYear.formatRange(startDate, endDate); + } + formatDateDuration({ years: numYears = 0, months: numMonths = 0, @@ -665,10 +735,6 @@ export class Language extends Thing { style = 'platform', context = 'generic', } = {}) { - if (!this.externalLinkSpec) { - throw new TypeError(`externalLinkSpec unavailable`); - } - // Null or undefined url is blank content. if (url === null || url === undefined) { return html.blank(); @@ -677,7 +743,7 @@ export class Language extends Thing { isExternalLinkContext(context); if (style === 'all') { - return getExternalLinkStringsFromDescriptors(url, this.externalLinkSpec, { + return getExternalLinkStringsFromDescriptors(url, externalLinkSpec, { language: this, context, }); @@ -686,7 +752,7 @@ export class Language extends Thing { isExternalLinkStyle(style); const result = - getExternalLinkStringOfStyleFromDescriptors(url, style, this.externalLinkSpec, { + getExternalLinkStringOfStyleFromDescriptors(url, style, externalLinkSpec, { language: this, context, }); @@ -842,6 +908,18 @@ export class Language extends Thing { } } + typicallyLowerCase(string) { + // Utter nonsense implementation, so this only works on strings, + // not actual HTML content, and may rudely disrespect *intentful* + // capitalization of whatever goes into it. + + if (typeof string !== 'string') return string; + if (string.length <= 1) return string; + if (/^\S+?[A-Z]/.test(string)) return string; + + return string[0].toLowerCase() + string.slice(1); + } + // Utility function to quickly provide a useful string key // (generally a prefix) to stuff nested beneath it. encapsulate(...args) { @@ -896,13 +974,14 @@ const countHelper = (stringKey, optionName = stringKey) => Object.assign(Language.prototype, { countAdditionalFiles: countHelper('additionalFiles', 'files'), countAlbums: countHelper('albums'), + countArtTags: countHelper('artTags', 'tags'), countArtworks: countHelper('artworks'), countCommentaryEntries: countHelper('commentaryEntries', 'entries'), countContributions: countHelper('contributions'), - countCoverArts: countHelper('coverArts'), countDays: countHelper('days'), countFlashes: countHelper('flashes'), countMonths: countHelper('months'), + countTimesFeatured: countHelper('timesFeatured'), countTimesReferenced: countHelper('timesReferenced'), countTimesUsed: countHelper('timesUsed'), countTracks: countHelper('tracks'), diff --git a/src/data/things/news-entry.js b/src/data/things/news-entry.js index 43d1638e..bb35d11b 100644 --- a/src/data/things/news-entry.js +++ b/src/data/things/news-entry.js @@ -1,20 +1,23 @@ export const NEWS_DATA_FILE = 'news.yaml'; +import {V} from '#composite'; import {sortChronologically} from '#sort'; import Thing from '#thing'; import {parseDate} from '#yaml'; +import {exposeConstant} from '#composite/control-flow'; import {contentString, directory, name, simpleDate} from '#composite/wiki-properties'; export class NewsEntry extends Thing { static [Thing.referenceType] = 'news-entry'; static [Thing.friendlyName] = `News Entry`; + static [Thing.wikiData] = 'newsData'; static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - name: name('Unnamed News Entry'), + name: name(V('Unnamed News Entry')), directory: directory(), date: simpleDate(), @@ -22,6 +25,8 @@ export class NewsEntry extends Thing { // Expose only + isNewsEntry: exposeConstant(V(true)), + contentShort: { flags: {expose: true}, @@ -64,8 +69,6 @@ export class NewsEntry extends Thing { documentMode: allInOne, documentThing: NewsEntry, - save: (results) => ({newsData: results}), - sort({newsData}) { sortChronologically(newsData, {latestFirst: true}); }, diff --git a/src/data/things/sorting-rule.js b/src/data/things/sorting-rule.js new file mode 100644 index 00000000..101a4966 --- /dev/null +++ b/src/data/things/sorting-rule.js @@ -0,0 +1,396 @@ +export const SORTING_RULE_DATA_FILE = 'sorting-rules.yaml'; + +import {readFile, writeFile} from 'node:fs/promises'; +import * as path from 'node:path'; + +import {V} from '#composite'; +import {chunkByProperties, compareArrays, unique} from '#sugar'; +import Thing from '#thing'; +import {isObject, isStringNonEmpty, anyOf, strictArrayOf} from '#validators'; + +import { + compareCaseLessSensitive, + sortByDate, + sortByDirectory, + sortByName, +} from '#sort'; + +import { + documentModes, + flattenThingLayoutToDocumentOrder, + getThingLayoutForFilename, + reorderDocumentsInYAMLSourceText, +} from '#yaml'; + +import {exposeConstant} from '#composite/control-flow'; +import {flag} from '#composite/wiki-properties'; + +function isSelectFollowingEntry(value) { + isObject(value); + + const {length} = Object.keys(value); + if (length !== 1) { + throw new Error(`Expected object with 1 key, got ${length}`); + } + + return true; +} + +export class SortingRule extends Thing { + static [Thing.friendlyName] = `Sorting Rule`; + static [Thing.wikiData] = 'sortingRules'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + active: flag(V(true)), + + message: { + flags: {update: true, expose: true}, + update: {validate: isStringNonEmpty}, + }, + + // Expose only + + isSortingRule: exposeConstant(V(true)), + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Message': {property: 'message'}, + 'Active': {property: 'active'}, + }, + }; + + static [Thing.getYamlLoadingSpec] = ({ + documentModes: {allInOne}, + thingConstructors: {DocumentSortingRule}, + }) => ({ + title: `Process sorting rules file`, + file: SORTING_RULE_DATA_FILE, + + documentMode: allInOne, + documentThing: document => + (document['Sort Documents'] + ? DocumentSortingRule + : null), + }); + + check(opts) { + return this.constructor.check(this, opts); + } + + apply(opts) { + return this.constructor.apply(this, opts); + } + + static check(rule, opts) { + const result = this.apply(rule, {...opts, dry: true}); + if (!result) return true; + if (!result.changed) return true; + return false; + } + + static async apply(_rule, _opts) { + throw new Error(`Not implemented`); + } + + static async* applyAll(_rules, _opts) { + throw new Error(`Not implemented`); + } + + static async* go({dataPath, wikiData, dry}) { + const rules = wikiData.sortingRules; + const constructors = unique(rules.map(rule => rule.constructor)); + + for (const constructor of constructors) { + yield* constructor.applyAll( + rules + .filter(rule => rule.active) + .filter(rule => rule.constructor === constructor), + {dataPath, wikiData, dry}); + } + } +} + +export class ThingSortingRule extends SortingRule { + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + properties: { + flags: {update: true, expose: true}, + update: { + validate: strictArrayOf(isStringNonEmpty), + }, + }, + + // Expose only + + isThingSortingRule: exposeConstant(V(true)), + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'By Properties': {property: 'properties'}, + }, + }; + + sort(sortable) { + if (this.properties) { + for (const property of this.properties.toReversed()) { + const get = thing => thing[property]; + const lc = property.toLowerCase(); + + if (lc.endsWith('date')) { + sortByDate(sortable, {getDate: get}); + continue; + } + + if (lc.endsWith('directory')) { + sortByDirectory(sortable, {getDirectory: get}); + continue; + } + + if (lc.endsWith('name')) { + sortByName(sortable, {getName: get}); + continue; + } + + const values = sortable.map(get); + + if (values.every(v => typeof v === 'string')) { + sortable.sort((a, b) => + compareCaseLessSensitive(get(a), get(b))); + continue; + } + + if (values.every(v => typeof v === 'number')) { + sortable.sort((a, b) => get(a) - get(b)); + continue; + } + + sortable.sort((a, b) => + (get(a).toString() < get(b).toString() + ? -1 + : get(a).toString() > get(b).toString() + ? +1 + : 0)); + } + } + + return sortable; + } +} + +export class DocumentSortingRule extends ThingSortingRule { + static [Thing.getPropertyDescriptors] = () => ({ + // Update & expose + + // TODO: glob :plead: + filename: { + flags: {update: true, expose: true}, + update: {validate: isStringNonEmpty}, + }, + + message: { + flags: {update: true, expose: true}, + update: {validate: isStringNonEmpty}, + + expose: { + dependencies: ['filename'], + transform: (value, {filename}) => + value ?? + `Sort ${filename}`, + }, + }, + + selectDocumentsFollowing: { + flags: {update: true, expose: true}, + + update: { + validate: + anyOf( + isSelectFollowingEntry, + strictArrayOf(isSelectFollowingEntry)), + }, + + compute: { + transform: value => + (Array.isArray(value) + ? value + : [value]), + }, + }, + + selectDocumentsUnder: { + flags: {update: true, expose: true}, + update: {validate: isStringNonEmpty}, + }, + + // Expose only + + isDocumentSortingRule: exposeConstant(V(true)), + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Sort Documents': {property: 'filename'}, + 'Select Documents Following': {property: 'selectDocumentsFollowing'}, + 'Select Documents Under': {property: 'selectDocumentsUnder'}, + }, + + invalidFieldCombinations: [ + {message: `Specify only one of these`, fields: [ + 'Select Documents Following', + 'Select Documents Under', + ]}, + ], + }; + + static async apply(rule, {wikiData, dataPath, dry}) { + const oldLayout = getThingLayoutForFilename(rule.filename, wikiData); + if (!oldLayout) return null; + + const newLayout = rule.#processLayout(oldLayout); + + const oldOrder = flattenThingLayoutToDocumentOrder(oldLayout); + const newOrder = flattenThingLayoutToDocumentOrder(newLayout); + const changed = compareArrays(oldOrder, newOrder); + + if (dry) return {changed}; + + const realPath = + path.join( + dataPath, + rule.filename.split(path.posix.sep).join(path.sep)); + + const oldSourceText = await readFile(realPath, 'utf8'); + const newSourceText = reorderDocumentsInYAMLSourceText(oldSourceText, newOrder); + + await writeFile(realPath, newSourceText); + + return {changed}; + } + + static async* applyAll(rules, {wikiData, dataPath, dry}) { + rules = rules + .toSorted((a, b) => a.filename.localeCompare(b.filename, 'en')); + + for (const {chunk, filename} of chunkByProperties(rules, ['filename'])) { + const initialLayout = getThingLayoutForFilename(filename, wikiData); + if (!initialLayout) continue; + + let currLayout = initialLayout; + let prevLayout = initialLayout; + let anyChanged = false; + + for (const rule of chunk) { + currLayout = rule.#processLayout(currLayout); + + const prevOrder = flattenThingLayoutToDocumentOrder(prevLayout); + const currOrder = flattenThingLayoutToDocumentOrder(currLayout); + + if (compareArrays(currOrder, prevOrder)) { + yield {rule, changed: false}; + } else { + anyChanged = true; + yield {rule, changed: true}; + } + + prevLayout = currLayout; + } + + if (!anyChanged) continue; + if (dry) continue; + + const newLayout = currLayout; + const newOrder = flattenThingLayoutToDocumentOrder(newLayout); + + const realPath = + path.join( + dataPath, + filename.split(path.posix.sep).join(path.sep)); + + const oldSourceText = await readFile(realPath, 'utf8'); + const newSourceText = reorderDocumentsInYAMLSourceText(oldSourceText, newOrder); + + await writeFile(realPath, newSourceText); + } + } + + #processLayout(layout) { + const fresh = {...layout}; + + let sortable = null; + switch (fresh.documentMode) { + case documentModes.headerAndEntries: + sortable = fresh.entryThings = + fresh.entryThings.slice(); + break; + + case documentModes.allInOne: + sortable = fresh.things = + fresh.things.slice(); + break; + + default: + throw new Error(`Invalid document type for sorting`); + } + + if (this.selectDocumentsFollowing) { + for (const entry of this.selectDocumentsFollowing) { + const [field, value] = Object.entries(entry)[0]; + + const after = + sortable.findIndex(thing => + thing[Thing.yamlSourceDocument][field] === value); + + const different = + after + + sortable + .slice(after) + .findIndex(thing => + Object.hasOwn(thing[Thing.yamlSourceDocument], field) && + thing[Thing.yamlSourceDocument][field] !== value); + + const before = + (different === -1 + ? sortable.length + : different); + + const subsortable = + sortable.slice(after + 1, before); + + this.sort(subsortable); + + sortable.splice(after + 1, before - after - 1, ...subsortable); + } + } else if (this.selectDocumentsUnder) { + const field = this.selectDocumentsUnder; + + const indices = + Array.from(sortable.entries()) + .filter(([_index, thing]) => + Object.hasOwn(thing[Thing.yamlSourceDocument], field)) + .map(([index, _thing]) => index); + + for (const [indicesIndex, after] of indices.entries()) { + const before = + (indicesIndex === indices.length - 1 + ? sortable.length + : indices[indicesIndex + 1]); + + const subsortable = + sortable.slice(after + 1, before); + + this.sort(subsortable); + + sortable.splice(after + 1, before - after - 1, ...subsortable); + } + } else { + this.sort(sortable); + } + + return fresh; + } +} diff --git a/src/data/things/static-page.js b/src/data/things/static-page.js index 03274979..999072d3 100644 --- a/src/data/things/static-page.js +++ b/src/data/things/static-page.js @@ -2,22 +2,25 @@ export const DATA_STATIC_PAGE_DIRECTORY = 'static-page'; import * as path from 'node:path'; +import {V} from '#composite'; import {traverse} from '#node-utils'; import {sortAlphabetically} from '#sort'; import Thing from '#thing'; import {isName} from '#validators'; -import {contentString, directory, name, simpleString} +import {exposeConstant} from '#composite/control-flow'; +import {contentString, directory, flag, name, simpleString} from '#composite/wiki-properties'; export class StaticPage extends Thing { static [Thing.referenceType] = 'static'; static [Thing.friendlyName] = `Static Page`; + static [Thing.wikiData] = 'staticPageData'; static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - name: name('Unnamed Static Page'), + name: name(V('Unnamed Static Page')), nameShort: { flags: {update: true, expose: true}, @@ -30,9 +33,16 @@ export class StaticPage extends Thing { }, directory: directory(), - content: contentString(), + stylesheet: simpleString(), script: simpleString(), + content: contentString(), + + absoluteLinks: flag(V(false)), + + // Expose only + + isStaticPage: exposeConstant(V(true)), }); static [Thing.findSpecs] = { @@ -48,6 +58,8 @@ export class StaticPage extends Thing { 'Short Name': {property: 'nameShort'}, 'Directory': {property: 'directory'}, + 'Absolute Links': {property: 'absoluteLinks'}, + 'Style': {property: 'stylesheet'}, 'Script': {property: 'script'}, 'Content': {property: 'content'}, @@ -71,8 +83,6 @@ export class StaticPage extends Thing { documentMode: onePerFile, documentThing: StaticPage, - save: (results) => ({staticPageData: results}), - sort({staticPageData}) { sortAlphabetically(staticPageData); }, diff --git a/src/data/things/track.js b/src/data/things/track.js index a0d2f641..ab7511a8 100644 --- a/src/data/things/track.js +++ b/src/data/things/track.js @@ -2,44 +2,70 @@ import {inspect} from 'node:util'; import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; -import find from '#find'; +import {input, V} from '#composite'; +import {onlyItem} from '#sugar'; +import {sortByDate} from '#sort'; import Thing from '#thing'; -import {isBoolean, isColor, isContributionList, isDate, isFileExtension} - from '#validators'; +import {getKebabCase} from '#wiki-data'; + +import { + isBoolean, + isColor, + isContentString, + isContributionList, + isDate, + isFileExtension, + validateReference, +} from '#validators'; import { parseAdditionalFiles, parseAdditionalNames, parseAnnotatedReferences, + parseArtwork, + parseCommentary, parseContributors, + parseCreditingSources, + parseReferencingSources, parseDate, parseDimensions, parseDuration, + parseLyrics, } from '#yaml'; -import {withPropertyFromObject} from '#composite/data'; - import { exitWithoutDependency, + exitWithoutUpdateValue, exposeConstant, exposeDependency, exposeDependencyOrContinue, exposeUpdateValueOrContinue, exposeWhetherDependencyAvailable, + withAvailabilityFilter, + withResultOfAvailabilityCheck, } from '#composite/control-flow'; import { + fillMissingListItems, + withFilteredList, + withFlattenedList, + withIndexInList, + withMappedList, + withPropertiesFromObject, + withPropertyFromList, + withPropertyFromObject, +} from '#composite/data'; + +import { withRecontextualizedContributionList, withRedatedContributionList, withResolvedContribs, + withResolvedReference, } from '#composite/wiki-data'; import { - additionalFiles, - additionalNameList, - commentary, commentatorArtists, + constitutibleArtworkList, contentString, contributionList, dimensions, @@ -50,266 +76,342 @@ import { referenceList, referencedArtworkList, reverseReferenceList, - reverseReferencedArtworkList, simpleDate, simpleString, - singleReference, + soupyFind, + soupyReverse, thing, + thingList, urls, wikiData, } from '#composite/wiki-properties'; import { - exitWithoutUniqueCoverArt, - inheritContributionListFromOriginalRelease, - inheritFromOriginalRelease, - trackReverseReferenceList, - withAlbum, - withAlwaysReferenceByDirectory, - withContainingTrackSection, - withDate, - withDirectorySuffix, - withHasUniqueCoverArt, - withOriginalRelease, - withOtherReleases, - withPropertyFromAlbum, - withSuffixDirectoryFromAlbum, - withTrackArtDate, + inheritContributionListFromMainRelease, + inheritFromMainRelease, } from '#composite/things/track'; export class Track extends Thing { static [Thing.referenceType] = 'track'; + static [Thing.wikiData] = 'trackData'; + + static [Thing.constitutibleProperties] = [ + // Contributions currently aren't being observed for constitution. + // 'artistContribs', // from main release or album + // 'contributorContribs', // from main release + // 'coverArtistContribs', // from main release + + 'trackArtworks', // from inline fields + ]; static [Thing.getPropertyDescriptors] = ({ + AdditionalFile, + AdditionalName, Album, ArtTag, - Artist, - Flash, + Artwork, + CommentaryEntry, + CreditingSourcesEntry, + LyricsEntry, + ReferencingSourcesEntry, TrackSection, WikiInfo, }) => ({ - // Update & expose + // > Update & expose - Internal relationships - name: name('Unnamed Track'), + album: thing(V(Album)), + trackSection: thing(V(TrackSection)), - directory: [ - withDirectorySuffix(), + // > Update & expose - Identifying metadata - directory({ - suffix: '#directorySuffix', - }), - ], + name: name(V('Unnamed Track')), + nameText: contentString(), - suffixDirectoryFromAlbum: [ - { - dependencies: [ - input.updateValue({validate: isBoolean}), - ], - - compute: (continuation, { - [input.updateValue()]: value, - }) => continuation({ - ['#flagValue']: value ?? false, - }), - }, + directory: directory({ + suffix: 'directorySuffix', + }), - withSuffixDirectoryFromAlbum({ - flagValue: '#flagValue', + suffixDirectoryFromAlbum: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - exposeDependency({ - dependency: '#suffixDirectoryFromAlbum', - }) + withPropertyFromObject('trackSection', V('suffixTrackDirectories')), + exposeDependency('#trackSection.suffixTrackDirectories'), ], - additionalNames: additionalNameList(), - - bandcampTrackIdentifier: simpleString(), - bandcampArtworkIdentifier: simpleString(), - - duration: duration(), - urls: urls(), - dateFirstReleased: simpleDate(), - - color: [ + // Controls how find.track works - it'll never be matched by + // a reference just to the track's name, which means you don't + // have to always reference some *other* (much more commonly + // referenced) track by directory instead of more naturally by name. + alwaysReferenceByDirectory: [ exposeUpdateValueOrContinue({ - validate: input.value(isColor), + validate: input.value(isBoolean), }), - withContainingTrackSection(), + withPropertyFromObject('album', V('alwaysReferenceTracksByDirectory')), - withPropertyFromObject({ - object: '#trackSection', - property: input.value('color'), + // Falsy mode means this exposes true if the album's property is true, + // but continues if the property is false (which is also the default). + exposeDependencyOrContinue({ + dependency: '#album.alwaysReferenceTracksByDirectory', + mode: input.value('falsy'), }), - exposeDependencyOrContinue({dependency: '#trackSection.color'}), + exitWithoutDependency('_mainRelease', V(false)), + exitWithoutDependency('mainReleaseTrack', V(false)), - withPropertyFromAlbum({ - property: input.value('color'), - }), + withPropertyFromObject('mainReleaseTrack', V('name')), - exposeDependency({dependency: '#album.color'}), + { + dependencies: ['name', '#mainReleaseTrack.name'], + compute: ({ + ['name']: name, + ['#mainReleaseTrack.name']: mainReleaseName, + }) => + getKebabCase(name) === + getKebabCase(mainReleaseName), + }, ], - alwaysReferenceByDirectory: [ - withAlwaysReferenceByDirectory(), - exposeDependency({dependency: '#alwaysReferenceByDirectory'}), - ], + // Album or track. The exposed value is really just what's provided here, + // whether or not a matching track is found on a provided album, for + // example. When presenting or processing, read `mainReleaseTrack`. + mainRelease: [ + exitWithoutUpdateValue({ + validate: input.value( + validateReference(['album', 'track'])), + }), - // Disables presenting the track as though it has its own unique artwork. - // This flag should only be used in select circumstances, i.e. to override - // an album's trackCoverArtists. This flag supercedes that property, as well - // as the track's own coverArtists. - disableUniqueCoverArt: flag(), + { + dependencies: ['name'], + transform: (ref, continuation, {name: ownName}) => + (ref === 'same name single' + ? continuation(ref, { + ['#albumOrTrackReference']: null, + ['#sameNameSingleReference']: ownName, + }) + : continuation(ref, { + ['#albumOrTrackReference']: ref, + ['#sameNameSingleReference']: null, + })), + }, - // File extension for track's corresponding media file. This represents the - // track's unique cover artwork, if any, and does not inherit the extension - // of the album's main artwork. It does inherit trackCoverArtFileExtension, - // if present on the album. - coverArtFileExtension: [ - exitWithoutUniqueCoverArt(), + withResolvedReference({ + ref: '#albumOrTrackReference', + find: soupyFind.input('trackMainReleasesOnly'), + }).outputs({ + '#resolvedReference': '#matchingTrack', + }), - exposeUpdateValueOrContinue({ - validate: input.value(isFileExtension), + withResolvedReference({ + ref: '#albumOrTrackReference', + find: soupyFind.input('album'), + }).outputs({ + '#resolvedReference': '#matchingAlbum', }), - withPropertyFromAlbum({ - property: input.value('trackCoverArtFileExtension'), + withResolvedReference({ + ref: '#sameNameSingleReference', + find: soupyFind.input('albumSinglesOnly'), + findOptions: input.value({ + fuzz: { + capitalization: true, + kebab: true, + }, + }), + }).outputs({ + '#resolvedReference': '#sameNameSingle', }), - exposeDependencyOrContinue({dependency: '#album.trackCoverArtFileExtension'}), + exposeDependencyOrContinue('#sameNameSingle'), - exposeConstant({ - value: input.value('jpg'), - }), - ], + { + dependencies: [ + '#matchingTrack', + '#matchingAlbum', + ], - coverArtDate: [ - withTrackArtDate({ - from: input.updateValue({ - validate: isDate, - }), - }), + compute: (continuation, { + ['#matchingTrack']: matchingTrack, + ['#matchingAlbum']: matchingAlbum, + }) => + (matchingTrack && matchingAlbum + ? continuation() + : matchingTrack ?? matchingAlbum + ? matchingTrack ?? matchingAlbum + : null), + }, + + withPropertyFromObject( '#matchingAlbum', V('tracks')), + + { + dependencies: [ + '#matchingAlbum.tracks', + '#matchingTrack', + ], - exposeDependency({dependency: '#trackArtDate'}), + compute: ({ + ['#matchingAlbum.tracks']: matchingAlbumTracks, + ['#matchingTrack']: matchingTrack, + }) => + (matchingAlbumTracks.includes(matchingTrack) + ? matchingTrack + : null), + }, ], - coverArtDimensions: [ - exitWithoutUniqueCoverArt(), + bandcampTrackIdentifier: simpleString(), + bandcampArtworkIdentifier: simpleString(), - withPropertyFromAlbum({ - property: input.value('trackDimensions'), - }), + additionalNames: thingList(V(AdditionalName)), - exposeDependencyOrContinue({dependency: '#album.trackDimensions'}), + dateFirstReleased: simpleDate(), - dimensions(), - ], + // > Update & expose - Credits and contributors - commentary: commentary(), - creditSources: commentary(), + artistText: [ + exposeUpdateValueOrContinue({ + validate: input.value(isContentString), + }), - lyrics: [ - inheritFromOriginalRelease(), - contentString(), + withPropertyFromObject('album', V('trackArtistText')), + exposeDependency('#album.trackArtistText'), ], - additionalFiles: additionalFiles(), - sheetMusicFiles: additionalFiles(), - midiProjectFiles: additionalFiles(), + artistTextInLists: [ + exposeUpdateValueOrContinue({ + validate: input.value(isContentString), + }), - originalReleaseTrack: singleReference({ - class: input.value(Track), - find: input.value(find.track), - data: 'trackData', - }), + exposeDependencyOrContinue('_artistText'), - // Internal use only - for directly identifying an album inside a track's - // util.inspect display, if it isn't indirectly available (by way of being - // included in an album's track list). - dataSourceAlbum: singleReference({ - class: input.value(Album), - find: input.value(find.album), - data: 'albumData', - }), + withPropertyFromObject('album', V('trackArtistText')), + exposeDependency('#album.trackArtistText'), + ], artistContribs: [ - inheritContributionListFromOriginalRelease(), - - withDate(), - withResolvedContribs({ from: input.updateValue({validate: isContributionList}), + date: 'date', thingProperty: input.thisProperty(), artistProperty: input.value('trackArtistContributions'), - date: '#date', }).outputs({ '#resolvedContribs': '#artistContribs', }), - exposeDependencyOrContinue({ - dependency: '#artistContribs', - mode: input.value('empty'), - }), + exposeDependencyOrContinue('#artistContribs', V('empty')), - withPropertyFromAlbum({ - property: input.value('artistContribs'), - }), + // Specifically inherit artist contributions later than artist contribs. + // Secondary releases' artists may differ from the main release. + inheritContributionListFromMainRelease(), + + withPropertyFromObject('album', V('trackArtistContribs')), withRecontextualizedContributionList({ - list: '#album.artistContribs', + list: '#album.trackArtistContribs', artistProperty: input.value('trackArtistContributions'), }), withRedatedContributionList({ - list: '#album.artistContribs', - date: '#date', + list: '#album.trackArtistContribs', + date: 'date', }), - exposeDependency({dependency: '#album.artistContribs'}), + exposeDependency('#album.trackArtistContribs'), ], contributorContribs: [ - inheritContributionListFromOriginalRelease(), - - withDate(), + inheritContributionListFromMainRelease(), contributionList({ - date: '#date', + date: 'date', artistProperty: input.value('trackContributorContributions'), }), ], - // Cover artists aren't inherited from the original release, since it - // typically varies by release and isn't defined by the musical qualities - // of the track. - coverArtistContribs: [ - exitWithoutUniqueCoverArt({ + // > Update & expose - General configuration + + countInArtistTotals: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withPropertyFromObject('trackSection', V('countTracksInArtistTotals')), + exposeDependency('#trackSection.countTracksInArtistTotals'), + ], + + disableUniqueCoverArt: flag(V(false)), + disableDate: flag(V(false)), + + // > Update & expose - General metadata + + duration: duration(), + + color: [ + exposeUpdateValueOrContinue({ + validate: input.value(isColor), + }), + + withPropertyFromObject('trackSection', V('color')), + exposeDependencyOrContinue('#trackSection.color'), + + withPropertyFromObject('album', V('color')), + exposeDependency('#album.color'), + ], + + needsLyrics: [ + exposeUpdateValueOrContinue({ + mode: input.value('falsy'), + validate: input.value(isBoolean), + }), + + exitWithoutDependency('_lyrics', { + value: input.value(false), + mode: input.value('empty'), + }), + + withPropertyFromList('_lyrics', V('helpNeeded')), + + { + dependencies: ['#lyrics.helpNeeded'], + compute: ({ + ['#lyrics.helpNeeded']: helpNeeded, + }) => + helpNeeded.includes(true) + }, + ], + + urls: urls(), + + // > Update & expose - Artworks + + trackArtworks: [ + exitWithoutDependency('hasUniqueCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), - withTrackArtDate({ - fallback: input.value(true), + constitutibleArtworkList.fromYAMLFieldSpec + .call(this, 'Track Artwork'), + ], + + coverArtistContribs: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value([]), + mode: input.value('falsy'), }), withResolvedContribs({ from: input.updateValue({validate: isContributionList}), - thingProperty: input.thisProperty(), + date: 'coverArtDate', + thingProperty: input.value('coverArtistContribs'), artistProperty: input.value('trackCoverArtistContributions'), - date: '#trackArtDate', - }).outputs({ - '#resolvedContribs': '#coverArtistContribs', }), - exposeDependencyOrContinue({ - dependency: '#coverArtistContribs', - mode: input.value('empty'), - }), + exposeDependencyOrContinue('#resolvedContribs', V('empty')), - withPropertyFromAlbum({ - property: input.value('trackCoverArtistContribs'), - }), + withPropertyFromObject('album', V('trackCoverArtistContribs')), withRecontextualizedContributionList({ list: '#album.trackCoverArtistContribs', @@ -318,165 +420,502 @@ export class Track extends Thing { withRedatedContributionList({ list: '#album.trackCoverArtistContribs', - date: '#trackArtDate', + date: 'coverArtDate', }), - exposeDependency({dependency: '#album.trackCoverArtistContribs'}), + exposeDependency('#album.trackCoverArtistContribs'), ], - referencedTracks: [ - inheritFromOriginalRelease({ - notFoundValue: input.value([]), + coverArtDate: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value(null), + mode: input.value('falsy'), }), - referenceList({ - class: input.value(Track), - find: input.value(find.track), - data: 'trackData', + exposeUpdateValueOrContinue({ + validate: input.value(isDate), }), + + withPropertyFromObject('album', V('trackArtDate')), + exposeDependencyOrContinue('#album.trackArtDate'), + + exposeDependency('date'), ], - sampledTracks: [ - inheritFromOriginalRelease({ - notFoundValue: input.value([]), + coverArtFileExtension: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value(null), + mode: input.value('falsy'), }), - referenceList({ - class: input.value(Track), - find: input.value(find.track), - data: 'trackData', + exposeUpdateValueOrContinue({ + validate: input.value(isFileExtension), }), + + withPropertyFromObject('album', V('trackCoverArtFileExtension')), + exposeDependencyOrContinue('#album.trackCoverArtFileExtension'), + + exposeConstant(V('jpg')), + ], + + coverArtDimensions: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + exposeUpdateValueOrContinue(), + + withPropertyFromObject('album', V('trackDimensions')), + exposeDependencyOrContinue('#album.trackDimensions'), + + dimensions(), ], artTags: [ - exitWithoutUniqueCoverArt({ + exitWithoutDependency('hasUniqueCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), referenceList({ class: input.value(ArtTag), - find: input.value(find.artTag), - data: 'artTagData', + find: soupyFind.input('artTag'), }), ], referencedArtworks: [ - exitWithoutUniqueCoverArt({ + exitWithoutDependency('hasUniqueCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), - withTrackArtDate({ - fallback: input.value(true), + referencedArtworkList(), + ], + + // > Update & expose - Referenced tracks + + previousProductionTracks: [ + inheritFromMainRelease(), + + referenceList({ + class: input.value(Track), + find: soupyFind.input('trackMainReleasesOnly'), }), + ], - referencedArtworkList({ - date: '#trackArtDate', + referencedTracks: [ + inheritFromMainRelease(), + + referenceList({ + class: input.value(Track), + find: soupyFind.input('trackMainReleasesOnly'), }), ], - // Update only + sampledTracks: [ + inheritFromMainRelease(), - albumData: wikiData({ - class: input.value(Album), - }), + referenceList({ + class: input.value(Track), + find: soupyFind.input('trackMainReleasesOnly'), + }), + ], - artistData: wikiData({ - class: input.value(Artist), - }), + // > Update & expose - Additional files - artTagData: wikiData({ - class: input.value(ArtTag), - }), + additionalFiles: thingList(V(AdditionalFile)), + sheetMusicFiles: thingList(V(AdditionalFile)), + midiProjectFiles: thingList(V(AdditionalFile)), - flashData: wikiData({ - class: input.value(Flash), - }), + // > Update & expose - Content entries - trackData: wikiData({ - class: input.value(Track), - }), + lyrics: [ + // TODO: Inherited lyrics are literally the same objects, so of course + // their .thing properties aren't going to point back to this one, and + // certainly couldn't be recontextualized... + inheritFromMainRelease(), - trackSectionData: wikiData({ - class: input.value(TrackSection), - }), + thingList(V(LyricsEntry)), + ], - wikiInfo: thing({ - class: input.value(WikiInfo), - }), + commentary: thingList(V(CommentaryEntry)), + creditingSources: thingList(V(CreditingSourcesEntry)), + referencingSources: thingList(V(ReferencingSourcesEntry)), - // Expose only + // > Update only + + find: soupyFind(), + reverse: soupyReverse(), + + // used for referencedArtworkList (mixedFind) + artworkData: wikiData(V(Artwork)), + + // used for withMatchingContributionPresets (indirectly by Contribution) + wikiInfo: thing(V(WikiInfo)), + + // > Expose only + + isTrack: exposeConstant(V(true)), commentatorArtists: commentatorArtists(), - album: [ - withAlbum(), - exposeDependency({dependency: '#album'}), + directorySuffix: [ + exitWithoutDependency('suffixDirectoryFromAlbum', { + value: input.value(null), + mode: input.value('falsy'), + }), + + withPropertyFromObject('trackSection', V('directorySuffix')), + exposeDependency('#trackSection.directorySuffix'), ], date: [ - withDate(), - exposeDependency({dependency: '#date'}), + { + dependencies: ['disableDate'], + compute: (continuation, {disableDate}) => + (disableDate + ? null + : continuation()), + }, + + exposeDependencyOrContinue('dateFirstReleased'), + + withPropertyFromObject('album', V('date')), + exposeDependency('#album.date'), ], - hasUniqueCoverArt: [ - withHasUniqueCoverArt(), - exposeDependency({dependency: '#hasUniqueCoverArt'}), + trackNumber: [ + // Zero is the fallback, not one, but in most albums the first track + // (and its intended output by this composition) will be one. + + exitWithoutDependency('trackSection', V(0)), + withPropertiesFromObject('trackSection', V(['tracks', 'startCountingFrom'])), + + withIndexInList('#trackSection.tracks', input.myself()), + exitWithoutDependency('#index', V(0), V('index')), + + { + dependencies: ['#trackSection.startCountingFrom', '#index'], + compute: ({ + ['#trackSection.startCountingFrom']: startCountingFrom, + ['#index']: index, + }) => startCountingFrom + index, + }, ], - isOriginalRelease: [ - withOriginalRelease(), + // Whether or not the track has "unique" cover artwork - a cover which is + // specifically associated with this track in particular, rather than with + // the track's album as a whole. This is typically used to select between + // displaying the track artwork and a fallback, such as the album artwork + // or a placeholder. (This property is named hasUniqueCoverArt instead of + // the usual hasCoverArt to emphasize that it does not inherit from the + // album.) + // + // hasUniqueCoverArt is based only around the presence of *specified* + // cover artist contributions, not whether the references to artists on those + // contributions actually resolve to anything. It completely evades interacting + // with find/replace. + hasUniqueCoverArt: [ + { + dependencies: ['disableUniqueCoverArt'], + compute: (continuation, {disableUniqueCoverArt}) => + (disableUniqueCoverArt + ? false + : continuation()), + }, + + withResultOfAvailabilityCheck({ + from: '_coverArtistContribs', + mode: input.value('empty'), + }), + + { + dependencies: ['#availability'], + compute: (continuation, { + ['#availability']: availability, + }) => + (availability + ? true + : continuation()), + }, + + withPropertyFromObject('album', { + property: input.value('trackCoverArtistContribs'), + internal: input.value(true), + }), + + withResultOfAvailabilityCheck({ + from: '#album.trackCoverArtistContribs', + mode: input.value('empty'), + }), + + { + dependencies: ['#availability'], + compute: (continuation, { + ['#availability']: availability, + }) => + (availability + ? true + : continuation()), + }, + + exitWithoutDependency('_trackArtworks', { + value: input.value(false), + mode: input.value('empty'), + }), + + withPropertyFromList('_trackArtworks', { + property: input.value('artistContribs'), + internal: input.value(true), + }), + + // Since we're getting the update value for each artwork's artistContribs, + // it may not be set at all, and in that case won't be exposing as []. + fillMissingListItems('#trackArtworks.artistContribs', V([])), + + withFlattenedList('#trackArtworks.artistContribs'), exposeWhetherDependencyAvailable({ - dependency: '#originalRelease', - negate: input.value(true), + dependency: '#flattenedList', + mode: input.value('empty'), }), ], - isRerelease: [ - withOriginalRelease(), + isMainRelease: + exposeWhetherDependencyAvailable({ + dependency: 'mainReleaseTrack', + negate: input.value(true), + }), + isSecondaryRelease: exposeWhetherDependencyAvailable({ - dependency: '#originalRelease', + dependency: 'mainReleaseTrack', }), + + mainReleaseTrack: [ + exitWithoutDependency('mainRelease'), + + withPropertyFromObject('mainRelease', V('isTrack')), + + { + dependencies: ['mainRelease', '#mainRelease.isTrack'], + compute: (continuation, { + ['mainRelease']: mainRelease, + ['#mainRelease.isTrack']: mainReleaseIsTrack, + }) => + (mainReleaseIsTrack + ? mainRelease + : continuation()), + }, + + { + dependencies: ['name', '_directory'], + compute: (continuation, { + ['name']: ownName, + ['_directory']: ownDirectory, + }) => { + const ownNameKebabed = getKebabCase(ownName); + + return continuation({ + ['#mapItsNameLikeName']: + name => getKebabCase(name) === ownNameKebabed, + + ['#mapItsDirectoryLikeDirectory']: + (ownDirectory + ? directory => directory === ownDirectory + : () => false), + + ['#mapItsNameLikeDirectory']: + (ownDirectory + ? name => getKebabCase(name) === ownDirectory + : () => false), + + ['#mapItsDirectoryLikeName']: + directory => directory === ownNameKebabed, + }); + }, + }, + + withPropertyFromObject('mainRelease', V('tracks')), + + withPropertyFromList('#mainRelease.tracks', { + property: input.value('mainRelease'), + internal: input.value(true), + }), + + withAvailabilityFilter({from: '#mainRelease.tracks.mainRelease'}), + + withMappedList({ + list: '#availabilityFilter', + map: input.value(item => !item), + }).outputs({ + '#mappedList': '#availabilityFilter', + }), + + withFilteredList('#mainRelease.tracks', '#availabilityFilter') + .outputs({'#filteredList': '#mainRelease.tracks'}), + + withPropertyFromList('#mainRelease.tracks', V('name')), + + withPropertyFromList('#mainRelease.tracks', { + property: input.value('directory'), + internal: input.value(true), + }), + + withMappedList('#mainRelease.tracks.name', '#mapItsNameLikeName') + .outputs({'#mappedList': '#filterItsNameLikeName'}), + + withMappedList('#mainRelease.tracks.directory', '#mapItsDirectoryLikeDirectory') + .outputs({'#mappedList': '#filterItsDirectoryLikeDirectory'}), + + withMappedList('#mainRelease.tracks.name', '#mapItsNameLikeDirectory') + .outputs({'#mappedList': '#filterItsNameLikeDirectory'}), + + withMappedList('#mainRelease.tracks.directory', '#mapItsDirectoryLikeName') + .outputs({'#mappedList': '#filterItsDirectoryLikeName'}), + + withFilteredList('#mainRelease.tracks', '#filterItsNameLikeName') + .outputs({'#filteredList': '#matchingItsNameLikeName'}), + + withFilteredList('#mainRelease.tracks', '#filterItsDirectoryLikeDirectory') + .outputs({'#filteredList': '#matchingItsDirectoryLikeDirectory'}), + + withFilteredList('#mainRelease.tracks', '#filterItsNameLikeDirectory') + .outputs({'#filteredList': '#matchingItsNameLikeDirectory'}), + + withFilteredList('#mainRelease.tracks', '#filterItsDirectoryLikeName') + .outputs({'#filteredList': '#matchingItsDirectoryLikeName'}), + + { + dependencies: [ + '#matchingItsNameLikeName', + '#matchingItsDirectoryLikeDirectory', + '#matchingItsNameLikeDirectory', + '#matchingItsDirectoryLikeName', + ], + + compute: (continuation, { + ['#matchingItsNameLikeName']: NLN, + ['#matchingItsDirectoryLikeDirectory']: DLD, + ['#matchingItsNameLikeDirectory']: NLD, + ['#matchingItsDirectoryLikeName']: DLN, + }) => continuation({ + ['#mainReleaseTrack']: + onlyItem(DLD) ?? + onlyItem(NLN) ?? + onlyItem(DLN) ?? + onlyItem(NLD) ?? + null, + }), + }, + + { + dependencies: ['#mainReleaseTrack', input.myself()], + compute: ({ + ['#mainReleaseTrack']: mainReleaseTrack, + [input.myself()]: thisTrack, + }) => + (mainReleaseTrack === thisTrack + ? null + : mainReleaseTrack), + }, + ], + + // Only has any value for main releases, because secondary releases + // are never secondary to *another* secondary release. + secondaryReleases: reverseReferenceList({ + reverse: soupyReverse.input('tracksWhichAreSecondaryReleasesOf'), + }), + + allReleases: [ + { + dependencies: [ + 'mainReleaseTrack', + 'secondaryReleases', + input.myself(), + ], + + compute: (continuation, { + mainReleaseTrack, + secondaryReleases, + [input.myself()]: thisTrack, + }) => + (mainReleaseTrack + ? continuation({ + ['#mainReleaseTrack']: mainReleaseTrack, + ['#secondaryReleaseTracks']: mainReleaseTrack.secondaryReleases, + }) + : continuation({ + ['#mainReleaseTrack']: thisTrack, + ['#secondaryReleaseTracks']: secondaryReleases, + })), + }, + + { + dependencies: [ + '#mainReleaseTrack', + '#secondaryReleaseTracks', + ], + + compute: ({ + ['#mainReleaseTrack']: mainReleaseTrack, + ['#secondaryReleaseTracks']: secondaryReleaseTracks, + }) => + sortByDate([mainReleaseTrack, ...secondaryReleaseTracks]), + }, ], otherReleases: [ - withOtherReleases(), - exposeDependency({dependency: '#otherReleases'}), + { + dependencies: [input.myself(), 'allReleases'], + compute: ({ + [input.myself()]: thisTrack, + ['allReleases']: allReleases, + }) => + allReleases.filter(track => track !== thisTrack), + }, ], - referencedByTracks: trackReverseReferenceList({ - list: input.value('referencedTracks'), - }), + commentaryFromMainRelease: [ + exitWithoutDependency('mainReleaseTrack', V([])), + + withPropertyFromObject('mainReleaseTrack', V('commentary')), + exposeDependency('#mainReleaseTrack.commentary'), + ], + + groups: [ + withPropertyFromObject('album', V('groups')), + exposeDependency('#album.groups'), + ], - sampledByTracks: trackReverseReferenceList({ - list: input.value('sampledTracks'), + followingProductionTracks: reverseReferenceList({ + reverse: soupyReverse.input('tracksWhichAreFollowingProductionsOf'), }), - featuredInFlashes: reverseReferenceList({ - data: 'flashData', - list: input.value('featuredTracks'), + referencedByTracks: reverseReferenceList({ + reverse: soupyReverse.input('tracksWhichReference'), }), - referencedByArtworks: [ - exitWithoutUniqueCoverArt({ - value: input.value([]), - }), + sampledByTracks: reverseReferenceList({ + reverse: soupyReverse.input('tracksWhichSample'), + }), - reverseReferencedArtworkList(), - ], + featuredInFlashes: reverseReferenceList({ + reverse: soupyReverse.input('flashesWhichFeature'), + }), }); static [Thing.yamlDocumentSpec] = { fields: { + // Identifying metadata + 'Track': {property: 'name'}, + 'Track Text': {property: 'nameText'}, 'Directory': {property: 'directory'}, 'Suffix Directory': {property: 'suffixDirectoryFromAlbum'}, - - 'Additional Names': { - property: 'additionalNames', - transform: parseAdditionalNames, - }, + 'Always Reference By Directory': {property: 'alwaysReferenceByDirectory'}, + 'Main Release': {property: 'mainRelease'}, 'Bandcamp Track ID': { property: 'bandcampTrackIdentifier', @@ -488,17 +927,86 @@ export class Track extends Thing { transform: String, }, + 'Additional Names': { + property: 'additionalNames', + transform: parseAdditionalNames, + }, + + 'Date First Released': { + property: 'dateFirstReleased', + transform: parseDate, + }, + + // Credits and contributors + + 'Artist Text': {property: 'artistText'}, + 'Artist Text In Lists': {property: 'artistTextInLists'}, + + 'Artists': { + property: 'artistContribs', + transform: parseContributors, + }, + + 'Contributors': { + property: 'contributorContribs', + transform: parseContributors, + }, + + // General configuration + + 'Count In Artist Totals': {property: 'countInArtistTotals'}, + + 'Has Cover Art': { + property: 'disableUniqueCoverArt', + transform: value => + (typeof value === 'boolean' + ? !value + : value), + }, + + 'Has Date': { + property: 'disableDate', + transform: value => + (typeof value === 'boolean' + ? !value + : value), + }, + + // General metadata + 'Duration': { property: 'duration', transform: parseDuration, }, 'Color': {property: 'color'}, + + 'Needs Lyrics': { + property: 'needsLyrics', + }, + 'URLs': {property: 'urls'}, - 'Date First Released': { - property: 'dateFirstReleased', - transform: parseDate, + // Artworks + + 'Track Artwork': { + property: 'trackArtworks', + transform: + parseArtwork({ + thingProperty: 'trackArtworks', + dimensionsFromThingProperty: 'coverArtDimensions', + fileExtensionFromThingProperty: 'coverArtFileExtension', + dateFromThingProperty: 'coverArtDate', + artTagsFromThingProperty: 'artTags', + referencedArtworksFromThingProperty: 'referencedArtworks', + artistContribsFromThingProperty: 'coverArtistContribs', + artistContribsArtistProperty: 'trackCoverArtistContributions', + }), + }, + + 'Cover Artists': { + property: 'coverArtistContribs', + transform: parseContributors, }, 'Cover Art Date': { @@ -513,19 +1021,20 @@ export class Track extends Thing { transform: parseDimensions, }, - 'Has Cover Art': { - property: 'disableUniqueCoverArt', - transform: value => - (typeof value === 'boolean' - ? !value - : value), + 'Art Tags': {property: 'artTags'}, + + 'Referenced Artworks': { + property: 'referencedArtworks', + transform: parseAnnotatedReferences, }, - 'Always Reference By Directory': {property: 'alwaysReferenceByDirectory'}, + // Referenced tracks + + 'Previous Productions': {property: 'previousProductionTracks'}, + 'Referenced Tracks': {property: 'referencedTracks'}, + 'Sampled Tracks': {property: 'sampledTracks'}, - 'Lyrics': {property: 'lyrics'}, - 'Commentary': {property: 'commentary'}, - 'Credit Sources': {property: 'creditSources'}, + // Additional files 'Additional Files': { property: 'additionalFiles', @@ -542,61 +1051,58 @@ export class Track extends Thing { transform: parseAdditionalFiles, }, - 'Originally Released As': {property: 'originalReleaseTrack'}, - 'Referenced Tracks': {property: 'referencedTracks'}, - 'Sampled Tracks': {property: 'sampledTracks'}, + // Content entries - 'Referenced Artworks': { - property: 'referencedArtworks', - transform: parseAnnotatedReferences, + 'Lyrics': { + property: 'lyrics', + transform: parseLyrics, }, - 'Franchises': {ignore: true}, - 'Inherit Franchises': {ignore: true}, - - 'Artists': { - property: 'artistContribs', - transform: parseContributors, + 'Commentary': { + property: 'commentary', + transform: parseCommentary, }, - 'Contributors': { - property: 'contributorContribs', - transform: parseContributors, + 'Crediting Sources': { + property: 'creditingSources', + transform: parseCreditingSources, }, - 'Cover Artists': { - property: 'coverArtistContribs', - transform: parseContributors, + 'Referencing Sources': { + property: 'referencingSources', + transform: parseReferencingSources, }, - 'Art Tags': {property: 'artTags'}, + // Shenanigans + 'Franchises': {ignore: true}, + 'Inherit Franchises': {ignore: true}, 'Review Points': {ignore: true}, }, invalidFieldCombinations: [ - {message: `Rereleases inherit references from the original`, fields: [ - 'Originally Released As', - 'Referenced Tracks', + {message: `Secondary releases never count in artist totals`, fields: [ + 'Main Release', + 'Count In Artist Totals', ]}, - {message: `Rereleases inherit samples from the original`, fields: [ - 'Originally Released As', - 'Sampled Tracks', + {message: `Secondary releases inherit references from the main one`, fields: [ + 'Main Release', + 'Referenced Tracks', ]}, - {message: `Rereleases inherit artists from the original`, fields: [ - 'Originally Released As', - 'Artists', + {message: `Secondary releases inherit samples from the main one`, fields: [ + 'Main Release', + 'Sampled Tracks', ]}, - {message: `Rereleases inherit contributors from the original`, fields: [ - 'Originally Released As', + {message: `Secondary releases inherit contributors from the main one`, fields: [ + 'Main Release', 'Contributors', ]}, - {message: `Rereleases inherit lyrics from the original`, fields: [ - 'Originally Released As', + {message: `Secondary releases inherit lyrics from the main one`, fields: [ + 'Main Release', 'Lyrics', ]}, @@ -617,6 +1123,7 @@ export class Track extends Thing { static [Thing.findSpecs] = { track: { referenceTypes: ['track'], + bindTo: 'trackData', getMatchableNames: track => @@ -625,12 +1132,12 @@ export class Track extends Thing { : [track.name]), }, - trackOriginalReleasesOnly: { + trackMainReleasesOnly: { referenceTypes: ['track'], bindTo: 'trackData', include: track => - !CacheableObject.getUpdateValue(track, 'originalReleaseTrack'), + !CacheableObject.getUpdateValue(track, 'mainRelease'), // It's still necessary to check alwaysReferenceByDirectory here, since // it may be set manually (with `Always Reference By Directory: true`), @@ -643,7 +1150,12 @@ export class Track extends Thing { }, trackWithArtwork: { - referenceTypes: ['track'], + referenceTypes: [ + 'track', + 'track-referencing-artworks', + 'track-referenced-artworks', + ], + bindTo: 'trackData', include: track => @@ -654,32 +1166,151 @@ export class Track extends Thing { ? [] : [track.name]), }, + + trackPrimaryArtwork: { + [Thing.findThisThingOnly]: false, + + referenceTypes: [ + 'track', + 'track-referencing-artworks', + 'track-referenced-artworks', + ], + + bindTo: 'artworkData', + + include: (artwork, {Artwork, Track}) => + artwork instanceof Artwork && + artwork.thing instanceof Track && + artwork === artwork.thing.trackArtworks[0], + + getMatchableNames: ({thing: track}) => + (track.alwaysReferenceByDirectory + ? [] + : [track.name]), + + getMatchableDirectories: ({thing: track}) => + [track.directory], + }, + }; + + static [Thing.reverseSpecs] = { + tracksWhichReference: { + bindTo: 'trackData', + + referencing: track => track.isMainRelease ? [track] : [], + referenced: track => track.referencedTracks, + }, + + tracksWhichSample: { + bindTo: 'trackData', + + referencing: track => track.isMainRelease ? [track] : [], + referenced: track => track.sampledTracks, + }, + + tracksWhoseArtworksFeature: { + bindTo: 'trackData', + + referencing: track => [track], + referenced: track => track.artTags, + }, + + trackArtistContributionsBy: + soupyReverse.contributionsBy('trackData', 'artistContribs'), + + trackContributorContributionsBy: + soupyReverse.contributionsBy('trackData', 'contributorContribs'), + + trackCoverArtistContributionsBy: + soupyReverse.artworkContributionsBy('trackData', 'trackArtworks'), + + tracksWithCommentaryBy: { + bindTo: 'trackData', + + referencing: track => [track], + referenced: track => track.commentatorArtists, + }, + + tracksWhichAreSecondaryReleasesOf: { + bindTo: 'trackData', + + referencing: track => track.isSecondaryRelease ? [track] : [], + referenced: track => [track.mainReleaseTrack], + }, + + tracksWhichAreFollowingProductionsOf: { + bindTo: 'trackData', + + referencing: track => track.isMainRelease ? [track] : [], + referenced: track => track.previousProductionTracks, + }, }; // Track YAML loading is handled in album.js. static [Thing.getYamlLoadingSpec] = null; + getOwnAdditionalFilePath(_file, filename) { + if (!this.album) return null; + + return [ + 'media.albumAdditionalFile', + this.album.directory, + filename, + ]; + } + + getOwnArtworkPath(artwork) { + if (!this.album) return null; + + return [ + 'media.trackCover', + this.album.directory, + + (artwork.unqualifiedDirectory + ? this.directory + '-' + artwork.unqualifiedDirectory + : this.directory), + + artwork.fileExtension, + ]; + } + + countOwnContributionInContributionTotals(_contrib) { + if (!this.countInArtistTotals) { + return false; + } + + if (this.isSecondaryRelease) { + return false; + } + + return true; + } + + countOwnContributionInDurationTotals(_contrib) { + if (!this.countInArtistTotals) { + return false; + } + + if (this.isSecondaryRelease) { + return false; + } + + return true; + } + [inspect.custom](depth) { const parts = []; parts.push(Thing.prototype[inspect.custom].apply(this)); - if (CacheableObject.getUpdateValue(this, 'originalReleaseTrack')) { - parts.unshift(`${colors.yellow('[rerelease]')} `); + if (CacheableObject.getUpdateValue(this, 'mainRelease')) { + parts.unshift(`${colors.yellow('[secrelease]')} `); } let album; if (depth >= 0) { - try { - album = this.album; - } catch (_error) { - // Computing album might crash for any reason, which we don't want to - // distract from another error we might be trying to work out at the - // moment (for which debugging might involve inspecting this track!). - } - - album ??= this.dataSourceAlbum; + album = this.album; } if (album) { diff --git a/src/data/things/wiki-info.js b/src/data/things/wiki-info.js index ef643681..26b69ba6 100644 --- a/src/data/things/wiki-info.js +++ b/src/data/things/wiki-info.js @@ -1,30 +1,35 @@ export const WIKI_INFO_FILE = 'wiki-info.yaml'; -import {input} from '#composite'; -import find from '#find'; +import {input, V} from '#composite'; import Thing from '#thing'; -import {parseContributionPresets} from '#yaml'; +import {isBoolean, isContributionPresetList, isLanguageCode, isName} + from '#validators'; +import {parseContributionPresets, parseWallpaperParts} from '#yaml'; + +import {exitWithoutDependency, exposeConstant} from '#composite/control-flow'; import { - isBoolean, - isColor, - isContributionPresetList, - isLanguageCode, - isName, - isURL, -} from '#validators'; - -import {exitWithoutDependency} from '#composite/control-flow'; -import {contentString, flag, name, referenceList, wikiData} - from '#composite/wiki-properties'; + canonicalBase, + color, + contentString, + fileExtension, + flag, + name, + referenceList, + simpleString, + soupyFind, + wallpaperParts, +} from '#composite/wiki-properties'; export class WikiInfo extends Thing { static [Thing.friendlyName] = `Wiki Info`; + static [Thing.wikiData] = 'wikiInfo'; + static [Thing.oneInstancePerWiki] = true; static [Thing.getPropertyDescriptors] = ({Group}) => ({ // Update & expose - name: name('Unnamed Wiki'), + name: name(V('Unnamed Wiki')), // Displayed in nav bar. nameShort: { @@ -37,14 +42,7 @@ export class WikiInfo extends Thing { }, }, - color: { - flags: {update: true, expose: true}, - update: {validate: isColor}, - - expose: { - transform: color => color ?? '#0088ff', - }, - }, + color: color(V('#0088ff')), // One-line description used for <meta rel="description"> tag. description: contentString(), @@ -56,23 +54,16 @@ export class WikiInfo extends Thing { update: {validate: isLanguageCode}, }, - canonicalBase: { - flags: {update: true, expose: true}, - update: {validate: isURL}, - expose: { - transform: (value) => - (value === null - ? null - : value.endsWith('/') - ? value - : value + '/'), - }, - }, + canonicalBase: canonicalBase(), + canonicalMediaBase: canonicalBase(), + + wikiWallpaperFileExtension: fileExtension(V('jpg')), + wikiWallpaperStyle: simpleString(), + wikiWallpaperParts: wallpaperParts(), divideTrackListsByGroups: referenceList({ class: input.value(Group), - find: input.value(find.group), - data: 'groupData', + find: soupyFind.input('group'), }), contributionPresets: { @@ -81,24 +72,25 @@ export class WikiInfo extends Thing { }, // Feature toggles - enableFlashesAndGames: flag(false), - enableListings: flag(false), - enableNews: flag(false), - enableArtTagUI: flag(false), - enableGroupUI: flag(false), + enableFlashesAndGames: flag(V(false)), + enableListings: flag(V(false)), + enableNews: flag(V(false)), + enableArtTagUI: flag(V(false)), + enableGroupUI: flag(V(false)), enableSearch: [ - exitWithoutDependency({ - dependency: 'searchDataAvailable', - mode: input.value('falsy'), + exitWithoutDependency('_searchDataAvailable', { value: input.value(false), + mode: input.value('falsy'), }), - flag(true), + flag(V(true)), ], // Update only + find: soupyFind(), + searchDataAvailable: { flags: {update: true}, update: { @@ -107,27 +99,44 @@ export class WikiInfo extends Thing { }, }, - groupData: wikiData({ - class: input.value(Group), - }), + // Expose only + + isWikiInfo: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { fields: { 'Name': {property: 'name'}, 'Short Name': {property: 'nameShort'}, + 'Color': {property: 'color'}, + 'Description': {property: 'description'}, + 'Footer Content': {property: 'footerContent'}, + 'Default Language': {property: 'defaultLanguage'}, + 'Canonical Base': {property: 'canonicalBase'}, - 'Divide Track Lists By Groups': {property: 'divideTrackListsByGroups'}, + 'Canonical Media Base': {property: 'canonicalMediaBase'}, + + 'Wiki Wallpaper File Extension': {property: 'wikiWallpaperFileExtension'}, + + 'Wiki Wallpaper Style': {property: 'wikiWallpaperStyle'}, + + 'Wiki Wallpaper Parts': { + property: 'wikiWallpaperParts', + transform: parseWallpaperParts, + }, + 'Enable Flashes & Games': {property: 'enableFlashesAndGames'}, 'Enable Listings': {property: 'enableListings'}, 'Enable News': {property: 'enableNews'}, 'Enable Art Tag UI': {property: 'enableArtTagUI'}, 'Enable Group UI': {property: 'enableGroupUI'}, + 'Divide Track Lists By Groups': {property: 'divideTrackListsByGroups'}, + 'Contribution Presets': { property: 'contributionPresets', transform: parseContributionPresets, @@ -144,13 +153,5 @@ export class WikiInfo extends Thing { documentMode: oneDocumentTotal, documentThing: WikiInfo, - - save(wikiInfo) { - if (!wikiInfo) { - return; - } - - return {wikiInfo}; - }, }); } diff --git a/src/data/validators.js b/src/data/validators.js deleted file mode 100644 index 84e08cb8..00000000 --- a/src/data/validators.js +++ /dev/null @@ -1,1104 +0,0 @@ -import {inspect as nodeInspect} from 'node:util'; - -import {openAggregate, withAggregate} from '#aggregate'; -import {colors, ENABLE_COLOR} from '#cli'; -import {cut, empty, matchMultiline, typeAppearance} from '#sugar'; -import {commentaryRegexCaseInsensitive, commentaryRegexCaseSensitiveOneShot} - 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 (caughtError) { - const indexPart = colors.yellow(`zero-index ${index}`) - const itemPart = inspect(item); - const message = `Error at ${indexPart}: ${itemPart}`; - const error = new Error(message, {cause: caughtError}); - error[Symbol.for('hsmusic.annotateError.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) { - isContentString(commentaryText); - - const rawMatches = - Array.from(commentaryText.matchAll(commentaryRegexCaseInsensitive)); - - 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 upToNextLineBreak = - (restOfInput.includes('\n') - ? restOfInput.slice(0, restOfInput.indexOf('\n')) - : restOfInput); - - 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)`); - } - - if (!commentaryRegexCaseSensitiveOneShot.test(ownInput)) { - throw new TypeError( - `Miscapitalization in commentary heading:\n` + - `${colors.red(`"${cut(ownInput, 60)}"`)}\n` + - `(Check for ${colors.red(`"<I>"`)} instead of ${colors.green(`"<i>"`)})`); - } - - 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 { - [validateProperties.validateOtherKeys]: validateOtherKeys = null, - [validateProperties.allowOtherKeys]: allowOtherKeys = false, - } = 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`}, ({push}) => { - const testEntries = specEntries.slice(); - - const unknownKeys = Object.keys(object).filter((key) => !specKeys.includes(key)); - if (validateOtherKeys) { - for (const key of unknownKeys) { - testEntries.push([key, validateOtherKeys]); - } - } - - for (const [specKey, specValidator] of testEntries) { - const value = object[specKey]; - try { - specValidator(value); - } catch (caughtError) { - const keyPart = colors.green(specKey); - const valuePart = inspect(value); - const message = `Error for key ${keyPart}: ${valuePart}`; - push(new Error(message, {cause: caughtError})); - } - } - - if (!validateOtherKeys && !allowOtherKeys && !empty(unknownKeys)) { - push(new Error( - `Unknown keys present (${unknownKeys.length}): [${unknownKeys.join(', ')}]`)); - } - }); - - return true; - }; -} - -validateProperties.validateOtherKeys = Symbol(); -validateProperties.allowOtherKeys = Symbol(); - -export const validateAllPropertyValues = (validator) => - validateProperties({ - [validateProperties.validateOtherKeys]: validator, - }); - -const illeaglInvisibleSpace = { - action: 'delete', -}; - -const illegalVisibleSpace = { - action: 'replace', - with: ' ', - withAnnotation: `normal space`, -}; - -const illegalContentSpec = [ - {illegal: '\u200b', annotation: `zero-width space`, ...illeaglInvisibleSpace}, - {illegal: '\u2005', annotation: `four-per-em space`, ...illegalVisibleSpace}, - {illegal: '\u205f', annotation: `medium mathematical space`, ...illegalVisibleSpace}, - {illegal: '\xa0', annotation: `non-breaking space`, ...illegalVisibleSpace}, - - { - action: 'replace', - illegal: '<a href', - annotation: `HTML-style link`, - with: '[...](...)', - withAnnotation: `markdown`, - }, -]; - -for (const entry of illegalContentSpec) { - entry.test = string => - string.startsWith(entry.illegal); - - if (entry.action === 'replace') { - entry.enact = string => - string.replaceAll(entry.illegal, entry.with); - } -} - -const illegalSequencesInContent = - illegalContentSpec - .map(entry => entry.illegal) - .map(illegal => - (illegal.length === 1 - ? `${illegal}+` - : `(?:${illegal})+`)) - .join('|'); - -const illegalContentRegexp = - new RegExp(illegalSequencesInContent, 'g'); - -const legalContentNearEndRegexp = - new RegExp(`(?<=^|${illegalSequencesInContent})(?:(?!${illegalSequencesInContent}).)+$`); - -const legalContentNearStartRegexp = - new RegExp(`^(?:(?!${illegalSequencesInContent}).)+`); - -const trimWhitespaceNearBothSidesRegexp = - /^ +| +$/gm; - -const trimWhitespaceNearEndRegexp = - / +$/gm; - -export function isContentString(content) { - isString(content); - - const mainAggregate = openAggregate({ - message: `Errors validating content string`, - translucent: 'single', - }); - - const illegalAggregate = openAggregate({ - message: `Illegal characters found in content string`, - }); - - for (const {match, where} of matchMultiline(content, illegalContentRegexp)) { - const {annotation, action, ...options} = - illegalContentSpec - .find(entry => entry.test(match[0])); - - const matchStart = match.index; - const matchEnd = match.index + match[0].length; - - const before = - content - .slice(Math.max(0, matchStart - 3), matchStart) - .match(legalContentNearEndRegexp) - ?.[0]; - - const after = - content - .slice(matchEnd, Math.min(content.length, matchEnd + 3)) - .match(legalContentNearStartRegexp) - ?.[0]; - - const beforePart = - before && `"${before}"`; - - const afterPart = - after && `"${after}"`; - - const surroundings = - (before && after - ? `between ${beforePart} and ${afterPart}` - : before - ? `after ${beforePart}` - : after - ? `before ${afterPart}` - : ``); - - const illegalPart = - colors.red( - (annotation - ? `"${match[0]}" (${annotation})` - : `"${match[0]}"`)); - - const replacement = - (action === 'replace' - ? options.enact(match[0]) - : null); - - const replaceWithPart = - (action === 'replace' - ? colors.green( - (options.withAnnotation - ? `"${replacement}" (${options.withAnnotation})` - : `"${replacement}"`)) - : null); - - const actionPart = - (action === `delete` - ? `Delete ${illegalPart}` - : action === 'replace' - ? `Replace ${illegalPart} with ${replaceWithPart}` - : `Matched ${illegalPart}`); - - const parts = [ - actionPart, - surroundings, - `(${where})`, - ].filter(Boolean); - - illegalAggregate.push(new TypeError(parts.join(` `))); - } - - const isMultiline = content.includes('\n'); - - const trimWhitespaceAggregate = openAggregate({ - message: - (isMultiline - ? `Whitespace found at end of line` - : `Whitespace found at start or end`), - }); - - const trimWhitespaceRegexp = - (isMultiline - ? trimWhitespaceNearEndRegexp - : trimWhitespaceNearBothSidesRegexp); - - for ( - const {match, lineNumber, columnNumber, containingLine} of - matchMultiline(content, trimWhitespaceRegexp, { - formatWhere: false, - getContainingLine: true, - }) - ) { - const linePart = - colors.yellow(`line ${lineNumber + 1}`); - - const where = - (match[0].length === containingLine.length - ? `as all of ${linePart}` - : columnNumber === 0 - ? (isMultiline - ? `at start of ${linePart}` - : `at start`) - : (isMultiline - ? `at end of ${linePart}` - : `at end`)); - - const whitespacePart = - colors.red(`"${match[0]}"`); - - const parts = [ - `Matched ${whitespacePart}`, - where, - ]; - - trimWhitespaceAggregate.push(new TypeError(parts.join(` `))); - } - - mainAggregate.call(() => illegalAggregate.close()); - mainAggregate.call(() => trimWhitespaceAggregate.close()); - mainAggregate.close(); - - return true; -} - -export function isThingClass(thingClass) { - isFunction(thingClass); - - // This is *expressly* no faster than an instanceof check, because it's - // deliberately still walking the prototype chain for the provided object. - // (This is necessary because the symbol we're checking is defined only on - // the Thing constructor, and not directly on each subclass.) However, it's - // preferred over an instanceof check anyway, because instanceof would - // require that the #validators module has access to #thing, which it - // currently doesn't! - if (!(Symbol.for('Thing.isThingConstructor') in thingClass)) { - throw new TypeError(`Expected a Thing constructor, missing Thing.isThingConstructor`); - } - - return true; -} - -export function isThing(thing) { - isObject(thing); - - // This *is* faster than an instanceof check, because it doesn't walk the - // prototype chain. It works because this property is set as part of every - // Thing subclass's inherited "public class fields" - it's set directly on - // every constructed Thing. - if (!Object.hasOwn(thing, Symbol.for('Thing.isThing'))) { - throw new TypeError(`Expected a Thing, missing Thing.isThing`); - } - - return true; -} - -export const isContribution = validateProperties({ - artist: isArtistRef, - annotation: optional(isStringNonEmpty), - - countInDurationTotals: optional(isBoolean), - countInContributionTotals: optional(isBoolean), -}); - -export const isContributionList = validateArrayItems(isContribution); - -export const contributionPresetPropertySpec = { - album: [ - 'artistContribs', - ], - - flash: [ - 'contributorContribs', - ], - - track: [ - 'artistContribs', - 'contributorContribs', - ], -}; - -// TODO: This validator basically constructs itself as it goes. -// This is definitely some shenanigans! -export function isContributionPresetContext(list) { - isArray(list); - - if (empty(list)) { - throw new TypeError(`Expected at least one item`); - } - - const isTarget = - is(...Object.keys(contributionPresetPropertySpec)); - - const [target, ...properties] = list; - - isTarget(target); - - const isProperty = - is(...contributionPresetPropertySpec[target]); - - const isPropertyList = - validateArrayItems(isProperty); - - isPropertyList(properties); - - return true; -} - -export const isContributionPreset = validateProperties({ - annotation: isStringNonEmpty, - context: isContributionPresetContext, - - countInDurationTotals: optional(isBoolean), - countInContributionTotals: optional(isBoolean), -}); - -export const isContributionPresetList = validateArrayItems(isContributionPreset); - -export const isAdditionalFile = validateProperties({ - title: isName, - description: optional(isContentString), - files: optional(validateArrayItems(isString)), -}); - -export const isAdditionalFileList = validateArrayItems(isAdditionalFile); - -export const isTrackSection = validateProperties({ - name: optional(isName), - color: optional(isColor), - dateOriginallyReleased: optional(isDate), - isDefaultTrackSection: optional(isBoolean), - tracks: optional(validateReferenceList('track')), -}); - -export const isTrackSectionList = validateArrayItems(isTrackSection); - -export const isSeries = validateProperties({ - name: isName, - description: optional(isContentString), - albums: optional(validateReferenceList('album')), - - showAlbumArtists: - optional(is('all', 'differing', 'none')), -}); - -export const isSeriesList = validateArrayItems(isSeries); - -export const isWallpaperPart = validateProperties({ - asset: optional(isString), - style: optional(isString), -}); - -export const isWallpaperPartList = validateArrayItems(isWallpaperPart); - -export function isDimensions(dimensions) { - isArray(dimensions); - - if (dimensions.length !== 2) throw new TypeError(`Expected 2 item array`); - - if (dimensions[0] !== null) { - isPositive(dimensions[0]); - isInteger(dimensions[0]); - } - - if (dimensions[1] !== null) { - 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 isContentString(name); -} - -export function isURL(string) { - isStringNonEmpty(string); - - new URL(string); - - return true; -} - -export function validateReference(type) { - 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 (Array.isArray(type)) { - if (!type.includes(typePart)) { - throw new TypeError( - `Expected ref to begin with one of ` + - type.map(type => `"${type}:"`).join(', ') + - `, got "${typePart}:"`); - } - } else 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)); -} - -export function validateThing({ - referenceType: expectedReferenceType = '', -} = {}) { - return (thing) => { - isThing(thing); - - if (expectedReferenceType) { - const {[Symbol.for('Thing.referenceType')]: referenceType} = - thing.constructor; - - if (referenceType !== expectedReferenceType) { - throw new TypeError(`Expected only ${expectedReferenceType}, got other type: ${referenceType}`); - } - } - - return true; - }; -} - -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) { - if (Object.hasOwn(object, Symbol.for('Thing.isThing'))) { - // 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`); - } - - foundThing = true; - allRefTypes.add(object.constructor[Symbol.for('Thing.referenceType')]); - } else { - // 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`); - } - - foundOtherObject = true; - } - } - - 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: isContentString, - annotation: optional(isContentString), -}); - -export const isAdditionalNameList = validateArrayItems(isAdditionalName); - -// Compositional utilities - -export function anyOf(...validators) { - const validConstants = new Set(); - const validConstructors = new Set(); - const validTypes = new Set(); - - const constantValidators = []; - const constructorValidators = []; - const typeValidators = []; - - 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); - } - - constantValidators.push(validator); - break; - - case validateInstanceOf: - validConstructors.add(creatorMeta.constructor); - constructorValidators.push(validator); - break; - - case validateType: - validTypes.add(creatorMeta.type); - typeValidators.push(validator); - 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([ - constantValidators, - offset++, - new TypeError( - `Expected any of ${constants.join(' ')}` + gotPart), - ]); - } - - if (!empty(validTypes)) { - const types = - Array.from(validTypes); - - const gotType = typeAppearance(value); - const gotPart = `, got ${gotType}`; - - prefaceErrorInfo.push([ - typeValidators, - offset++, - new TypeError( - `Expected any 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([ - constructorValidators, - offset++, - new TypeError( - `Expected any 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 = - (Array.isArray(validator) && validator.length === 1 - ? validator[0] - : validator); - - errors.push(error); - } - - const total = offset + leftoverValidators.length; - throw new AggregateError(errors, - `Expected any of ${total} possible checks, ` + - `but none were true`); - }; -} diff --git a/src/data/yaml.js b/src/data/yaml.js index 64223662..fbb4e5d6 100644 --- a/src/data/yaml.js +++ b/src/data/yaml.js @@ -8,11 +8,14 @@ import {inspect as nodeInspect} from 'node:util'; import yaml from 'js-yaml'; import {colors, ENABLE_COLOR, logInfo, logWarn} from '#cli'; +import {parseContentNodes, splitContentNodesAround} from '#replacer'; import {sortByName} from '#sort'; import Thing from '#thing'; import thingConstructors from '#things'; +import {matchContentEntries, multipleLyricsDetectionRegex} from '#wiki-data'; import { + aggregateThrows, annotateErrorWithFile, decorateErrorWithIndex, decorateErrorWithAnnotation, @@ -30,8 +33,10 @@ import { atOffset, empty, filterProperties, + getNestedProp, stitchArrays, typeAppearance, + unique, withEntries, } from '#sugar'; @@ -39,6 +44,42 @@ function inspect(value, opts = {}) { return nodeInspect(value, {colors: ENABLE_COLOR, ...opts}); } +function makeEmptyWikiData() { + const wikiData = {}; + + for (const thingConstructor of Object.values(thingConstructors)) { + if (thingConstructor[Thing.wikiData]) { + if (thingConstructor[Thing.oneInstancePerWiki]) { + wikiData[thingConstructor[Thing.wikiData]] = null; + } else { + wikiData[thingConstructor[Thing.wikiData]] = []; + } + } + } + + return wikiData; +} + +function pushWikiData(a, b) { + for (const key of Object.keys(b)) { + if (!Object.hasOwn(a, key)) { + throw new Error(`${key} not present`); + } + + if (Array.isArray(a[key])) { + if (Array.isArray(b[key])) { + a[key].push(...b[key]); + } else { + throw new Error(`${key} is an array, expected array of items to push`); + } + } else if (a[key] === null) { + a[key] = b[key]; + } else if (b[key] !== null) { + throw new Error(`${key} already has a value: ${inspect(a[key])}`); + } + } +} + // General function for inputting a single document (usually loaded from YAML) // and outputting an instance of a provided Thing subclass. // @@ -82,10 +123,14 @@ function makeProcessDocument(thingConstructor, { // ] // // ...means A can't coexist with B or C, B can't coexist with A or C, and - // C can't coexist iwth A, B, or D - but it's okay for D to coexist with + // C can't coexist with A, B, or D - but it's okay for D to coexist with // A or B. // invalidFieldCombinations = [], + + // Bouncing function used to process subdocuments: this is a function which + // in turn calls the appropriate *result of* makeProcessDocument. + processDocument: bouncer, }) { if (!thingConstructor) { throw new Error(`Missing Thing class`); @@ -95,6 +140,10 @@ function makeProcessDocument(thingConstructor, { throw new Error(`Expected fields to be provided`); } + if (!bouncer) { + throw new Error(`Missing processDocument bouncer`); + } + const knownFields = Object.keys(fieldSpecs); const ignoredFields = @@ -142,9 +191,22 @@ function makeProcessDocument(thingConstructor, { : `document`); const aggregate = openAggregate({ + ...aggregateThrows(ProcessDocumentError), message: `Errors processing ${constructorPart}` + namePart, }); + const thing = Reflect.construct(thingConstructor, []); + + const wikiData = makeEmptyWikiData(); + const flat = [thing]; + if (thingConstructor[Thing.wikiData]) { + if (thingConstructor[Thing.oneInstancePerWiki]) { + wikiData[thingConstructor[Thing.wikiData]] = thing; + } else { + wikiData[thingConstructor[Thing.wikiData]] = [thing]; + } + } + const documentEntries = Object.entries(document) .filter(([field]) => !ignoredFields.includes(field)); @@ -166,9 +228,22 @@ function makeProcessDocument(thingConstructor, { const fieldCombinationErrors = []; - for (const {message, fields} of invalidFieldCombinations) { + for (const {message, fields: fieldsSpec} of invalidFieldCombinations) { const fieldsPresent = - presentFields.filter(field => fields.includes(field)); + fieldsSpec.flatMap(fieldSpec => { + if (Array.isArray(fieldSpec)) { + const [field, match] = fieldSpec; + if (!presentFields.includes(field)) return []; + if (typeof match === 'function') { + return match(document[field]) ? [field] : []; + } else { + return document[field] === match ? [field] : []; + } + } + + const field = fieldSpec; + return presentFields.includes(field) ? [field] : []; + }); if (fieldsPresent.length >= 2) { const filteredDocument = @@ -178,7 +253,10 @@ function makeProcessDocument(thingConstructor, { {preserveOriginalOrder: true}); fieldCombinationErrors.push( - new FieldCombinationError(filteredDocument, message)); + new FieldCombinationError( + filteredDocument, + fieldsSpec, + message)); for (const field of Object.keys(filteredDocument)) { skippedFields.add(field); @@ -192,13 +270,52 @@ function makeProcessDocument(thingConstructor, { const fieldValues = {}; + const subdocSymbol = Symbol('subdoc'); + const subdocLayouts = {}; + + const isSubdocToken = value => + typeof value === 'object' && + value !== null && + Object.hasOwn(value, subdocSymbol); + + const transformUtilities = { + ...thingConstructors, + + subdoc(documentType, data, { + bindInto = null, + provide = null, + } = {}) { + if (!documentType) + throw new Error(`Expected document type, got ${typeAppearance(documentType)}`); + if (!data) + throw new Error(`Expected data, got ${typeAppearance(data)}`); + if (typeof data !== 'object' || data === null) + throw new Error(`Expected data to be an object, got ${typeAppearance(data)}`); + if (typeof bindInto !== 'string' && bindInto !== null) + throw new Error(`Expected bindInto to be a string, got ${typeAppearance(bindInto)}`); + if (typeof provide !== 'object' && provide !== null) + throw new Error(`Expected provide to be an object, got ${typeAppearance(provide)}`); + + return { + [subdocSymbol]: { + documentType, + data, + bindInto, + provide, + }, + }; + }, + }; + for (const [field, documentValue] of documentEntries) { if (skippedFields.has(field)) continue; // This variable would like to certify itself as "not into capitalism". let propertyValue = - (fieldSpecs[field].transform - ? fieldSpecs[field].transform(documentValue) + (documentValue === null + ? null + : fieldSpecs[field].transform + ? fieldSpecs[field].transform(documentValue, transformUtilities) : documentValue); // Completely blank items in a YAML list are read as null. @@ -221,10 +338,102 @@ function makeProcessDocument(thingConstructor, { } } + if (isSubdocToken(propertyValue)) { + subdocLayouts[field] = propertyValue[subdocSymbol]; + continue; + } + + if (Array.isArray(propertyValue) && propertyValue.every(isSubdocToken)) { + subdocLayouts[field] = + propertyValue + .map(token => token[subdocSymbol]); + continue; + } + fieldValues[field] = propertyValue; } - const thing = Reflect.construct(thingConstructor, []); + const subdocErrors = []; + + const followSubdocSetup = setup => { + let error = null; + + let result; + try { + let aggregate; + ({result, aggregate} = bouncer(setup.data, setup.documentType)); + aggregate.close(); + } catch (caughtError) { + error = caughtError; + } + + if (result.thing) { + if (setup.bindInto) { + result.thing[setup.bindInto] = thing; + } + + if (setup.provide) { + Object.assign(result.thing, setup.provide); + } + } + + pushWikiData(wikiData, result.wikiData); + flat.push(...result.flat); + + return {error, subthing: result.thing}; + }; + + for (const [field, layout] of Object.entries(subdocLayouts)) { + if (Array.isArray(layout)) { + const subthings = []; + let anySucceeded = false; + let anyFailed = false; + + for (const [index, setup] of layout.entries()) { + const {subthing, error} = followSubdocSetup(setup); + if (error) { + subdocErrors.push(new SubdocError( + {field, index}, + setup, + {cause: error})); + } + + if (subthing) { + subthings.push(subthing); + anySucceeded = true; + } else { + anyFailed = true; + } + } + + if (anySucceeded) { + fieldValues[field] = subthings; + } else if (anyFailed) { + skippedFields.add(field); + } + } else { + const setup = layout; + const {subthing, error} = followSubdocSetup(setup); + + if (error) { + subdocErrors.push(new SubdocError( + {field}, + setup, + {cause: error})); + } + + if (subthing) { + fieldValues[field] = subthing; + } else { + skippedFields.add(field); + } + } + } + + if (!empty(subdocErrors)) { + aggregate.push(new SubdocAggregateError( + subdocErrors, thingConstructor)); + } const fieldValueErrors = []; @@ -254,10 +463,19 @@ function makeProcessDocument(thingConstructor, { {preserveOriginalOrder: true}))); } - return {thing, aggregate}; + return { + aggregate, + result: { + thing, + flat, + wikiData, + }, + }; }); } +export class ProcessDocumentError extends AggregateError {} + export class UnknownFieldsError extends Error { constructor(fields) { super(`Unknown fields ignored: ${fields.map(field => colors.red(field)).join(', ')}`); @@ -272,19 +490,36 @@ export class FieldCombinationAggregateError extends AggregateError { } export class FieldCombinationError extends Error { - constructor(fields, message) { - const fieldNames = Object.keys(fields); + constructor(filteredDocument, fieldsSpec, message) { + const fieldNames = Object.keys(filteredDocument); const fieldNamesText = fieldNames - .map(field => colors.red(field)) + .map(field => { + if (fieldsSpec.includes(field)) { + return colors.red(field); + } + + const match = + fieldsSpec + .find(fieldSpec => + Array.isArray(fieldSpec) && + fieldSpec[0] === field) + .at(1); + + if (typeof match === 'function') { + return colors.red(`${field}: ${filteredDocument[field]}`); + } else { + return colors.red(`${field}: ${match}`); + } + }) .join(', '); const mainMessage = `Don't combine ${fieldNamesText}`; const causeMessage = (typeof message === 'function' - ? message(fields) + ? message(filteredDocument) : typeof message === 'string' ? message : null); @@ -296,7 +531,7 @@ export class FieldCombinationError extends Error { : null), }); - this.fields = fields; + this.fields = fieldNames; } } @@ -345,12 +580,46 @@ export class SkippedFieldsSummaryError extends Error { : `${entries.length} fields`); super( - colors.bright(colors.yellow(`Altogether, skipped ${numFieldsText}:\n`)) + + colors.bright(colors.yellow(`Altogether, skipped ${numFieldsText}:`)) + '\n' + lines.join('\n') + '\n' + colors.bright(colors.yellow(`See above errors for details.`))); } } +export class SubdocError extends Error { + constructor({field, index = null}, setup, options) { + const fieldText = + (index === null + ? colors.green(`"${field}"`) + : colors.yellow(`#${index + 1}`) + ' in ' + + colors.green(`"${field}"`)); + + const constructorText = + setup.documentType.name; + + if (options.cause instanceof ProcessDocumentError) { + options.cause[Symbol.for('hsmusic.aggregate.translucent')] = true; + } + + super( + `Errors processing ${constructorText} for ${fieldText} field`, + options); + } +} + +export class SubdocAggregateError extends AggregateError { + [Symbol.for('hsmusic.aggregate.translucent')] = true; + + constructor(errors, thingConstructor) { + const constructorText = + colors.green(thingConstructor.name); + + super( + errors, + `Errors processing subdocuments for ${constructorText}`); + } +} + export function parseDate(date) { return new Date(date); } @@ -433,49 +702,39 @@ export function parseContributors(entries) { }); } -export function parseAdditionalFiles(entries) { +export function parseAdditionalFiles(entries, {subdoc, AdditionalFile}) { return parseArrayEntries(entries, item => { if (typeof item !== 'object') return item; - return { - title: item['Title'], - description: item['Description'] ?? null, - files: item['Files'], - }; + return subdoc(AdditionalFile, item, {bindInto: 'thing'}); }); } -export function parseAdditionalNames(entries) { +export function parseAdditionalNames(entries, {subdoc, AdditionalName}) { return parseArrayEntries(entries, item => { - if (typeof item === 'object' && typeof item['Name'] === 'string') - return { - name: item['Name'], - annotation: item['Annotation'] ?? null, - }; + if (typeof item === 'object') { + return subdoc(AdditionalName, item, {bindInto: 'thing'}); + } if (typeof item !== 'string') return item; const match = item.match(extractAccentRegex); if (!match) return item; - return { - name: match.groups.main, - annotation: match.groups.accent ?? null, + const document = { + ['Name']: match.groups.main, + ['Annotation']: match.groups.accent ?? null, }; + + return subdoc(AdditionalName, document, {bindInto: 'thing'}); }); } -export function parseSerieses(entries) { +export function parseSerieses(entries, {subdoc, Series}) { return parseArrayEntries(entries, item => { if (typeof item !== 'object') return item; - return { - name: item['Name'], - description: item['Description'] ?? null, - albums: item['Albums'] ?? null, - - showAlbumArtists: item['Show Album Artists'] ?? null, - }; + return subdoc(Series, item, {bindInto: 'group'}); }); } @@ -613,6 +872,196 @@ export function parseAnnotatedReferences(entries, { }); } +export function parseArtwork({ + single = false, + thingProperty = null, + dimensionsFromThingProperty = null, + fileExtensionFromThingProperty = null, + dateFromThingProperty = null, + artistContribsFromThingProperty = null, + artistContribsArtistProperty = null, + artTagsFromThingProperty = null, + referencedArtworksFromThingProperty = null, +}) { + const provide = { + thingProperty, + dimensionsFromThingProperty, + fileExtensionFromThingProperty, + dateFromThingProperty, + artistContribsFromThingProperty, + artistContribsArtistProperty, + artTagsFromThingProperty, + referencedArtworksFromThingProperty, + }; + + const parseSingleEntry = (entry, {subdoc, Artwork}) => + subdoc(Artwork, entry, {bindInto: 'thing', provide}); + + const transform = (value, ...args) => + (Array.isArray(value) + ? value.map(entry => parseSingleEntry(entry, ...args)) + : single + ? parseSingleEntry(value, ...args) + : [parseSingleEntry(value, ...args)]); + + transform.provide = provide; + + return transform; +} + +export function parseContentEntriesFromSourceText(thingClass, sourceText, {subdoc}) { + function map(matchEntry) { + let artistText = null, artistReferences = null; + + const artistTextNodes = + Array.from( + splitContentNodesAround( + parseContentNodes(matchEntry.artistText), + /\|/g)); + + const separatorIndices = + artistTextNodes + .filter(node => node.type === 'separator') + .map(node => artistTextNodes.indexOf(node)); + + if (empty(separatorIndices)) { + if (artistTextNodes.length === 1 && artistTextNodes[0].type === 'text') { + artistReferences = matchEntry.artistText; + } else { + artistText = matchEntry.artistText; + } + } else { + const firstSeparatorIndex = + separatorIndices.at(0); + + const secondSeparatorIndex = + separatorIndices.at(1) ?? + artistTextNodes.length; + + artistReferences = + matchEntry.artistText.slice( + artistTextNodes.at(0).i, + artistTextNodes.at(firstSeparatorIndex - 1).iEnd); + + artistText = + matchEntry.artistText.slice( + artistTextNodes.at(firstSeparatorIndex).iEnd, + artistTextNodes.at(secondSeparatorIndex - 1).iEnd); + } + + if (artistReferences) { + artistReferences = + artistReferences + .split(',') + .map(ref => ref.trim()); + } + + return { + 'Artists': + artistReferences, + + 'Artist Text': + artistText, + + 'Annotation': + matchEntry.annotation, + + 'Date': + matchEntry.date, + + 'Second Date': + matchEntry.secondDate, + + 'Date Kind': + matchEntry.dateKind, + + 'Access Date': + matchEntry.accessDate, + + 'Access Kind': + matchEntry.accessKind, + + 'Body': + matchEntry.body, + }; + } + + const documents = + matchContentEntries(sourceText) + .map(matchEntry => + withEntries( + map(matchEntry), + entries => entries + .filter(([key, value]) => + value !== undefined && + value !== null))); + + const subdocs = + documents.map(document => + subdoc(thingClass, document, {bindInto: 'thing'})); + + return subdocs; +} + +export function parseContentEntries(thingClass, value, {subdoc}) { + if (typeof value === 'string') { + return parseContentEntriesFromSourceText(thingClass, value, {subdoc}); + } else if (Array.isArray(value)) { + return value.map(doc => subdoc(thingClass, doc, {bindInto: 'thing'})); + } else { + return value; + } +} + +export function parseCommentary(value, {subdoc, CommentaryEntry}) { + return parseContentEntries(CommentaryEntry, value, {subdoc}); +} + +export function parseCreditingSources(value, {subdoc, CreditingSourcesEntry}) { + return parseContentEntries(CreditingSourcesEntry, value, {subdoc}); +} + +export function parseReferencingSources(value, {subdoc, ReferencingSourcesEntry}) { + return parseContentEntries(ReferencingSourcesEntry, value, {subdoc}); +} + +export function parseLyrics(value, {subdoc, LyricsEntry}) { + if ( + typeof value === 'string' && + !multipleLyricsDetectionRegex.test(value) + ) { + const document = {'Body': value}; + + return [subdoc(LyricsEntry, document, {bindInto: 'thing'})]; + } + + return parseContentEntries(LyricsEntry, value, {subdoc}); +} + +export function parseArtistAliases(value, {subdoc, Artist}) { + return parseArrayEntries(value, item => { + const config = { + bindInto: 'aliasedArtist', + provide: {isAlias: true}, + }; + + if (typeof item === 'string') { + return subdoc(Artist, {'Artist': item}, config); + } else if (typeof item === 'object' && !Array.isArray(item)) { + if (item['Name']) { + const clone = {...item}; + clone['Artist'] = item['Name']; + delete clone['Name']; + return subdoc(Artist, clone, config); + } else { + return subdoc(Artist, item, config); + } + } else { + return item; + } + }); +} + // documentModes: Symbols indicating sets of behavior for loading and processing // data files. export const documentModes = { @@ -642,6 +1091,12 @@ export const documentModes = { // array of processed documents (wiki objects). allInOne: Symbol('Document mode: allInOne'), + // allTogether: One or more documens, spread across any number of files. + // Expects files array (or function) and processDocument function. + // Calls save with an array of processed documents (wiki objects) - this is + // a flat array, *not* an array of the documents processed from *each* file. + allTogether: Symbol('Document mode: allTogether'), + // oneDocumentTotal: Just a single document, represented in one file. // Expects file string (or function) and processDocument function. Calls // save with the single processed wiki document (data object). @@ -688,16 +1143,23 @@ export const documentModes = { export function getAllDataSteps() { try { thingConstructors; - } catch (error) { + } catch { throw new Error(`Thing constructors aren't ready yet, can't get all data steps`); } const steps = []; + const seenLoadingFns = new Set(); + for (const thingConstructor of Object.values(thingConstructors)) { const getSpecFn = thingConstructor[Thing.getYamlLoadingSpec]; if (!getSpecFn) continue; + // Subclasses can expose literally the same static properties + // by inheritence. We don't want to double-count those! + if (seenLoadingFns.has(getSpecFn)) continue; + seenLoadingFns.add(getSpecFn); + steps.push(getSpecFn({ documentModes, thingConstructors, @@ -745,6 +1207,7 @@ export async function getFilesFromDataStep(dataStep, {dataPath}) { } } + case documentModes.allTogether: case documentModes.headerAndEntries: case documentModes.onePerFile: { if (!dataStep.files) { @@ -890,7 +1353,7 @@ export function processThingsFromDataStep(documents, dataStep) { throw new Error(`Class "${thingClass.name}" doesn't specify Thing.yamlDocumentSpec`); } - fn = makeProcessDocument(thingClass, spec); + fn = makeProcessDocument(thingClass, {...spec, processDocument}); submap.set(thingClass, fn); } @@ -900,30 +1363,60 @@ export function processThingsFromDataStep(documents, dataStep) { const {documentMode} = dataStep; switch (documentMode) { - case documentModes.allInOne: { - const result = []; + case documentModes.allInOne: + case documentModes.allTogether: { + const things = []; + const flat = []; + const wikiData = makeEmptyWikiData(); const aggregate = openAggregate({message: `Errors processing documents`}); documents.forEach( - decorateErrorWithIndex(document => { - const {thing, aggregate: subAggregate} = + decorateErrorWithIndex((document, index) => { + const {result, aggregate: subAggregate} = processDocument(document, dataStep.documentThing); - result.push(thing); + result.thing[Thing.yamlSourceDocument] = document; + result.thing[Thing.yamlSourceDocumentPlacement] = + [documentModes.allInOne, index]; + + things.push(result.thing); + flat.push(...result.flat); + pushWikiData(wikiData, result.wikiData); + aggregate.call(subAggregate.close); })); - return {aggregate, result}; + return { + aggregate, + result: { + network: things, + flat: things, + file: things, + wikiData, + }, + }; } case documentModes.oneDocumentTotal: { if (documents.length > 1) throw new Error(`Only expected one document to be present, got ${documents.length}`); - const {thing, aggregate} = + const {result, aggregate} = processDocument(documents[0], dataStep.documentThing); - return {aggregate, result: thing}; + result.thing[Thing.yamlSourceDocument] = documents[0]; + result.thing[Thing.yamlSourceDocumentPlacement] = + [documentModes.oneDocumentTotal]; + + return { + aggregate, + result: { + network: result.thing, + flat: result.flat, + file: [result.thing], + wikiData: result.wikiData, + }, + }; } case documentModes.headerAndEntries: { @@ -934,10 +1427,17 @@ export function processThingsFromDataStep(documents, dataStep) { throw new Error(`Missing header document (empty file or erroneously starting with "---"?)`); const aggregate = openAggregate({message: `Errors processing documents`}); + const wikiData = makeEmptyWikiData(); - const {thing: headerThing, aggregate: headerAggregate} = + const {result: headerResult, aggregate: headerAggregate} = processDocument(headerDocument, dataStep.headerDocumentThing); + headerResult.thing[Thing.yamlSourceDocument] = headerDocument; + headerResult.thing[Thing.yamlSourceDocumentPlacement] = + [documentModes.headerAndEntries, 'header']; + + pushWikiData(wikiData, headerResult.wikiData); + try { headerAggregate.close(); } catch (caughtError) { @@ -945,13 +1445,18 @@ export function processThingsFromDataStep(documents, dataStep) { aggregate.push(caughtError); } - const entryThings = []; + const entryResults = []; for (const [index, entryDocument] of entryDocuments.entries()) { - const {thing: entryThing, aggregate: entryAggregate} = + const {result: entryResult, aggregate: entryAggregate} = processDocument(entryDocument, dataStep.entryDocumentThing); - entryThings.push(entryThing); + entryResult.thing[Thing.yamlSourceDocument] = entryDocument; + entryResult.thing[Thing.yamlSourceDocumentPlacement] = + [documentModes.headerAndEntries, 'entry', index]; + + entryResults.push(entryResult); + pushWikiData(wikiData, entryResult.wikiData); try { entryAggregate.close(); @@ -964,8 +1469,15 @@ export function processThingsFromDataStep(documents, dataStep) { return { aggregate, result: { - header: headerThing, - entries: entryThings, + network: { + header: headerResult.thing, + entries: entryResults.map(result => result.thing), + }, + + flat: headerResult.flat.concat(entryResults.flatMap(result => result.flat)), + file: [headerResult.thing, ...entryResults.map(result => result.thing)], + + wikiData, }, }; } @@ -977,10 +1489,22 @@ export function processThingsFromDataStep(documents, dataStep) { if (empty(documents) || !documents[0]) throw new Error(`Expected a document, this file is empty`); - const {thing, aggregate} = + const {result, aggregate} = processDocument(documents[0], dataStep.documentThing); - return {aggregate, result: thing}; + result.thing[Thing.yamlSourceDocument] = documents[0]; + result.thing[Thing.yamlSourceDocumentPlacement] = + [documentModes.onePerFile]; + + return { + aggregate, + result: { + network: result.thing, + flat: result.flat, + file: [result.thing], + wikiData: result.wikiData, + }, + }; } default: @@ -1083,6 +1607,13 @@ export async function processThingsFromDataSteps(documentLists, fileLists, dataS const {result, aggregate} = processThingsFromDataStep(documents, dataStep); + for (const thing of result.file) { + thing[Thing.yamlSourceFilename] = + path.relative(dataPath, file) + .split(path.sep) + .join(path.posix.sep); + } + const close = decorateErrorWithFileFromDataPath(aggregate.close, {dataPath}); aggregate.close = () => close({file}); @@ -1103,41 +1634,35 @@ export async function processThingsFromDataSteps(documentLists, fileLists, dataS translucent: true, }).contain(await fileListPromise)); - const thingLists = + const results = aggregate .receive(await Promise.all(dataStepPromises)); - return {aggregate, result: thingLists}; + return {aggregate, result: results}; } -// Flattens a list of *lists* of things for a given data step (each list -// corresponding to one YAML file) into results to be saved on the final -// wikiData object, routing thing lists into the step's save() function. -export function saveThingsFromDataStep(thingLists, dataStep) { +// Runs a data step's connect() function, if present, with representations +// of the results from the YAML files, called "networks" - one network and +// one call to .connect() per YAML file - in order to form data connections +// (direct links) between related objects within a file. +export function connectThingsFromDataStep(results, dataStep) { const {documentMode} = dataStep; switch (documentMode) { - case documentModes.allInOne: { - const things = - (empty(thingLists) - ? [] - : thingLists[0]); - - return dataStep.save(things); + case documentModes.oneDocumentTotal: + case documentModes.onePerFile: { + // These results are never connected. + return; } - case documentModes.oneDocumentTotal: { - const thing = - (empty(thingLists) - ? {} - : thingLists[0]); - - return dataStep.save(thing); - } + case documentModes.allInOne: + case documentModes.allTogether: + case documentModes.headerAndEntries: { + for (const result of results) { + dataStep.connect?.(result.network); + } - case documentModes.headerAndEntries: - case documentModes.onePerFile: { - return dataStep.save(thingLists); + break; } default: @@ -1145,60 +1670,70 @@ export function saveThingsFromDataStep(thingLists, dataStep) { } } -// Flattens a list of *lists* of things for each data step (each list -// corresponding to one YAML file) into the final wikiData object, -// routing thing lists into each step's save() function. -export function saveThingsFromDataSteps(thingLists, dataSteps) { +export function connectThingsFromDataSteps(processThingResultLists, dataSteps) { const aggregate = openAggregate({ - message: `Errors finalizing things from data files`, + message: `Errors connecting things from data files`, translucent: true, }); - const wikiData = {}; - stitchArrays({ dataStep: dataSteps, - thingLists: thingLists, - }).map(({dataStep, thingLists}) => { + processThingResults: processThingResultLists, + }).forEach(({dataStep, processThingResults}) => { try { - return saveThingsFromDataStep(thingLists, dataStep); + connectThingsFromDataStep(processThingResults, dataStep); } catch (caughtError) { const error = new Error( - `Error finalizing things for data step: ${colors.bright(dataStep.title)}`, + `Error connecting things for data step: ${colors.bright(dataStep.title)}`, {cause: caughtError}); error[Symbol.for('hsmusic.aggregate.translucent')] = true; aggregate.push(error); - - return null; } - }) - .filter(Boolean) - .forEach(saveResult => { - for (const [saveKey, saveValue] of Object.entries(saveResult)) { - if (Object.hasOwn(wikiData, saveKey)) { - if (Array.isArray(wikiData[saveKey])) { - if (Array.isArray(saveValue)) { - wikiData[saveKey].push(...saveValue); - } else { - throw new Error(`${saveKey} already present, expected array of items to push`); - } - } else { - if (Array.isArray(saveValue)) { - throw new Error(`${saveKey} already present and not an array, refusing to overwrite`); - } else { - throw new Error(`${saveKey} already present, refusing to overwrite`); - } - } - } else { - wikiData[saveKey] = saveValue; + }); + + return {result: null, aggregate}; +} + +export function makeWikiDataFromDataSteps(processThingResultLists, _dataSteps) { + const wikiData = makeEmptyWikiData(); + + for (const result of processThingResultLists.flat(2)) { + pushWikiData(wikiData, result.wikiData); + } + + const scanForConstituted = + processThingResultLists.flat(2).flatMap(result => result.flat); + + const exists = new Set(scanForConstituted); + + while (scanForConstituted.length) { + const scanningThing = scanForConstituted.pop(); + + for (const key of scanningThing.constructor[Thing.constitutibleProperties] ?? []) { + const maybeConstitutedThings = + (Array.isArray(scanningThing[key]) + ? scanningThing[key] + : scanningThing[key] + ? [scanningThing[key]] + : []); + + for (const thing of maybeConstitutedThings) { + if (exists.has(thing)) continue; + exists.add(thing); + + if (thing.constructor[Thing.wikiData]) { + pushWikiData(wikiData, {[thing.constructor[Thing.wikiData]]: [thing]}); } + + scanForConstituted.push(thing); } - }); + } + } - return {aggregate, result: wikiData}; + return wikiData; } export async function loadAndProcessDataDocuments(dataSteps, {dataPath}) { @@ -1211,13 +1746,15 @@ export async function loadAndProcessDataDocuments(dataSteps, {dataPath}) { aggregate.receive( await loadYAMLDocumentsFromDataSteps(dataSteps, {dataPath})); - const thingLists = + const processThingResultLists = aggregate.receive( await processThingsFromDataSteps(documentLists, fileLists, dataSteps, {dataPath})); + aggregate.receive( + connectThingsFromDataSteps(processThingResultLists, dataSteps)); + const wikiData = - aggregate.receive( - saveThingsFromDataSteps(thingLists, dataSteps)); + makeWikiDataFromDataSteps(processThingResultLists, dataSteps); return {aggregate, result: wikiData}; } @@ -1225,93 +1762,106 @@ export async function loadAndProcessDataDocuments(dataSteps, {dataPath}) { // Data linking! Basically, provide (portions of) wikiData to the Things which // require it - they'll expose dynamically computed properties as a result (many // of which are required for page HTML generation and other expected behavior). -export function linkWikiDataArrays(wikiData) { +export function linkWikiDataArrays(wikiData, {bindFind, bindReverse}) { const linkWikiDataSpec = new Map([ - [wikiData.albumData, [ - 'albumData', - 'artTagData', - 'artistData', - 'groupData', - 'trackData', + // entries must be present here even without any properties to explicitly + // link if the 'find' or 'reverse' properties will be implicitly linked + + ['albumData', [ + 'artworkData', 'wikiInfo', ]], - [wikiData.artTagData, [ - 'albumData', - 'trackData', - ]], + ['artTagData', [/* reverse */]], - [wikiData.artistData, [ - 'albumData', - 'artistData', - 'flashData', - 'groupData', - 'trackData', - ]], + ['artistData', [/* find, reverse */]], + + ['artworkData', ['artworkData']], + + ['commentaryData', [/* find */]], - [wikiData.flashData, [ - 'artistData', - 'flashActData', - 'trackData', + ['creditingSourceData', [/* find */]], + + ['flashData', [ 'wikiInfo', ]], - [wikiData.flashActData, [ - 'flashData', - 'flashSideData', - ]], + ['flashActData', [/* find, reverse */]], - [wikiData.flashSideData, [ - 'flashActData', - ]], + ['flashSideData', [/* find */]], - [wikiData.groupData, [ - 'albumData', - 'artistData', - 'groupCategoryData', - ]], + ['groupData', [/* find, reverse */]], - [wikiData.groupCategoryData, [ - 'groupData', - ]], + ['groupCategoryData', [/* find */]], - [wikiData.homepageLayout?.rows, [ - 'albumData', - 'groupData', - ]], + ['homepageLayout.sections.rows', [/* find */]], + + ['lyricsData', [/* find */]], + + ['referencingSourceData', [/* find */]], - [wikiData.trackData, [ - 'albumData', - 'artTagData', - 'artistData', - 'flashData', - 'trackData', - 'trackSectionData', + ['seriesData', [/* find */]], + + ['trackData', [ + 'artworkData', 'wikiInfo', ]], - [wikiData.trackSectionData, [ - 'albumData', - ]], + ['trackSectionData', [/* reverse */]], - [[wikiData.wikiInfo], [ - 'groupData', - ]], + ['wikiInfo', [/* find */]], ]); - for (const [things, keys] of linkWikiDataSpec.entries()) { - if (things === undefined) continue; + const constructorHasFindMap = new Map(); + const constructorHasReverseMap = new Map(); + + const boundFind = bindFind(wikiData); + const boundReverse = bindReverse(wikiData); + + for (const [thingDataProp, keys] of linkWikiDataSpec.entries()) { + const thingData = getNestedProp(wikiData, thingDataProp); + const things = + (Array.isArray(thingData) + ? thingData.flat(Infinity) + : [thingData]); + for (const thing of things) { if (thing === undefined) continue; + + let hasFind; + if (constructorHasFindMap.has(thing.constructor)) { + hasFind = constructorHasFindMap.get(thing.constructor); + } else { + hasFind = 'find' in thing; + constructorHasFindMap.set(thing.constructor, hasFind); + } + + if (hasFind) { + thing.find = boundFind; + } + + let hasReverse; + if (constructorHasReverseMap.has(thing.constructor)) { + hasReverse = constructorHasReverseMap.get(thing.constructor); + } else { + hasReverse = 'reverse' in thing; + constructorHasReverseMap.set(thing.constructor, hasReverse); + } + + if (hasReverse) { + thing.reverse = boundReverse; + } + for (const key of keys) { if (!(key in wikiData)) continue; + thing[key] = wikiData[key]; } } } } -export function sortWikiDataArrays(dataSteps, wikiData) { +export function sortWikiDataArrays(dataSteps, wikiData, {bindFind, bindReverse}) { for (const [key, value] of Object.entries(wikiData)) { if (!Array.isArray(value)) continue; wikiData[key] = value.slice(); @@ -1327,7 +1877,7 @@ export function sortWikiDataArrays(dataSteps, wikiData) { // slices instead of the original arrays) - this is so that the object // caching system understands that it's working with a new ordering. // We still need to actually provide those updated arrays over again! - linkWikiDataArrays(wikiData); + linkWikiDataArrays(wikiData, {bindFind, bindReverse}); } // Utility function for loading all wiki data from the provided YAML data @@ -1339,6 +1889,7 @@ export function sortWikiDataArrays(dataSteps, wikiData) { export async function quickLoadAllFromYAML(dataPath, { find, bindFind, + bindReverse, getAllFindSpecs, showAggregate: customShowAggregate = showAggregate, @@ -1363,7 +1914,7 @@ export async function quickLoadAllFromYAML(dataPath, { } } - linkWikiDataArrays(wikiData); + linkWikiDataArrays(wikiData, {bindFind, bindReverse}); try { reportDirectoryErrors(wikiData, {getAllFindSpecs}); @@ -1389,7 +1940,203 @@ export async function quickLoadAllFromYAML(dataPath, { logWarn`Content text errors found.`; } - sortWikiDataArrays(dataSteps, wikiData); + sortWikiDataArrays(dataSteps, wikiData, {bindFind, bindReverse}); return wikiData; } + +export function cruddilyGetAllThings(wikiData) { + const allThings = []; + + for (const v of Object.values(wikiData)) { + if (Array.isArray(v)) { + allThings.push(...v); + } else { + allThings.push(v); + } + } + + return allThings; +} + +export function getThingLayoutForFilename(filename, wikiData) { + const things = + cruddilyGetAllThings(wikiData) + .filter(thing => + thing[Thing.yamlSourceFilename] === filename); + + if (empty(things)) { + return null; + } + + const allDocumentModes = + unique(things.map(thing => + thing[Thing.yamlSourceDocumentPlacement][0])); + + if (allDocumentModes.length > 1) { + throw new Error(`More than one document mode for documents from ${filename}`); + } + + const documentMode = allDocumentModes[0]; + + switch (documentMode) { + case documentModes.allInOne: { + return { + documentMode, + things: + things.sort((a, b) => + a[Thing.yamlSourceDocumentPlacement][1] - + b[Thing.yamlSourceDocumentPlacement][1]), + }; + } + + case documentModes.oneDocumentTotal: + case documentModes.onePerFile: { + if (things.length > 1) { + throw new Error(`More than one document for ${filename}`); + } + + return { + documentMode, + thing: things[0], + }; + } + + case documentModes.headerAndEntries: { + const headerThings = + things.filter(thing => + thing[Thing.yamlSourceDocumentPlacement][1] === 'header'); + + if (headerThings.length > 1) { + throw new Error(`More than one header document for ${filename}`); + } + + return { + documentMode, + headerThing: headerThings[0] ?? null, + entryThings: + things + .filter(thing => + thing[Thing.yamlSourceDocumentPlacement][1] === 'entry') + .sort((a, b) => + a[Thing.yamlSourceDocumentPlacement][2] - + b[Thing.yamlSourceDocumentPlacement][2]), + }; + } + + default: { + return {documentMode}; + } + } +} + +export function flattenThingLayoutToDocumentOrder(layout) { + switch (layout.documentMode) { + case documentModes.oneDocumentTotal: + case documentModes.onePerFile: { + if (layout.thing) { + return [0]; + } else { + return []; + } + } + + case documentModes.allInOne: { + const indices = + layout.things + .map(thing => thing[Thing.yamlSourceDocumentPlacement][1]); + + return indices; + } + + case documentModes.headerAndEntries: { + const entryIndices = + layout.entryThings + .map(thing => thing[Thing.yamlSourceDocumentPlacement][2]) + .map(index => index + 1); + + if (layout.headerThing) { + return [0, ...entryIndices]; + } else { + return entryIndices; + } + } + + default: { + throw new Error(`Unknown document mode`); + } + } +} + +export function* splitDocumentsInYAMLSourceText(sourceText) { + // Not multiline! + const dividerRegex = /(?:\r\n|\n|^)-{3,}(?:\r\n|\n|$)/g; + + let previousDivider = ''; + + while (true) { + const {lastIndex} = dividerRegex; + const match = dividerRegex.exec(sourceText); + if (match) { + const nextDivider = match[0]; + + yield { + previousDivider, + nextDivider, + text: sourceText.slice(lastIndex, match.index), + }; + + previousDivider = nextDivider; + } else { + const nextDivider = ''; + const lineBreak = previousDivider.match(/\r?\n/)?.[0] ?? ''; + + yield { + previousDivider, + nextDivider, + text: sourceText.slice(lastIndex).replace(/(?<!\n)$/, lineBreak), + }; + + return; + } + } +} + +export function recombineDocumentsIntoYAMLSourceText(documents) { + const dividers = + unique( + documents + .flatMap(d => [d.previousDivider, d.nextDivider]) + .filter(Boolean)); + + const divider = dividers[0]; + + if (dividers.length > 1) { + // TODO: Accommodate mixed dividers as best as we can lol + logWarn`Found multiple dividers in this file, using only ${divider}`; + } + + let sourceText = ''; + + for (const document of documents) { + if (sourceText) { + sourceText += divider; + } + + sourceText += document.text; + } + + return sourceText; +} + +export function reorderDocumentsInYAMLSourceText(sourceText, order) { + const sourceDocuments = + Array.from(splitDocumentsInYAMLSourceText(sourceText)); + + const sortedDocuments = + Array.from( + order, + sourceIndex => sourceDocuments[sourceIndex]); + + return recombineDocumentsIntoYAMLSourceText(sortedDocuments); +} |