-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathcodegen.plugin.ts
63 lines (55 loc) · 1.78 KB
/
codegen.plugin.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
import { readdirSync } from 'node:fs';
const fileRegex = /\.tsx$/;
const codegenRegex = /\/\/ @codegen (.*)/g;
const DIRECTIVES = readdirSync('./components/ui/directives')
.filter((x) => x !== 'index.ts')
.map((x) => x.substring(0, x.length - 3));
const directiveRegex = new RegExp('use:(' + DIRECTIVES.join('|') + ')');
export default function codegenPlugin() {
return {
name: 'codegen',
enforce: 'pre' as const,
transform(src: string, id: string) {
if (fileRegex.test(id)) {
src = src.replace(codegenRegex, (substring, group1) => {
const rawArgs: string[] = group1.split(' ');
const type = rawArgs.shift();
const args = rawArgs.reduce(
(d, arg) => {
const [key, value] = arg.split('=');
return {
...d,
[key]: value,
};
},
{ type }
) as {
type: 'directives';
props?: string;
include?: string;
};
switch (args.type) {
case 'directives':
// Generate directives forwarding
const source = args.props ?? 'props';
const permitted: string[] =
args.include?.split(',') ?? DIRECTIVES;
return DIRECTIVES.filter((d) => permitted.includes(d))
.map((d) => `use:${d}={${source}["use:${d}"]}`)
.join('\n');
default:
return substring;
}
});
if (directiveRegex.test(src)) {
if (!id.endsWith('client/components/ui/index.tsx'))
src =
`import { ${DIRECTIVES.join(
', '
)} } from "@revolt/ui/directives";\n` + src;
}
return src;
}
},
};
}