foundry-dsa41-game/transformSources.mjs

65 lines
2.2 KiB
JavaScript

let crypto;
import { readdirSync, readFileSync, writeFileSync } from "fs";
import {dirname, join} from "path";
try {
crypto = await import('node:crypto');
/**
* Generate a random alphanumeric string ID of a given requested length using `crypto.getRandomValues()`.
* @param {number} length The length of the random string to generate, which must be at most 16384.
* @returns {string} A string containing random letters (A-Z, a-z) and numbers (0-9).
*/
function randomID(length = 16) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const cutoff = 0x100000000 - (0x100000000 % chars.length);
const random = new Uint32Array(length);
do {
crypto.getRandomValues(random);
} while (random.some(x => x >= cutoff));
let id = "";
for (let i = 0; i < length; i++) id += chars[random[i] % chars.length];
return id;
}
const convert = function (from, to, ofType) {
const SOURCE = from;
const DEST = to;
const TYPE = ofType;
readdirSync(SOURCE).forEach(file => {
console.log(join(SOURCE, file));
let originalSource = JSON.parse(readFileSync(join(SOURCE, file), {encoding: "utf8"}));
let id = randomID();
let targetSource = {
_id: id,
_key: "!items!" + id,
type: TYPE,
img: originalSource.image,
name: originalSource.name.trim(),
system: {...originalSource}
}
delete targetSource.system.image;
let target = JSON.stringify(targetSource, null, 2);
let newFileName = "./" + join(DEST, targetSource.name.toLowerCase().replace(/[ /]/g, "-").replace(/\--{2,}/g, "-").replace(/[.,!]/g, "").trim() + ".json");
console.log(newFileName);
writeFileSync(newFileName, target, {encoding: "utf8"});
});
}
convert("./src/packs/_source/zauber", "./src/packs/__source/zauber", "Spell");
convert("./src/packs/_source/vorteile", "./src/packs/__source/vorteile", "Advantage");
convert("./src/packs/_source/waffen", "./src/packs/__source/waffen", "Equipment");
convert("./src/packs/_source/munition", "./src/packs/__source/munition", "Equipment");
convert("./src/packs/_source/ruestzeug", "./src/packs/__source/ruestzeug", "Equipment");
} catch (err) {
console.error(err);
}