UNPKG

2.59 kBJavaScriptView Raw
1"use strict";
2function __export(m) {
3 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4}
5Object.defineProperty(exports, "__esModule", { value: true });
6const common_1 = require("@xmcl/common");
7common_1.GameSetting.parse = parse;
8common_1.GameSetting.stringify = stringify;
9/**
10 * Parse raw game setting options.txt content
11 *
12 * @param str the options.txt content
13 * @param strict strictly follow the current version of options format (outdate version might cause problem. If your options.txt is new one with new fields, don't turn on this)
14 */
15function parse(str, strict) {
16 const lines = str.split("\n");
17 const intPattern = /^\d+$/;
18 const floatPattern = /^[-+]?[0-9]*\.[0-9]+$/;
19 const booleanPattern = /^(true)|(false)$/;
20 if (!lines || lines.length === 0) {
21 return strict ? common_1.GameSetting.getDefaultFrame() : {};
22 }
23 const setting = lines.map((line) => line.trim().split(":"))
24 .filter((pair) => pair[0].length !== 0)
25 .map((pair) => {
26 let value = pair[1];
27 if (intPattern.test(value)) {
28 value = Number.parseInt(value, 10);
29 }
30 else if (floatPattern.test(value)) {
31 value = Number.parseFloat(value);
32 }
33 else if (booleanPattern.test(value)) {
34 value = value === "true";
35 }
36 else {
37 try {
38 value = JSON.parse(value);
39 }
40 catch (e) { }
41 }
42 return { [pair[0]]: value };
43 })
44 .reduce((prev, current) => Object.assign(prev, current), {});
45 if (!strict) {
46 return setting;
47 }
48 const source = common_1.GameSetting.getDefaultFrame();
49 const target = {};
50 Object.keys(source).forEach((key) => {
51 target[key] = typeof setting[key] === typeof source[key] ? setting[key] : source[key];
52 delete setting.key;
53 });
54 return target;
55}
56function stringify(setting, original, eol = "\n") {
57 let model;
58 if (original) {
59 model = parse(original);
60 for (const key in model) {
61 if (model.hasOwnProperty(key) && setting.hasOwnProperty(key)) {
62 model[key] = setting[key];
63 }
64 }
65 }
66 else {
67 model = setting;
68 }
69 return Object.keys(model)
70 .filter((key) => key !== undefined && key !== "undefined")
71 .map((key) => {
72 const val = model[key];
73 return typeof val !== "string" ? `${key}:${JSON.stringify(val)}` : `${key}:${val}`;
74 }).join(eol);
75}
76__export(require("@xmcl/common/gamesetting"));
77//# sourceMappingURL=index.js.map
\No newline at end of file