Repository navigation
Expand file tree
/
Copy pathbuild.ts
More file actions
496 lines (435 loc) · 16.8 KB
/
Copy pathbuild.ts
File metadata and controls
496 lines (435 loc) · 16.8 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import minify, { type Plugin } from 'imagemin';
import minifyPng from 'imagemin-pngquant';
import minifyJpeg from 'imagemin-jpegtran';
import fetch from 'node-fetch';
import sharp from 'sharp';
import Progress from './progress';
import stringify, { stringifyWarnings } from './stringify';
import scraper from './scraper';
import parser from './parser';
import hashManager from './hashManager';
import readJson from './readJson';
import type {
RawItemData,
Item,
ImageManifest,
Warnings,
CachedItem,
PatchlogWrap,
CategoryData,
ApiCategory
} from './types/shared';
import { createHash } from 'node:crypto';
let imageCache: CachedItem[] = [];
const allowedCustomCategories = ['SentinelWeapons'];
const get = async (url: string, binary = true): Promise<Buffer | string> => {
const res = await fetch(url);
return binary ? res.buffer() : res.text();
};
const force = process.argv.slice(2).some((arg) => ['--force', '-f'].includes(arg)) || process.env.FORCE === 'true';
class Build {
async init(): Promise<void> {
const warnings = await readJson<Warnings>(new URL('../data/warnings.json', import.meta.url));
// Load image cache
imageCache = await readJson<CachedItem[]>(new URL('../data/cache/.images.json', import.meta.url));
await scraper.checkOriginServerAvailability();
await hashManager.updateExportCache();
if (!force && hashManager.isUpdated) {
console.log('Data already up-to-date');
return;
}
const resources = await scraper.fetchResources();
const raw: RawItemData = {
api: resources.en as ApiCategory[],
manifest: (await scraper.fetchImageManifest()) as ImageManifest,
drops: (await scraper.fetchDropRates()) as never,
patchlogs: (await scraper.fetchPatchLogs()) as unknown as PatchlogWrap,
wikia: await scraper.fetchWikiaData(),
relics: ((await scraper.generateRelicData()) ?? []) as never,
i18n: resources
};
const parsed = parser.parse(raw);
parsed.warnings.failedImage = [...warnings.failedImage]; // The parser doesn't keep tracked of failed images so this will be empty
const data = this.applyCustomCategories(parsed.data);
parser.extractComponentCatalog(data);
const i18n = parser.applyI18n(data, raw.i18n);
this.dedupImageNames(data, raw.manifest, warnings);
await this.saveImages(data, raw.manifest, parsed.warnings);
await this.alignImageNamesToDisk(data);
await this.saveJson(data, i18n);
await this.saveWarnings(parsed.warnings);
await this.updateReadme(raw.patchlogs);
// Log number of warnings at the end of the script
let warningNum = 0;
for (const warning of Object.keys(parsed.warnings)) {
warningNum += parsed.warnings[warning as keyof Warnings].length;
}
await hashManager.saveExportCache();
console.log(`\nFinished with ${String(warningNum)} warnings.`);
}
/**
* Match imageName casing to files already in data/img (Linux/CI case-sensitive).
* Deterministic given the committed image tree.
*/
async alignImageNamesToDisk(data: Record<string, Item[]>): Promise<void> {
const imgDir = fileURLToPath(new URL('../data/img/', import.meta.url));
const files = await fs.readdir(imgDir);
const byLower = new Map(files.map((f) => [f.toLowerCase(), f]));
for (const items of Object.values(data)) {
for (const item of items) {
if (!item.imageName || item.imageName === 'missing.png') continue;
const onDisk = byLower.get(item.imageName.toLowerCase());
if (onDisk) item.imageName = onDisk;
}
}
}
/**
* DE's data categories are a bit vague, so we'll use the ones
* we generated in item.category instead. (parser.addCategory)
* @param data items to parse out
* @returns categorized items
*/
applyCustomCategories(data: CategoryData[]): Record<string, Item[]> {
const result: Record<string, Item[]> = {};
for (const chunk of data) {
if (chunk.category === 'Recipes') continue; // Skip blueprints
for (const item of chunk.data) {
if (!item) continue;
// write an additional file for the desired custom categories
if (item.productCategory && allowedCustomCategories.includes(item.productCategory)) {
if (result[item.productCategory]) {
result[item.productCategory]?.push(item);
} else {
result[item.productCategory] = [item];
}
continue;
}
if (result[item.category]) {
result[item.category]?.push(item);
} else {
result[item.category] = [item];
}
}
}
return result;
}
/**
* Generate JSON file for each category and one for all combined.
* @param categories list of categories to save and separate
* @param i18n internationalization partials of Items
* @returns all items
*/
async saveJson(
categories: Record<string, Item[]>,
i18n: Record<string, Record<string, Partial<Item>>>
): Promise<void> {
let all: Item[] = [];
const sort = (a: Item, b: Item): number => {
if (!a.name) console.log(a);
const res = a.name.localeCompare(b.name);
if (res === 0) {
return a.uniqueName.localeCompare(b.uniqueName);
}
return res;
};
// Category names are provided by this.applyCustomCategories
for (const category of Object.keys(categories)) {
const categoryData = categories[category];
if (!categoryData) continue;
const data = categoryData.sort(sort);
all = all.concat(data);
await fs.writeFile(
new URL(`../data/json/${category}.json`, import.meta.url),
JSON.stringify(JSON.parse(stringify(data)))
);
}
// All.json (all items in one file)
all.sort(sort);
await fs.writeFile(new URL('../data/json/All.json', import.meta.url), stringify(all));
// Per-locale i18n: data/json/i18n/{locale}.json
const i18nDir = new URL('../data/json/i18n/', import.meta.url);
await fs.mkdir(i18nDir, { recursive: true });
const byLocale: Record<string, Record<string, Partial<Item>>> = {};
for (const [uniqueName, locales] of Object.entries(i18n)) {
for (const [locale, partial] of Object.entries(locales)) {
byLocale[locale] ??= {};
byLocale[locale][uniqueName] = partial;
}
}
for (const [locale, data] of Object.entries(byLocale)) {
await fs.writeFile(
new URL(`../data/json/i18n/${locale}.json`, import.meta.url),
JSON.stringify(JSON.parse(stringify(data)))
);
}
// Drop legacy monolith if present
try {
await fs.unlink(new URL('../data/json/i18n.json', import.meta.url));
} catch {
// absent ok
}
}
/**
* Store warnings during parse process to disk
* @param warnings warnings to save to file
*/
async saveWarnings(warnings: Warnings): Promise<void> {
return fs.writeFile(new URL('../data/warnings.json', import.meta.url), stringifyWarnings(warnings));
}
/**
* Get all images unless hashes match with existing images
* @param items items to append images to
* @param manifest image manifest to look up items from
*/
async saveImages(categories: Record<string, Item[]>, manifest: ImageManifest, warnings: Warnings): Promise<void> {
// No need to go through every item if the manifest didn't change. I'm
// guessing the `fileTime` key in each element works more or less like a
// hash, so any change to that changes the hash of the full thing.
if (!hashManager.hasChanged('Manifest')) return;
const items = Object.values(categories).flat();
const bar = new Progress('Fetching Images', items.length);
const history: string[] = []; // Don't download component images or relics twice
for (const category of Object.keys(categories)) {
if (category === 'Components') continue;
const categoryData = categories[category];
if (!categoryData) continue;
for (const item of categoryData) {
try {
// Save image for parent item
await this.saveImage(item, false, history, manifest);
// Save images for abilities
if (item.abilities) {
for (const ability of item.abilities) {
await this.saveImage(ability as Item, false, history, manifest);
}
}
} catch {
if (!warnings.failedImage.includes(item.name)) warnings.failedImage.push(item.name);
item.imageName = 'missing.png';
}
bar.tick();
}
}
// Save catalog component images once (parents only keep refs)
for (const component of categories.Components ?? []) {
try {
await this.saveImage(component, true, history, manifest);
} catch {
if (!warnings.failedImage.includes(component.name)) warnings.failedImage.push(component.name);
component.imageName = 'missing.png';
}
bar.tick();
}
// write the manifests after images have all succeeded
hashManager.imagesUpdated = true;
try {
await hashManager.saveExportCache();
// Write new cache to disk
await hashManager.saveImageCache(imageCache);
} catch (error) {
console.error(error);
}
}
/**
* Download and save images for items or components.
* @param item to determine and save an image for
* @param isComponent whether the item is a component or a parent
* @param processed list of duplicated (already existing) image names
* @param manifest image lookup list
*/
async saveImage(item: Item, isComponent: boolean, history: string[], manifest: ImageManifest): Promise<void> {
const imageBase = manifest.find((i) => i.uniqueName === item.uniqueName);
if (!imageBase) return;
const imageStub = imageBase.textureLocation.replace(/\\/g, '/').replace('xport/', '');
const imageHash = /!00_([\S]+)/.exec(imageStub);
const imageUrl = `https://content.warframe.com/PublicExport/${imageStub}`;
const basePath = fileURLToPath(new URL('../data/img/', import.meta.url));
const filePath = path.join(basePath, item.imageName);
const hash
= imageBase?.fileTime ?? imageHash?.[1] ?? createHash('md5').update(imageBase.textureLocation).digest('hex');
const cached = imageCache.find((c) => c.uniqueName === item.uniqueName);
// We'll use a custom blueprint and arcane image.
// Use the unmodified texture location as some broken images share the same hash but should be different,
// i.e. some focus icons are just white images most likely placeholders on DE's side but want to track them seperatly in case either changes
if (item.name === 'Blueprint' || item.name === 'Arcane' || history.includes(imageBase.textureLocation)) return;
history.push(imageBase.textureLocation);
if (cached?.hash !== hash) {
try {
const retry = (err: Error & { code?: string }): Promise<Buffer | string> => {
if (err.code === 'ENOTFOUND') {
return get(imageUrl);
}
throw err;
};
const image = await get(imageUrl).catch(retry).catch(retry);
await sharp(image as Buffer).toFile(filePath);
await minify([filePath], {
destination: basePath,
plugins: [
minifyJpeg(),
minifyPng({
quality: [0.2, 0.4]
})
] as Plugin[]
});
this.updateCache(item, cached, hash, isComponent);
} catch (e) {
// swallow error
console.error(e);
throw e;
}
}
}
/**
* Update image cache with new hash if things changed
* @param item item to add to the cache
* @param cached list of existing cached items
* @param hash of an existing cached item
* @param isComponent whether the item to be cached is a component
*/
updateCache(item: Item, cached: CachedItem | undefined, hash: string | undefined, isComponent: boolean): void {
if (!cached) {
imageCache.push({
uniqueName: item.uniqueName,
hash: hash ?? '',
isComponent
});
} else {
cached.hash = hash ?? '';
cached.isComponent = isComponent;
}
}
/**
* Update readme with newest patchlog version
* @param patchlogs for pulling the latest update
*/
async updateReadme(patchlogs: PatchlogWrap): Promise<void> {
const logob64 = await readJson<string>(new URL('../data/logo.json', import.meta.url));
const firstPost = patchlogs.posts[0];
if (!firstPost) return;
const version = firstPost.name
.replace(/ \+ /g, '--')
.replace(/[^0-9\-.]/g, '')
.trim();
const { url } = firstPost;
const readmeLocation = new URL('../README.md', import.meta.url);
const readmeOld = await fs.readFile(readmeLocation, 'utf-8');
const readmeNew = readmeOld.replace(
/\[!\[warframe update.*/,
`[})](${url})`
);
return fs.writeFile(readmeLocation, readmeNew);
}
dedupImageNames(data: Record<string, Item[]>, manifest: ImageManifest, warnings: Warnings): void {
const priorityMap: Record<string, number> = {
Warframes: -1,
Archwing: 0,
Primary: 1,
Secondary: 2,
Melee: 3,
'Arch-Gun': 4,
'Arch-Melee': 5,
Railjack: 7,
Sentinels: 8,
SentinelWeapons: 8,
Pets: 9,
Mods: 10,
Arcanes: 11,
Relics: 12,
Quests: 13,
Gear: 14,
Resources: 15,
Fish: 16,
Skins: 17,
Glyphs: 18,
Sigils: 19,
Node: 20,
Enemy: 21,
Misc: 22, // K-Drives, Drones, etc.
Components: 23
};
const items = Object.values(data).flat();
const noImage = items.filter((i) => !i.imageName);
const hasImage = items.filter((i) => i.imageName);
const itemsByImageName: Record<string, Item[]> = {};
for (const item of hasImage) {
if (warnings.failedImage.includes(item.name)) {
item.imageName = 'missing.png';
noImage.push(item);
continue;
}
(itemsByImageName[item.imageName] ??= []).push(item);
}
const hashMap = manifest.reduce<Record<string, string>>((acc, entry) => {
const hash = entry.textureLocation.split('!')[1] ?? createHash('md5').update(entry.textureLocation).digest('hex');
acc[entry.uniqueName] = hash;
return acc;
}, {});
const relicRegex = /Relic(?:Lith|Meso|Neo|Axi)[A-D]/;
const processedItems: Item[] = [];
for (const imageName of Object.keys(itemsByImageName)) {
// Items are grouped by imageName, there are non in this loop that will be undefined
const group = itemsByImageName[imageName]!;
if (group.length === 1) {
processedItems.push(...group);
continue;
}
// Components, Generic, Relics, OmegaMod, blueprint, and arcane are shared images —
// do not invent category-suffixed filenames that are never written to disk.
if (
imageName.includes('Component')
|| imageName.includes('Generic')
|| relicRegex.test(imageName)
|| imageName.includes('OmegaMod')
|| imageName === 'blueprint.png'
|| imageName === 'arcane.png'
) {
processedItems.push(...group);
continue;
}
group.sort((a, b) => {
if (
(a.productCategory || b.productCategory)
&& allowedCustomCategories.includes(a.productCategory ?? b.productCategory ?? '')
) {
return (
(priorityMap[a.productCategory ?? a.category] ?? Infinity)
- (priorityMap[b.productCategory ?? b.category] ?? Infinity)
);
}
return (priorityMap[a.category] ?? Infinity) - (priorityMap[b.category] ?? Infinity);
});
const mainItem = group[0]!;
processedItems.push(mainItem);
const seen = new Set<string>([mainItem.uniqueName]);
for (const item of group.slice(1)) {
// Don't rename duplicate items so that dedup can remove them when writing json files
if (!seen.has(item.uniqueName) && hashMap[item.uniqueName] !== hashMap[mainItem.uniqueName]) {
const imageName = item.imageName;
const index = imageName.indexOf('.');
item.imageName = imageName.slice(0, index) + item.category + imageName.slice(index);
}
processedItems.push(item);
seen.add(item.uniqueName);
}
}
for (const key of Object.keys(data)) {
data[key] = [];
}
for (const item of [...processedItems, ...noImage]) {
if (item.productCategory && allowedCustomCategories.includes(item.productCategory)) {
// Since we're following the same logic as applying custom categories all keys should have an empty array and if they don't we should consider it an error
data[item.productCategory]!.push(item);
continue;
}
data[item.category]!.push(item);
}
}
}
const build = new Build();
void build.init();