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
|
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 {annotateError, annotateErrorWithFile, showAggregate, withAggregate}
from '#aggregate';
import {externalLinkSpec} from '#external-links';
import {colors, logWarn} from '#cli';
import {splitKeys, withEntries} 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};
}
export 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);
}
export function unflattenLanguageSpec(flat, reference) {
const setNestedProp = (obj, key, value) => {
const recursive = (o, k) => {
if (k.length === 1) {
o[k[0]] = value;
return;
}
if (typeof o[k[0]] === 'undefined') {
o[k[0]] = {};
} else if (typeof o[k[0]] === 'string') {
o[k[0]] = {_: o[k[0]]};
}
recursive(o[k[0]], k.slice(1));
};
return recursive(obj, splitKeys(key));
};
const walkEntries = (ownNode, refNode) => {
const recursive = (refKeys, ownNode, refNode) => {
const [firstKey, ...restKeys] = refKeys;
if (typeof ownNode[firstKey] === 'undefined') {
return undefined;
}
const result =
(refKeys.length === 1
? walkEntry(ownNode[firstKey], refNode)
: recursive(restKeys, ownNode[firstKey], refNode));
if (typeof result === 'undefined') {
return undefined;
}
if (typeof result === 'string') {
delete ownNode[firstKey];
return {[firstKey]: result};
}
const resultKeys = Object.keys(result);
if (resultKeys.length === 1 && resultKeys[0] === '_') {
delete ownNode[firstKey];
return {[firstKey]: result._};
}
if (refKeys.length > 1) {
return withEntries(result, entries =>
entries.map(([key, value]) => [`${firstKey}.${key}`, value]));
} else {
return {[firstKey]: result};
}
};
let mapped;
for (const [key, value] of Object.entries(refNode)) {
const result = recursive(splitKeys(key), ownNode, refNode[key]);
if (!result) continue;
if (!mapped) mapped = {};
Object.assign(mapped, result);
}
return mapped;
};
const walkEntry = (ownNode, refNode) => {
if (
typeof ownNode === 'object' &&
typeof refNode === 'object'
) {
return walkEntries(ownNode, refNode);
}
if (
typeof ownNode === 'string' &&
typeof refNode === 'object' &&
typeof refNode._ === 'string'
) {
return {_: ownNode};
}
if (
typeof ownNode === 'object' &&
typeof refNode === 'string' &&
typeof ownNode._ === 'string'
) {
return ownNode._;
}
if (
typeof ownNode === 'string' &&
typeof refNode === 'string'
) {
return ownNode;
}
return undefined;
};
const clean = node => {
if (typeof node === 'string') {
return node;
}
const entries = Object.entries(node);
if (entries.length === 0) {
return undefined;
}
let results;
for (const [key, value] of entries) {
const cleanValue = clean(value);
if (typeof cleanValue === 'undefined') continue;
if (!results) results = {};
results[key] = cleanValue;
}
return results;
};
const storage = {};
for (const [key, value] of Object.entries(flat)) {
setNestedProp(storage, key, value);
}
const rootResult = walkEntries(storage, reference);
const spec = rootResult ?? {};
const unmapped = clean(storage);
if (unmapped) {
spec['meta.unmapped'] = unmapped;
}
return 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();
}
}
|