« get me outta code hell

init.js « things « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things/init.js
blob: e705f626397b8c344c826d5247319d4e522c373a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// This is the actual entry point for #things.

import * as path from 'node:path';
import {fileURLToPath} from 'node:url';

import {openAggregate, showAggregate} from '#aggregate';
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 indexExports from './index.js';

const thingConstructors = Object.create(null);

// src/data/things/index.js -> src/
const __dirname = path.dirname(
  path.resolve(
    fileURLToPath(import.meta.url),
    '../..'));

function niceShowAggregate(error, ...opts) {
  showAggregate(error, {
    pathToFileURL: (f) => path.relative(__dirname, fileURLToPath(f)),
    showClasses: false,
    ...opts,
  });
}

function sortThingConstructors() {
  let remaining = [];
  for (const constructor of Object.values(indexExports)) {
    if (typeof constructor !== 'function') continue;
    if (!(constructor.prototype instanceof Thing)) continue;
    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) {
    thingConstructors[constructor.name] = constructor;
  }
}

function descriptorAggregateHelper({
  showFailedClasses,
  message,
  op,
}) {
  const failureSymbol = Symbol();
  const aggregate = openAggregate({
    message,
    returnOnFail: failureSymbol,
  });

  const failedClasses = [];

  for (const [name, constructor] of Object.entries(thingConstructors)) {
    const result = aggregate.call(op, constructor);

    if (result === failureSymbol) {
      failedClasses.push(name);
    }
  }

  try {
    aggregate.close();
    return true;
  } catch (error) {
    niceShowAggregate(error);
    showFailedClasses(failedClasses);

    /*
    if (error.errors) {
      for (const sub of error.errors) {
        console.error(sub);
      }
    }
    */

    return false;
  }
}

function evaluatePropertyDescriptors() {
  const opts = {...thingConstructors};

  return descriptorAggregateHelper({
    message: `Errors evaluating Thing class property descriptors`,

    op(constructor) {
      if (!constructor[Thing.getPropertyDescriptors]) {
        throw new Error(`Missing [Thing.getPropertyDescriptors] function`);
      }

      const results = constructor[Thing.getPropertyDescriptors](opts);

      for (const [key, value] of Object.entries(results)) {
        if (Array.isArray(value)) {
          results[key] = compositeFrom({
            annotation: `${constructor.name}.${key}`,
            compose: false,
            steps: value,
          });
        } else if (value.toResolvedComposition) {
          results[key] = compositeFrom(value.toResolvedComposition());
        }
      }

      constructor[CacheableObject.propertyDescriptors] =
        Object.create(constructor[CacheableObject.propertyDescriptors] ?? null);

      Object.assign(constructor[CacheableObject.propertyDescriptors], results);
    },

    showFailedClasses(failedClasses) {
      logError`Failed to evaluate property descriptors for classes: ${failedClasses.join(', ')}`;
    },
  });
}

function evaluateSerializeDescriptors() {
  const opts = {...thingConstructors, serialize};

  return descriptorAggregateHelper({
    message: `Errors evaluating Thing class serialize descriptors`,

    op(constructor) {
      if (!constructor[Thing.getSerializeDescriptors]) {
        return;
      }

      constructor[serialize.serializeDescriptors] =
        constructor[Thing.getSerializeDescriptors](opts);
    },

    showFailedClasses(failedClasses) {
      logError`Failed to evaluate serialize descriptors for classes: ${failedClasses.join(', ')}`;
    },
  });
}

function finalizeYamlDocumentSpecs() {
  return descriptorAggregateHelper({
    message: `Errors finalizing Thing YAML document specs`,

    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();
    },

    showFailedClasses(failedClasses) {
      logError`Failed to finalize cacheable object prototypes for classes: ${failedClasses.join(', ')}`;
    },
  });
}

sortThingConstructors();

if (!evaluatePropertyDescriptors()) process.exit(1);
if (!evaluateSerializeDescriptors()) process.exit(1);
if (!finalizeYamlDocumentSpecs()) process.exit(1);
if (!finalizeCacheableObjectPrototypes()) process.exit(1);

Object.assign(thingConstructors, {Thing});

export default thingConstructors;