-
Notifications
You must be signed in to change notification settings - Fork 6
/
copy.mjs
55 lines (47 loc) · 1.53 KB
/
copy.mjs
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
import watcher from "@parcel/watcher";
import { copyFile, mkdir } from "fs/promises";
import { glob } from "glob";
import { minimatch } from "minimatch";
import { dirname, join, relative } from "path";
const watch = !!process.argv.find((arg) => arg === "--watch");
const srcRegExp = /^src\//;
const patterns = ["src/**/*.d.ts", "package.json", "*.md"];
if (watch) {
const debouncedCopy = debounceByArgs(copy, 100);
watcher.subscribe(process.cwd(), (error, events) => {
if (error) {
console.error("The filesystem watcher encountered an error:");
console.error(error);
process.exit(1);
}
events.forEach((event) => {
if (event.type !== "create" && event.type !== "update") return;
const path = relative(process.cwd(), event.path);
if (!patterns.some((pattern) => minimatch(path, pattern))) return;
debouncedCopy(path);
});
});
} else {
glob(patterns).then((paths) => Promise.all(paths.map(copy)));
}
async function copy(path) {
const libPath = srcRegExp.test(path)
? path.replace(/^src/, "lib")
: join("lib", path);
const dir = dirname(libPath);
await mkdir(dir, { recursive: true });
await copyFile(path, libPath);
console.log(`Copied ${path} to ${libPath}`);
}
export function debounceByArgs(func, waitFor) {
const timeouts = {};
return (...args) => {
const argsKey = JSON.stringify(args);
const later = () => {
delete timeouts[argsKey];
func(...args);
};
clearTimeout(timeouts[argsKey]);
timeouts[argsKey] = setTimeout(later, waitFor);
};
}