-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvite.config.ts
More file actions
173 lines (160 loc) · 5.59 KB
/
Copy pathvite.config.ts
File metadata and controls
173 lines (160 loc) · 5.59 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
import { loadEnv } from 'vite';
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
const proxyTarget = env.VITE_DEV_API_PROXY_TARGET || env.REACT_APP_DEV_API_PROXY_TARGET;
const useLocalApiMiddleware = !proxyTarget;
Object.entries(env).forEach(([key, value]) => {
if (process.env[key] === undefined) {
process.env[key] = value;
}
});
if (process.env.NODE_ENV === undefined) {
process.env.NODE_ENV = mode;
}
const localApiPlugin = useLocalApiMiddleware
? {
name: 'local-api-middleware',
configureServer(server) {
const buildQuery = (searchParams: URLSearchParams) => {
const query: Record<string, string | string[]> = {};
searchParams.forEach((value, key) => {
const existing = query[key];
if (Array.isArray(existing)) {
existing.push(value);
} else if (existing !== undefined) {
query[key] = [existing, value];
} else {
query[key] = value;
}
});
return query;
};
const patchResponse = (res) => {
res.status = (statusCode: number) => {
res.statusCode = statusCode;
return res;
};
res.json = (payload) => {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/json');
}
res.end(JSON.stringify(payload));
return res;
};
return res;
};
// Cache handlers across requests. We used to `delete require.cache`
// on every call so edits to api/*.js hot-reloaded — but the per-
// request module re-evaluation single-threaded Node's event loop
// and made 14 concurrent /api/metrics/* requests pile up pending
// for 60+ seconds. Set VITE_RELOAD_API=1 to opt back into the
// hot-reload behavior when actively editing API handlers.
const reloadApi = env.VITE_RELOAD_API === '1';
const handlerCache = new Map<string, any>();
const loadApiHandler = (modulePath: string) => {
if (reloadApi) {
const resolved = require.resolve(modulePath);
delete require.cache[resolved];
return require(resolved);
}
const cached = handlerCache.get(modulePath);
if (cached) return cached;
const handler = require(modulePath);
handlerCache.set(modulePath, handler);
return handler;
};
server.middlewares.use(async (req, res, next) => {
const url = new URL(req.url || '/', 'http://localhost');
const pathname = url.pathname;
const handler =
pathname === '/api/account-portfolio-search' ? loadApiHandler('./api/account-portfolio-search') :
pathname === '/api/validator-explorer-search' ? loadApiHandler('./api/validator-explorer-search') :
pathname === '/api/metrics' || pathname.startsWith('/api/metrics/') ? loadApiHandler('./api/metrics') :
null;
if (!handler) {
next();
return;
}
req.query = buildQuery(url.searchParams);
patchResponse(res);
try {
await handler(req, res);
} catch (error) {
next(error);
}
});
}
}
: null;
// Build-only: strip the inline SQL (`query` template literal) from client
// bundles. The frontend fetches data by metric id (/api/metrics/<id>); the
// backend reads the SQL from api/queries/<id>.json, and scripts/export-queries.js
// reads the source .js directly — so the query string is dead weight on the
// client. `apply: 'build'` keeps dev HMR and vitest untouched.
const stripMetricSql = {
name: 'strip-metric-sql',
apply: 'build' as const,
enforce: 'pre' as const,
transform(code: string, id: string) {
if (!/\/src\/queries\/.+\.js(\?|$)/.test(id) || id.includes('/index.js')) return null;
// Match the `query` field (key may be quoted, value may use backtick,
// single- or double-quote) and blank it. Escapes are honored so the match
// spans the whole literal.
const out = code.replace(
/(?:"query"|'query'|query)\s*:\s*(?:`(?:[^`\\]|\\.)*`|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/g,
"query: ''"
);
return out === code ? null : { code: out, map: null };
},
};
return {
plugins: [
react({
include: /\.[jt]sx?$/
}),
stripMetricSql,
localApiPlugin
].filter(Boolean),
envPrefix: ['VITE_', 'REACT_APP_'],
esbuild: {
loader: 'jsx',
include: /src\/.*\.[jt]sx?$/,
exclude: []
},
optimizeDeps: {
esbuildOptions: {
loader: {
'.js': 'jsx'
}
}
},
build: {
outDir: 'build'
},
server: proxyTarget
? {
proxy: {
'/api': {
target: proxyTarget,
changeOrigin: true,
secure: false
}
}
}
: undefined,
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setupTests.js',
css: true,
coverage: {
provider: 'v8',
reporter: ['text', 'html']
}
}
};
});