« get me outta code hell

language.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/language.js
blob: 6f774f278bef1a852b5c8dcd23a292c4e19249af (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
import EventEmitter from 'node:events';
import {readFile} from 'node:fs/promises';
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 {externalLinkSpec} from '#external-links';
import {colors, logWarn} from '#cli';
import {annotateError, annotateErrorWithFile, showAggregate, withAggregate}
  from '#sugar';
import T from '#things';

const {Language} = T;

export const DEFAULT_STRINGS_FILE = 'strings-default.yaml';

export const internalDefaultStringsFile =
  path.resolve(
    path.dirname(fileURLToPath(import.meta.url)),
    '../',
    DEFAULT_STRINGS_FILE);

export function processLanguageSpec(spec, {existingCode = null} = {}) {
  const {
    'meta.languageCode': code,
    'meta.languageName': name,

    'meta.languageIntlCode': intlCode = null,
    'meta.hidden': hidden = false,

    ...strings
  } = spec;

  withAggregate({message: `Errors validating language spec`}, ({push}) => {
    if (!code) {
      push(new Error(`Missing language code`));
    }

    if (!name) {
      push(new Error(`Missing language name`));
    }

    if (code && existingCode && code !== existingCode) {
      push(new Error(`Language code (${code}) doesn't match previous value\n(You'll have to reload hsmusic to load this)`));
    }
  });

  return {code, intlCode, name, hidden, strings};
}

function flattenLanguageSpec(spec) {
  const recursive = (keyPath, value) =>
    (typeof value === 'object'
      ? Object.assign({}, ...
          Object.entries(value)
            .map(([key, value]) =>
              (key === '_'
                ? {[keyPath]: value}
                : recursive(
                    (keyPath ? `${keyPath}.${key}` : key),
                    value))))
      : {[keyPath]: value});

  return recursive('', spec);
}

async function processLanguageSpecFromFile(file, processLanguageSpecOpts) {
  let contents;

  try {
    contents = await readFile(file, 'utf-8');
  } catch (caughtError) {
    throw annotateError(
      new Error(`Failed to read language file`, {cause: caughtError}),
      error => annotateErrorWithFile(error, file));
  }

  let rawSpec;
  let parseLanguage;

  try {
    if (path.extname(file) === '.yaml') {
      parseLanguage = 'YAML';
      rawSpec = yaml.load(contents);
    } else {
      parseLanguage = 'JSON';
      rawSpec = JSON.parse(contents);
    }
  } catch (caughtError) {
    throw annotateError(
      new Error(`Failed to parse language file as valid ${parseLanguage}`, {cause: caughtError}),
      error => annotateErrorWithFile(error, file));
  }

  const flattenedSpec = flattenLanguageSpec(rawSpec);

  try {
    return processLanguageSpec(flattenedSpec, processLanguageSpecOpts);
  } catch (caughtError) {
    throw annotateErrorWithFile(caughtError, file);
  }
}

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 properties = await processLanguageSpecFromFile(file);
  return Object.assign(language, properties);
}

export function watchLanguageFile(file, {
  logging = true,
} = {}) {
  const basename = path.basename(file);

  const events = new EventEmitter();
  const language = initializeLanguageObject();

  let emittedReady = false;
  let successfullyAppliedLanguage = false;

  Object.assign(events, {language, close});

  const watcher = chokidar.watch(file);
  watcher.on('change', () => handleFileUpdated());

  setImmediate(handleFileUpdated);

  return events;

  async function close() {
    return watcher.close();
  }

  function checkReadyConditions() {
    if (emittedReady) return;
    if (!successfullyAppliedLanguage) return;

    events.emit('ready');
    emittedReady = true;
  }

  async function handleFileUpdated() {
    let properties;

    try {
      properties = await processLanguageSpecFromFile(file, {
        existingCode:
          (successfullyAppliedLanguage
            ? language.code
            : null),
      });
    } catch (error) {
      events.emit('error', error);

      if (logging) {
        const label =
          (successfullyAppliedLanguage
            ? `${language.name} (${language.code})`
            : basename);

        if (successfullyAppliedLanguage) {
          logWarn`Failed to load language ${label} - using existing version`;
        } else {
          logWarn`Failed to load language ${label} - no prior version loaded`;
        }
        showAggregate(error, {showTraces: false});
      }

      return;
    }

    Object.assign(language, properties);
    successfullyAppliedLanguage = true;

    if (logging && emittedReady) {
      const timestamp = new Date().toLocaleString('en-US', {timeStyle: 'medium'});
      console.log(colors.green(`[${timestamp}] Updated language ${language.name} (${language.code})`));
    }

    events.emit('update');
    checkReadyConditions();
  }
}