-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugin.ts
More file actions
175 lines (157 loc) · 4.21 KB
/
plugin.ts
File metadata and controls
175 lines (157 loc) · 4.21 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import type { Plugin } from "vite";
import process from "process";
import path from "path";
import { exec } from "child_process";
import fs from "fs/promises";
interface PluginConfig {
port?: number;
experimentalAutoGenerateTypes?: boolean;
runtime: "cloudflare" | "bun";
}
const cwd = process.cwd();
const DEFAULT_PORT = 8787;
const GEN_PROMISE_KEY = "deco-gen";
const GEN_FILE = "deco.gen.ts";
async function performDecoGen() {
// @ts-ignore
const cmd = typeof Bun === "undefined" ? "npm run gen" : "bun run gen";
exec(cmd, { cwd }, (error) => {
if (error) {
console.error(`Error performing deco gen: ${error}`);
}
});
}
function shouldPerformDecoGen({ filePath }: { filePath: string }): boolean {
return filePath.startsWith("server/") && !filePath.endsWith(GEN_FILE);
}
const FILES_TO_REMOVE = [
"wrangler.json",
".dev.vars",
// TODO: Support source maps
"index.js.map",
];
const RENAME_MAP = {
"index.js": "main.js",
};
const OPERATIONS = [
...FILES_TO_REMOVE.map((file) => ({
type: "remove" as const,
file,
})),
...Object.entries(RENAME_MAP).map(([oldFile, newFile]) => ({
type: "rename" as const,
oldFile,
newFile,
})),
];
async function fixCloudflareBuild({
outputDirectory,
}: {
outputDirectory: string;
}) {
const files = await fs.readdir(outputDirectory);
const isCloudflareViteBuild = files.some((file) => file === "wrangler.json");
if (!isCloudflareViteBuild) {
return;
}
const results = await Promise.allSettled(
OPERATIONS.map(async (operation) => {
if (operation.type === "remove") {
await fs.rm(path.join(outputDirectory, operation.file));
} else if (operation.type === "rename") {
await fs.rename(
path.join(outputDirectory, operation.oldFile),
path.join(outputDirectory, operation.newFile),
);
}
}),
);
results.forEach((result) => {
if (result.status === "rejected") {
console.error(`Error performing operation: ${result.reason}`);
}
});
}
export function deco(decoConfig: PluginConfig = {}): Plugin {
let outputDirectory = "dist";
const singleFlight = new Map<string, Promise<void>>();
return {
name: "vite-plugin-deco",
enforce: "post",
configResolved(config) {
outputDirectory = config.build.outDir || "dist";
},
buildStart() {
if (!decoConfig.experimentalAutoGenerateTypes) {
return;
}
performDecoGen();
},
async closeBundle() {
await fixCloudflareBuild({ outputDirectory });
},
handleHotUpdate(ctx) {
// skip hmr entirely for the deco gen file
if (ctx.file.endsWith(GEN_FILE)) {
return [];
}
if (!decoConfig.experimentalAutoGenerateTypes) {
return ctx.modules;
}
const relative = path.relative(cwd, ctx.file);
if (!shouldPerformDecoGen({ filePath: relative })) {
return ctx.modules;
}
const promise = singleFlight.get(GEN_PROMISE_KEY);
if (promise) {
return ctx.modules;
}
const newPromise = performDecoGen().finally(() => {
singleFlight.delete(GEN_PROMISE_KEY);
});
singleFlight.set(GEN_PROMISE_KEY, newPromise);
return ctx.modules;
},
config: () => ({
server: {
port: decoConfig.port || DEFAULT_PORT,
strictPort: true,
},
worker: {
format: "es",
},
optimizeDeps: {
force: true,
},
build: {
sourcemap: true,
},
}),
};
}
export function importSqlStringPlugin(): Plugin {
return {
name: "vite-plugin-import-sql-string",
transform(content: string, id: string) {
if (id.endsWith(".sql")) {
return {
code: `export default ${JSON.stringify(content)};`,
map: null,
};
}
},
};
}
const VITE_SERVER_ENVIRONMENT_NAME = "server";
export default function vitePlugins(decoConfig: PluginConfig = {}): Plugin[] {
const cloudflarePlugin =
decoConfig.runtime === "cloudflare"
? cloudflare({
configPath: "wrangler.toml",
viteEnvironment: {
name: VITE_SERVER_ENVIRONMENT_NAME,
},
})
: undefined;
return [deco(decoConfig), importSqlStringPlugin(), cloudflarePlugin];
}