« get me outta code hell

content-function.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/content-function.js
blob: 0f49936e6e3e3cb90d8c4175a9d48160719f7b1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import {inspect as nodeInspect} from 'node:util';

import {decorateError} from '#aggregate';
import {colors, decorateTime, ENABLE_COLOR} from '#cli';
import {Template} from '#html';
import {empty} from '#sugar';

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

const DECORATE_TIME = process.env.HSMUSIC_DEBUG_CONTENT_PERF === '1';

export class ContentFunctionSpecError extends Error {}

export default function contentFunction(spec) {
  if (!spec.generate) {
    throw new ContentFunctionSpecError(`Expected generate function`);
  }

  if (spec.slots) {
    Template.validateSlotsDescription(spec.slots);
  }

  return expectDependencies(spec);
}

contentFunction.identifyingSymbol = Symbol(`Is a content function?`);

export function expectDependencies(spec, {
  boundExtraDependencies = null,
} = {}) {
  const optionalDecorateTime = (prefix, fn) =>
    (DECORATE_TIME
      ? decorateTime(`${prefix}/${generate.name}`, fn)
      : fn);

  let generate = ([arg1, arg2], ...extraArgs) => {
    if (spec.data && !arg1) {
      throw new Error(`Expected data`);
    }

    if (spec.data && spec.relations && !arg2) {
      throw new Error(`Expected relations`);
    }

    if (spec.relations && !arg1) {
      throw new Error(`Expected relations`);
    }

    try {
      if (spec.data && spec.relations) {
        return spec.generate(arg1, arg2, ...extraArgs, boundExtraDependencies);
      } else if (spec.data || spec.relations) {
        return spec.generate(arg1, ...extraArgs, boundExtraDependencies);
      } else {
        return spec.generate(...extraArgs, boundExtraDependencies);
      }
    } catch (caughtError) {
      const error = new Error(
        `Error generating content for ${spec.generate.name}`,
        {cause: caughtError});

      error[Symbol.for(`hsmusic.aggregate.alwaysTrace`)] = true;
      error[Symbol.for(`hsmusic.aggregate.traceFrom`)] = caughtError;

      error[Symbol.for(`hsmusic.aggregate.unhelpfulTraceLines`)] = [
        /content-function\.js/,
        /util\/html\.js/,
      ];

      error[Symbol.for(`hsmusic.aggregate.helpfulTraceLines`)] = [
        /content\/dependencies\/(.*\.js:.*(?=\)))/,
      ];

      throw error;
    }
  };

  generate = optionalDecorateTime(`generate`, generate);

  if (spec.slots) {
    const normalGenerate = generate;

    let stationery = null;
    generate = function(...args) {
      stationery ??= boundExtraDependencies.html.stationery({
        annotation: generate.name,

        // These extra slots are for the data and relations (positional) args.
        // No hacks to store them temporarily or otherwise "invisibly" alter
        // the behavior of the template description's `content`, since that
        // would be expressly against the purpose of templates!
        slots: {
          _cfArg1: {validate: v => v.isObject},
          _cfArg2: {validate: v => v.isObject},
          ...spec.slots,
        },

        content(slots) {
          const args = [slots._cfArg1, slots._cfArg2];
          return normalGenerate(args, slots);
        },
      });

      return stationery.template().slots({
        _cfArg1: args[0] ?? null,
        _cfArg2: args[1] ?? null,
      });
    };
  } else {
    const normalGenerate = generate;
    generate = (...args) => normalGenerate(args);
  }

  generate.fulfill = function() {
    throw new Error(`not part of the flow`);
  };

  Object.defineProperty(generate, 'fulfilled', {
    get() {
      throw new Error(`unknowable`);
    }
  });

  generate[contentFunction.identifyingSymbol] = true;

  for (const key of ['sprawl', 'query', 'relations', 'data']) {
    if (spec[key]) {
      generate[key] = optionalDecorateTime(`sprawl`, spec[key]);
    }
  }

  generate.bindExtraDependencies = (extraDependencies) =>
    expectDependencies(spec, {
      boundExtraDependencies: extraDependencies,
    });

  return generate;
}

