Files
2026-11-13 17:21:35 +08:00

293 lines
12 KiB
TypeScript

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import { VitePWA } from 'vite-plugin-pwa';
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const localizedJsxRuntime = fileURLToPath(new URL('../common/jsx-runtime.ts', import.meta.url));
function gitSha(short = false): string | undefined {
try {
return execSync(`git rev-parse ${short ? '--short ' : ''}HEAD`)
.toString()
.trim();
} catch {
return undefined; // building outside a checkout (a source tarball)
}
}
// A short build stamp (git SHA + UTC time) so the running app can show exactly
// which deploy is loaded, this makes "am I on the latest build?" verifiable
// instead of guessing when behaviour looks stale.
function buildStamp(): string {
const sha = gitSha(true);
if (!sha) return 'dev';
return `${sha} ${new Date().toISOString().slice(0, 16).replace('T', ' ')}Z`;
}
/**
* The release identity shared by the running app and the uploaded source maps.
*
* Both sides must agree exactly or symbolication silently does nothing: Sentry
* matches an incoming event's `release` against the release the maps were
* uploaded under, and a mismatch just leaves the stack minified. So this value
* is computed once here and used for both.
*
* Vercel does not run the build inside a git checkout, so its own commit SHA is
* the only source there.
*/
const RELEASE: string = process.env.VERCEL_GIT_COMMIT_SHA ?? gitSha() ?? 'dev';
// Read by designer/src/telemetry/reporter.ts. Assigned rather than overwritten
// so an explicit VITE_RELEASE in the environment still wins.
process.env.VITE_RELEASE ??= RELEASE;
/**
* Source maps are uploaded to Sentry and then deleted, never deployed.
*
* `sourcemap: 'hidden'` generates them without leaving a `//# sourceMappingURL`
* comment in the bundle, so nothing advertises them, and
* `filesToDeleteAfterUpload` removes them before the output directory ships.
* Sentry gets readable stack traces; the public site never serves our source.
*
* The whole thing is off unless all three credentials are present. That keeps
* `pnpm build` working for contributors and in CI, and, importantly, means a
* build without the token emits no maps at all rather than emitting them and
* quietly publishing them.
*/
const SENTRY_ORG = process.env.SENTRY_ORG;
const SENTRY_PROJECT = process.env.SENTRY_PROJECT;
const SENTRY_AUTH_TOKEN = process.env.SENTRY_AUTH_TOKEN;
const telemetryEnabled = process.env.VITE_ENABLE_TELEMETRY === 'true';
const uploadMaps = telemetryEnabled && !!(SENTRY_ORG && SENTRY_PROJECT && SENTRY_AUTH_TOKEN);
// Default deployment: https://cadworld-studio.robotquan.com/pcb/.
// Assets, the router and the installed PWA share this base. VITE_BASE can
// override it when building for another deployment path.
const APP_BASE = process.env.VITE_BASE ?? '/pcb/';
function pcbProxy(): import('vite').ProxyOptions {
return {
target: process.env.PCB_API_TARGET || 'http://39.105.93.138:8003',
changeOrigin: true,
rewrite: (path: string) => '/api' + path.slice(`${APP_BASE}pcb-api`.length),
configure: (proxy) => {
proxy.on('proxyReq', (request) =>
request.setHeader('Origin', process.env.PCB_API_ORIGIN || 'http://127.0.0.1:5173'),
);
},
};
}
export default defineConfig({
base: APP_BASE,
resolve: {
alias: [
{ find: /^react\/jsx-runtime$/, replacement: localizedJsxRuntime },
{ find: /^react\/jsx-dev-runtime$/, replacement: localizedJsxRuntime },
],
},
define: { __BUILD_STAMP__: JSON.stringify(buildStamp()) },
build: {
sourcemap: uploadMaps ? 'hidden' : false,
/**
* Bitmaps are files, as KiCad's are.
*
* Vite's default inlines any asset under 4 KB as a data: URI, and the
* toolbar's 472 icons are all under it — so 799 KB of base64 SVG sat in
* the entry chunk, downloaded and parsed before the sign-in screen could
* paint, for icons nothing shows until an editor frame does. As files
* they are hashed and immutable and fetched when a frame first paints.
* The platform list never warms editor frames. The entry drops by half.
*/
assetsInlineLimit: 0,
},
/**
* ES, not Vite's default IIFE.
*
* The OCCT worker (`3d-viewer/occt_worker.ts`) lazily imports the 7.6 MB
* WASM kernel, and a lazy import is a code split. Rollup cannot emit a
* split build as IIFE, so the default fails the whole build with "UMD and
* IIFE output formats are not supported for code-splitting builds" — not at
* dev time, only at `vite build`, which is why this arrived with the worker
* and was found one commit later.
*
* Every browser that has `Worker` at all supports module workers, and the
* loader falls back to the main thread where it does not.
*/
worker: { format: 'es' },
plugins: [
{
name: 'pcb-worker-safe-react-refresh',
apply: 'serve',
enforce: 'post',
transform(code, id) {
if (id !== '/@react-refresh') return;
// Native plotters reach shared JSX helpers. The refresh wrapper already
// skips workers, but its runtime registers this hook unconditionally.
// globalThis is window on the page and self inside the cover worker.
return code.replace(
'window.__registerBeforePerformReactRefresh',
'globalThis.__registerBeforePerformReactRefresh',
);
},
},
{
name: 'pcb-production-mode',
configResolved(config) {
// React explicitly includes these even when excluded above. The alias
// is application source and must share i18n with the rest of the app.
config.optimizeDeps.include = config.optimizeDeps.include?.filter(
(id) => id !== 'react/jsx-runtime' && id !== 'react/jsx-dev-runtime',
);
if (config.command === 'build' && config.env.VITE_PCB_API_MODE === 'mock')
throw new Error('PCB mock mode is development-only. Build with real API mode.');
},
},
{
name: 'pcb-service-deployment',
generateBundle() {
this.emitFile({
type: 'asset',
fileName: 'pcb-service-config.json',
source: JSON.stringify({ base: APP_BASE }),
});
},
},
react(),
/**
* The app is installed, not fetched.
*
* KiCad's editors are on disk; opening one never waits for a network. Ours
* were downloaded on every visit — Vercel serves hashed chunks as
* `max-age=0, must-revalidate` unless told otherwise (that is now
* vercel.json's job) — and an editor nobody had opened yet was fetched the
* moment they first asked for it, behind a "Loading the board editor..."
* overlay. The platform precaches only its small shell. Native editors,
* libraries and kernels load on demand; authenticated data and project
* archives never belong in the service worker cache.
*
* `prompt`, not `autoUpdate`: a new deploy is *installed* in the background
* but *activates* only once every tab of the old build is closed — the way
* a desktop update applies at the next launch. `autoUpdate` would swap the
* worker under a running editor, whose still-lazy chunks then hit the
* network for hashes the new deploy no longer serves.
*/
VitePWA({
registerType: 'prompt',
// registerSW.js as a separate script rather than inline: index.html carries
// no CSP nonce and we want the register call to stay out of the entry.
injectRegister: 'script-defer',
manifest: {
name: 'VibeMake PCB',
short_name: 'VibeMake PCB',
description: 'VibeMake 原理图与 PCB 设计工作区,支持工程保存与 KiCad 原生文件。',
start_url: APP_BASE,
scope: APP_BASE,
display: 'standalone',
// The chrome the shell paints while the first chunk loads. Matches the
// mark's own ground in favicon.svg and the dark shell in ui/shell.css.
background_color: '#07080a',
theme_color: '#07080a',
icons: [
{ src: 'icons/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: 'icons/icon-512.png', sizes: '512x512', type: 'image/png' },
{
src: 'icons/icon-512-maskable.png',
sizes: '512x512',
type: 'image/png',
purpose: 'maskable',
},
],
},
workbox: {
// The code, and only the code. public/ also ships 50 MB of symbol
// libraries, 5 MB of templates and the demo boards; those are data the
// app fetches when a project needs them, and precaching them would turn
// the first visit into a download of the whole library. Likewise the
// 7.4 MB OCCT kernel is cached the first time a 3D view asks for it,
// below, not up front.
globPatterns: [
'index.html',
'brand/*',
'icons/*.png',
'assets/index-*.js',
'assets/index-*.css',
],
// ...with one exception, for the same reason: the DRC worker carries
// the whole engine, every test provider and the board parser, and at
// 2.3 MB it is the largest asset in the build - larger than the app.
// It is fetched the first time someone runs a DRC, and cached then
// (runtimeCaching below), rather than by everyone who opens the site.
globIgnores: ['assets/drc_worker-*.js'],
// Keep an explicit upper bound even if the shell grows in a future build.
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024,
// Only the /pcb/ application scope uses this navigation fallback.
navigateFallback: 'index.html',
navigateFallbackDenylist: [/\/api\//, /\/pcb-api\//, /\.zip(?:\?|$)/],
runtimeCaching: [
{
// WASM kernels are hashed like every other asset, so cache-first is
// exact; they are just too big to insist on before first paint.
urlPattern: ({ url, sameOrigin }) =>
sameOrigin && /\/assets\/[^/]+\.wasm$/.test(url.pathname),
handler: 'CacheFirst',
options: { cacheName: 'wasm', expiration: { maxEntries: 8 } },
},
{
// The DRC worker, kept out of the precache above. Hashed like
// every other asset, so cache-first is exact, and a second DRC -
// or a DRC offline - has it in hand.
urlPattern: ({ url }: { url: URL }) =>
/\/assets\/drc_worker-.*\.js$/.test(url.pathname),
handler: 'CacheFirst',
options: { cacheName: 'drc-worker', expiration: { maxEntries: 4 } },
},
],
},
// Dev keeps Vite's own module server, where a stale worker would serve
// yesterday's source; the worker exists in builds only.
devOptions: { enabled: false },
}),
...(uploadMaps
? [
sentryVitePlugin({
org: SENTRY_ORG,
project: SENTRY_PROJECT,
authToken: SENTRY_AUTH_TOKEN,
// Use the explicitly configured Sentry endpoint for this build.
url: process.env.SENTRY_URL,
release: { name: RELEASE },
// Paths are relative to the Vite root (designer/).
sourcemaps: { filesToDeleteAfterUpload: ['./dist/**/*.map'] },
// We do not send our own build telemetry to Sentry either.
telemetry: false,
}),
]
: []),
],
server: {
port: 5173,
proxy: {
[`${APP_BASE}pcb-api`]: pcbProxy(),
'/api': {
target: process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com',
changeOrigin: true,
configure(proxy) {
proxy.on('proxyReq', (request) => {
request.removeHeader('origin');
request.removeHeader('referer');
});
},
},
},
},
// zstd-wasm locates zstd.wasm next to its own module via import.meta.url;
// pre-bundling would move the JS into .vite/deps without the wasm, so serve
// the package as-is (production builds handle new URL(..., import.meta.url)
// natively and copy the asset).
// Prebundling the aliased JSX runtime would embed a second i18n singleton.
// Keep it as source so language changes reach both native tools and the shell.
optimizeDeps: { exclude: ['@bokuweb/zstd-wasm', 'react/jsx-runtime', 'react/jsx-dev-runtime'] },
});