forked from SveltyCMS/SveltyCMS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
455 lines (400 loc) · 16.5 KB
/
vite.config.ts
File metadata and controls
455 lines (400 loc) · 16.5 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/**
* @file vite.config.ts
* @description This file contains the Vite configuration for the SvelteKit project, optimized for performance and developer experience.
* It employs a unified config structure with conditional plugins for the initial setup wizard vs. normal development mode.
*
* Key Features:
* - Centralized path management and logging utilities.
* - Efficient, direct Hot Module Replacement (HMR) for content structure without fake HTTP requests.
* - Dynamic compilation of user-defined collections with real-time feedback.
* - Seamless integration with Paraglide for i18n and better-svelte-email for email templating.
*/
import { paraglideVitePlugin } from '@inlang/paraglide-js';
import { sveltekit } from '@sveltejs/kit/vite';
import { existsSync, promises as fs } from 'fs';
import { builtinModules } from 'module';
import path from 'path';
import type { Plugin, UserConfig, ViteDevServer } from 'vite';
import { defineConfig } from 'vite';
import { compile } from './src/utils/compilation/compile';
import { isSetupComplete } from './src/utils/setupCheck';
import { securityCheckPlugin } from './src/utils/vitePluginSecurityCheck';
import { exec } from 'node:child_process';
import { platform } from 'node:os';
// Cross-platform open URL function (replaces 'open' package)
function openUrl(url: string) {
const plat = platform();
let cmd;
if (plat === 'win32') {
cmd = `start "" "${url}"`;
} else if (plat === 'darwin') {
cmd = `open "${url}"`;
} else {
cmd = `xdg-open "${url}"`;
}
exec(cmd);
}
// --- Constants & Configuration ---
const CWD = process.cwd();
const paths = {
configDir: path.resolve(CWD, 'config'),
privateConfig: path.resolve(CWD, 'config/private.ts'),
userCollections: path.resolve(CWD, 'config/collections'),
compiledCollections: path.resolve(CWD, 'compiledCollections'),
widgets: path.resolve(CWD, 'src/widgets')
};
// --- Utilities ---
const useColor = process.stdout.isTTY;
// Standardized logger for build-time scripts, mimicking the main application logger's style.
// Colored tag printed once so message-local color codes render correctly.
const TAG = useColor ? `\x1b[34m[SveltyCMS]\x1b[0m` : `[SveltyCMS]`;
const log = {
// Info level — tag is blue, message follows (may contain its own color codes)
info: (message: string) => console.log(`${TAG} ${message}`),
// Custom success level for clarity in build process
success: (message: string) => console.log(`${TAG} ${useColor ? `✅ \x1b[32m${message}\x1b[0m` : `✅ ${message}`}`),
// Corresponds to 'warn' level
warn: (message: string) => console.warn(`${TAG} ${useColor ? `⚠️ \x1b[33m${message}\x1b[0m` : `⚠️ ${message}`}`),
// Corresponds to 'error' level
error: (message: string, error?: unknown) => console.error(`${TAG} ${useColor ? `❌ \x1b[31m${message}\x1b[0m` : `❌ ${message}`}`, error ?? '')
};
/**
* Ensures collection directories exist and performs an initial compilation if needed.
* Creates placeholder files if no collections are found to prevent module import errors.
*/
let hasLoggedCollectionInit = false; // Prevent duplicate logs during multi-build
async function initializeCollectionsStructure() {
await fs.mkdir(paths.userCollections, { recursive: true });
await fs.mkdir(paths.compiledCollections, { recursive: true });
const sourceFiles = (await fs.readdir(paths.userCollections, { recursive: true })).filter(
(file): file is string => typeof file === 'string' && (file.endsWith('.ts') || file.endsWith('.js'))
);
if (sourceFiles.length > 0) {
if (!hasLoggedCollectionInit) {
log.info(`Found \x1b[32m${sourceFiles.length}\x1b[0m collection(s), compiling...`);
}
await compile({ userCollections: paths.userCollections, compiledCollections: paths.compiledCollections });
if (!hasLoggedCollectionInit) {
log.success('Initial collection compilation successful!');
hasLoggedCollectionInit = true;
}
} else {
if (!hasLoggedCollectionInit) {
log.info('No user collections found. Creating placeholder structure.');
hasLoggedCollectionInit = true;
}
const placeholderContent = '// This is a placeholder file generated by Vite.\nexport default {};';
const collectionsDir = path.resolve(paths.compiledCollections, 'Collections');
const menuDir = path.resolve(paths.compiledCollections, 'Menu');
await fs.mkdir(collectionsDir, { recursive: true });
await fs.mkdir(menuDir, { recursive: true });
await fs.writeFile(path.resolve(collectionsDir, '_placeholder.js'), placeholderContent);
await fs.writeFile(path.resolve(menuDir, '_placeholder.js'), placeholderContent);
}
}
// Force exit on SIGINT to prevent hanging processes
process.on('SIGINT', () => {
log.warn('\nReceived SIGINT, forcing exit...');
process.exit(0);
});
// --- Vite Plugins ---
/**
* A lightweight plugin to handle the initial setup wizard.
* Checks if private.ts exists and opens the setup page if needed.
* The setup wizard will create private.ts with real credentials.
*/
function setupWizardPlugin(): Plugin {
let wasPrivateConfigMissing = false;
return {
name: 'svelty-cms-setup-wizard',
async buildStart() {
// 🔍 CHECK ONLY: Don't create blank template
// The setup wizard will create private.ts with real database credentials
wasPrivateConfigMissing = !existsSync(paths.privateConfig);
if (wasPrivateConfigMissing) {
// Ensure config directory exists (but don't create the file)
await fs.mkdir(paths.configDir, { recursive: true });
log.info('Setup mode: config/private.ts will be created during setup wizard');
} else {
log.info('Setup complete: config/private.ts exists');
}
// Ensure collections are ready even in setup mode
await initializeCollectionsStructure();
},
config: () => ({
define: { __FRESH_INSTALL__: JSON.stringify(wasPrivateConfigMissing) }
}),
configureServer(server) {
// Only open setup wizard if private.ts is missing
if (!wasPrivateConfigMissing) {
return; // Setup already completed, skip browser opening
}
const originalListen = server.listen;
server.listen = function (port?: number, isRestart?: boolean) {
const result = originalListen.apply(this, [port, isRestart]);
result.then(() => {
setTimeout(async () => {
const address = server.httpServer?.address();
const resolvedPort = typeof address === 'object' && address ? address.port : 5173;
const setupUrl = `http://localhost:${resolvedPort}/setup`;
try {
log.info(`Opening setup wizard in your browser...`);
openUrl(setupUrl);
} catch {
const coloredUrl = useColor ? `\x1b[34m${setupUrl}\x1b[0m` : setupUrl;
log.info(`Please open this URL to continue setup: ${coloredUrl}`);
}
}, 1000);
});
return result;
};
}
};
}
/**
* Plugin to watch for changes in collections and widgets, triggering
* recompilation and efficient HMR updates.
*/
function cmsWatcherPlugin(): Plugin {
let compileTimeout: NodeJS.Timeout;
let widgetTimeout: NodeJS.Timeout; // Debounce timer for widgets
const handleHmr = async (server: ViteDevServer, file: string) => {
const isCollectionFile = file.startsWith(paths.userCollections) && /\.(ts|js)$/.test(file);
const isWidgetFile = file.startsWith(paths.widgets) && (file.endsWith('index.ts') || file.endsWith('.svelte'));
if (isCollectionFile) {
clearTimeout(compileTimeout);
compileTimeout = setTimeout(async () => {
log.info(`Collection change detected. Recompiling...`);
try {
await compile({ userCollections: paths.userCollections, compiledCollections: paths.compiledCollections });
log.success('Re-compilation successful!');
// Register collection models in database after recompilation
try {
const { dbAdapter } = await server.ssrLoadModule('./src/databases/db.ts?t=' + Date.now());
if (dbAdapter && dbAdapter.collection) {
const { scanCompiledCollections } = await server.ssrLoadModule('./src/content/collectionScanner.ts?t=' + Date.now());
const collections = await scanCompiledCollections();
log.info(`Found ${collections.length} collections, registering models...`);
// Register each collection sequentially with delay (prevent race condition)
for (const schema of collections) {
await dbAdapter.collection.createModel(schema);
await new Promise((resolve) => setTimeout(resolve, 100)); // 100ms delay
}
log.success(`Collection models registered! (${collections.length} total)`);
} else {
log.warn('Database adapter not available, skipping model registration');
}
} catch (dbError) {
log.error('Failed to register collection models (non-fatal):', dbError);
// Don't fail the entire HMR process
}
const { generateContentTypes } = await server.ssrLoadModule('./src/content/vite.ts');
await generateContentTypes(server);
log.info('Content structure types regenerated.');
server.ws.send({ type: 'full-reload', path: '*' });
} catch (error) {
log.error(`Error recompiling collections:`, error);
}
}, 150); // Debounce changes
}
// --- WATCHER LOGIC ---
if (isWidgetFile) {
clearTimeout(widgetTimeout);
widgetTimeout = setTimeout(async () => {
log.info(`Widget file change detected. Reloading widget store...`);
try {
// Invalidate and reload the widget store module to get the latest code
const { widgetStoreActions } = await server.ssrLoadModule('./src/stores/widgetStore.svelte.ts?t=' + Date.now());
// Call the reload action, which re-scans the filesystem
await widgetStoreActions.reloadWidgets();
// Trigger a full reload on the client to reflect the changes
server.ws.send({ type: 'full-reload', path: '*' });
log.success('Widgets reloaded and client updated.');
} catch (err) {
log.error('Error reloading widgets:', err);
}
}, 150); // Debounce changes
}
};
return {
name: 'svelty-cms-watcher',
enforce: 'post',
async buildStart() {
await initializeCollectionsStructure();
},
configureServer(server) {
server.watcher.on('all', (event, file) => {
if (event === 'add' || event === 'change' || event === 'unlink') {
handleHmr(server, file);
}
});
}
};
}
// --- Main Vite Configuration ---
const setupComplete = isSetupComplete();
const isBuild = process.env.NODE_ENV === 'production' || process.argv.includes('build');
export default defineConfig((): UserConfig => {
// Only log during dev mode, not during builds
if (!isBuild) {
if (setupComplete) {
log.success('Setup check passed. Initializing full dev environment...');
} else {
log.info('Starting in setup mode...');
}
}
return {
plugins: [
// Security check plugin runs first to detect private setting imports
securityCheckPlugin({
failOnError: true,
showWarnings: true,
extensions: ['.svelte', '.ts', '.js']
}),
sveltekit(),
!setupComplete ? setupWizardPlugin() : cmsWatcherPlugin(),
paraglideVitePlugin({
project: './project.inlang',
outdir: './src/paraglide'
})
],
server: {
fs: {
allow: ['static', '.'],
deny: ['**/tests/**']
},
watch: {
// Prevent watcher from triggering on generated/sensitive files
ignored: ['**/config/private.ts', '**/config/private.backup.*.ts', '**/compiledCollections/**', '**/tests/**']
}
},
ssr: {
noExternal: [],
external: ['bun:test', 'redis']
},
resolve: {
alias: {
'@root': path.resolve(CWD, './'),
'@src': path.resolve(CWD, './src'),
'@components': path.resolve(CWD, './src/components'),
'@content': path.resolve(CWD, './src/content'),
'@utils': path.resolve(CWD, './src/utils'),
'@stores': path.resolve(CWD, './src/stores'),
'@widgets': path.resolve(CWD, './src/widgets')
}
},
define: {
__FRESH_INSTALL__: false, // Default, may be overridden by setupWizardPlugin
// NOTE: PKG_VERSION is now provided by the server at runtime from package.json
// This ensures version always reflects installed package, not build-time snapshot
// SUPERFORMS_LEGACY: true, // Uncomment if using older versions of Superforms
// `global` polyfill for libraries that expect it (e.g., older crypto libs)
global: 'globalThis',
// Inline LOG_LEVELS at build time for aggressive tree-shaking
// Production default: 'info,warn,error' (no debug/trace)
// Development default: 'info,warn,error,debug' (includes debug)
// Override via LOG_LEVELS env var, e.g. LOG_LEVELS=fatal,error,warn or LOG_LEVELS=none
'import.meta.env.VITE_LOG_LEVELS': JSON.stringify(process.env.LOG_LEVELS || (isBuild ? 'info,warn,error' : 'info,warn,error,debug'))
},
build: {
target: 'esnext',
minify: 'esbuild',
sourcemap: true,
chunkSizeWarningLimit: 600, // Increase from 500KB (after optimizations)
rollupOptions: {
// Aggressive tree-shaking for production builds
treeshake: {
moduleSideEffects: false, // Assume modules have no side effects unless marked
propertyReadSideEffects: false, // Allow property reads to be removed
tryCatchDeoptimization: false // Don't deoptimize try-catch blocks
},
onwarn(warning, warn) {
// Suppress circular dependency warnings from third-party libraries
// These are internal to the libraries and don't affect functionality
if (warning.code === 'CIRCULAR_DEPENDENCY') {
// Check all possible fields where the path might be
const ids = warning.ids || [];
const message = warning.message || '';
// Combine all text to check
const allText = [message, ...ids].join(' ');
// If it contains node_modules, it's a third-party circular dependency - suppress it
if (allText.includes('node_modules')) {
return; // Suppress warnings from these specific packages
}
}
// Suppress unused external import warnings
if (warning.code === 'UNUSED_EXTERNAL_IMPORT') {
return;
}
// Suppress eval warnings from Vite (common in dev dependencies)
if (warning.code === 'EVAL' && warning.id?.includes('node_modules')) {
return;
}
// Suppress "dynamic import will not move module" warnings for known patterns
// This happens when a module is both statically and dynamically imported
// It's intentional in our architecture (eager + lazy loading patterns)
if (warning.message?.includes('dynamic import will not move module')) {
const knownPatterns = ['widgetStore.svelte.ts', 'richText/Input.svelte'];
if (knownPatterns.some((pattern) => warning.message?.includes(pattern))) {
return; // Suppress these specific warnings
}
}
// Show all other warnings
warn(warning);
},
external: [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'typescript', 'ts-node'],
output: {
// Optimized chunking for better caching and smaller initial load
manualChunks: (id: string) => {
// Only split vendor libraries (node_modules)
if (id.includes('node_modules')) {
// Rich text editors (TipTap, ProseMirror) - usually large (~150KB)
if (id.includes('tiptap') || id.includes('prosemirror')) {
return 'vendor-editor';
}
// Code editor (CodeMirror) - large (~100KB)
if (id.includes('codemirror') || id.includes('@codemirror')) {
return 'vendor-codemirror';
}
// Chart/visualization libraries
if (id.includes('chart') || id.includes('d3')) {
return 'vendor-charts';
}
// MongoDB/Mongoose - server-side only, shouldn't be in client bundle
if (id.includes('mongodb') || id.includes('mongoose')) {
return 'vendor-db';
}
// Skeleton UI components
if (id.includes('@skeletonlabs/skeleton')) {
return 'skeleton-ui';
}
// Svelte ecosystem (including SvelteKit to avoid circular deps)
if (id.includes('svelte')) {
return 'vendor-svelte';
}
// Everything else (core utilities)
return 'vendor';
}
// Route-based code splitting for admin vs public routes
// This keeps admin-heavy features separate from public pages
if (id.includes('src/routes/(app)/dashboard')) {
return 'route-dashboard';
}
if (id.includes('src/routes/(app)/config')) {
return 'route-admin-config';
}
if (id.includes('src/routes/(app)/mediagallery')) {
return 'route-media';
}
// Let Vite handle other application code automatically
}
}
}
},
optimizeDeps: {
exclude: [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'redis', '@src/databases/CacheService'],
include: ['@skeletonlabs/skeleton'],
entries: ['!tests/**/*', '!**/*.server.ts', '!**/*.server.js']
}
};
});