export function getArgsForRelationsAndData(contentFunction, wikiData, ...args) {
  const insertArgs = [];

  if (contentFunction.sprawl) {
    insertArgs.push(contentFunction.sprawl(wikiData, ...args));
  }

  if (contentFunction.query) {
    insertArgs.unshift(contentFunction.query(...insertArgs, ...args));
  }

  // Note: Query is generally intended to "filter" the provided args/sprawl,
  // so in most cases it shouldn't be necessary to access the original args
  // or sprawl afterwards. These are left available for now (as the second
  // and later arguments in relations/data), but if they don't find any use,
  // we can refactor this step to remove them.

  return [...insertArgs, ...args];
}

export function getRelationsTree(dependencies, contentFunctionName, wikiData, ...args) {
  const relationIdentifier = Symbol('Relation');

  function recursive(contentFunctionName, args, traceStack) {
    const contentFunction = dependencies[contentFunctionName];
    if (!contentFunction) {
      throw new Error(`Couldn't find dependency ${contentFunctionName}`);
    }

    // TODO: It's a bit awkward to pair this list of arguments with the output of
    // getRelationsTree, but we do need to evaluate it right away (for the upcoming
    // call to relations), and we're going to be reusing the same results for a
    // later call to data (outside of getRelationsTree). There might be a nicer way
    // of handling this.
    const argsForRelationsAndData =
      decorateErrorWithRelationStack(getArgsForRelationsAndData, traceStack)
        (contentFunction, wikiData, ...args);

    const result = {
      name: contentFunctionName,
      args: argsForRelationsAndData,
      trace: traceStack,
    };

    if (contentFunction.relations) {
      // Note: "slots" here is a completely separate concept from HTML template
      // slots, which are handled completely within the content function. Here,
      // relation slots are just references to a position within the relations
      // layout that are referred to by a symbol - when the relation is ready,
      // its result will be "slotted" into the layout.
      const relationSlots = {};

      const relationSymbolMessage = (() => {
        let num = 1;
        return name => `#${num++} ${name}`;
      })();

      const relationFunction = (name, ...args) => {
        const relationSymbol = Symbol(relationSymbolMessage(name));
        const traceError = new Error();

        relationSlots[relationSymbol] = {name, args, traceError};

        return {[relationIdentifier]: relationSymbol};
      };

      const relationsLayout =
        contentFunction.relations(relationFunction, ...argsForRelationsAndData);

      const relationsTree = Object.fromEntries(
        Object.getOwnPropertySymbols(relationSlots)
          .map(symbol => [symbol, relationSlots[symbol]])
          .map(([symbol, {name, args, traceError}]) => [
            symbol,
            recursive(name, args, [...traceStack, {name, args, traceError}]),
          ]));

      result.relations = {
        layout: relationsLayout,
        slots: relationSlots,
        tree: relationsTree,
      };
    }

    return result;
  }

  const root =
    recursive(contentFunctionName, args,
      [{name: contentFunctionName, args, traceError: new Error()}]);

  return {root, relationIdentifier};
}

export function flattenRelationsTree({root, relationIdentifier}) {
  const flatRelationSlots = {};

  function recursive(node) {
    const flatNode = {
      name: node.name,
      args: node.args,
      trace: node.trace,
      relations: node.relations?.layout ?? null,
    };

    if (node.relations) {
      const {tree, slots} = node.relations;
      for (const slot of Object.getOwnPropertySymbols(slots)) {
        flatRelationSlots[slot] = recursive(tree[slot]);
      }
    }

    return flatNode;
  }

  return {
    root: recursive(root, []),
    relationIdentifier,
    flatRelationSlots,
  };
}

