forked from openai/openai-apps-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.mts
More file actions
232 lines (205 loc) · 6.47 KB
/
vite.config.mts
File metadata and controls
232 lines (205 loc) · 6.47 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { defineConfig, type Plugin } from "vite";
import react from "@vitejs/plugin-react";
import fg from "fast-glob";
import path from "node:path";
import fs from "node:fs";
import tailwindcss from "@tailwindcss/vite";
function buildInputs() {
const files = fg.sync("src/**/index.{tsx,jsx}", { dot: false });
return Object.fromEntries(
files.map((f) => [path.basename(path.dirname(f)), path.resolve(f)])
);
}
const toFs = (abs: string) => "/@fs/" + abs.replace(/\\/g, "/");
const toServerRoot = (abs: string) => {
const rel = path.relative(process.cwd(), abs).replace(/\\/g, "/");
// If it's not really relative (different drive or absolute), fall back to fs URL
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return toFs(abs);
return "./" + rel;
};
function multiEntryDevEndpoints(options: {
entries: Record<string, string>;
globalCss?: string[];
perEntryCssGlob?: string;
perEntryCssIgnore?: string[];
}): Plugin {
const {
entries,
globalCss = ["src/index.css"],
perEntryCssGlob = "**/*.{css,pcss,scss,sass}",
perEntryCssIgnore = ["**/*.module.*"],
} = options;
const V_PREFIX = "\0multi-entry:"; // Rollup “virtual module” prefix
const HIDE_FROM_HOME = new Set(["flashcards", "daw"]);
const renderIndexHtml = (names: string[]): string => `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>ecosystem ui examples</title>
<style>
body { font: 15px/1.5 system-ui, sans-serif; margin: 32px; color: #1f2933; }
h1 { font-size: 20px; margin-bottom: 12px; }
ul { padding-left: 18px; }
li { margin-bottom: 6px; }
a { color: #2563eb; text-decoration: none; }
a:hover { text-decoration: underline; }
code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 13px; margin-left: 6px; color: #64748b; }
</style>
</head>
<body>
<h1>Examples</h1>
<ul>
${names
.filter((n) => !HIDE_FROM_HOME.has(n))
.toSorted()
.map(
(name) =>
`<li><a href="/${name}.html">${name}</a><code>/${name}.html</code></li>`
)
.join("\n ")}
</ul>
</body>
</html>`;
const renderDevHtml = (name: string): string => `<!doctype html>
<html>
<head>
<script type="module" src="/${name}.js"></script>
<link rel="stylesheet" href="/${name}.css">
</head>
<body>
<div id="${name}-root"></div>
</body>
</html>`;
return {
name: "multi-entry-dev-endpoints",
configureServer(server) {
const names = Object.keys(entries);
const list = names
.map((n) => `/${n}.html, /${n}.js, /${n}.css`)
.join("\n ");
server.config.logger.info(`\nDev endpoints:\n ${list}\n`);
server.middlewares.use((req, res, next) => {
try {
if (req.method !== "GET" || !req.url) return next();
const url = req.url.split("?")[0];
if (url === "/" || url === "" || url === "/index.html") {
const html = renderIndexHtml(names);
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(html);
return;
}
const bareMatch = url.match(/^\/?([\w-]+)\/?$/);
if (bareMatch && entries[bareMatch[1]]) {
const name = bareMatch[1];
const html = renderDevHtml(name);
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(html);
return;
}
if (!url.endsWith(".html")) return next();
const m = url.match(/^\/?([\w-]+)\.html$/);
if (!m) return next();
const name = m[1];
if (!entries[name]) return next();
const html = renderDevHtml(name);
res.setHeader("Content-Type", "text/html");
res.end(html);
return;
} catch {
// fall through
}
next();
});
},
resolveId(id: string) {
// Map request paths to virtual ids
if (id.startsWith("/")) id = id.slice(1);
if (id.endsWith(".js")) {
const name = id.slice(0, -3);
if (entries[name]) return `${V_PREFIX}entry:${name}`;
}
if (id.endsWith(".css")) {
const name = id.slice(0, -4);
if (entries[name]) return `${V_PREFIX}style:${name}.css`;
}
if (id.startsWith(V_PREFIX)) return id;
return null;
},
load(id: string) {
if (!id.startsWith(V_PREFIX)) return null;
const rest = id.slice(V_PREFIX.length); // "entry:foo" or "style:foo.css"
const [kind, nameWithExt] = rest.split(":", 2);
const name = nameWithExt.replace(/\.css$/, "");
const entry = entries[name];
if (!entry) return null;
const entryDir = path.dirname(entry);
// Collect CSS (global first for stable cascade)
const globals = globalCss
.map((p) => path.resolve(p))
.filter((p) => fs.existsSync(p));
const perEntry = fg.sync(perEntryCssGlob, {
cwd: entryDir,
absolute: true,
dot: false,
ignore: perEntryCssIgnore,
});
if (kind === "style") {
const allCss = [...globals, ...perEntry]; // absolute paths on disk
const lines = [
`@source "./src";`,
...allCss.map((p) => `@import "${toServerRoot(p)}";`),
];
return lines.join("\n");
}
if (kind === "entry") {
const spec = toFs(entry);
const lines: string[] = [];
// Import Vite HMR client from root
lines.push(`import "/@vite/client";`);
lines.push(`
import RefreshRuntime from "/@react-refresh";
if (!window.__vite_plugin_react_preamble_installed__) {
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
}
`);
lines.push(`import "/${name}.css";`);
lines.push(`await import(${JSON.stringify(spec)});`);
return lines.join("\n");
}
return null;
},
};
}
const inputs = buildInputs();
export default defineConfig(({}) => ({
plugins: [
tailwindcss(),
react(),
multiEntryDevEndpoints({ entries: inputs }),
],
cacheDir: "node_modules/.vite-react",
server: {
port: 4444,
strictPort: true,
cors: true,
},
esbuild: {
jsx: "automatic",
jsxImportSource: "react",
target: "es2022",
},
build: {
target: "es2022",
sourcemap: true,
minify: "esbuild",
outDir: "assets",
assetsDir: ".",
rollupOptions: {
input: inputs,
preserveEntrySignatures: "strict",
},
},
}));