-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvite.config.ts
More file actions
340 lines (332 loc) · 10.9 KB
/
Copy pathvite.config.ts
File metadata and controls
340 lines (332 loc) · 10.9 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import react from '@vitejs/plugin-react';
import { defineConfig, Plugin } from 'vite';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import topLevelAwait from 'vite-plugin-top-level-await';
import wasm from 'vite-plugin-wasm';
import fs from 'node:fs';
import path from 'node:path';
const DEPLOYED_LOCAL_PATH = path.resolve(
process.cwd(),
'config/deployed.local.json'
);
const VIRTUAL_ID = '\0virtual:deployed-local-config';
/** Injects deployed.local.json via virtual module (avoids glob+gitignore issues). */
const injectDeployedLocal = (): Plugin => ({
name: 'inject-deployed-local',
resolveId(id) {
if (id === 'virtual:deployed-local-config') return VIRTUAL_ID;
return null;
},
load(id) {
if (id !== VIRTUAL_ID) return null;
try {
const raw = fs.readFileSync(DEPLOYED_LOCAL_PATH, 'utf-8');
return `export default ${raw};`;
} catch {
return 'export default {};';
}
},
configureServer(server) {
server.watcher.add(DEPLOYED_LOCAL_PATH);
const maybeReload = (file: string) => {
if (path.normalize(file) === path.normalize(DEPLOYED_LOCAL_PATH)) {
const mod = server.moduleGraph.getModuleById(VIRTUAL_ID);
if (mod) server.moduleGraph.invalidateModule(mod);
server.ws.send({ type: 'full-reload' });
}
};
server.watcher.on('change', maybeReload);
server.watcher.on('add', maybeReload);
},
});
/**
* Plugin to fix static class field initialization issue with Rollup bundling.
* When Rollup bundles classes, it transforms `class Foo {}` to `let Foo; Foo = class {}`
* This breaks static initializers like `static ZERO = new AztecAddress(...)` because
* they execute before the assignment completes.
*
* This plugin runs AFTER minification (writeBundle hook) and transforms the minified
* pattern to a lazy getter that defers initialization.
*/
const fixStaticFieldInit = (): Plugin => ({
name: 'fix-static-field-init',
enforce: 'post',
async writeBundle(options, bundle) {
const fs = await import('fs');
const path = await import('path');
const outDir = options.dir || 'dist';
for (const [fileName, chunk] of Object.entries(bundle)) {
if (chunk.type === 'chunk' && fileName.endsWith('.js')) {
const filePath = path.default.join(outDir, fileName);
let code = fs.default.readFileSync(filePath, 'utf-8');
// Pattern for minified code: static ZERO=new X(Y.alloc(32,0))
// Both class name and Buffer get minified to short identifiers
const minifiedPattern =
/static ZERO=new (\w+)\((\w+)\.alloc\(32,0\)\)/g;
if (minifiedPattern.test(code)) {
code = code.replace(
/static ZERO=new (\w+)\((\w+)\.alloc\(32,0\)\)/g,
'static get ZERO(){return this._ZC||(this._ZC=new $1($2.alloc(32,0)))}'
);
fs.default.writeFileSync(filePath, code);
console.log(`[fix-static-field-init] Patched ${fileName}`);
}
}
}
},
});
/**
* Plugin to shim Node.js built-in modules that shouldn't run in browser.
* Must run before nodePolyfills to intercept fs/promises correctly.
*/
const nodeBuiltinsShim = (): Plugin => ({
name: 'node-builtins-shim',
enforce: 'pre', // Run before other plugins
resolveId(source) {
// Intercept Node.js modules that need shimming
if (
source === 'fs/promises' ||
source === 'fs' ||
source === 'net' ||
source === 'tty'
) {
return `\0virtual:${source}`;
}
return null;
},
load(id) {
// Provide shims for Node.js-only modules
if (id === '\0virtual:fs/promises') {
return `
export const mkdir = () => Promise.reject(new Error('fs/promises not available in browser'));
export const writeFile = () => Promise.reject(new Error('fs/promises not available in browser'));
export const readFile = () => Promise.reject(new Error('fs/promises not available in browser'));
export const rm = () => Promise.reject(new Error('fs/promises not available in browser'));
export default { mkdir, writeFile, readFile, rm };
`;
}
if (id === '\0virtual:fs') {
return `
export const existsSync = () => false;
export const readFileSync = () => { throw new Error('fs not available in browser'); };
export const writeFileSync = () => { throw new Error('fs not available in browser'); };
export const mkdirSync = () => { throw new Error('fs not available in browser'); };
export default { existsSync, readFileSync, writeFileSync, mkdirSync };
`;
}
if (id === '\0virtual:net') {
return `
export const Socket = class Socket { constructor() { throw new Error('net not available in browser'); } };
export const connect = () => { throw new Error('net not available in browser'); };
export default { Socket, connect };
`;
}
if (id === '\0virtual:tty') {
return `
export const isatty = () => false;
export default { isatty };
`;
}
return null;
},
});
export default defineConfig(() => {
const proxyConfig = {
'/rpc': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: () => '/',
},
'/api/local-network-status': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: () => '/status',
},
'/api/testnet-status': {
target: 'https://rpc.testnet.aztec-labs.com',
changeOrigin: true,
rewrite: () => '/status',
},
'/api/testnet': {
target: 'https://rpc.testnet.aztec-labs.com',
changeOrigin: true,
rewrite: (path: string) => path.replace(/^\/api\/testnet/, '') || '/',
},
};
return {
// Suppress Rollup warnings that originate from node_modules and are not actionable.
// @aztec/noir-protocol-circuits-types imports the same JSON artifact files both with
// and without `{ type: 'json' }` assertions — nothing we can do without patching upstream.
onLog(level, log, handler) {
if (
level === 'warn' &&
log.message.includes('"type": "json" attributes') &&
log.message.includes('node_modules')
) {
return;
}
handler(level, log);
},
plugins: [
nodeBuiltinsShim(), // Must be first to intercept before nodePolyfills
injectDeployedLocal(),
react(),
wasm(),
topLevelAwait(),
fixStaticFieldInit(), // Fix static field initialization after bundling
nodePolyfills({
// Include specific polyfills that your Webpack config provided
include: [
'buffer',
'crypto',
'util',
'assert',
'process',
'stream',
'path',
'events',
],
globals: {
Buffer: true,
global: true,
process: true,
},
// Exclude modules we're shimming ourselves
exclude: ['fs', 'net', 'tty'],
}),
],
assetsInclude: ['**/*.wasm'],
define: {
global: 'globalThis',
},
worker: {
format: 'es',
},
esbuild: {
target: 'esnext',
// Avoid TDZ issues from minified class static field initializers in
// Aztec/Foundation classes (e.g. static ZERO = new Fr(...)).
supported: {
'class-static-field': false,
},
},
resolve: {
alias: {
// Ensure artifact JSON imports resolve from src/artifacts
'../target': path.resolve(__dirname, 'src/target'),
// Additional polyfills for blockchain dependencies
crypto: 'crypto-browserify',
stream: 'stream-browserify',
util: 'util',
path: 'path-browserify',
// Use browser-safe pino version
pino: 'pino/browser.js',
// Force specific hash.js path for proper CommonJS handling
'hash.js': 'hash.js/lib/hash.js',
// Fix sha3 CommonJS exports
sha3: 'sha3/index.js',
// Fix lodash.chunk CommonJS exports
'lodash.chunk': 'lodash.chunk/index.js',
// Fix lodash.times CommonJS exports
'lodash.times': 'lodash.times/index.js',
// Fix lodash.isequal CommonJS exports
'lodash.isequal': 'lodash.isequal/index.js',
// Fix lodash.pickby CommonJS exports
'lodash.pickby': 'lodash.pickby/index.js',
// Fix json-stringify-deterministic CommonJS exports
'json-stringify-deterministic':
'json-stringify-deterministic/lib/index.js',
},
dedupe: [
'@aztec/foundation',
'@aztec/circuits.js',
'@noble/curves',
'@noble/hashes',
],
},
server: {
port: 3000,
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'credentialless',
'Cross-Origin-Resource-Policy': 'cross-origin',
},
fs: {
allow: ['..'],
},
proxy: proxyConfig,
},
preview: {
port: 3000,
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'credentialless',
'Cross-Origin-Resource-Policy': 'cross-origin',
},
proxy: proxyConfig,
},
build: {
sourcemap: false, // Disable sourcemaps to reduce memory usage
minify: 'esbuild',
// Barretenberg WASM wrappers and ML artifact chunks are inherently large;
// raise the limit so that only genuinely unexpected large chunks surface.
chunkSizeWarningLimit: 50_000,
target: 'esnext',
commonjsOptions: {
// Forces @aztec packages to be treated as ESM to prevent class identity errors
defaultIsModuleExports: (id) => {
if (id.includes('@aztec/')) {
return false;
}
return 'auto';
},
exclude: [
'@aztec/stdlib/**',
'@aztec/foundation/**',
'@aztec/aztec.js/**',
],
},
rollupOptions: {
output: {
format: 'es',
preserveModules: false,
inlineDynamicImports: false,
interop: 'auto',
manualChunks: (id: string) => {
if (id.includes('@noble/curves') || id.includes('@noble/hashes')) {
return 'vendor-noble';
}
if (id.includes('@aztec/foundation')) {
return 'vendor-aztec-foundation';
}
},
assetFileNames: (assetInfo) => {
if (assetInfo.names.some((name) => name.endsWith('.wasm'))) {
return 'assets/[name]-[hash][extname]';
}
return 'assets/[name]-[hash][extname]';
},
},
},
},
optimizeDeps: {
include: [
'react',
'react-dom',
'react/jsx-runtime',
'buffer',
'crypto-browserify',
'stream-browserify',
'util',
'path-browserify',
'@tanstack/react-query',
],
exclude: ['@aztec/noir-acvm_js', '@aztec/noir-noirc_abi', '@aztec/bb.js'],
esbuildOptions: {
define: {
global: 'globalThis',
},
},
},
};
});