import { defineConfig, loadEnv, type UserConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'node:path' import { existsSync } from 'node:fs' import { cmsLivePlugin } from './vite/live' import { cmsMockPlugin } from './vite/mock' export default defineConfig(({ command, mode }): UserConfig => { const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env } as Record // Shared @k6n/cms-editor sources. As a submodule of the ecommerce monorepo the // backoffice is a sibling; a standalone checkout sits next to ../ecommerce. const editorSrc = path.resolve( env.CMS_EDITOR_SRC || ['../backoffice/web/packages/cms-editor/src', '../ecommerce/backoffice/web/packages/cms-editor/src', './.cms-editor/src'].find((p) => existsSync(path.resolve(p)), ) || '../backoffice/web/packages/cms-editor/src', ) // CMS_ONPAGE_OUT: build straight into an instance's public/ (dev launcher --watch). const outDir = env.CMS_ONPAGE_OUT ? path.resolve(env.CMS_ONPAGE_OUT) : 'dist' const emptyOutDir = !env.CMS_ONPAGE_OUT const common: UserConfig = { plugins: [react()], resolve: { alias: { '@k6n/cms-editor': path.join(editorSrc, 'index.ts') }, // The shared package imports tiptap from its own location; keep a single copy. dedupe: ['react', 'react-dom', '@tiptap/core', '@tiptap/pm'], }, server: { port: 5173, strictPort: true /* the issuer's CORS allowlist names localhost:5173 */, fs: { allow: [process.cwd(), path.resolve(editorSrc, '..')] } }, test: { environment: 'jsdom', environmentOptions: { jsdom: { pretendToBeVisual: true } }, include: ['test/**/*.test.{ts,tsx}', 'src/**/*.test.{ts,tsx}', 'mock/**/*.test.ts'], setupFiles: ['test/setup.ts'], }, } as UserConfig if (command === 'build' && mode === 'loader') { // /editor/cms-client.js: the stable URL page templates reference. Classic // script (IIFE), tiny; imports the editor bundle only for editors. return { ...common, define: { 'process.env.NODE_ENV': '"production"' }, build: { outDir, emptyOutDir: false, lib: { entry: 'src/loader.ts', name: 'CMSClient', formats: ['iife'], fileName: () => 'cms-client.js' }, sourcemap: true, }, } } if (command === 'build') { // The artifact served at /editor/onpage-editor.js. One self-contained file; // only loaded when the preview cookie is present (see src/main.ts). return { ...common, define: { 'process.env.NODE_ENV': '"production"' }, build: { outDir, emptyOutDir, lib: { entry: 'src/main.ts', formats: ['es'], fileName: () => 'onpage-editor.js' }, sourcemap: true, cssCodeSplit: false, }, } } const mock = (env.CMS_MODE || 'live') === 'mock' return { ...common, plugins: [...(common.plugins ?? []), mock ? cmsMockPlugin() : cmsLivePlugin(env)], } })