-
Notifications
You must be signed in to change notification settings - Fork 0
/
openapi-bundler.js
105 lines (92 loc) · 2.48 KB
/
openapi-bundler.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
93
94
95
96
97
98
99
100
101
102
103
104
105
const exec = require("child_process").exec;
const chokidar = require("chokidar");
const packageJSON = require("./package.json");
const defaultDocfiles = [
{
path: "./openapi/v1.yaml",
out: "./content/openapi/v1.yaml",
name: "V1",
},
];
const docs =
Array.isArray(packageJSON.docfiles) && packageJSON.docfiles.length > 0
? packageJSON.docfiles
: defaultDocfiles;
function bundleDocDef(doc) {
exec(
`openapi bundle ${doc.path} -o ${doc.out}`,
function (error, stdout, stderr) {
console.log(`Doc "${doc.name}" bundled`);
if (error) {
console.error(error)
}
}
);
}
const DEFAULT_OPTIONS = {
delay: 250,
events: ["add", "change", "unlink"],
fireFirst: false,
fireLast: true,
chokidarOptions: {
ignoreInitial: true,
followSymlinks: false,
},
};
function watch(paths = [], options = {}, callback = () => {}) {
options = { ...DEFAULT_OPTIONS, ...options };
const watcher = chokidar.watch(paths, options.chokidarOptions);
const debounceEvent =
(callback, time = DEFAULT_OPTIONS.delay, interval) =>
(...args) => {
clearTimeout(interval);
interval = setTimeout(
() => (options.fireLast ? callback(...args) : () => {}),
time
);
};
function onChange(event, path, stats, error) {
if (error && watcher.listenerCount("error")) {
watcher.emit("error", error);
return;
}
if (options.fireFirst) {
callback(event, path, stats);
}
debounceEvent(callback(event, path, stats), 250);
}
options.events.forEach((event) => {
if (
["add", "change", "unlink", "addDir", "unlinkDir"].indexOf(event) !== -1
) {
watcher.on(event, (path) => onChange(event, path, null, null));
} else if (event === "change") {
watcher.on(event, (path, stats) => onChange(event, path, stats, null));
} else if (event === "error") {
watcher.on(event, (error) => onChange(event, "", null, error));
} else if (event === "ready") {
watcher.on(event, () => onChange(event, "", null, null));
} else if (event === "raw") {
watcher.on(event, (event, path, details) =>
onChange(event, path, details, null)
);
}
});
return watcher;
}
if(process.argv.includes('watch')) {
watch(
"openapi/",
{
fireFirst: false,
fireLast: false,
},
(event, path, stats, error) => {
if (error) {
console.error(error);
}
docs.forEach(bundleDocDef);
}
);
}
docs.forEach(bundleDocDef);