forked from CherryHQ/cherry-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelectron.vite.config.ts
More file actions
313 lines (295 loc) · 13.6 KB
/
Copy pathelectron.vite.config.ts
File metadata and controls
313 lines (295 loc) · 13.6 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
import { readdirSync, readFileSync } from 'fs'
import { join, resolve } from 'path'
import { sentryVitePlugin } from '@sentry/vite-plugin'
import tailwindcss from '@tailwindcss/vite'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
import react from '@vitejs/plugin-react'
import { CodeInspectorPlugin } from 'code-inspector-plugin'
import { defineConfig } from 'electron-vite'
import { visualizer } from 'rollup-plugin-visualizer'
import type { Plugin } from 'vite'
import { parse } from 'yaml'
// Import attributes are not supported by the current Electron config loader.
// import pkg from './package.json' assert { type: 'json' }
import pkg from './package.json'
import { buildFlatContractCss } from './packages/ui/scripts/build-theme-css'
import { chunkExportGuardPlugin } from './scripts/checkChunkExports'
import { uiContractPlugin } from './scripts/uiContract/vitePlugin'
import { APP_EDITIONS, type AppEdition } from './src/shared/types/appEdition'
import { parseReleaseHistory, validateCurrentReleaseHistory } from './src/shared/utils/releaseNotes'
import { getSentryBuildContext } from './src/shared/utils/sentry'
type ElectronBuilderConfig = {
releaseInfo?: {
releaseNotes?: unknown
}
}
const electronBuilderConfig = parse(
readFileSync(resolve(__dirname, 'electron-builder.yml'), 'utf8')
) as ElectronBuilderConfig
const bundledReleaseNotes = electronBuilderConfig.releaseInfo?.releaseNotes
const bundledReleaseHistory = parseReleaseHistory(
readFileSync(resolve(__dirname, 'resources/cherry-studio/release-history.json'), 'utf8')
)
if (typeof bundledReleaseNotes !== 'string' || !bundledReleaseNotes.trim()) {
throw new Error('electron-builder.yml must define non-empty releaseInfo.releaseNotes')
}
validateCurrentReleaseHistory({ releaseNotes: bundledReleaseNotes, version: pkg.version }, bundledReleaseHistory)
const visualizerPlugin = (type: 'renderer' | 'main') => {
return process.env[`VISUALIZER_${type.toUpperCase()}`] ? [visualizer({ open: true })] : []
}
const isDev = process.env.NODE_ENV === 'development'
const isProd = process.env.NODE_ENV === 'production'
const SENTRY_UPLOAD_ENV_KEYS = ['SENTRY_AUTH_TOKEN', 'SENTRY_ORG', 'SENTRY_PROJECT'] as const
export function resolveSentryBuildSettings(env: NodeJS.ProcessEnv) {
const sourceMapUploadEnabled = env.NODE_ENV === 'production' && env.SENTRY_SOURCE_MAP_UPLOAD === 'true'
const missingUploadEnv = sourceMapUploadEnabled ? SENTRY_UPLOAD_ENV_KEYS.filter((key) => !env[key]?.trim()) : []
if (missingUploadEnv.length > 0) {
throw new Error(`Sentry production builds require: ${missingUploadEnv.join(', ')}`)
}
return { sourceMapUploadEnabled }
}
export function resolveRendererEdition(value: string | undefined): AppEdition {
const edition = value?.trim().toLowerCase() || 'global'
if (APP_EDITIONS.includes(edition as AppEdition)) return edition as AppEdition
throw new Error(`Unsupported renderer edition: ${edition}`)
}
const rendererEdition = resolveRendererEdition(process.env.CHERRY_EDITION)
const sentryBuildContext = getSentryBuildContext(pkg.name, pkg.version, rendererEdition)
const { sourceMapUploadEnabled } = resolveSentryBuildSettings(process.env)
const sentrySourceMap = sourceMapUploadEnabled ? ('hidden' as const) : isDev
const sentrySourceMapPlugins = (outputDirectory: 'main' | 'preload' | 'renderer') =>
sourceMapUploadEnabled
? sentryVitePlugin({
authToken: process.env.SENTRY_AUTH_TOKEN,
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
telemetry: false,
release: {
name: sentryBuildContext.release,
create: false,
finalize: false,
setCommits: false
},
sourcemaps: {
filesToDeleteAfterUpload: `./out/${outputDirectory}/**/*.map`
}
})
: []
// Bundle/externalize split for the main process: everything in `dependencies` is
// externalized below (kept in node_modules of the packaged app), and everything
// NOT in `dependencies` (i.e. in `devDependencies`) is bundled into the main bundle by
// Rolldown. The API gateway's Elysia stack (`elysia`, `@elysia/*`) is intentionally in
// `devDependencies` for exactly this reason — it is pure JS and bundles cleanly. Do NOT
// move it to `dependencies`: that would externalize it, and since devDependencies are
// pruned from production packages, the packaged app would fail at runtime with
// MODULE_NOT_FOUND (no test catches this). See docs/references/api-gateway/README.md.
const mainExternalDependencies = [
...Object.keys(pkg.dependencies),
// optionalDependencies too: platform-gated natives (e.g. node-mac-permissions) are real import
// targets, not napi sub-packages, so rollup would fail on the .node; production keeps them installed.
...Object.keys(pkg.optionalDependencies ?? {})
]
export const mainExternalModules = ['bufferutil', 'utf-8-validate', 'electron', ...mainExternalDependencies]
export const isMainExternalModule = (id: string) => {
return mainExternalModules.some((moduleId) => id === moduleId || id.startsWith(`${moduleId}/`))
}
// Ships the flat theme contract next to the main bundle so mini apps can be served
// `assets/miniAppTheme.css`. Built in-process: nothing in the app pipeline runs the ui package build.
const miniAppThemeAssetPlugin = (): Plugin => ({
name: 'cherry-mini-app-theme-asset',
// The sources live outside the main bundle's module graph, so `electron-vite dev` would
// serve a stale `miniAppTheme.css` after a token edit. Registered in `buildStart` because
// `addWatchFile` is a build-phase call — it is not available from `generateBundle`.
buildStart() {
const stylesDir = resolve('packages/ui/src/styles')
for (const name of readdirSync(stylesDir, { recursive: true, encoding: 'utf8' })) {
if (name.endsWith('.css')) this.addWatchFile(join(stylesDir, name))
}
},
async generateBundle() {
let source: string
try {
source = await buildFlatContractCss()
} catch (error) {
return this.error(`failed to build assets/miniAppTheme.css: ${error instanceof Error ? error.message : error}`)
}
this.emitFile({ type: 'asset', fileName: 'assets/miniAppTheme.css', source })
}
})
/** Shared with the utility-process entries build, which must resolve identically. */
export const mainResolveAlias = {
'@main': resolve('src/main'),
'@application': resolve('src/main/core/application/Application'),
'@data': resolve('src/main/data'),
'@shared': resolve('src/shared'),
'@logger': resolve('src/main/core/logger/LoggerService'),
'@cherrystudio/ai-core/provider': resolve('packages/aiCore/src/core/providers'),
'@cherrystudio/ai-core/built-in/plugins': resolve('packages/aiCore/src/core/plugins/built-in'),
'@cherrystudio/ai-core': resolve('packages/aiCore/src'),
'@cherrystudio/ai-sdk-provider': resolve('packages/ai-sdk-provider/src'),
'@cherrystudio/provider-registry/node': resolve('packages/provider-registry/src/registry-loader'),
'@cherrystudio/provider-registry': resolve('packages/provider-registry/src'),
'@test-mocks': resolve('tests/__mocks__'),
'@test-helpers': resolve('tests/helpers')
}
export default defineConfig({
main: {
define: { __APP_EDITION__: JSON.stringify(rendererEdition) },
plugins: [
chunkExportGuardPlugin(),
miniAppThemeAssetPlugin(),
...visualizerPlugin('main'),
...sentrySourceMapPlugins('main')
],
resolve: { alias: mainResolveAlias },
build: {
externalizeDeps: {
include: mainExternalModules
},
lib: { entry: resolve(__dirname, 'src/main/main.ts') },
rolldownOptions: {
output: {
manualChunks: (id) => {
// conf removes its containing file from require.cache; isolate it so the app entry stays cached.
if (id.includes('/node_modules/conf/')) return 'electron-store-conf'
// rolldown drops this chunk's named exports when it merges with a re-export-only
// facade chunk, leaving createOpenAI undefined at runtime. Keep it alone.
if (id.includes('/node_modules/@ai-sdk/openai/')) return 'ai-sdk-openai'
return undefined
},
comments: isProd ? { legal: false } : undefined
},
onwarn(warning, warn) {
if (warning.code === 'COMMONJS_VARIABLE_IN_ESM') return
warn(warning)
}
},
sourcemap: sentrySourceMap
},
optimizeDeps: {
noDiscovery: isDev
}
},
preload: {
plugins: [...sentrySourceMapPlugins('preload')],
resolve: {
alias: {
'@shared': resolve('src/shared')
}
},
build: {
sourcemap: sentrySourceMap,
rolldownOptions: {
// Unlike renderer which auto-discovers entries from HTML files,
// preload requires explicit entry point configuration for multiple scripts
input: {
preload: resolve(__dirname, 'src/preload/preload.ts'),
simplest: resolve(__dirname, 'src/preload/simplest.ts'), // Minimal preload
webview: resolve(__dirname, 'src/preload/webview.ts'), // Site `<webview>` guests
miniAppBridge: resolve(__dirname, 'src/preload/miniAppBridge.ts') // Local mini app guests (`window.cherry`)
},
external: ['electron'],
output: {
entryFileNames: '[name].js',
format: 'cjs'
}
}
}
},
renderer: {
define: {
__APP_EDITION__: JSON.stringify(rendererEdition),
__APP_RELEASE_HISTORY__: JSON.stringify(bundledReleaseHistory),
__APP_RELEASE_NOTES__: JSON.stringify(bundledReleaseNotes),
__APP_RELEASE_VERSION__: JSON.stringify(pkg.version)
},
plugins: [
uiContractPlugin(),
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
routesDirectory: resolve('src/renderer/routes'),
generatedRouteTree: resolve('src/renderer/routeTree.gen.ts')
}),
tailwindcss(),
react(),
...(isDev ? [CodeInspectorPlugin({ bundler: 'vite' })] : []), // 只在开发环境下启用 CodeInspectorPlugin
...visualizerPlugin('renderer'),
...sentrySourceMapPlugins('renderer')
],
resolve: {
alias: {
'@renderer': resolve('src/renderer'),
'@shared': resolve('src/shared'),
'@logger': resolve('src/renderer/services/LoggerService'),
'@data': resolve('src/renderer/data'),
'@cherrystudio/ai-core/provider': resolve('packages/aiCore/src/core/providers'),
'@cherrystudio/ai-core/built-in/plugins': resolve('packages/aiCore/src/core/plugins/built-in'),
'@cherrystudio/ai-core': resolve('packages/aiCore/src'),
'@cherrystudio/extension-table-plus': resolve('packages/extension-table-plus/src'),
'@cherrystudio/ai-sdk-provider': resolve('packages/ai-sdk-provider/src'),
'@cherrystudio/provider-registry/node': resolve('packages/provider-registry/src/registry-loader'),
'@cherrystudio/provider-registry': resolve('packages/provider-registry/src'),
'@cherrystudio/ui/icons/providers': resolve('packages/ui/src/components/icons/providers'),
'@cherrystudio/ui/icons': resolve('packages/ui/src/components/icons'),
'@cherrystudio/ui': resolve('packages/ui/src'),
'@test-mocks': resolve('tests/__mocks__')
}
},
optimizeDeps: {
exclude: ['pyodide'],
rolldownOptions: {
transform: {
target: 'esnext' // for dev
}
}
},
worker: {
format: 'es'
},
build: {
sourcemap: sentrySourceMap,
target: 'esnext', // for build
rolldownOptions: {
input: {
index: resolve(__dirname, 'src/renderer/windows/main/index.html'),
quickAssistant: resolve(__dirname, 'src/renderer/windows/quickAssistant/index.html'),
selectionToolbar: resolve(__dirname, 'src/renderer/windows/selection/toolbar/index.html'),
selectionAction: resolve(__dirname, 'src/renderer/windows/selection/action/index.html'),
migrationV2: resolve(__dirname, 'src/renderer/windows/migrationV2/index.html'),
userDataRelocation: resolve(__dirname, 'src/renderer/windows/userDataRelocation/index.html'),
subWindow: resolve(__dirname, 'src/renderer/windows/subWindow/index.html'),
screenshot: resolve(__dirname, 'src/renderer/windows/screenshot/index.html')
},
onwarn(warning, warn) {
if (warning.code === 'COMMONJS_VARIABLE_IN_ESM') return
warn(warning)
},
output: {
comments: isProd ? { legal: false } : undefined,
advancedChunks: {
// Without this, groups recursively capture dependencies — React
// itself ends up inside an icon bucket and every window preloads it.
includeDependenciesRecursively: false,
groups: [
// Bucket per-icon lazy modules into mid-size chunks instead of one
// tiny chunk per icon. Model icons only: they are reached solely
// through the dynamic loaders, so the buckets stay off every
// window's eager graph. Provider icons must NOT be grouped — a few
// files statically import specific providers from
// @cherrystudio/ui/icons/providers, and bucketing would chain
// whole buckets of unrelated SVGs into those windows' first load.
// Only the SVG component files (*.tsx) may match: each icon dir's
// meta.ts is eagerly imported by the meta-catalogs.
{
name: 'icons-models',
test: /packages\/ui\/src\/components\/icons\/models\/[^/]+\/(?:index|light|dark|avatar)\.tsx$/,
maxSize: 150_000
}
]
}
}
}
}
}
})