-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
92 lines (80 loc) · 1.9 KB
/
main.js
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
const objectPath = require("object-path");
const DEFAULT_KEYS = [
"author",
"contributors",
"description",
"keywords",
"repository",
"bugs",
"bin",
"main",
"module",
"dependencies",
"peerDependencies",
"license"
];
/**
* @typedef Options
* @property {string[]} [omit]
* @property {string[]} [include]
* @property {string} [indent]
*/
/**
* makePackage
* @param {string} config_data
* @param {Options} options
* @returns {string}
*/
function makePackage(config_data, options) {
options = {
omit: options.omit || [],
include: options.include || [],
indent: options.indent || " "
};
let config;
try {
config = JSON.parse(config_data);
} catch (error) {
throw Error("ParseError: 'package.json' is not valid");
}
const new_config = {};
const keys = [
...DEFAULT_KEYS.map(inclusion),
...options.include.map(inclusion),
...options.omit.map(omission)
].sort(require("./path-sort"));
for (const { key, action } of keys) {
if (action === "include" && objectPath(config).has(key)) {
objectPath(new_config).set(key, objectPath(config).get(key));
} else if (action === "omit") {
objectPath(new_config).del(key);
}
}
const required_keys = ["name", "version"];
const required_config = {};
for (const key of required_keys) {
if (objectPath(config).has(key)) {
objectPath(required_config).set(key, objectPath(config).get(key));
} else {
throw Error(`Missing required key ${key}`);
}
}
return JSON.stringify(
Object.assign(required_config, new_config),
null,
options.indent
);
}
/**
* @param {string} key
* @returns {{ key: string, action: 'omit' }} */
function omission(key) {
return { key, action: "omit" };
}
/**
* @param {string} key
* @returns {{ key: string, action: 'include' }} */
function inclusion(key) {
return { key, action: "include" };
}
module.exports = makePackage;