export function fillRelationsLayoutFromSlotResults(relationIdentifier, results, layout) {
  function recursive(object) {
    if (typeof object !== 'object' || object === null) {
      return object;
    }

    if (Array.isArray(object)) {
      return object.map(recursive);
    }

    if (relationIdentifier in object) {
      return results[object[relationIdentifier]];
    }

    if (object.constructor !== Object) {
      throw new Error(`Expected primitive, array, relation, or normal {key: value} style Object, got constructor ${object.constructor?.name}`);
    }

    return Object.fromEntries(
      Object.entries(object)
        .map(([key, value]) => [key, recursive(value)]));
  }

  return recursive(layout);
}

export const decorateErrorWithRelationStack = (fn, traceStack) =>
  decorateError(fn, caughtError => {
    let cause = caughtError;

    for (const {name, args, traceError} of traceStack.slice().reverse()) {
      const nameText = colors.green(`"${name}"`);
      const namePart = `Error in relation(${nameText})`;

      const argsPart =
        (empty(args)
          ? ``
          : ` called with args: ${inspect(args)}`);

      const error = new Error(namePart + argsPart, {cause});

      error[Symbol.for('hsmusic.aggregate.alwaysTrace')] = true;
      error[Symbol.for('hsmusic.aggregate.traceFrom')] = traceError;

      error[Symbol.for(`hsmusic.aggregate.unhelpfulTraceLines`)] = [
        /content-function\.js/,
        /util\/html\.js/,
      ];

      error[Symbol.for(`hsmusic.aggregate.helpfulTraceLines`)] = [
        /content\/dependencies\/(.*\.js:.*(?=\)))/,
      ];

      cause = error;
    }

    return cause;
  });

export function quickEvaluate({
  contentDependencies: allContentDependencies,
  extraDependencies: allExtraDependencies,

  name,
  args = [],
  slots = null,
  multiple = null,
  postprocess = null,
}) {
  if (multiple !== null) {
    return multiple.map(opts =>
      quickEvaluate({
        contentDependencies: allContentDependencies,
        extraDependencies: allExtraDependencies,

        ...opts,
        name: opts.name ?? name,
        args: opts.args ?? args,
        slots: opts.slots ?? slots,
        postprocess: opts.postprocess ?? postprocess,
      }));
  }

  const treeInfo = getRelationsTree(allContentDependencies, name, allExtraDependencies.wikiData ?? {}, ...args);
  const flatTreeInfo = flattenRelationsTree(treeInfo);
  const {root, relationIdentifier, flatRelationSlots} = flatTreeInfo;

  allContentDependencies = {...allContentDependencies};
  for (const [name, contentFunction] of Object.entries(allContentDependencies)) {
    allContentDependencies[name] =
      contentFunction.bindExtraDependencies(allExtraDependencies);
  }

  const slotResults = {};

  function runContentFunction({name, args, relations: layout, trace: traceStack}) {
    const callDecorated = (fn, ...args) =>
      decorateErrorWithRelationStack(fn, traceStack)(...args);

    const contentFunction = allContentDependencies[name];
    if (!contentFunction) {
      throw new Error(`Content function ${name} not listed`);
    }

    const generateArgs = [];

    if (contentFunction.data) {
      generateArgs.push(callDecorated(contentFunction.data, ...args));
    }

    if (layout) {
      generateArgs.push(fillRelationsLayoutFromSlotResults(relationIdentifier, slotResults, layout));
    }

    return callDecorated(contentFunction, ...generateArgs);
  }

  for (const slot of Object.getOwnPropertySymbols(flatRelationSlots)) {
    slotResults[slot] = runContentFunction(flatRelationSlots[slot]);
  }

  let topLevelResult = runContentFunction(root);

  if (slots) {
    topLevelResult.setSlots(slots);
  }

  if (postprocess) {
    topLevelResult = postprocess(topLevelResult);
  }

  return topLevelResult;
}