-
Notifications
You must be signed in to change notification settings - Fork 1
/
parseUserConfig.ts
90 lines (78 loc) · 2.01 KB
/
parseUserConfig.ts
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
import { readFile } from "fs-extra";
import { load, YAMLException } from "js-yaml";
import JSON5 from "json5";
import { extname } from "path";
import { logger } from "@lib/logger";
/**
* Parses a file in Javascript, Json or Yaml format
* @param configFilePath The path to the config
* @returns The data inside the config
*/
export const parseUserConfig = async (
configFilePath: string
): Promise<Record<string, unknown> | false> => {
const ext = extname(configFilePath);
if (ext == ".js") {
try {
const imported = await import(configFilePath);
const data = imported.default;
if (typeof data == "object" && data) {
return data as Record<string, unknown>;
} else if (typeof data == "function") {
const generatedData = data();
if (generatedData instanceof Promise) {
logger.configPromise();
}
return await generatedData;
} else {
logger.configJSInvalidType({
type: typeof data,
expected: ["object", "function"]
});
return false;
}
} catch (error) {
logger.configJSError({ error });
return false;
}
}
const content = await readFile(configFilePath, "utf-8");
if (ext.match(/^\.ya?ml$/)) {
try {
return load(content) as Record<string, unknown>;
} catch (error) {
logger.configYamlError({ error: error as YAMLException });
return false;
}
}
if (ext.match(/^\.json[c5]?$/)) {
try {
return JSON5.parse(content, (_, value) => {
if (typeof value == "string") {
const matches = value.match(/%env:([\w-]+)%/g);
if (matches) {
matches.forEach((match) => {
const env = match.match(/%env:([\w-]+)%/)![1];
if (process.env[env]) {
value = value.replace(
`%env:${env}%`,
process.env[env]
);
} else {
logger.configENVNotFound({
env,
envKey: match
});
}
});
}
}
return value;
});
} catch (error) {
logger.configJSONError({ error });
return false;
}
}
throw new Error(`Unsupported Extension: ${ext}`);
};